rtci_stream_driver/runtime/mod.rs
1//! The async runtime a driver runs on, injected per driver.
2//!
3//! The engine is sans-I/O; the driver owns sockets, tasks and timers. Everything of those that
4//! touches a reactor or a clock goes through one object-safe trait, [`Runtime`], given to each
5//! driver as an `Arc<dyn Runtime>` ([`StreamDriver::with_runtime`](crate::StreamDriver::with_runtime),
6//! [`PeerDriver::with_runtime`](crate::peer::PeerDriver::with_runtime)):
7//!
8//! | Injected (reactor or clock) | Not injected (executor-agnostic, one implementation) |
9//! | --- | --- |
10//! | spawning a task ([`Runtime::spawn`]) | channels and wake-ups between the driver's tasks |
11//! | the clock and timers ([`Runtime::now`], [`Runtime::sleep_until`]) | [`sleep`], [`timeout`], [`yield_now`]: free functions on top |
12//! | UDP sockets, multicast included ([`Runtime::bind_udp`], [`Runtime::bind_udp_multicast`]) | |
13//! | TCP listeners and connections ([`Runtime::listen_tcp`], [`Runtime::connect_tcp`]) | |
14//! | name resolution ([`Runtime::resolve_host`] and the optional record lookups) | |
15//! | running a future to completion ([`Runtime::block_on`]) | |
16//!
17//! There is no global or default runtime in the library, and none can be set: each driver is
18//! given its own. Cargo features only decide which built-in runtime *types* exist
19//! (`runtime-tokio`, on by default: `TokioRuntime`; `runtime-smol`: `SmolRuntime`;
20//! `runtime-mock`: `MockRuntime`, virtual time and an in-memory network); they never
21//! decide what the driver uses, and several can be on at once.
22//! With `default-features = false` and no built-in runtime the crate builds without any of them,
23//! and an application implements [`Runtime`] for its own executor (the `custom-runtime`
24//! example).
25//!
26//! The design follows the upstream project's "Bring Your Own Async Runtime"
27//! (webrtc.rs, 2026-07-30), with one addition: the clock ([`Runtime::now`]) is the runtime's,
28//! because the driver stamps every engine input with a time and a virtual clock must be the
29//! one both the engine and the timers see.
30
31#[cfg(feature = "runtime-mock")]
32pub mod mock;
33#[cfg(feature = "runtime-smol")]
34mod smol_runtime;
35#[cfg(feature = "runtime-tokio")]
36mod tokio_runtime;
37#[cfg(feature = "runtime-mock")]
38pub use mock::{MockClock, MockNet, MockRuntime};
39#[cfg(feature = "runtime-smol")]
40pub use smol_runtime::SmolRuntime;
41#[cfg(feature = "runtime-tokio")]
42pub use tokio_runtime::TokioRuntime;
43
44use shared::stream::{DnsRecord, RecordKind};
45use socket2::{Domain, Protocol, SockRef, Socket, Type};
46use std::fmt::Debug;
47use std::future::Future;
48use std::io::{self, IoSliceMut};
49use std::net::{IpAddr, Ipv4Addr, Ipv6Addr, SocketAddr};
50use std::pin::Pin;
51use std::sync::Arc;
52use std::sync::atomic::{AtomicU16, Ordering};
53use std::task::{Context, Poll};
54use std::time::{Duration, Instant};
55
56/// A boxed future that can move between threads.
57pub type BoxFuture<'a, T> = Pin<Box<dyn Future<Output = T> + Send + 'a>>;
58
59/// What a driver needs from an async runtime: the primitives that touch a reactor or a clock.
60///
61/// Object safe (`&self` receivers, no generic methods): drivers hold an `Arc<dyn Runtime>`.
62/// See the [module documentation](self) for what is and is not here.
63pub trait Runtime: Send + Sync + Debug + 'static {
64 /// Runs `future` as a task of its own. Dropping the handle detaches the task (it runs on);
65 /// [`JoinHandle::abort`] cancels it.
66 fn spawn(&self, future: BoxFuture<'static, ()>) -> Box<dyn JoinHandle>;
67
68 /// The runtime's clock. Every time the driver gives the engine comes from here, so a
69 /// virtual clock drives the engine's timers too.
70 fn now(&self) -> Instant;
71
72 /// A future that completes once [`now`](Self::now) has reached `deadline` (at once when it
73 /// has already).
74 fn sleep_until(&self, deadline: Instant) -> BoxFuture<'static, ()>;
75
76 /// A UDP socket bound to `local` (port 0: any free port).
77 ///
78 /// # Errors
79 ///
80 /// The bind failed: `AddrInUse` for a port in use, `PermissionDenied` for one the host
81 /// refuses (both are skipped inside a port range).
82 fn bind_udp(&self, local: SocketAddr) -> io::Result<Arc<dyn AsyncUdpSocket>>;
83
84 /// A UDP socket joined to a multicast group (mDNS: 224.0.0.251 or ff02::fb on 5353).
85 ///
86 /// # Errors
87 ///
88 /// The bind or the join failed (a host without IPv6, say).
89 fn bind_udp_multicast(&self, config: &MulticastConfig) -> io::Result<Arc<dyn AsyncUdpSocket>>;
90
91 /// A TCP listener on `local` (backlog 128). `reuse_address` sets `SO_REUSEADDR` (and
92 /// `SO_REUSEPORT` where the platform has it).
93 ///
94 /// # Errors
95 ///
96 /// As [`bind_udp`](Self::bind_udp).
97 fn listen_tcp(
98 &self,
99 local: SocketAddr,
100 reuse_address: bool,
101 ) -> io::Result<Arc<dyn AsyncTcpListener>>;
102
103 /// A TCP connection from `local` (bound first: an ICE-TCP active candidate's address) to
104 /// `remote`, with `TCP_NODELAY` set. The driver bounds it with its connect timeout.
105 fn connect_tcp(
106 &self,
107 local: SocketAddr,
108 remote: SocketAddr,
109 reuse_address: bool,
110 ) -> BoxFuture<'static, io::Result<Arc<dyn AsyncTcpStream>>>;
111
112 /// The addresses of `host` with `port`, both families together (the system resolver asks
113 /// for AAAA and A at once, RFC 8305 section 3).
114 fn resolve_host(
115 &self,
116 host: &str,
117 port: u16,
118 ) -> BoxFuture<'static, io::Result<Vec<SocketAddr>>>;
119
120 /// The addresses of one family of `host`, when the runtime can ask for AAAA and A apart
121 /// (RFC 8305 section 3: the engine starts on the first answer). `None`, the default: it
122 /// cannot, and the driver uses [`resolve_host`](Self::resolve_host).
123 fn resolve_family(
124 &self,
125 host: &str,
126 port: u16,
127 ipv6: bool,
128 ) -> Option<BoxFuture<'static, Vec<SocketAddr>>> {
129 let _ = (host, port, ipv6);
130 None
131 }
132
133 /// The SRV or NAPTR records of `name` (RFC 5928, RFC 8489 section 8). The default answers
134 /// none, and the engine then uses the host and the scheme's default port.
135 fn resolve_records(&self, name: &str, kind: RecordKind) -> BoxFuture<'static, Vec<DnsRecord>> {
136 let _ = (name, kind);
137 Box::pin(std::future::ready(Vec::new()))
138 }
139
140 /// Runs `future` to completion on the calling thread. The future need not be `Send`.
141 fn block_on(&self, future: Pin<Box<dyn Future<Output = ()> + '_>>);
142
143 /// Whether [`now`](Self::now) is a virtual clock (a mock's) rather than the wall clock.
144 /// What is kept per process on the wall clock (the mDNS budget,
145 /// [`process_mdns_rate_limit`](crate::peer::process_mdns_rate_limit)) is not shared with a
146 /// driver on a virtual clock, whose times run elsewhere. `false` by default.
147 fn virtual_clock(&self) -> bool {
148 false
149 }
150
151 /// Every address of every interface of the host that is up, unfiltered: what address
152 /// selection ([`crate::sockets::AddressSelection`]) chooses from. The default reads the
153 /// operating system's list ([`host_interfaces`]); a runtime with a network of its own (a
154 /// mock's) answers with that network's.
155 ///
156 /// # Errors
157 ///
158 /// The list could not be read.
159 fn interfaces(&self) -> io::Result<Vec<LocalInterface>> {
160 host_interfaces()
161 }
162
163 /// The source address the system would use towards a global destination of the family
164 /// (IPv6 when `ipv6`): the default route's address, `None` without a route. With IPv6
165 /// privacy extensions (RFC 8981) it is the temporary address (RFC 6724 rule 7). The
166 /// default asks the system with an unconnected UDP socket connected to a documentation
167 /// address (RFC 5737, RFC 3849): connecting a UDP socket sends nothing.
168 fn preferred_source(&self, ipv6: bool) -> Option<IpAddr> {
169 host_preferred_source(ipv6)
170 }
171
172 /// The source address the system's routing table picks towards `destination` (`None`
173 /// without a route): RFC 8828 section 5.2 Mode 2 "MUST follow the kernel routing table
174 /// rules", and with an enterprise TURN server "the preferred route MUST be through" it, so
175 /// the interface of the route to that server is the one gathered on. The default asks the
176 /// system with a UDP socket connected to `destination` (connecting sends nothing).
177 fn route_source(&self, destination: IpAddr) -> Option<IpAddr> {
178 host_route_source(destination)
179 }
180}
181
182/// One address of one interface of the host ([`Runtime::interfaces`]).
183#[derive(Debug, Clone, PartialEq, Eq)]
184#[non_exhaustive]
185pub struct LocalInterface {
186 /// The interface's name (`en0`, `eth0`, an adapter name on Windows).
187 pub name: String,
188 /// The address.
189 pub ip: IpAddr,
190 /// The length of its network prefix, when known (IPv6 addresses of one interface in one
191 /// prefix are one network: address selection keeps one of them).
192 pub prefix_len: Option<u8>,
193 /// Whether the system flags it as an RFC 8981 (RFC 4941) temporary IPv6 address.
194 pub temporary: bool,
195 /// Whether the system flags it as deprecated (RFC 4862 section 5.5.4: past its preferred
196 /// lifetime; a temporary address replaced by a newer one, RFC 8981 section 3.4).
197 pub deprecated: bool,
198}
199
200impl LocalInterface {
201 /// `ip` on the interface `name`, prefix unknown, not temporary.
202 pub fn new(name: impl Into<String>, ip: IpAddr) -> Self {
203 Self {
204 name: name.into(),
205 ip,
206 prefix_len: None,
207 temporary: false,
208 deprecated: false,
209 }
210 }
211
212 /// Flagged deprecated or not.
213 #[must_use]
214 pub fn with_deprecated(mut self, deprecated: bool) -> Self {
215 self.deprecated = deprecated;
216 self
217 }
218
219 /// With a prefix length.
220 #[must_use]
221 pub fn with_prefix_len(mut self, prefix_len: u8) -> Self {
222 self.prefix_len = Some(prefix_len);
223 self
224 }
225
226 /// Flagged temporary (RFC 8981) or not.
227 #[must_use]
228 pub fn with_temporary(mut self, temporary: bool) -> Self {
229 self.temporary = temporary;
230 self
231 }
232}
233
234/// The operating system's interface addresses, with their prefix lengths and the temporary
235/// flag (`shared::ifaces::temporary_ipv6_addresses`: Linux, Android, macOS and iOS report it;
236/// elsewhere nothing is marked).
237///
238/// # Errors
239///
240/// The list could not be read.
241pub fn host_interfaces() -> io::Result<Vec<LocalInterface>> {
242 let temporary = shared::ifaces::temporary_ipv6_addresses().unwrap_or_default();
243 let deprecated = shared::ifaces::deprecated_ipv6_addresses().unwrap_or_default();
244 let mut out: Vec<LocalInterface> = Vec::new();
245 for interface in shared::ifaces::ifaces()? {
246 let Some(addr) = interface.addr else {
247 continue;
248 };
249 let ip = addr.ip();
250 if out.iter().any(|i| i.ip == ip && i.name == interface.name) {
251 continue;
252 }
253 let prefix_len = interface.mask.map(|mask| prefix_length(mask.ip()));
254 out.push(LocalInterface {
255 name: interface.name,
256 ip,
257 prefix_len,
258 temporary: matches!(ip, IpAddr::V6(v6) if temporary.contains(&v6)),
259 deprecated: matches!(ip, IpAddr::V6(v6) if deprecated.contains(&v6)),
260 });
261 }
262 Ok(out)
263}
264
265/// The number of leading one bits of a netmask.
266fn prefix_length(mask: IpAddr) -> u8 {
267 let ones = match mask {
268 IpAddr::V4(m) => u32::from(m).leading_ones(),
269 IpAddr::V6(m) => u128::from(m).leading_ones(),
270 };
271 u8::try_from(ones).unwrap_or(u8::MAX)
272}
273
274/// [`Runtime::preferred_source`] on the operating system: the route to a documentation
275/// address (RFC 5737, RFC 3849), which only a default route covers.
276pub fn host_preferred_source(ipv6: bool) -> Option<IpAddr> {
277 host_route_source(if ipv6 {
278 IpAddr::V6(Ipv6Addr::new(0x2001, 0xdb8, 0, 0, 0, 0, 0, 1))
279 } else {
280 IpAddr::V4(Ipv4Addr::new(198, 51, 100, 1))
281 })
282}
283
284/// [`Runtime::route_source`] on the operating system.
285pub fn host_route_source(destination: IpAddr) -> Option<IpAddr> {
286 let bind: SocketAddr = match destination {
287 IpAddr::V6(_) => (Ipv6Addr::UNSPECIFIED, 0).into(),
288 IpAddr::V4(_) => (Ipv4Addr::UNSPECIFIED, 0).into(),
289 };
290 let socket = std::net::UdpSocket::bind(bind).ok()?;
291 socket.connect(SocketAddr::new(destination, 9)).ok()?;
292 let ip = socket.local_addr().ok()?.ip();
293 (!ip.is_unspecified()).then_some(ip)
294}
295
296/// A task spawned with [`Runtime::spawn`]. Dropping it detaches the task.
297pub trait JoinHandle: Send + Debug {
298 /// Cancels the task (it is dropped at its next await point, or before it starts).
299 fn abort(&self);
300
301 /// Whether the task has ended (finished or cancelled).
302 fn is_finished(&self) -> bool;
303
304 /// Ready once the task has ended.
305 fn poll_join(&mut self, cx: &mut Context<'_>) -> Poll<()>;
306}
307
308impl<'a> dyn JoinHandle + 'a {
309 /// Waits for the task to end.
310 pub fn join(&mut self) -> impl Future<Output = ()> + '_ {
311 std::future::poll_fn(move |cx| self.poll_join(cx))
312 }
313}
314
315/// One datagram (or, with `segment_size`, several of one size back to back) to send.
316#[derive(Debug, Clone, Copy)]
317pub struct Transmit<'a> {
318 /// Where to.
319 pub destination: SocketAddr,
320 /// The bytes.
321 pub contents: &'a [u8],
322 /// The byte for the IPv4 TOS / IPv6 Traffic Class field: the DSCP in the upper six bits
323 /// (RFC 2474), the ECN codepoint in the lower two (RFC 3168). The engine gives one per
324 /// datagram (`RTCPeerConnection::traffic_class`, RFC 8837).
325 pub traffic_class: u8,
326 /// `Some(n)`: `contents` is several datagrams of `n` bytes (the last may be shorter), for a
327 /// socket that sends them in one call (GSO). The driver sends one datagram per transmit.
328 pub segment_size: Option<usize>,
329 /// The address the datagram is to leave from, for a socket bound to the unspecified
330 /// address: the engine names one for each mDNS datagram (an answer leaves from the address
331 /// of its record, on that address's interface, RFC 6762 section 14). `None`: the socket's
332 /// own address, or the system's choice.
333 pub source: Option<IpAddr>,
334}
335
336/// What [`AsyncUdpSocket::poll_recv`] says about one buffer it filled.
337#[derive(Debug, Clone, Copy)]
338pub struct RecvMeta {
339 /// The sender.
340 pub addr: SocketAddr,
341 /// How many bytes of the buffer were filled.
342 pub len: usize,
343 /// The size of each datagram in the buffer (`len` when it holds one; less when the socket
344 /// coalesced several of one sender, GRO).
345 pub stride: usize,
346 /// The ECN codepoint the datagram arrived with, when the socket reports it.
347 pub ecn: Option<u8>,
348 /// The local address it was sent to, when the socket reports it.
349 pub dst_ip: Option<IpAddr>,
350}
351
352impl Default for RecvMeta {
353 fn default() -> Self {
354 Self {
355 addr: SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0),
356 len: 0,
357 stride: 0,
358 ecn: None,
359 dst_ip: None,
360 }
361 }
362}
363
364/// A UDP socket of a runtime, in the poll form of quinn-udp's so that batched send and receive
365/// (`sendmmsg`, `recvmmsg`, GSO, GRO) fit.
366pub trait AsyncUdpSocket: Send + Sync + Debug {
367 /// Sends `transmit`, marked with its `traffic_class`. `Pending` when the socket cannot take
368 /// it now (the driver then counts it lost, as UDP would).
369 fn poll_send(&self, cx: &mut Context<'_>, transmit: &Transmit<'_>) -> Poll<io::Result<usize>>;
370
371 /// Receives up to `bufs.len()` datagrams (at most [`max_receive_batch`](Self::max_receive_batch)),
372 /// filling `meta` alongside; how many.
373 fn poll_recv(
374 &self,
375 cx: &mut Context<'_>,
376 bufs: &mut [IoSliceMut<'_>],
377 meta: &mut [RecvMeta],
378 ) -> Poll<io::Result<usize>>;
379
380 /// The address it is bound to.
381 fn local_addr(&self) -> io::Result<SocketAddr>;
382
383 /// How many buffers one [`poll_recv`](Self::poll_recv) can fill. 1 by default.
384 fn max_receive_batch(&self) -> usize {
385 1
386 }
387
388 /// The TOS / Traffic Class byte the operating system reports for the socket (`getsockopt`
389 /// of `IP_TOS` / `IPV6_TCLASS`): what its next datagram carries.
390 ///
391 /// # Errors
392 ///
393 /// The option is not offered on this platform.
394 fn traffic_class(&self) -> io::Result<u32>;
395
396 /// Whether the platform refused to mark this socket: its datagrams leave with traffic
397 /// class 0 whatever the transmit asks (see [`crate::sockets::set_traffic_class`]).
398 fn unmarked(&self) -> bool {
399 false
400 }
401
402 /// Sets whether the socket's next datagrams go with the IPv4 Don't Fragment bit set and,
403 /// over IPv6, without local fragmentation (`true`), or may be fragmented (`false`): what
404 /// `RTCPeerConnection::dont_fragment` asks per datagram (RFC 8261 section 5, RFC 6347
405 /// section 4.1.1.1, RFC 9147 section 4.4; RFC 9260 section 6.9: a fragment made before a
406 /// path MTU reduction "MUST" be IP-fragmented). `Unsupported` by default, and where the
407 /// platform has no such option: its datagrams keep the system's default.
408 ///
409 /// # Errors
410 ///
411 /// The platform refused the option, or has none.
412 fn set_dont_fragment(&self, on: bool) -> io::Result<()> {
413 let _ = on;
414 Err(io::ErrorKind::Unsupported.into())
415 }
416}
417
418/// A TCP connection of a runtime. `&self` methods: the driver's reader and writer tasks share
419/// one `Arc`.
420pub trait AsyncTcpStream: Send + Sync + Debug {
421 /// Reads into `buf`; 0 at the peer's end of stream.
422 fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>>;
423
424 /// Writes some of `buf`; how much.
425 fn poll_write(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>>;
426
427 /// Ends the sending direction (FIN).
428 ///
429 /// # Errors
430 ///
431 /// The socket refused.
432 fn shutdown_write(&self) -> io::Result<()>;
433
434 /// Makes the close abortive (`SO_LINGER` 0): when the last reference is dropped the
435 /// connection is reset (RST) instead of closed with FIN.
436 ///
437 /// # Errors
438 ///
439 /// The socket refused.
440 fn reset_on_close(&self) -> io::Result<()>;
441
442 /// Sets the socket's TOS / Traffic Class byte and returns what the operating system reports
443 /// for it afterwards.
444 ///
445 /// # Errors
446 ///
447 /// The platform refused the option or does not offer it.
448 fn set_traffic_class(&self, value: u8) -> io::Result<u32>;
449
450 /// Its local address.
451 fn local_addr(&self) -> io::Result<SocketAddr>;
452
453 /// The peer's address.
454 fn peer_addr(&self) -> io::Result<SocketAddr>;
455}
456
457/// A TCP listener of a runtime.
458pub trait AsyncTcpListener: Send + Sync + Debug {
459 /// The next connection, with `TCP_NODELAY` set, and its peer's address.
460 fn poll_accept(
461 &self,
462 cx: &mut Context<'_>,
463 ) -> Poll<io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)>>;
464
465 /// The address it listens on.
466 fn local_addr(&self) -> io::Result<SocketAddr>;
467}
468
469impl<'a> dyn AsyncTcpListener + 'a {
470 /// Waits for the next connection.
471 pub async fn accept(&self) -> io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)> {
472 std::future::poll_fn(|cx| self.poll_accept(cx)).await
473 }
474}
475
476impl<'a> dyn AsyncTcpStream + 'a {
477 /// Reads into `buf`; 0 at the peer's end of stream.
478 pub async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
479 std::future::poll_fn(|cx| self.poll_read(cx, buf)).await
480 }
481
482 /// Writes all of `buf`.
483 pub async fn write_all(&self, mut buf: &[u8]) -> io::Result<()> {
484 while !buf.is_empty() {
485 let n = std::future::poll_fn(|cx| self.poll_write(cx, buf)).await?;
486 if n == 0 {
487 return Err(io::ErrorKind::WriteZero.into());
488 }
489 buf = &buf[n..];
490 }
491 Ok(())
492 }
493}
494
495impl<'a> dyn AsyncUdpSocket + 'a {
496 /// Waits for one datagram: its length and sender.
497 pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
498 std::future::poll_fn(|cx| {
499 let mut meta = [RecvMeta::default()];
500 let mut bufs = [IoSliceMut::new(&mut *buf)];
501 match self.poll_recv(cx, &mut bufs, &mut meta) {
502 Poll::Ready(Ok(_)) => Poll::Ready(Ok((meta[0].len, meta[0].addr))),
503 Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
504 Poll::Pending => Poll::Pending,
505 }
506 })
507 .await
508 }
509
510 /// Sends one datagram, unmarked, waiting for room.
511 pub async fn send_to(&self, buf: &[u8], destination: SocketAddr) -> io::Result<usize> {
512 let transmit = Transmit {
513 destination,
514 contents: buf,
515 traffic_class: 0,
516 segment_size: None,
517 source: None,
518 };
519 std::future::poll_fn(|cx| self.poll_send(cx, &transmit)).await
520 }
521
522 /// Sends `transmit` if the socket can take it now: how many bytes, or the system's error
523 /// (`WouldBlock` when the socket cannot take it now).
524 ///
525 /// # Errors
526 ///
527 /// The send failed, or would block.
528 pub fn try_send(&self, transmit: &Transmit<'_>) -> io::Result<usize> {
529 let mut cx = Context::from_waker(std::task::Waker::noop());
530 match self.poll_send(&mut cx, transmit) {
531 Poll::Ready(result) => result,
532 Poll::Pending => Err(io::ErrorKind::WouldBlock.into()),
533 }
534 }
535}
536
537/// What a multicast socket is bound and joined to.
538#[derive(Debug, Clone, PartialEq, Eq)]
539#[non_exhaustive]
540pub struct MulticastConfig {
541 /// The group (224.0.0.251 or ff02::fb for mDNS).
542 pub group: IpAddr,
543 /// The port (5353 for mDNS).
544 pub port: u16,
545 /// The addresses of the interfaces to join the group on: one membership per interface
546 /// that has one of them (the addresses of the group's family; an IPv6 address names its
547 /// interface by index, [`interface_index`]). Empty: the system's default interface only.
548 /// RFC 6762 section 14: a host on several links takes part in mDNS on each of them.
549 pub interfaces: Vec<IpAddr>,
550 /// TTL / hop limit of what it sends, multicast and unicast (255 for mDNS, RFC 6762
551 /// section 11).
552 pub hop_limit: u32,
553 /// Shares the port with other processes (`SO_REUSEADDR`, and `SO_REUSEPORT` where the
554 /// platform has it).
555 pub reuse_address: bool,
556}
557
558impl MulticastConfig {
559 /// `group` on `port`: the default interface, hop limit 1, the port not shared.
560 pub fn new(group: IpAddr, port: u16) -> Self {
561 Self {
562 group,
563 port,
564 interfaces: Vec::new(),
565 hop_limit: 1,
566 reuse_address: false,
567 }
568 }
569
570 /// Joined on these [`interfaces`](Self::interfaces).
571 #[must_use]
572 pub fn with_interfaces(mut self, interfaces: Vec<IpAddr>) -> Self {
573 self.interfaces = interfaces;
574 self
575 }
576 /// With a [`hop_limit`](Self::hop_limit).
577 #[must_use]
578 pub fn with_hop_limit(mut self, hop_limit: u32) -> Self {
579 self.hop_limit = hop_limit;
580 self
581 }
582 /// Sharing the port ([`reuse_address`](Self::reuse_address)) or not.
583 #[must_use]
584 pub fn with_reuse_address(mut self, reuse_address: bool) -> Self {
585 self.reuse_address = reuse_address;
586 self
587 }
588 /// mDNS on `group` (224.0.0.251 or ff02::fb): port 5353, joined on the interfaces of
589 /// `interfaces` (the default interface when empty), hop limit 255, the port shared with
590 /// the host's other responders.
591 pub fn mdns(group: IpAddr, interfaces: Vec<IpAddr>) -> Self {
592 Self {
593 group,
594 port: 5353,
595 interfaces,
596 hop_limit: 255,
597 reuse_address: true,
598 }
599 }
600
601 /// The addresses of [`interfaces`](Self::interfaces) of the group's family.
602 pub fn interfaces_of_family(&self) -> impl Iterator<Item = IpAddr> + '_ {
603 let v4 = self.group.is_ipv4();
604 self.interfaces
605 .iter()
606 .copied()
607 .filter(move |ip| ip.is_ipv4() == v4 && !ip.is_unspecified())
608 }
609}
610
611/// The index of the interface that holds the IPv6 address `ip` (what `IPV6_MULTICAST_IF` and
612/// an IPv6 group membership name an interface by), `None` when no interface of the host holds
613/// it.
614pub fn interface_index(ip: Ipv6Addr) -> Option<u32> {
615 let interfaces = shared::ifaces::ifaces().ok()?;
616 let entry = interfaces
617 .iter()
618 .find(|i| matches!(i.addr, Some(SocketAddr::V6(a)) if *a.ip() == ip))?;
619 if let Some(SocketAddr::V6(a)) = entry.addr
620 && a.scope_id() != 0
621 {
622 return Some(a.scope_id());
623 }
624 name_to_index(&entry.name)
625}
626
627#[cfg(unix)]
628fn name_to_index(name: &str) -> Option<u32> {
629 let name = std::ffi::CString::new(name).ok()?;
630 // SAFETY: `name` is a NUL-terminated string that outlives the call.
631 let index = unsafe { libc::if_nametoindex(name.as_ptr()) };
632 (index != 0).then_some(index)
633}
634
635#[cfg(not(unix))]
636fn name_to_index(_: &str) -> Option<u32> {
637 None
638}
639
640/// The name of the interface that holds `ip`, `None` when no interface of the host holds it.
641pub fn interface_name(ip: IpAddr) -> Option<String> {
642 shared::ifaces::ifaces()
643 .ok()?
644 .into_iter()
645 .find(|i| i.addr.is_some_and(|a| a.ip() == ip))
646 .map(|i| i.name)
647}
648
649/// Applies a [`Transmit::source`] to a real multicast socket bound to the unspecified address:
650/// before a datagram to a multicast group, it sets the interface the datagram leaves by
651/// (`IP_MULTICAST_IF` to the source address, `IPV6_MULTICAST_IF` to the index of the interface
652/// that holds it) when it differs from the last one set. The system then sends from that
653/// interface's address: on Linux exactly the address given (`IP_MULTICAST_IF` with an address
654/// sets the source), on macOS and Windows the interface's address, the same one where the
655/// interface has one address of the family. For built-in and third-party runtimes whose sockets
656/// have a file descriptor.
657#[derive(Debug, Default)]
658pub struct MulticastInterfaceSelector {
659 last: std::sync::Mutex<Option<IpAddr>>,
660}
661
662impl MulticastInterfaceSelector {
663 /// Sets the interface of `transmit` on `socket`. A transmit to a unicast destination, or
664 /// without a source of the destination's family, changes nothing.
665 ///
666 /// # Errors
667 ///
668 /// The source is on no interface of the host, or the system refused the option: the
669 /// datagram is not to be sent from another interface instead.
670 pub fn apply(&self, socket: SockRef<'_>, transmit: &Transmit<'_>) -> io::Result<()> {
671 let destination = transmit.destination.ip();
672 let Some(source) = transmit.source.filter(|source| {
673 destination.is_multicast()
674 && !source.is_unspecified()
675 && source.is_ipv4() == destination.is_ipv4()
676 }) else {
677 return Ok(());
678 };
679 let mut last = self
680 .last
681 .lock()
682 .unwrap_or_else(std::sync::PoisonError::into_inner);
683 if *last == Some(source) {
684 return Ok(());
685 }
686 match source {
687 IpAddr::V4(source) => socket.set_multicast_if_v4(&source)?,
688 IpAddr::V6(source) => {
689 let index = interface_index(source).ok_or_else(|| {
690 io::Error::new(
691 io::ErrorKind::AddrNotAvailable,
692 format!("no interface holds {source}"),
693 )
694 })?;
695 socket.set_multicast_if_v6(index)?;
696 }
697 }
698 *last = Some(source);
699 Ok(())
700 }
701}
702
703/// Waits `duration` on `runtime`'s clock.
704pub fn sleep(runtime: &dyn Runtime, duration: Duration) -> BoxFuture<'static, ()> {
705 runtime.sleep_until(runtime.now() + duration)
706}
707
708/// [`timeout`] ran out.
709#[derive(Debug, Clone, Copy, PartialEq, Eq)]
710pub struct Elapsed;
711
712impl std::fmt::Display for Elapsed {
713 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
714 f.write_str("deadline elapsed")
715 }
716}
717
718impl std::error::Error for Elapsed {}
719
720/// `future`'s output, or [`Elapsed`] if `duration` of `runtime`'s clock passes first.
721pub async fn timeout<T>(
722 runtime: &dyn Runtime,
723 duration: Duration,
724 future: impl Future<Output = T>,
725) -> Result<T, Elapsed> {
726 timeout_at(runtime, runtime.now() + duration, future).await
727}
728
729/// `future`'s output, or [`Elapsed`] if `runtime`'s clock reaches `deadline` first.
730pub async fn timeout_at<T>(
731 runtime: &dyn Runtime,
732 deadline: Instant,
733 future: impl Future<Output = T>,
734) -> Result<T, Elapsed> {
735 let mut future = std::pin::pin!(future);
736 let mut sleep = runtime.sleep_until(deadline);
737 std::future::poll_fn(|cx| {
738 if let Poll::Ready(value) = future.as_mut().poll(cx) {
739 return Poll::Ready(Ok(value));
740 }
741 sleep.as_mut().poll(cx).map(|()| Err(Elapsed))
742 })
743 .await
744}
745
746/// Gives other tasks a turn: pending once, with the task woken at once.
747pub async fn yield_now() {
748 let mut yielded = false;
749 std::future::poll_fn(|cx| {
750 if yielded {
751 return Poll::Ready(());
752 }
753 yielded = true;
754 cx.waker().wake_by_ref();
755 Poll::Pending
756 })
757 .await
758}
759
760/// Applies a [`Transmit::traffic_class`] to a real socket: sets `IP_TOS` / `IPV6_TCLASS` when
761/// the value differs from the last one set, and stops asking once the platform refused (its
762/// datagrams then leave unmarked, [`AsyncUdpSocket::unmarked`]). For built-in and third-party
763/// runtimes whose sockets have a file descriptor.
764#[derive(Debug)]
765pub struct TrafficClassMarker {
766 /// The byte last set (a new socket's is 0), or [`Self::REFUSED`].
767 state: AtomicU16,
768}
769
770impl Default for TrafficClassMarker {
771 fn default() -> Self {
772 Self {
773 state: AtomicU16::new(0),
774 }
775 }
776}
777
778impl TrafficClassMarker {
779 const REFUSED: u16 = 0x100;
780
781 /// Marks `socket` (IPv6 when `ipv6`) with `value` before a datagram: what the datagram
782 /// carries (0 once the platform refused).
783 pub fn apply(&self, socket: SockRef<'_>, ipv6: bool, value: u8) -> u8 {
784 let current = self.state.load(Ordering::Relaxed);
785 if current == Self::REFUSED {
786 return 0;
787 }
788 if current == u16::from(value) {
789 return value;
790 }
791 match crate::sockets::set_traffic_class(socket, ipv6, value) {
792 Ok(()) => {
793 self.state.store(u16::from(value), Ordering::Relaxed);
794 value
795 }
796 // The platform does not mark (RFC 8835 4.2: "appropriate to depart ... on platforms
797 // where QoS marking is not implemented"): the socket is not asked again.
798 Err(_) => {
799 self.state.store(Self::REFUSED, Ordering::Relaxed);
800 0
801 }
802 }
803 }
804
805 /// Whether the platform refused.
806 pub fn refused(&self) -> bool {
807 self.state.load(Ordering::Relaxed) == Self::REFUSED
808 }
809}
810
811/// A non-blocking std UDP socket on `local`: what the built-in runtimes wrap.
812///
813/// # Errors
814///
815/// The bind failed.
816pub fn std_udp(local: SocketAddr) -> io::Result<std::net::UdpSocket> {
817 let socket = std::net::UdpSocket::bind(local)?;
818 socket.set_nonblocking(true)?;
819 Ok(socket)
820}
821
822/// A non-blocking std UDP socket joined as `config` says: for IPv4 what rtci-mdns'
823/// `MulticastSocket` builds (bound to the group on Linux, to 0.0.0.0 elsewhere), for IPv6
824/// `[::]:port`, IPv6 only; a membership of the group on every interface of
825/// [`MulticastConfig::interfaces`] (the default interface when there is none).
826///
827/// # Errors
828///
829/// The bind failed, or no membership could be joined (an interface that refuses one is
830/// skipped while another joins).
831pub fn std_multicast(config: &MulticastConfig) -> io::Result<std::net::UdpSocket> {
832 let domain = match config.group {
833 IpAddr::V4(_) => Domain::IPV4,
834 IpAddr::V6(_) => Domain::IPV6,
835 };
836 let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
837 if config.group.is_ipv6() {
838 socket.set_only_v6(true)?;
839 }
840 if config.reuse_address {
841 socket.set_reuse_address(true)?;
842 #[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
843 socket.set_reuse_port(true)?;
844 }
845 socket.set_nonblocking(true)?;
846 let interfaces: Vec<IpAddr> = config.interfaces_of_family().collect();
847 match config.group {
848 IpAddr::V4(group) => {
849 socket.set_multicast_ttl_v4(config.hop_limit)?;
850 socket.set_ttl_v4(config.hop_limit)?;
851 // The group itself does not bind on macOS and Windows; 0.0.0.0 does.
852 let local = if cfg!(target_os = "linux") {
853 group
854 } else {
855 Ipv4Addr::UNSPECIFIED
856 };
857 socket.bind(&SocketAddr::new(local.into(), config.port).into())?;
858 join_each(&interfaces, |interface| match interface {
859 Some(IpAddr::V4(interface)) => {
860 if cfg!(windows) && interface.is_loopback() {
861 warn_loopback_join_on_windows(group);
862 }
863 socket.join_multicast_v4(&group, &interface)
864 }
865 _ => socket.join_multicast_v4(&group, &Ipv4Addr::UNSPECIFIED),
866 })?;
867 }
868 IpAddr::V6(group) => {
869 socket.set_multicast_hops_v6(config.hop_limit)?;
870 socket.set_unicast_hops_v6(config.hop_limit)?;
871 socket.bind(&SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), config.port).into())?;
872 join_each(&interfaces, |interface| {
873 let index = match interface {
874 Some(IpAddr::V6(ip)) => interface_index(ip).ok_or_else(|| {
875 io::Error::new(
876 io::ErrorKind::AddrNotAvailable,
877 format!("no interface holds {ip}"),
878 )
879 })?,
880 _ => 0,
881 };
882 socket.join_multicast_v6(&group, index)
883 })?;
884 }
885 }
886 Ok(socket.into())
887}
888
889/// On Windows a socket joined on the loopback interface that sends to the group leaves the
890/// group's destination-cache entry on loopback after the process has exited, and the system
891/// then answers 127.0.0.1 for the group to every process that asks which address reaches it,
892/// until the entry is deleted (`peer` module documentation). Said once per process.
893fn warn_loopback_join_on_windows(group: Ipv4Addr) {
894 static ONCE: std::sync::Once = std::sync::Once::new();
895 ONCE.call_once(|| {
896 log::warn!(
897 "joining {group} on the loopback interface: on Windows mDNS sent there leaves the \
898 group's destination-cache route on loopback after this process, for other \
899 processes too (netsh interface ipv4 delete destinationcache, as administrator)"
900 );
901 });
902}
903
904/// Joins once per interface (`None`: the default one, when there is no interface): an error
905/// only when no membership was made. A second address of an interface already joined is
906/// refused by the system (`EADDRINUSE`) and changes nothing.
907fn join_each(
908 interfaces: &[IpAddr],
909 mut join: impl FnMut(Option<IpAddr>) -> io::Result<()>,
910) -> io::Result<()> {
911 if interfaces.is_empty() {
912 return join(None);
913 }
914 let mut first_error = None;
915 let mut joined = false;
916 for interface in interfaces {
917 match join(Some(*interface)) {
918 Ok(()) => joined = true,
919 Err(e) if e.kind() == io::ErrorKind::AddrInUse => joined = true,
920 Err(e) => {
921 first_error.get_or_insert(e);
922 }
923 }
924 }
925 match (joined, first_error) {
926 (false, Some(e)) => Err(e),
927 _ => Ok(()),
928 }
929}
930
931fn tcp_socket(addr: SocketAddr, reuse_address: bool) -> io::Result<Socket> {
932 let socket = Socket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))?;
933 if reuse_address {
934 socket.set_reuse_address(true)?;
935 #[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos"))))]
936 socket.set_reuse_port(true)?;
937 }
938 socket.set_nonblocking(true)?;
939 Ok(socket)
940}
941
942/// A non-blocking std TCP listener on `local`, backlog 128.
943///
944/// # Errors
945///
946/// The bind failed.
947pub fn std_tcp_listener(
948 local: SocketAddr,
949 reuse_address: bool,
950) -> io::Result<std::net::TcpListener> {
951 let socket = tcp_socket(local, reuse_address)?;
952 socket.bind(&local.into())?;
953 socket.listen(128)?;
954 Ok(socket.into())
955}
956
957/// A non-blocking TCP socket bound to `local`, for a runtime to connect to a peer.
958///
959/// # Errors
960///
961/// The bind failed.
962pub fn std_tcp_bound(local: SocketAddr, reuse_address: bool) -> io::Result<Socket> {
963 let socket = tcp_socket(local, reuse_address)?;
964 socket.bind(&local.into())?;
965 Ok(socket)
966}
967
968/// Starts a non-blocking TCP connection from `local` to `remote`: the socket is bound, and the
969/// handshake runs. A runtime waits for it to become writable, then reads `take_error` and
970/// `peer_addr` (what async-io's own `connect` does), for runtimes whose connect cannot bind a
971/// local address first.
972///
973/// # Errors
974///
975/// The bind failed, or the connection failed at once.
976pub fn std_tcp_connect_start(
977 local: SocketAddr,
978 remote: SocketAddr,
979 reuse_address: bool,
980) -> io::Result<std::net::TcpStream> {
981 let socket = std_tcp_bound(local, reuse_address)?;
982 match socket.connect(&remote.into()) {
983 Ok(()) => {}
984 Err(e) if connect_in_progress(&e) => {}
985 Err(e) => return Err(e),
986 }
987 Ok(socket.into())
988}
989
990/// Whether a non-blocking connect's error only says the handshake is under way.
991fn connect_in_progress(e: &io::Error) -> bool {
992 #[cfg(unix)]
993 if e.raw_os_error() == Some(libc::EINPROGRESS) {
994 return true;
995 }
996 // Windows: WSAEWOULDBLOCK.
997 e.kind() == io::ErrorKind::WouldBlock
998}
999
1000/// Makes `socket`'s close abortive (`SO_LINGER` 0: RST instead of FIN), for
1001/// [`AsyncTcpStream::reset_on_close`].
1002///
1003/// # Errors
1004///
1005/// The socket refused.
1006pub fn reset_on_close(socket: SockRef<'_>) -> io::Result<()> {
1007 socket.set_linger(Some(Duration::ZERO))
1008}
1009
1010/// Sets `socket`'s TOS / Traffic Class and reads it back (for [`AsyncTcpStream::set_traffic_class`]).
1011///
1012/// # Errors
1013///
1014/// The platform refused the option or does not offer it.
1015pub fn set_and_read_traffic_class(socket: SockRef<'_>, ipv6: bool, value: u8) -> io::Result<u32> {
1016 crate::sockets::set_traffic_class(SockRef::from(&*socket), ipv6, value)?;
1017 crate::sockets::traffic_class(socket, ipv6)
1018}
1019
1020/// Asks the system to report each received datagram's TOS / Traffic Class byte
1021/// (`IP_RECVTOS`, `IPV6_RECVTCLASS`), from which [`recv_from_with_ecn`] reads the ECN field
1022/// (RFC 3168; RFC 6679 section 7.2.1: receivers "listen for ECT/CE"). Unix only; elsewhere
1023/// `Unsupported`, and received datagrams carry no ECN.
1024///
1025/// # Errors
1026///
1027/// The system refused the option.
1028#[cfg(unix)]
1029pub fn enable_ecn_receive(socket: SockRef<'_>, ipv6: bool) -> io::Result<()> {
1030 use std::os::fd::AsRawFd;
1031 let on: libc::c_int = 1;
1032 let (level, name) = if ipv6 {
1033 (libc::IPPROTO_IPV6, libc::IPV6_RECVTCLASS)
1034 } else {
1035 (libc::IPPROTO_IP, libc::IP_RECVTOS)
1036 };
1037 // SAFETY: a valid descriptor, a c_int option value of the size given.
1038 let r = unsafe {
1039 libc::setsockopt(
1040 socket.as_raw_fd(),
1041 level,
1042 name,
1043 (&on as *const libc::c_int).cast(),
1044 std::mem::size_of::<libc::c_int>() as libc::socklen_t,
1045 )
1046 };
1047 if r == 0 {
1048 Ok(())
1049 } else {
1050 Err(io::Error::last_os_error())
1051 }
1052}
1053
1054/// See the unix version: no ECN is read on this system.
1055///
1056/// # Errors
1057///
1058/// Always `Unsupported`.
1059#[cfg(not(unix))]
1060pub fn enable_ecn_receive(socket: SockRef<'_>, ipv6: bool) -> io::Result<()> {
1061 let _ = (socket, ipv6);
1062 Err(io::ErrorKind::Unsupported.into())
1063}
1064
1065/// Receives one datagram into `buf` (`recvmsg`): its length, its sender, and the ECN codepoint
1066/// of its IP header (the two low bits of the TOS / Traffic Class byte) when the system reports
1067/// it ([`enable_ecn_receive`]). A datagram longer than `buf` is truncated, as `recv_from`
1068/// truncates it.
1069///
1070/// # Errors
1071///
1072/// As `recv_from` (`WouldBlock` on a non-blocking socket with nothing to read).
1073#[cfg(unix)]
1074pub fn recv_from_with_ecn(
1075 socket: SockRef<'_>,
1076 buf: &mut [u8],
1077) -> io::Result<(usize, SocketAddr, Option<u8>)> {
1078 use std::os::fd::AsRawFd;
1079 // SAFETY: zeroed plain-old-data C structures.
1080 let mut name: libc::sockaddr_storage = unsafe { std::mem::zeroed() };
1081 let mut iov = libc::iovec {
1082 iov_base: buf.as_mut_ptr().cast(),
1083 iov_len: buf.len(),
1084 };
1085 // Room for one TOS / Traffic Class control message and more, aligned for cmsghdr.
1086 let mut control = [0u64; 16];
1087 // SAFETY: as above.
1088 let mut msg: libc::msghdr = unsafe { std::mem::zeroed() };
1089 msg.msg_name = (&mut name as *mut libc::sockaddr_storage).cast();
1090 msg.msg_namelen = std::mem::size_of::<libc::sockaddr_storage>() as libc::socklen_t;
1091 msg.msg_iov = &mut iov;
1092 msg.msg_iovlen = 1 as _;
1093 msg.msg_control = control.as_mut_ptr().cast();
1094 msg.msg_controllen = std::mem::size_of_val(&control) as _;
1095 // SAFETY: every pointer in `msg` is to a live buffer of the length given.
1096 let n = unsafe { libc::recvmsg(socket.as_raw_fd(), &mut msg, 0) };
1097 if n < 0 {
1098 return Err(io::Error::last_os_error());
1099 }
1100 let mut ecn = None;
1101 // SAFETY: the control messages are the ones recvmsg wrote into `control`, walked with the
1102 // system's macros; each value is read unaligned.
1103 unsafe {
1104 let mut cmsg = libc::CMSG_FIRSTHDR(&msg);
1105 while !cmsg.is_null() {
1106 let header = &*cmsg;
1107 let data = libc::CMSG_DATA(cmsg);
1108 // Linux reports IPv4's byte as IP_TOS, Apple systems and the BSDs as IP_RECVTOS;
1109 // IPv6's is an int under IPV6_TCLASS everywhere.
1110 let byte = if header.cmsg_level == libc::IPPROTO_IP
1111 && (header.cmsg_type == libc::IP_TOS || header.cmsg_type == libc::IP_RECVTOS)
1112 {
1113 Some(std::ptr::read_unaligned(data))
1114 } else if header.cmsg_level == libc::IPPROTO_IPV6
1115 && header.cmsg_type == libc::IPV6_TCLASS
1116 {
1117 Some(std::ptr::read_unaligned(data.cast::<libc::c_int>()) as u8)
1118 } else {
1119 None
1120 };
1121 if let Some(byte) = byte {
1122 ecn = Some(byte & 0b11);
1123 }
1124 cmsg = libc::CMSG_NXTHDR(&msg, cmsg);
1125 }
1126 }
1127 let from = socket_addr_of(&name)
1128 .ok_or_else(|| io::Error::new(io::ErrorKind::InvalidData, "no sender address"))?;
1129 Ok((n as usize, from, ecn))
1130}
1131
1132/// The address in a `sockaddr_storage` recvmsg filled (IPv4 or IPv6).
1133#[cfg(unix)]
1134fn socket_addr_of(name: &libc::sockaddr_storage) -> Option<SocketAddr> {
1135 match libc::c_int::from(name.ss_family) {
1136 libc::AF_INET => {
1137 // SAFETY: the family says the storage holds a sockaddr_in.
1138 let v4 =
1139 unsafe { &*(name as *const libc::sockaddr_storage).cast::<libc::sockaddr_in>() };
1140 Some(SocketAddr::new(
1141 Ipv4Addr::from(u32::from_be(v4.sin_addr.s_addr)).into(),
1142 u16::from_be(v4.sin_port),
1143 ))
1144 }
1145 libc::AF_INET6 => {
1146 // SAFETY: the family says the storage holds a sockaddr_in6.
1147 let v6 =
1148 unsafe { &*(name as *const libc::sockaddr_storage).cast::<libc::sockaddr_in6>() };
1149 Some(SocketAddr::V6(std::net::SocketAddrV6::new(
1150 Ipv6Addr::from(v6.sin6_addr.s6_addr),
1151 u16::from_be(v6.sin6_port),
1152 v6.sin6_flowinfo,
1153 v6.sin6_scope_id,
1154 )))
1155 }
1156 _ => None,
1157 }
1158}
1159
1160/// Sets the Don't Fragment state of `socket` (IPv6 when `ipv6`): `true` sets the IPv4 DF bit and
1161/// forbids local fragmentation over IPv6, `false` lets the datagram be fragmented. Linux and
1162/// Android: `IP_MTU_DISCOVER` / `IPV6_MTU_DISCOVER` to `PMTUDISC_DO` or `PMTUDISC_DONT`; Apple
1163/// systems and FreeBSD: `IP_DONTFRAG` / `IPV6_DONTFRAG`. Elsewhere `Unsupported`.
1164///
1165/// # Errors
1166///
1167/// The platform refused the option, or has none.
1168pub fn set_dont_fragment(socket: SockRef<'_>, ipv6: bool, on: bool) -> io::Result<()> {
1169 #[cfg(any(target_os = "linux", target_os = "android"))]
1170 let (level, name, value) = match (ipv6, on) {
1171 (false, true) => (
1172 libc::IPPROTO_IP,
1173 libc::IP_MTU_DISCOVER,
1174 libc::IP_PMTUDISC_DO,
1175 ),
1176 (false, false) => (
1177 libc::IPPROTO_IP,
1178 libc::IP_MTU_DISCOVER,
1179 libc::IP_PMTUDISC_DONT,
1180 ),
1181 (true, true) => (
1182 libc::IPPROTO_IPV6,
1183 libc::IPV6_MTU_DISCOVER,
1184 libc::IPV6_PMTUDISC_DO,
1185 ),
1186 (true, false) => (
1187 libc::IPPROTO_IPV6,
1188 libc::IPV6_MTU_DISCOVER,
1189 libc::IPV6_PMTUDISC_DONT,
1190 ),
1191 };
1192 #[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
1193 let (level, name, value) = if ipv6 {
1194 (
1195 libc::IPPROTO_IPV6,
1196 libc::IPV6_DONTFRAG,
1197 libc::c_int::from(on),
1198 )
1199 } else {
1200 (libc::IPPROTO_IP, libc::IP_DONTFRAG, libc::c_int::from(on))
1201 };
1202 #[cfg(any(
1203 target_os = "linux",
1204 target_os = "android",
1205 target_vendor = "apple",
1206 target_os = "freebsd"
1207 ))]
1208 {
1209 use std::os::fd::AsRawFd;
1210 // SAFETY: a valid descriptor, a c_int option value of the size given.
1211 let r = unsafe {
1212 libc::setsockopt(
1213 socket.as_raw_fd(),
1214 level,
1215 name,
1216 (&value as *const libc::c_int).cast(),
1217 std::mem::size_of::<libc::c_int>() as libc::socklen_t,
1218 )
1219 };
1220 if r == 0 {
1221 Ok(())
1222 } else {
1223 Err(io::Error::last_os_error())
1224 }
1225 }
1226 #[cfg(not(any(
1227 target_os = "linux",
1228 target_os = "android",
1229 target_vendor = "apple",
1230 target_os = "freebsd"
1231 )))]
1232 {
1233 let _ = (socket, ipv6, on);
1234 Err(io::ErrorKind::Unsupported.into())
1235 }
1236}
1237
1238/// The Don't Fragment state [`set_dont_fragment`] set, as the operating system reports it
1239/// (`getsockopt`): `true` for DF / no local fragmentation.
1240///
1241/// # Errors
1242///
1243/// The platform refused the query, or has no such option.
1244pub fn dont_fragment(socket: SockRef<'_>, ipv6: bool) -> io::Result<bool> {
1245 #[cfg(any(target_os = "linux", target_os = "android"))]
1246 let (level, name) = if ipv6 {
1247 (libc::IPPROTO_IPV6, libc::IPV6_MTU_DISCOVER)
1248 } else {
1249 (libc::IPPROTO_IP, libc::IP_MTU_DISCOVER)
1250 };
1251 #[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
1252 let (level, name) = if ipv6 {
1253 (libc::IPPROTO_IPV6, libc::IPV6_DONTFRAG)
1254 } else {
1255 (libc::IPPROTO_IP, libc::IP_DONTFRAG)
1256 };
1257 #[cfg(any(
1258 target_os = "linux",
1259 target_os = "android",
1260 target_vendor = "apple",
1261 target_os = "freebsd"
1262 ))]
1263 {
1264 use std::os::fd::AsRawFd;
1265 let mut value: libc::c_int = 0;
1266 let mut len = std::mem::size_of::<libc::c_int>() as libc::socklen_t;
1267 // SAFETY: a valid descriptor, a c_int buffer of the size given.
1268 let r = unsafe {
1269 libc::getsockopt(
1270 socket.as_raw_fd(),
1271 level,
1272 name,
1273 (&mut value as *mut libc::c_int).cast(),
1274 &mut len,
1275 )
1276 };
1277 if r != 0 {
1278 return Err(io::Error::last_os_error());
1279 }
1280 #[cfg(any(target_os = "linux", target_os = "android"))]
1281 let on = value == libc::IP_PMTUDISC_DO;
1282 #[cfg(any(target_vendor = "apple", target_os = "freebsd"))]
1283 let on = value != 0;
1284 Ok(on)
1285 }
1286 #[cfg(not(any(
1287 target_os = "linux",
1288 target_os = "android",
1289 target_vendor = "apple",
1290 target_os = "freebsd"
1291 )))]
1292 {
1293 let _ = (socket, ipv6);
1294 Err(io::ErrorKind::Unsupported.into())
1295 }
1296}