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
152/// A task spawned with [`Runtime::spawn`]. Dropping it detaches the task.
153pub trait JoinHandle: Send + Debug {
154 /// Cancels the task (it is dropped at its next await point, or before it starts).
155 fn abort(&self);
156
157 /// Whether the task has ended (finished or cancelled).
158 fn is_finished(&self) -> bool;
159
160 /// Ready once the task has ended.
161 fn poll_join(&mut self, cx: &mut Context<'_>) -> Poll<()>;
162}
163
164impl<'a> dyn JoinHandle + 'a {
165 /// Waits for the task to end.
166 pub fn join(&mut self) -> impl Future<Output = ()> + '_ {
167 std::future::poll_fn(move |cx| self.poll_join(cx))
168 }
169}
170
171/// One datagram (or, with `segment_size`, several of one size back to back) to send.
172#[derive(Debug, Clone, Copy)]
173pub struct Transmit<'a> {
174 /// Where to.
175 pub destination: SocketAddr,
176 /// The bytes.
177 pub contents: &'a [u8],
178 /// The byte for the IPv4 TOS / IPv6 Traffic Class field: the DSCP in the upper six bits
179 /// (RFC 2474), the ECN codepoint in the lower two (RFC 3168). The engine gives one per
180 /// datagram (`RTCPeerConnection::traffic_class`, RFC 8837).
181 pub traffic_class: u8,
182 /// `Some(n)`: `contents` is several datagrams of `n` bytes (the last may be shorter), for a
183 /// socket that sends them in one call (GSO). The driver sends one datagram per transmit.
184 pub segment_size: Option<usize>,
185 /// The address the datagram is to leave from, for a socket bound to the unspecified
186 /// address: the engine names one for each mDNS datagram (an answer leaves from the address
187 /// of its record, on that address's interface, RFC 6762 section 14). `None`: the socket's
188 /// own address, or the system's choice.
189 pub source: Option<IpAddr>,
190}
191
192/// What [`AsyncUdpSocket::poll_recv`] says about one buffer it filled.
193#[derive(Debug, Clone, Copy)]
194pub struct RecvMeta {
195 /// The sender.
196 pub addr: SocketAddr,
197 /// How many bytes of the buffer were filled.
198 pub len: usize,
199 /// The size of each datagram in the buffer (`len` when it holds one; less when the socket
200 /// coalesced several of one sender, GRO).
201 pub stride: usize,
202 /// The ECN codepoint the datagram arrived with, when the socket reports it.
203 pub ecn: Option<u8>,
204 /// The local address it was sent to, when the socket reports it.
205 pub dst_ip: Option<IpAddr>,
206}
207
208impl Default for RecvMeta {
209 fn default() -> Self {
210 Self {
211 addr: SocketAddr::new(Ipv4Addr::UNSPECIFIED.into(), 0),
212 len: 0,
213 stride: 0,
214 ecn: None,
215 dst_ip: None,
216 }
217 }
218}
219
220/// A UDP socket of a runtime, in the poll form of quinn-udp's so that batched send and receive
221/// (`sendmmsg`, `recvmmsg`, GSO, GRO) fit.
222pub trait AsyncUdpSocket: Send + Sync + Debug {
223 /// Sends `transmit`, marked with its `traffic_class`. `Pending` when the socket cannot take
224 /// it now (the driver then counts it lost, as UDP would).
225 fn poll_send(&self, cx: &mut Context<'_>, transmit: &Transmit<'_>) -> Poll<io::Result<usize>>;
226
227 /// Receives up to `bufs.len()` datagrams (at most [`max_receive_batch`](Self::max_receive_batch)),
228 /// filling `meta` alongside; how many.
229 fn poll_recv(
230 &self,
231 cx: &mut Context<'_>,
232 bufs: &mut [IoSliceMut<'_>],
233 meta: &mut [RecvMeta],
234 ) -> Poll<io::Result<usize>>;
235
236 /// The address it is bound to.
237 fn local_addr(&self) -> io::Result<SocketAddr>;
238
239 /// How many buffers one [`poll_recv`](Self::poll_recv) can fill. 1 by default.
240 fn max_receive_batch(&self) -> usize {
241 1
242 }
243
244 /// The TOS / Traffic Class byte the operating system reports for the socket (`getsockopt`
245 /// of `IP_TOS` / `IPV6_TCLASS`): what its next datagram carries.
246 ///
247 /// # Errors
248 ///
249 /// The option is not offered on this platform.
250 fn traffic_class(&self) -> io::Result<u32>;
251
252 /// Whether the platform refused to mark this socket: its datagrams leave with traffic
253 /// class 0 whatever the transmit asks (see [`crate::sockets::set_traffic_class`]).
254 fn unmarked(&self) -> bool {
255 false
256 }
257}
258
259/// A TCP connection of a runtime. `&self` methods: the driver's reader and writer tasks share
260/// one `Arc`.
261pub trait AsyncTcpStream: Send + Sync + Debug {
262 /// Reads into `buf`; 0 at the peer's end of stream.
263 fn poll_read(&self, cx: &mut Context<'_>, buf: &mut [u8]) -> Poll<io::Result<usize>>;
264
265 /// Writes some of `buf`; how much.
266 fn poll_write(&self, cx: &mut Context<'_>, buf: &[u8]) -> Poll<io::Result<usize>>;
267
268 /// Ends the sending direction (FIN).
269 ///
270 /// # Errors
271 ///
272 /// The socket refused.
273 fn shutdown_write(&self) -> io::Result<()>;
274
275 /// Makes the close abortive (`SO_LINGER` 0): when the last reference is dropped the
276 /// connection is reset (RST) instead of closed with FIN.
277 ///
278 /// # Errors
279 ///
280 /// The socket refused.
281 fn reset_on_close(&self) -> io::Result<()>;
282
283 /// Sets the socket's TOS / Traffic Class byte and returns what the operating system reports
284 /// for it afterwards.
285 ///
286 /// # Errors
287 ///
288 /// The platform refused the option or does not offer it.
289 fn set_traffic_class(&self, value: u8) -> io::Result<u32>;
290
291 /// Its local address.
292 fn local_addr(&self) -> io::Result<SocketAddr>;
293
294 /// The peer's address.
295 fn peer_addr(&self) -> io::Result<SocketAddr>;
296}
297
298/// A TCP listener of a runtime.
299pub trait AsyncTcpListener: Send + Sync + Debug {
300 /// The next connection, with `TCP_NODELAY` set, and its peer's address.
301 fn poll_accept(
302 &self,
303 cx: &mut Context<'_>,
304 ) -> Poll<io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)>>;
305
306 /// The address it listens on.
307 fn local_addr(&self) -> io::Result<SocketAddr>;
308}
309
310impl<'a> dyn AsyncTcpListener + 'a {
311 /// Waits for the next connection.
312 pub async fn accept(&self) -> io::Result<(Arc<dyn AsyncTcpStream>, SocketAddr)> {
313 std::future::poll_fn(|cx| self.poll_accept(cx)).await
314 }
315}
316
317impl<'a> dyn AsyncTcpStream + 'a {
318 /// Reads into `buf`; 0 at the peer's end of stream.
319 pub async fn read(&self, buf: &mut [u8]) -> io::Result<usize> {
320 std::future::poll_fn(|cx| self.poll_read(cx, buf)).await
321 }
322
323 /// Writes all of `buf`.
324 pub async fn write_all(&self, mut buf: &[u8]) -> io::Result<()> {
325 while !buf.is_empty() {
326 let n = std::future::poll_fn(|cx| self.poll_write(cx, buf)).await?;
327 if n == 0 {
328 return Err(io::ErrorKind::WriteZero.into());
329 }
330 buf = &buf[n..];
331 }
332 Ok(())
333 }
334}
335
336impl<'a> dyn AsyncUdpSocket + 'a {
337 /// Waits for one datagram: its length and sender.
338 pub async fn recv_from(&self, buf: &mut [u8]) -> io::Result<(usize, SocketAddr)> {
339 std::future::poll_fn(|cx| {
340 let mut meta = [RecvMeta::default()];
341 let mut bufs = [IoSliceMut::new(&mut *buf)];
342 match self.poll_recv(cx, &mut bufs, &mut meta) {
343 Poll::Ready(Ok(_)) => Poll::Ready(Ok((meta[0].len, meta[0].addr))),
344 Poll::Ready(Err(e)) => Poll::Ready(Err(e)),
345 Poll::Pending => Poll::Pending,
346 }
347 })
348 .await
349 }
350
351 /// Sends one datagram, unmarked, waiting for room.
352 pub async fn send_to(&self, buf: &[u8], destination: SocketAddr) -> io::Result<usize> {
353 let transmit = Transmit {
354 destination,
355 contents: buf,
356 traffic_class: 0,
357 segment_size: None,
358 source: None,
359 };
360 std::future::poll_fn(|cx| self.poll_send(cx, &transmit)).await
361 }
362
363 /// Sends `transmit` if the socket can take it now: how many bytes, or the system's error
364 /// (`WouldBlock` when the socket cannot take it now).
365 ///
366 /// # Errors
367 ///
368 /// The send failed, or would block.
369 pub fn try_send(&self, transmit: &Transmit<'_>) -> io::Result<usize> {
370 let mut cx = Context::from_waker(std::task::Waker::noop());
371 match self.poll_send(&mut cx, transmit) {
372 Poll::Ready(result) => result,
373 Poll::Pending => Err(io::ErrorKind::WouldBlock.into()),
374 }
375 }
376}
377
378/// What a multicast socket is bound and joined to.
379#[derive(Debug, Clone, PartialEq, Eq)]
380pub struct MulticastConfig {
381 /// The group (224.0.0.251 or ff02::fb for mDNS).
382 pub group: IpAddr,
383 /// The port (5353 for mDNS).
384 pub port: u16,
385 /// The addresses of the interfaces to join the group on: one membership per interface
386 /// that has one of them (the addresses of the group's family; an IPv6 address names its
387 /// interface by index, [`interface_index`]). Empty: the system's default interface only.
388 /// RFC 6762 section 14: a host on several links takes part in mDNS on each of them.
389 pub interfaces: Vec<IpAddr>,
390 /// TTL / hop limit of what it sends, multicast and unicast (255 for mDNS, RFC 6762
391 /// section 11).
392 pub hop_limit: u32,
393 /// Shares the port with other processes (`SO_REUSEADDR`, and `SO_REUSEPORT` where the
394 /// platform has it).
395 pub reuse_address: bool,
396}
397
398impl MulticastConfig {
399 /// mDNS on `group` (224.0.0.251 or ff02::fb): port 5353, joined on the interfaces of
400 /// `interfaces` (the default interface when empty), hop limit 255, the port shared with
401 /// the host's other responders.
402 pub fn mdns(group: IpAddr, interfaces: Vec<IpAddr>) -> Self {
403 Self {
404 group,
405 port: 5353,
406 interfaces,
407 hop_limit: 255,
408 reuse_address: true,
409 }
410 }
411
412 /// The addresses of [`interfaces`](Self::interfaces) of the group's family.
413 pub fn interfaces_of_family(&self) -> impl Iterator<Item = IpAddr> + '_ {
414 let v4 = self.group.is_ipv4();
415 self.interfaces
416 .iter()
417 .copied()
418 .filter(move |ip| ip.is_ipv4() == v4 && !ip.is_unspecified())
419 }
420}
421
422/// The index of the interface that holds the IPv6 address `ip` (what `IPV6_MULTICAST_IF` and
423/// an IPv6 group membership name an interface by), `None` when no interface of the host holds
424/// it.
425pub fn interface_index(ip: Ipv6Addr) -> Option<u32> {
426 let interfaces = shared::ifaces::ifaces().ok()?;
427 let entry = interfaces
428 .iter()
429 .find(|i| matches!(i.addr, Some(SocketAddr::V6(a)) if *a.ip() == ip))?;
430 if let Some(SocketAddr::V6(a)) = entry.addr
431 && a.scope_id() != 0
432 {
433 return Some(a.scope_id());
434 }
435 name_to_index(&entry.name)
436}
437
438#[cfg(unix)]
439fn name_to_index(name: &str) -> Option<u32> {
440 let name = std::ffi::CString::new(name).ok()?;
441 // SAFETY: `name` is a NUL-terminated string that outlives the call.
442 let index = unsafe { libc::if_nametoindex(name.as_ptr()) };
443 (index != 0).then_some(index)
444}
445
446#[cfg(not(unix))]
447fn name_to_index(_: &str) -> Option<u32> {
448 None
449}
450
451/// The name of the interface that holds `ip`, `None` when no interface of the host holds it.
452pub fn interface_name(ip: IpAddr) -> Option<String> {
453 shared::ifaces::ifaces()
454 .ok()?
455 .into_iter()
456 .find(|i| i.addr.is_some_and(|a| a.ip() == ip))
457 .map(|i| i.name)
458}
459
460/// Applies a [`Transmit::source`] to a real multicast socket bound to the unspecified address:
461/// before a datagram to a multicast group, it sets the interface the datagram leaves by
462/// (`IP_MULTICAST_IF` to the source address, `IPV6_MULTICAST_IF` to the index of the interface
463/// that holds it) when it differs from the last one set. The system then sends from that
464/// interface's address: on Linux exactly the address given (`IP_MULTICAST_IF` with an address
465/// sets the source), on macOS and Windows the interface's address, the same one where the
466/// interface has one address of the family. For built-in and third-party runtimes whose sockets
467/// have a file descriptor.
468#[derive(Debug, Default)]
469pub struct MulticastInterfaceSelector {
470 last: std::sync::Mutex<Option<IpAddr>>,
471}
472
473impl MulticastInterfaceSelector {
474 /// Sets the interface of `transmit` on `socket`. A transmit to a unicast destination, or
475 /// without a source of the destination's family, changes nothing.
476 ///
477 /// # Errors
478 ///
479 /// The source is on no interface of the host, or the system refused the option: the
480 /// datagram is not to be sent from another interface instead.
481 pub fn apply(&self, socket: SockRef<'_>, transmit: &Transmit<'_>) -> io::Result<()> {
482 let destination = transmit.destination.ip();
483 let Some(source) = transmit.source.filter(|source| {
484 destination.is_multicast()
485 && !source.is_unspecified()
486 && source.is_ipv4() == destination.is_ipv4()
487 }) else {
488 return Ok(());
489 };
490 let mut last = self
491 .last
492 .lock()
493 .unwrap_or_else(std::sync::PoisonError::into_inner);
494 if *last == Some(source) {
495 return Ok(());
496 }
497 match source {
498 IpAddr::V4(source) => socket.set_multicast_if_v4(&source)?,
499 IpAddr::V6(source) => {
500 let index = interface_index(source).ok_or_else(|| {
501 io::Error::new(
502 io::ErrorKind::AddrNotAvailable,
503 format!("no interface holds {source}"),
504 )
505 })?;
506 socket.set_multicast_if_v6(index)?;
507 }
508 }
509 *last = Some(source);
510 Ok(())
511 }
512}
513
514/// Waits `duration` on `runtime`'s clock.
515pub fn sleep(runtime: &dyn Runtime, duration: Duration) -> BoxFuture<'static, ()> {
516 runtime.sleep_until(runtime.now() + duration)
517}
518
519/// [`timeout`] ran out.
520#[derive(Debug, Clone, Copy, PartialEq, Eq)]
521pub struct Elapsed;
522
523impl std::fmt::Display for Elapsed {
524 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
525 f.write_str("deadline elapsed")
526 }
527}
528
529impl std::error::Error for Elapsed {}
530
531/// `future`'s output, or [`Elapsed`] if `duration` of `runtime`'s clock passes first.
532pub async fn timeout<T>(
533 runtime: &dyn Runtime,
534 duration: Duration,
535 future: impl Future<Output = T>,
536) -> Result<T, Elapsed> {
537 timeout_at(runtime, runtime.now() + duration, future).await
538}
539
540/// `future`'s output, or [`Elapsed`] if `runtime`'s clock reaches `deadline` first.
541pub async fn timeout_at<T>(
542 runtime: &dyn Runtime,
543 deadline: Instant,
544 future: impl Future<Output = T>,
545) -> Result<T, Elapsed> {
546 let mut future = std::pin::pin!(future);
547 let mut sleep = runtime.sleep_until(deadline);
548 std::future::poll_fn(|cx| {
549 if let Poll::Ready(value) = future.as_mut().poll(cx) {
550 return Poll::Ready(Ok(value));
551 }
552 sleep.as_mut().poll(cx).map(|()| Err(Elapsed))
553 })
554 .await
555}
556
557/// Gives other tasks a turn: pending once, with the task woken at once.
558pub async fn yield_now() {
559 let mut yielded = false;
560 std::future::poll_fn(|cx| {
561 if yielded {
562 return Poll::Ready(());
563 }
564 yielded = true;
565 cx.waker().wake_by_ref();
566 Poll::Pending
567 })
568 .await
569}
570
571/// Applies a [`Transmit::traffic_class`] to a real socket: sets `IP_TOS` / `IPV6_TCLASS` when
572/// the value differs from the last one set, and stops asking once the platform refused (its
573/// datagrams then leave unmarked, [`AsyncUdpSocket::unmarked`]). For built-in and third-party
574/// runtimes whose sockets have a file descriptor.
575#[derive(Debug)]
576pub struct TrafficClassMarker {
577 /// The byte last set (a new socket's is 0), or [`Self::REFUSED`].
578 state: AtomicU16,
579}
580
581impl Default for TrafficClassMarker {
582 fn default() -> Self {
583 Self {
584 state: AtomicU16::new(0),
585 }
586 }
587}
588
589impl TrafficClassMarker {
590 const REFUSED: u16 = 0x100;
591
592 /// Marks `socket` (IPv6 when `ipv6`) with `value` before a datagram: what the datagram
593 /// carries (0 once the platform refused).
594 pub fn apply(&self, socket: SockRef<'_>, ipv6: bool, value: u8) -> u8 {
595 let current = self.state.load(Ordering::Relaxed);
596 if current == Self::REFUSED {
597 return 0;
598 }
599 if current == u16::from(value) {
600 return value;
601 }
602 match crate::sockets::set_traffic_class(socket, ipv6, value) {
603 Ok(()) => {
604 self.state.store(u16::from(value), Ordering::Relaxed);
605 value
606 }
607 // The platform does not mark (RFC 8835 4.2: "appropriate to depart ... on platforms
608 // where QoS marking is not implemented"): the socket is not asked again.
609 Err(_) => {
610 self.state.store(Self::REFUSED, Ordering::Relaxed);
611 0
612 }
613 }
614 }
615
616 /// Whether the platform refused.
617 pub fn refused(&self) -> bool {
618 self.state.load(Ordering::Relaxed) == Self::REFUSED
619 }
620}
621
622/// A non-blocking std UDP socket on `local`: what the built-in runtimes wrap.
623///
624/// # Errors
625///
626/// The bind failed.
627pub fn std_udp(local: SocketAddr) -> io::Result<std::net::UdpSocket> {
628 let socket = std::net::UdpSocket::bind(local)?;
629 socket.set_nonblocking(true)?;
630 Ok(socket)
631}
632
633/// A non-blocking std UDP socket joined as `config` says: for IPv4 what rtci-mdns'
634/// `MulticastSocket` builds (bound to the group on Linux, to 0.0.0.0 elsewhere), for IPv6
635/// `[::]:port`, IPv6 only; a membership of the group on every interface of
636/// [`MulticastConfig::interfaces`] (the default interface when there is none).
637///
638/// # Errors
639///
640/// The bind failed, or no membership could be joined (an interface that refuses one is
641/// skipped while another joins).
642pub fn std_multicast(config: &MulticastConfig) -> io::Result<std::net::UdpSocket> {
643 let domain = match config.group {
644 IpAddr::V4(_) => Domain::IPV4,
645 IpAddr::V6(_) => Domain::IPV6,
646 };
647 let socket = Socket::new(domain, Type::DGRAM, Some(Protocol::UDP))?;
648 if config.group.is_ipv6() {
649 socket.set_only_v6(true)?;
650 }
651 if config.reuse_address {
652 socket.set_reuse_address(true)?;
653 #[cfg(all(unix, not(target_os = "solaris"), not(target_os = "illumos")))]
654 socket.set_reuse_port(true)?;
655 }
656 socket.set_nonblocking(true)?;
657 let interfaces: Vec<IpAddr> = config.interfaces_of_family().collect();
658 match config.group {
659 IpAddr::V4(group) => {
660 socket.set_multicast_ttl_v4(config.hop_limit)?;
661 socket.set_ttl_v4(config.hop_limit)?;
662 // The group itself does not bind on macOS and Windows; 0.0.0.0 does.
663 let local = if cfg!(target_os = "linux") {
664 group
665 } else {
666 Ipv4Addr::UNSPECIFIED
667 };
668 socket.bind(&SocketAddr::new(local.into(), config.port).into())?;
669 join_each(&interfaces, |interface| match interface {
670 Some(IpAddr::V4(interface)) => {
671 if cfg!(windows) && interface.is_loopback() {
672 warn_loopback_join_on_windows(group);
673 }
674 socket.join_multicast_v4(&group, &interface)
675 }
676 _ => socket.join_multicast_v4(&group, &Ipv4Addr::UNSPECIFIED),
677 })?;
678 }
679 IpAddr::V6(group) => {
680 socket.set_multicast_hops_v6(config.hop_limit)?;
681 socket.set_unicast_hops_v6(config.hop_limit)?;
682 socket.bind(&SocketAddr::new(Ipv6Addr::UNSPECIFIED.into(), config.port).into())?;
683 join_each(&interfaces, |interface| {
684 let index = match interface {
685 Some(IpAddr::V6(ip)) => interface_index(ip).ok_or_else(|| {
686 io::Error::new(
687 io::ErrorKind::AddrNotAvailable,
688 format!("no interface holds {ip}"),
689 )
690 })?,
691 _ => 0,
692 };
693 socket.join_multicast_v6(&group, index)
694 })?;
695 }
696 }
697 Ok(socket.into())
698}
699
700/// On Windows a socket joined on the loopback interface that sends to the group leaves the
701/// group's destination-cache entry on loopback after the process has exited, and the system
702/// then answers 127.0.0.1 for the group to every process that asks which address reaches it,
703/// until the entry is deleted (`peer` module documentation). Said once per process.
704fn warn_loopback_join_on_windows(group: Ipv4Addr) {
705 static ONCE: std::sync::Once = std::sync::Once::new();
706 ONCE.call_once(|| {
707 log::warn!(
708 "joining {group} on the loopback interface: on Windows mDNS sent there leaves the \
709 group's destination-cache route on loopback after this process, for other \
710 processes too (netsh interface ipv4 delete destinationcache, as administrator)"
711 );
712 });
713}
714
715/// Joins once per interface (`None`: the default one, when there is no interface): an error
716/// only when no membership was made. A second address of an interface already joined is
717/// refused by the system (`EADDRINUSE`) and changes nothing.
718fn join_each(
719 interfaces: &[IpAddr],
720 mut join: impl FnMut(Option<IpAddr>) -> io::Result<()>,
721) -> io::Result<()> {
722 if interfaces.is_empty() {
723 return join(None);
724 }
725 let mut first_error = None;
726 let mut joined = false;
727 for interface in interfaces {
728 match join(Some(*interface)) {
729 Ok(()) => joined = true,
730 Err(e) if e.kind() == io::ErrorKind::AddrInUse => joined = true,
731 Err(e) => {
732 first_error.get_or_insert(e);
733 }
734 }
735 }
736 match (joined, first_error) {
737 (false, Some(e)) => Err(e),
738 _ => Ok(()),
739 }
740}
741
742fn tcp_socket(addr: SocketAddr, reuse_address: bool) -> io::Result<Socket> {
743 let socket = Socket::new(Domain::for_address(addr), Type::STREAM, Some(Protocol::TCP))?;
744 if reuse_address {
745 socket.set_reuse_address(true)?;
746 #[cfg(all(unix, not(any(target_os = "solaris", target_os = "illumos"))))]
747 socket.set_reuse_port(true)?;
748 }
749 socket.set_nonblocking(true)?;
750 Ok(socket)
751}
752
753/// A non-blocking std TCP listener on `local`, backlog 128.
754///
755/// # Errors
756///
757/// The bind failed.
758pub fn std_tcp_listener(
759 local: SocketAddr,
760 reuse_address: bool,
761) -> io::Result<std::net::TcpListener> {
762 let socket = tcp_socket(local, reuse_address)?;
763 socket.bind(&local.into())?;
764 socket.listen(128)?;
765 Ok(socket.into())
766}
767
768/// A non-blocking TCP socket bound to `local`, for a runtime to connect to a peer.
769///
770/// # Errors
771///
772/// The bind failed.
773pub fn std_tcp_bound(local: SocketAddr, reuse_address: bool) -> io::Result<Socket> {
774 let socket = tcp_socket(local, reuse_address)?;
775 socket.bind(&local.into())?;
776 Ok(socket)
777}
778
779/// Starts a non-blocking TCP connection from `local` to `remote`: the socket is bound, and the
780/// handshake runs. A runtime waits for it to become writable, then reads `take_error` and
781/// `peer_addr` (what async-io's own `connect` does), for runtimes whose connect cannot bind a
782/// local address first.
783///
784/// # Errors
785///
786/// The bind failed, or the connection failed at once.
787pub fn std_tcp_connect_start(
788 local: SocketAddr,
789 remote: SocketAddr,
790 reuse_address: bool,
791) -> io::Result<std::net::TcpStream> {
792 let socket = std_tcp_bound(local, reuse_address)?;
793 match socket.connect(&remote.into()) {
794 Ok(()) => {}
795 Err(e) if connect_in_progress(&e) => {}
796 Err(e) => return Err(e),
797 }
798 Ok(socket.into())
799}
800
801/// Whether a non-blocking connect's error only says the handshake is under way.
802fn connect_in_progress(e: &io::Error) -> bool {
803 #[cfg(unix)]
804 if e.raw_os_error() == Some(libc::EINPROGRESS) {
805 return true;
806 }
807 // Windows: WSAEWOULDBLOCK.
808 e.kind() == io::ErrorKind::WouldBlock
809}
810
811/// Makes `socket`'s close abortive (`SO_LINGER` 0: RST instead of FIN), for
812/// [`AsyncTcpStream::reset_on_close`].
813///
814/// # Errors
815///
816/// The socket refused.
817pub fn reset_on_close(socket: SockRef<'_>) -> io::Result<()> {
818 socket.set_linger(Some(Duration::ZERO))
819}
820
821/// Sets `socket`'s TOS / Traffic Class and reads it back (for [`AsyncTcpStream::set_traffic_class`]).
822///
823/// # Errors
824///
825/// The platform refused the option or does not offer it.
826pub fn set_and_read_traffic_class(socket: SockRef<'_>, ipv6: bool, value: u8) -> io::Result<u32> {
827 crate::sockets::set_traffic_class(SockRef::from(&*socket), ipv6, value)?;
828 crate::sockets::traffic_class(socket, ipv6)
829}