Skip to main content

rtci_stream_driver/
peer.rs

1//! A whole peer connection driven over sockets the driver owns (feature `peer`, on by
2//! default): its UDP sockets for the ICE host candidates, and the TCP sockets of the engine's
3//! stream interface through a [`StreamDriver`].
4//!
5//! [`PeerDriver`] gathers for the application and keeps the gathering right across what makes
6//! a transport lose its candidates. The engine has no sockets, so it tells the application
7//! with `RTCPeerConnectionEvent::OnLocalCandidatesNeeded` when a transport needs a new set of
8//! local candidates: a new DTLS association over UDP runs on a new 3-tuple (RFC 8842 section
9//! 5.1), so after an ICE restart for a new association (automatic SRTP re-keying included) or
10//! on the transport that replaced one an answer closed, the transport's previous UDP addresses
11//! are refused. The driver reacts by itself: it binds new UDP ports (inside
12//! [`PeerDriverConfig::udp_port_range`], skipping ports the host refuses), adds their host
13//! candidates for the event's section, ends the generation, and closes the previous sockets
14//! only once a candidate pair on a new one is selected for that transport (and then after
15//! [`PeerDriverConfig::retired_socket_linger`], for what the peer still sends there before its
16//! own selection switches), or the transport is closed: until then the previous path keeps
17//! carrying the transport's packets. The engine's
18//! ICE-TCP listener is kept (RFC 8842 asks a new 3-tuple of unordered transports only), and
19//! its server-reflexive and TURN gathering follow the new host candidates by themselves.
20//!
21//! # Addresses
22//!
23//! The UDP sockets are bound on [`PeerDriverConfig::addresses`], or, with
24//! [`PeerDriverConfig::address_selection`], on the addresses selected from the runtime's
25//! interface list ([`crate::runtime::Runtime::interfaces`], [`crate::sockets::select_addresses`])
26//! at every gathering: an ICE restart, even one that keeps the DTLS association, gathers on the
27//! addresses the host has then, retiring the sockets of addresses it no longer has.
28//!
29//! # STUN and TURN
30//!
31//! The engine gathers server-reflexive and relayed (TURN over UDP) candidates itself, sending
32//! from the bases of the driver's host candidates; the driver sends what it writes from the
33//! socket of that base and hands back what arrives. A socket the engine's TURN client still
34//! uses (`RTCPeerConnection::turn_local_addresses_in_use`: an allocation, an Allocate, a
35//! release under way) is kept open after ICE is done with it, and
36//! [`PeerDriver::shutdown`] waits for the releases (RFC 8656 section 8).
37//!
38//! With `SettingEngineBuilder::with_dtls_new_association_on_previous_addresses(true)` the
39//! engine keeps the candidates and fires no event: the driver keeps its sockets and gives their
40//! candidates to each new ICE generation again.
41//!
42//! # mDNS
43//!
44//! A connection with mDNS on (`SettingEngineBuilder::with_multicast_dns_mode`) publishes its
45//! host addresses behind `.local` names and resolves the peer's: its ICE agents write their
46//! mDNS datagrams from local port 5353. At the first one the driver binds the host's mDNS
47//! sockets, port 5353 joined to 224.0.0.251 and, where the host has IPv6, to ff02::fb (shared
48//! with other mDNS responders of the host through address reuse), on the interface of every
49//! address of [`PeerDriverConfig::addresses`]; it sends the connection's queries, probes and
50//! answers there and hands what arrives back to the connection. A connection without mDNS
51//! writes none, and the driver binds nothing.
52//!
53//! RFC 6762 section 14: a host on several links takes part in mDNS on each, and an answer
54//! carries only addresses valid on the interface it leaves by. The engine names, for each
55//! message, the address it is about (its record's); the driver sends it by that address's
56//! interface (`Transmit::source`: `IP_MULTICAST_IF` / `IPV6_MULTICAST_IF`), an IPv6 record's
57//! on the IPv6 group (and on the IPv4 group of the same interface where the driver has an IPv4
58//! address there), and a query once on each interface.
59//!
60//! On Windows, a process that joins the IPv4 mDNS group on the loopback interface (a driver
61//! given 127.0.0.1) and sends to the group there leaves a stale route for the group behind
62//! it: the system's destination cache holds 224.0.0.251 with source 127.0.0.1 on the
63//! "Loopback Pseudo-Interface" after the process has exited (`netsh interface ipv4 show
64//! destinationcache address=224.0.0.251`), and from then on any process that asks which
65//! address reaches the group (a UDP socket connected to it) gets 127.0.0.1. Measured on
66//! Windows 11 and on GitHub's Windows image; the joins table entry for the group on the
67//! loopback interface that the join also leaves (`show joins`, references 0) is not what moves
68//! the answer. A later join, send and leave on the network interface does not clear the
69//! entry; deleting it does, at once: `netsh interface ipv4 delete destinationcache
70//! interface=<the loopback interface's index> address=224.0.0.251`, from an administrator
71//! prompt (measured on Windows 11 and on GitHub's Windows image). The same may hold for IPv6's
72//! ff02::fb; that was not measured. So on Windows the driver, by default, takes no part in
73//! IPv4 mDNS on loopback: it does not join 224.0.0.251 on the loopback interface and sends
74//! nothing to the group from a loopback address (the messages about a loopback address's name
75//! are dropped, counted in [`PeerDriver::unsent_datagrams`]); a driver whose only IPv4
76//! addresses are loopback binds no IPv4 mDNS socket and tells the connection that its IPv4
77//! names cannot be published ([`PeerDriver::mdns_available`] is `false`). Loopback candidates
78//! are for local use only (RFC 8445 section 5.1.1.1: "Addresses from a loopback interface MUST
79//! NOT be included in the candidate addresses"), and RFC 6762 asks no mDNS on loopback.
80//! [`PeerDriverConfig::mdns_on_loopback_on_windows`] turns it back on, as on other systems;
81//! the driver then logs a warning when it makes such a join, and an application or test host
82//! that does so cleans the entry as above when it is done. The driver changes no host routing
83//! state itself.
84//!
85//! Where mDNS cannot be sent (a socket that cannot be bound, or a system that refuses every
86//! send to the group: no multicast route, or a Mac application without the Local Network
87//! permission) the driver tells the application with
88//! [`PeerDriverEvent::MdnsUnavailable`] ([`PeerDriver::poll_driver_event`]), with the system's
89//! error, counts it ([`PeerDriver::mdns_send_failures`], [`PeerDriver::mdns_bind_failures`]),
90//! and tells the connection that the family's names cannot be published. It tries again at the
91//! next gathering and, while mDNS datagrams wait, after a back-off; the first send that works
92//! is reported as [`PeerDriverEvent::MdnsAvailable`]. The connection itself goes on over its
93//! other candidates, or fails as ICE does.
94//!
95//! With `QueryAndGather` the driver binds the mDNS sockets before it adds the first host
96//! candidates and tells the connection for which address families it has one
97//! (`RTCPeerConnection::set_multicast_dns_publishing`): a host address of a family without one
98//! cannot have its name published (draft-ietf-mmusic-mdns-ice-candidates section 3.1.1 step
99//! 4), and its candidates go out under a `.local` name that is not published, or not at all
100//! when the connection fails closed (`SettingEngineBuilder::with_multicast_dns_fail_closed`).
101//! [`PeerDriverConfig::mdns_sockets`] `false` binds none.
102//!
103//! Every mDNS datagram takes one message from a budget shared by every driver of the process
104//! ([`process_mdns_rate_limit`], unless [`PeerDriverConfig::mdns_rate_limit`] names another):
105//! draft-ietf-mmusic-mdns-ice-candidates section 7.1 requires "an implementation-wide rate
106//! limit" over the mDNS queries and responses of all connections. A datagram the budget refuses
107//! waits in the driver and leaves, in order, when the budget has room.
108//!
109//! # The loop
110//!
111//! ```text
112//! let mut driver = PeerDriver::new(pc, PeerDriverConfig::on(vec![ip]));
113//! // offer / answer through the application's signalling, on driver.pc_mut();
114//! // after the first local description, the driver gathers by itself;
115//! loop {
116//!     driver.step(Duration::from_millis(20)).await?;
117//!     while let Some(event) = driver.poll_event() {
118//!         // signal OnIceCandidateEvent candidates to the peer (the end-of-candidates one
119//!         // too: without it the peer's transport is "disconnected", never "failed", when
120//!         // the path is lost), answer negotiation-needed, ...
121//!     }
122//!     while let Some(read) = driver.pc_mut().poll_read() { /* media, data channels */ }
123//! }
124//! ```
125
126use crate::mdns_io::{MDNS_MAX_DATAGRAM, MdnsEgress, mdns_v4, mdns_v6};
127pub use crate::mdns_io::{
128    MDNS_MULTICAST_IPV6, process_mdns_rate_limit, set_process_mdns_rate_limit,
129};
130use crate::runtime::{self, AsyncUdpSocket, JoinHandle, Runtime, Transmit};
131use crate::sockets::{self, AddressSelection, PortRange};
132use crate::{DriverConfig, DriverInput, StreamDriver};
133use bytes::BytesMut;
134use rtci::ice::mdns::{MulticastDnsMode, MulticastDnsPublishing};
135use rtci::mdns::{MDNS_MULTICAST_IPV4, MDNS_PORT, MdnsRateLimit};
136use rtci::peer_connection::RTCPeerConnection;
137use rtci::peer_connection::event::{
138    RTCLocalCandidatesNeededEvent, RTCLocalCandidatesNeededReason, RTCPeerConnectionEvent,
139    RTCTransportEventKind,
140};
141use rtci::peer_connection::state::{RTCIceGatheringState, RTCSignalingState};
142use rtci::peer_connection::transport::{
143    CandidateConfig, CandidateHostConfig, RTCIceCandidate, RTCIceCandidateInit, RTCIceProtocol,
144    RTCIceTransportState, RTCTransportId,
145};
146use rtci::sansio::Protocol;
147use rtci::shared::error::{Error, IoError, Result};
148use rtci::shared::{EcnCodepoint, TaggedBytesMut, TransportContext, TransportProtocol};
149use std::collections::{HashSet, VecDeque};
150use std::future::Future;
151use std::io;
152use std::net::{IpAddr, SocketAddr};
153use std::sync::Arc;
154use std::sync::atomic::{AtomicU64, Ordering};
155use std::task::{Context, Poll, Waker};
156use std::time::{Duration, Instant};
157
158/// A datagram a socket of the driver received: its local address, the sender, the bytes, and
159/// when the reader took it off the socket (the runtime's clock; RFC 8888 section 3: "the
160/// arrival time at the receiver needs to be recorded at the earliest available opportunity").
161struct Received {
162    /// The local address it arrived at (the group's, for mDNS, where the socket reports it).
163    local: SocketAddr,
164    /// The sender.
165    peer: SocketAddr,
166    /// The datagram.
167    data: Vec<u8>,
168    /// When the reader took it off the socket.
169    at: Instant,
170    /// The ECN codepoint of its IP header, where the socket reports it.
171    ecn: Option<u8>,
172}
173
174/// What a [`PeerDriver`] binds.
175#[derive(Debug, Clone)]
176#[non_exhaustive]
177pub struct PeerDriverConfig {
178    /// The local addresses that get a host candidate: one UDP socket per address for each
179    /// transport.
180    pub addresses: Vec<IpAddr>,
181    /// The UDP sockets take a port of this range (any free port without one). A port the
182    /// host refuses to applications is skipped like a port in use
183    /// ([`sockets::bind_udp_in_range`]).
184    pub udp_port_range: Option<PortRange>,
185    /// The engine's TCP sockets (ICE-TCP, TURN over TCP and TLS), with their port range.
186    pub streams: DriverConfig,
187    /// How long a previous socket stays open after its transport selected a pair on a new one:
188    /// the peer may still send to the previous address until its own selection switches
189    /// (each side selects on its own), and those packets must not be lost. 5 seconds by
190    /// default.
191    pub retired_socket_linger: Duration,
192    /// The budget the connection's mDNS datagrams take from
193    /// (draft-ietf-mmusic-mdns-ice-candidates section 7.1). `None`, the default: the one of
194    /// the process, [`process_mdns_rate_limit`], shared by every driver that has none named
195    /// (on a runtime with a virtual clock, [`Runtime::virtual_clock`], one of the driver's own).
196    /// A limit given here is shared by the drivers given clones of it.
197    pub mdns_rate_limit: Option<MdnsRateLimit>,
198    /// Whether the driver binds the host's mDNS sockets (`true` by default). `false`: it
199    /// binds none, its connection's mDNS datagrams are unsent, and the connection is told it
200    /// can publish no name (`RTCPeerConnection::set_multicast_dns_publishing`), as when the
201    /// host refuses the sockets.
202    pub mdns_sockets: bool,
203    /// On Windows, whether the driver takes part in IPv4 mDNS on loopback addresses of
204    /// [`addresses`](Self::addresses): joins 224.0.0.251 on the loopback interface and sends the
205    /// messages about a loopback address's name there. `false` by default: on Windows mDNS sent
206    /// on loopback leaves the group's destination-cache route on loopback for every process of
207    /// the host after this one has exited (see the [module documentation](self)), so loopback
208    /// addresses get no mDNS and their `.local` names are not published. `true` does what other
209    /// systems always do, with one warning per process. Ignored on other systems.
210    pub mdns_on_loopback_on_windows: bool,
211    /// Choose [`addresses`](Self::addresses) from the host's interfaces
212    /// ([`crate::runtime::Runtime::interfaces`]) instead, again at every gathering: the first
213    /// local description's, each ICE restart's, each new set of candidates a transport needs.
214    /// An ICE restart then gathers on the addresses the host has at that moment (a laptop that
215    /// moved to another network). A selection that finds no address, or an interface list that
216    /// cannot be read, keeps the previous addresses. `None` (the default of [`Self::on`]): the
217    /// addresses given.
218    pub address_selection: Option<AddressSelection>,
219    /// With an [`address_selection`](Self::address_selection): how often the driver reads the
220    /// host's interfaces between gatherings (RFC 8445 section 5.1.1.4: "ICE agents SHOULD
221    /// monitor the interfaces", RFC8445-5.1.1.4-3). When the selected addresses change it
222    /// closes the sockets of the addresses that went, restarts ICE
223    /// (`RTCPeerConnection::restart_ice`: negotiation is needed, and the new generation
224    /// gathers on the addresses the host has then) and tells the connection the network
225    /// changed (`RTCPeerConnection::network_changed`: mDNS starts over, RFC 6762 sections 8,
226    /// 10.2, and its first questions ask for a unicast response, section 5.4), and reports
227    /// [`PeerDriverEvent::AddressesChanged`]. A wake from sleep seen meanwhile (the wall clock
228    /// moved further than the monotonic one, which stops in suspend on Linux and macOS) is
229    /// told to the connection too ([`PeerDriverEvent::NetworkChanged`]). `None` (the default of
230    /// [`Self::on`]): no monitoring; [`Self::on_interfaces`]: every 2 seconds.
231    /// [`PeerDriver::network_changed`] is the same check on the application's word (an
232    /// operating system notification).
233    pub interface_check_interval: Option<Duration>,
234}
235
236impl PeerDriverConfig {
237    /// With [`addresses`](Self::addresses).
238    #[must_use]
239    pub fn with_addresses(mut self, addresses: Vec<IpAddr>) -> Self {
240        self.addresses = addresses;
241        self
242    }
243    /// With a [`udp_port_range`](Self::udp_port_range).
244    #[must_use]
245    pub fn with_udp_port_range(mut self, udp_port_range: PortRange) -> Self {
246        self.udp_port_range = Some(udp_port_range);
247        self
248    }
249    /// With the TCP side's settings ([`streams`](Self::streams)).
250    #[must_use]
251    pub fn with_streams(mut self, streams: DriverConfig) -> Self {
252        self.streams = streams;
253        self
254    }
255    /// With a [`retired_socket_linger`](Self::retired_socket_linger).
256    #[must_use]
257    pub fn with_retired_socket_linger(mut self, retired_socket_linger: Duration) -> Self {
258        self.retired_socket_linger = retired_socket_linger;
259        self
260    }
261    /// With a budget of its own ([`mdns_rate_limit`](Self::mdns_rate_limit)).
262    #[must_use]
263    pub fn with_mdns_rate_limit(mut self, mdns_rate_limit: MdnsRateLimit) -> Self {
264        self.mdns_rate_limit = Some(mdns_rate_limit);
265        self
266    }
267    /// Whether the mDNS sockets are bound ([`mdns_sockets`](Self::mdns_sockets)).
268    #[must_use]
269    pub fn with_mdns_sockets(mut self, mdns_sockets: bool) -> Self {
270        self.mdns_sockets = mdns_sockets;
271        self
272    }
273    /// See [`mdns_on_loopback_on_windows`](Self::mdns_on_loopback_on_windows).
274    #[must_use]
275    pub fn with_mdns_on_loopback_on_windows(mut self, mdns_on_loopback_on_windows: bool) -> Self {
276        self.mdns_on_loopback_on_windows = mdns_on_loopback_on_windows;
277        self
278    }
279    /// With an [`address_selection`](Self::address_selection).
280    #[must_use]
281    pub fn with_address_selection(mut self, address_selection: AddressSelection) -> Self {
282        self.address_selection = Some(address_selection);
283        self
284    }
285    /// Host candidates on `addresses`, any free port. With a loopback address and mDNS on
286    /// Windows, see the module documentation: mDNS sent on loopback leaves a stale
287    /// destination-cache route for the group after the process, so by default the driver sends
288    /// none there ([`mdns_on_loopback_on_windows`](Self::mdns_on_loopback_on_windows)).
289    pub fn on(addresses: Vec<IpAddr>) -> Self {
290        Self {
291            addresses,
292            udp_port_range: None,
293            streams: DriverConfig::default(),
294            retired_socket_linger: Duration::from_secs(5),
295            mdns_rate_limit: None,
296            mdns_sockets: true,
297            mdns_on_loopback_on_windows: false,
298            address_selection: None,
299            interface_check_interval: None,
300        }
301    }
302
303    /// Host candidates on the addresses `selection` chooses from the host's interfaces, read
304    /// again at every gathering ([`address_selection`](Self::address_selection)), any free
305    /// port.
306    pub fn on_interfaces(selection: AddressSelection) -> Self {
307        Self {
308            address_selection: Some(selection),
309            interface_check_interval: Some(Duration::from_secs(2)),
310            ..Self::on(Vec::new())
311        }
312    }
313
314    /// With an [`interface_check_interval`](Self::interface_check_interval) (`None`: no
315    /// monitoring).
316    #[must_use]
317    pub fn with_interface_check_interval(mut self, interval: Option<Duration>) -> Self {
318        self.interface_check_interval = interval;
319        self
320    }
321
322    /// Whether this configuration keeps IPv4 mDNS off loopback addresses on this system: on
323    /// Windows unless [`mdns_on_loopback_on_windows`](Self::mdns_on_loopback_on_windows).
324    fn skips_loopback_mdns_v4(&self) -> bool {
325        cfg!(windows) && !self.mdns_on_loopback_on_windows
326    }
327
328    /// The budget this configuration's mDNS takes from: the one named, or the process's.
329    pub fn mdns_rate_limit(&self) -> MdnsRateLimit {
330        self.mdns_rate_limit
331            .clone()
332            .unwrap_or_else(process_mdns_rate_limit)
333    }
334}
335
336/// Why the driver's mDNS of one address family stopped: what [`PeerDriverEvent::MdnsUnavailable`]
337/// tells the application.
338#[derive(Debug, Clone, PartialEq, Eq)]
339pub struct MdnsFailure {
340    /// The family: IPv6 (`true`) or IPv4.
341    pub ipv6: bool,
342    /// What failed.
343    pub stage: MdnsStage,
344    /// The operating system's error.
345    pub kind: io::ErrorKind,
346    /// Its code, where it has one (`EHOSTUNREACH`, `WSAENETUNREACH`, ...).
347    pub os_error: Option<i32>,
348    /// Its text.
349    pub message: String,
350}
351
352impl MdnsFailure {
353    fn new(ipv6: bool, stage: MdnsStage, error: &io::Error) -> Self {
354        Self {
355            ipv6,
356            stage,
357            kind: error.kind(),
358            os_error: error.raw_os_error(),
359            message: error.to_string(),
360        }
361    }
362}
363
364/// What failed in a [`MdnsFailure`].
365#[derive(Debug, Clone, Copy, PartialEq, Eq)]
366pub enum MdnsStage {
367    /// The mDNS socket could not be bound or joined to the group.
368    Bind,
369    /// The socket is bound but the system refuses to send to the group (no multicast route;
370    /// on a Mac, an application without the Local Network permission).
371    Send,
372}
373
374/// Something the driver itself reports to the application ([`PeerDriver::poll_driver_event`]),
375/// beside the connection's own events.
376#[derive(Debug, Clone, PartialEq, Eq)]
377#[non_exhaustive]
378pub enum PeerDriverEvent {
379    /// The driver cannot send mDNS for a family: the socket could not be bound, or the system
380    /// refused its sends. Told once until it works again. Its names are no longer published
381    /// (`RTCPeerConnection::set_multicast_dns_publishing`) for the candidates gathered next,
382    /// and the peer's `.local` names of that family will not resolve: the connection goes on
383    /// over its other candidates, or fails as ICE does. The driver tries again at the next
384    /// gathering and, while datagrams wait, after a back-off (1 s, doubling to 60 s).
385    MdnsUnavailable(MdnsFailure),
386    /// mDNS of the family works again (a datagram was sent after a failure).
387    MdnsAvailable {
388        /// The family: IPv6 (`true`) or IPv4.
389        ipv6: bool,
390    },
391    /// The host's selected addresses changed ([`PeerDriverConfig::interface_check_interval`]):
392    /// the sockets of `removed` are closed, ICE is restarted (answer the negotiation-needed
393    /// event with an offer), and the connection was told the network changed.
394    AddressesChanged {
395        /// Addresses the host has now that it had not.
396        added: Vec<IpAddr>,
397        /// Addresses the host no longer has.
398        removed: Vec<IpAddr>,
399    },
400    /// The host woke from sleep, or the application said the network changed
401    /// ([`PeerDriver::network_changed`]), with the same addresses: the connection was told
402    /// (`RTCPeerConnection::network_changed`: mDNS starts over, its first questions asking for
403    /// a unicast response, RFC 6762 section 5.4).
404    NetworkChanged,
405}
406
407/// The first wait before the driver tries an mDNS socket again after a failure.
408const MDNS_RETRY_FIRST: Duration = Duration::from_secs(1);
409/// The longest wait between two tries.
410const MDNS_RETRY_MAX: Duration = Duration::from_secs(60);
411/// How many sends in a row may fail before the family is declared unavailable (an error that
412/// says there is no route, or no permission, does it at once).
413const MDNS_FAILURES_BEFORE_UNAVAILABLE: u32 = 3;
414/// How many received mDNS datagrams wait for the driver at most; past it the oldest is
415/// dropped ([`PeerDriver::mdns_datagrams_dropped`]): any host on the link can send mDNS, and a
416/// driver that is not stepped must not grow with it.
417const MAX_QUEUED_MDNS_RECEIVED: usize = 256;
418
419/// One family's mDNS socket, and what the driver knows of it.
420struct MdnsFamily {
421    socket: Option<(Arc<dyn AsyncUdpSocket>, Box<dyn JoinHandle>)>,
422    /// One configured address per interface: what a message that names no address of its
423    /// own (a query) leaves from, once on each interface (RFC 6762 section 14).
424    links: Vec<IpAddr>,
425    /// Sends that failed in a row.
426    failures: u32,
427    /// Reported unavailable ([`PeerDriverEvent::MdnsUnavailable`]) and not yet working again.
428    unavailable: bool,
429    /// Not tried again before.
430    retry_at: Option<Instant>,
431    backoff: Duration,
432    /// Never bound: every configured address of the family is a loopback one the driver keeps
433    /// mDNS off ([`PeerDriverConfig::mdns_on_loopback_on_windows`]).
434    off: bool,
435}
436
437impl MdnsFamily {
438    fn new(links: Vec<IpAddr>) -> Self {
439        Self {
440            off: false,
441            socket: None,
442            links,
443            failures: 0,
444            unavailable: false,
445            retry_at: None,
446            backoff: MDNS_RETRY_FIRST,
447        }
448    }
449
450    fn close(&mut self) {
451        if let Some((_, reader)) = self.socket.take() {
452            reader.abort();
453        }
454    }
455}
456
457impl Drop for MdnsFamily {
458    fn drop(&mut self) {
459        self.close();
460    }
461}
462
463/// The host's mDNS sockets of a driver, bound at the connection's first mDNS datagram.
464struct MdnsSockets {
465    v4: MdnsFamily,
466    v6: MdnsFamily,
467    /// For an IPv6 address, the configured IPv4 address of the same interface: an IPv6
468    /// record's messages also leave on the IPv4 group of its own interface.
469    companions: Vec<(IpAddr, IpAddr)>,
470    /// IPv4 mDNS is kept off loopback addresses: a message about one is sent nowhere
471    /// ([`PeerDriverConfig::mdns_on_loopback_on_windows`]).
472    skips_loopback_v4: bool,
473}
474
475impl MdnsSockets {
476    /// Where one mDNS datagram of the engine goes: (destination, address it leaves from).
477    /// The engine names the address of the record a message is about (its own interface's,
478    /// RFC 6762 section 14), or the unspecified address for a query; it addresses every
479    /// multicast message to the IPv4 group. An IPv4 record's message leaves from its address
480    /// on the IPv4 group; an IPv6 record's from its address on the IPv6 group, and from the
481    /// IPv4 address of its interface on the IPv4 group where the driver has one (resolvers
482    /// that listen on one family); a query once from each interface, on each family's group.
483    /// A multicast message about an IPv4 loopback address goes nowhere when
484    /// [`skips_loopback_v4`](Self::skips_loopback_v4).
485    fn routes(&self, from: IpAddr, to: SocketAddr) -> Vec<(SocketAddr, Option<IpAddr>)> {
486        let group_v4 = SocketAddr::new(MDNS_MULTICAST_IPV4.into(), MDNS_PORT);
487        let group_v6 = SocketAddr::new(MDNS_MULTICAST_IPV6.into(), MDNS_PORT);
488        if !to.ip().is_multicast() {
489            // A unicast reply to an asker (RFC 6762 sections 5.5, 6.7).
490            let source = (!from.is_unspecified() && from.is_ipv4() == to.is_ipv4()).then_some(from);
491            return vec![(to, source)];
492        }
493        if self.skips_loopback_v4 && from.is_loopback() && from.is_ipv4() {
494            // Not on the group from loopback (Windows: the destination-cache route it leaves).
495            return vec![];
496        }
497        if from.is_unspecified() {
498            let routes: Vec<_> = (self.v4.links.iter().map(|ip| (group_v4, Some(*ip))))
499                .chain(self.v6.links.iter().map(|ip| (group_v6, Some(*ip))))
500                .collect();
501            if routes.is_empty() {
502                return vec![(to, None)];
503            }
504            return routes;
505        }
506        match from {
507            IpAddr::V4(_) => vec![(group_v4, Some(from))],
508            IpAddr::V6(_) => std::iter::once((group_v6, Some(from)))
509                .chain(
510                    self.companions
511                        .iter()
512                        .filter(|(v6, _)| *v6 == from)
513                        .map(|(_, v4)| (group_v4, Some(*v4))),
514                )
515                .collect(),
516        }
517    }
518}
519
520/// `addresses` with one per interface (the first of each), of one family. An address on no
521/// interface the host lists (a mock network's) counts as an interface of its own.
522fn one_per_interface(addresses: &[IpAddr], ipv4: bool) -> Vec<IpAddr> {
523    let mut seen = HashSet::new();
524    addresses
525        .iter()
526        .copied()
527        .filter(|ip| ip.is_ipv4() == ipv4 && !ip.is_unspecified())
528        .filter(|ip| seen.insert(runtime::interface_name(*ip).unwrap_or_else(|| ip.to_string())))
529        .collect()
530}
531
532/// The addresses whose interfaces get mDNS: `addresses` without the IPv4 loopback ones when
533/// `skips_loopback_v4` ([`PeerDriverConfig::mdns_on_loopback_on_windows`]).
534fn mdns_addresses(addresses: &[IpAddr], skips_loopback_v4: bool) -> Vec<IpAddr> {
535    addresses
536        .iter()
537        .copied()
538        .filter(|ip| !(skips_loopback_v4 && ip.is_ipv4() && ip.is_loopback()))
539        .collect()
540}
541
542/// Says once per process that IPv4 mDNS is kept off loopback on Windows.
543fn note_loopback_mdns_skipped() {
544    static ONCE: std::sync::Once = std::sync::Once::new();
545    ONCE.call_once(|| {
546        log::info!(
547            "no IPv4 mDNS on loopback on Windows: it would leave the group's destination-cache \
548             route on loopback for the whole host (PeerDriverConfig::mdns_on_loopback_on_windows)"
549        );
550    });
551}
552
553/// One UDP socket of the connection, with the reader that hands its datagrams to the driver.
554struct HostSocket {
555    socket: Arc<dyn AsyncUdpSocket>,
556    local: SocketAddr,
557    /// The section its candidate was added for.
558    mid: String,
559    /// Set when the engine refused its address for `transport` (`OnLocalCandidatesNeeded`):
560    /// it is closed once that transport has selected a pair on another socket, or closed.
561    retired_for: Option<RTCTransportId>,
562    /// Once its transport selected a pair on another socket: when it is closed.
563    close_at: Option<Instant>,
564    /// The transport whose selected candidate pair has its candidate as the local one (the
565    /// last `SelectedCandidatePairChange`): through an ICE restart the transport keeps sending
566    /// on that pair until the restart selects one (RFC 8445 section 9: "during the restart,
567    /// data can continue to be sent using existing data sessions"), so the socket stays
568    /// open until then ([`PeerDriver::match_sockets_to_candidates`]).
569    selected_by: Option<RTCTransportId>,
570    /// Counted in [`PeerDriver::unmarked_sockets`] (the platform refused to mark it: its
571    /// datagrams leave unmarked).
572    counted_unmarked: bool,
573    /// The Don't Fragment state set on it: `None` while it has the system's default (no
574    /// datagram asked for DF yet), or once the platform refused the option.
575    dont_fragment: Option<bool>,
576    /// The platform refused to set Don't Fragment: its datagrams keep the system's default.
577    dont_fragment_refused: bool,
578    /// Datagrams the socket was not ready for yet (its send returned `Pending`: a socket the
579    /// runtime's reactor has not reported writable, the first send after the bind among
580    /// them), in order; [`PeerDriver::step`] waits for the socket and sends them. At most
581    /// [`MAX_WAITING_SENDS`]: beyond that a datagram is lost, as from a full send buffer.
582    waiting: VecDeque<WaitingSend>,
583    reader: Box<dyn JoinHandle>,
584}
585
586/// The most datagrams a socket holds while it is not ready to send ([`HostSocket::waiting`]).
587const MAX_WAITING_SENDS: usize = 64;
588
589/// A datagram of the engine waiting for its socket, with the marking it is to go with.
590struct WaitingSend {
591    datagram: TaggedBytesMut,
592    traffic_class: u8,
593    dont_fragment: bool,
594}
595
596impl HostSocket {
597    /// Whether it serves its transport's current generation: not retired, and not closing
598    /// (a rolled-back generation's socket kept open only for the engine's TURN release).
599    fn serves(&self) -> bool {
600        self.retired_for.is_none() && self.close_at.is_none()
601    }
602
603    /// Offers `waiting` to the socket: the engine's Don't Fragment for this datagram (RFC 8261
604    /// section 5; RFC 9260 section 6.9: a fragment made before a path MTU reduction is sent
605    /// fragmentable) is set on the socket first when it differs from the socket's state (a
606    /// socket keeps the system's default until a datagram first asks for DF). `Pending`: the
607    /// socket is not ready yet, and `cx` is woken when it may be.
608    fn poll_transmit(
609        &mut self,
610        cx: &mut Context<'_>,
611        waiting: &WaitingSend,
612    ) -> Poll<io::Result<usize>> {
613        let dont_fragment = waiting.dont_fragment;
614        if !self.dont_fragment_refused
615            && self.dont_fragment != Some(dont_fragment)
616            && (dont_fragment || self.dont_fragment.is_some())
617        {
618            match self.socket.set_dont_fragment(dont_fragment) {
619                Ok(()) => self.dont_fragment = Some(dont_fragment),
620                Err(_) => {
621                    self.dont_fragment_refused = true;
622                    self.dont_fragment = None;
623                }
624            }
625        }
626        self.socket.poll_send(
627            cx,
628            &Transmit {
629                destination: waiting.datagram.transport.peer_addr,
630                contents: &waiting.datagram.message,
631                traffic_class: waiting.traffic_class,
632                segment_size: None,
633                source: None,
634            },
635        )
636    }
637
638    /// Offers the first waiting datagram to the socket: it and the send's result once the
639    /// socket took or refused it, `Pending` (the datagram kept first) while it is not ready.
640    fn poll_waiting(&mut self, cx: &mut Context<'_>) -> Poll<(WaitingSend, io::Result<usize>)> {
641        let Some(next) = self.waiting.pop_front() else {
642            return Poll::Pending;
643        };
644        match self.poll_transmit(cx, &next) {
645            Poll::Ready(result) => Poll::Ready((next, result)),
646            Poll::Pending => {
647                self.waiting.push_front(next);
648                Poll::Pending
649            }
650        }
651    }
652}
653
654impl Drop for HostSocket {
655    fn drop(&mut self) {
656        self.reader.abort();
657    }
658}
659
660/// Drives an `RTCPeerConnection` over sockets of its own (see the [module documentation](self)).
661pub struct PeerDriver {
662    runtime: Arc<dyn Runtime>,
663    pc: RTCPeerConnection,
664    streams: StreamDriver,
665    config: PeerDriverConfig,
666    sockets: Vec<HostSocket>,
667    datagrams_tx: async_channel::Sender<Received>,
668    datagrams: async_channel::Receiver<Received>,
669    /// What the mDNS sockets received: bounded, the oldest dropped.
670    mdns_tx: async_channel::Sender<Received>,
671    mdns_rx: async_channel::Receiver<Received>,
672    /// Received mDNS datagrams dropped from a full queue ([`Self::mdns_datagrams_dropped`]).
673    mdns_dropped: Arc<AtomicU64>,
674    /// The driver's own events ([`Self::poll_driver_event`]).
675    driver_events: VecDeque<PeerDriverEvent>,
676    /// mDNS sends the system refused ([`Self::mdns_send_failures`]).
677    mdns_send_failures: u64,
678    /// mDNS socket binds that failed ([`Self::mdns_bind_failures`]).
679    mdns_bind_failures: u64,
680    /// [`Self::shutdown`] ran: nothing is left for `Drop` to do.
681    shut_down: bool,
682    /// The engine's events, for the application, after the driver had its look.
683    events: VecDeque<RTCPeerConnectionEvent>,
684    /// The transports whose generation the driver gathered for on an
685    /// `OnLocalCandidatesNeeded`: their `gatheringstatechange` that follows needs nothing.
686    gathered: HashSet<RTCTransportId>,
687    /// Datagrams the engine wrote that no socket sent ([`Self::unsent_datagrams`]).
688    unsent: u64,
689    /// The connection's mDNS datagrams, held to the budget.
690    mdns_egress: MdnsEgress,
691    /// `None` until the connection writes its first mDNS datagram, or, with
692    /// `QueryAndGather`, until it gathers.
693    mdns_sockets: Option<MdnsSockets>,
694    /// What the connection was last told about the families its names can be published for.
695    mdns_publishing_told: Option<MulticastDnsPublishing>,
696    /// mDNS datagrams sent ([`Self::mdns_datagrams_sent`]).
697    mdns_sent: u64,
698    /// mDNS datagrams received ([`Self::mdns_datagrams_received`]).
699    mdns_received: u64,
700    /// Sockets on which the platform refused a TOS / Traffic Class ([`Self::unmarked_sockets`]).
701    unmarked_sockets: u64,
702    /// Datagrams sent, by the TOS / Traffic Class their socket had ([`Self::sent_by_traffic_class`]).
703    sent_by_traffic_class: std::collections::BTreeMap<u8, u64>,
704    /// The latest time given to the engine with a datagram or a timeout: a received datagram's
705    /// time is never earlier ([`Self::feed`]).
706    engine_time: Instant,
707    /// The selected addresses the interface monitor last saw (`None`: not yet).
708    monitored: Option<Vec<IpAddr>>,
709    /// When the monitor reads the interfaces next.
710    next_interface_check: Option<Instant>,
711    /// The monotonic and wall clocks at the monitor's last look, for wake detection.
712    wall_mark: Option<(Instant, std::time::SystemTime)>,
713}
714
715impl PeerDriver {
716    /// A driver for `pc` on tokio ([`runtime::TokioRuntime::new`]: it must be used inside a
717    /// tokio runtime), with no socket yet: it binds when the connection's first local
718    /// description begins gathering. Feature `runtime-tokio` (on by default).
719    #[cfg(feature = "runtime-tokio")]
720    pub fn new(pc: RTCPeerConnection, config: PeerDriverConfig) -> Self {
721        Self::with_runtime(Arc::new(runtime::TokioRuntime::new()), pc, config)
722    }
723
724    /// A driver for `pc` on `runtime`, with no socket yet: it binds when the connection's first
725    /// local description begins gathering. Every time it gives the connection is the
726    /// runtime's ([`Runtime::now`]).
727    pub fn with_runtime(
728        runtime: Arc<dyn Runtime>,
729        pc: RTCPeerConnection,
730        config: PeerDriverConfig,
731    ) -> Self {
732        // The driver hands each mDNS datagram over with its destination (the group's where it
733        // knows the datagram arrived there: RFC 6762 section 11 then deems it on the link).
734        let mut pc = pc;
735        pc.set_multicast_dns_destination_reported(true);
736        let virtual_clock = runtime.virtual_clock();
737        let runtime_now = runtime.now();
738        let (datagrams_tx, datagrams) = async_channel::unbounded();
739        let (mdns_tx, mdns_rx) = async_channel::bounded(MAX_QUEUED_MDNS_RECEIVED);
740        Self {
741            streams: StreamDriver::with_runtime(runtime.clone(), config.streams),
742            runtime,
743            pc,
744            sockets: Vec::new(),
745            datagrams_tx,
746            datagrams,
747            mdns_tx,
748            mdns_rx,
749            mdns_dropped: Arc::new(AtomicU64::new(0)),
750            driver_events: VecDeque::new(),
751            mdns_send_failures: 0,
752            mdns_bind_failures: 0,
753            shut_down: false,
754            events: VecDeque::new(),
755            gathered: HashSet::new(),
756            unsent: 0,
757            // A driver on a virtual clock does not share the process's budget, whose times
758            // are the wall clock's: a mock clock ahead would leave it empty for real drivers,
759            // one behind would never see it refill.
760            mdns_egress: MdnsEgress::new(match &config.mdns_rate_limit {
761                None if virtual_clock => MdnsRateLimit::default(),
762                _ => config.mdns_rate_limit(),
763            }),
764            mdns_sockets: None,
765            mdns_publishing_told: None,
766            mdns_sent: 0,
767            mdns_received: 0,
768            config,
769            unmarked_sockets: 0,
770            sent_by_traffic_class: std::collections::BTreeMap::new(),
771            engine_time: runtime_now,
772            monitored: None,
773            next_interface_check: None,
774            wall_mark: None,
775        }
776    }
777
778    /// The runtime the driver runs on.
779    pub fn runtime(&self) -> &Arc<dyn Runtime> {
780        &self.runtime
781    }
782
783    /// The connection's `targetLatency` (webrtc-extensions section 16), which the driver, as
784    /// what sets up the network link, reads: "lowest" asks it to optimise latency, with "a
785    /// technique like network slicing" (ETSI TS 128 530) where one is available. None is: the
786    /// socket interfaces the driver uses on Linux, macOS, Windows and the BSDs expose no
787    /// network slice or latency class to a process (on Android a slice is requested through
788    /// `ConnectivityManager`, outside any socket). The driver's sockets are therefore the same
789    /// under both values; DSCP marking (RFC 8837) is the engine's per flow either way.
790    pub fn target_latency(
791        &self,
792    ) -> rtci::peer_connection::configuration::RTCConfigurationTargetLatency {
793        self.pc.get_configuration().target_latency()
794    }
795
796    /// The peer connection.
797    pub fn pc(&self) -> &RTCPeerConnection {
798        &self.pc
799    }
800
801    /// The peer connection, for signalling, media and data channels. Call
802    /// [`flush`](Self::flush) (or [`step`](Self::step)) after changing it, so that what it
803    /// wants to send leaves and the driver sees its events.
804    pub fn pc_mut(&mut self) -> &mut RTCPeerConnection {
805        &mut self.pc
806    }
807
808    /// The local addresses of the UDP sockets open, the previous ones still waiting for a new
809    /// pair included.
810    pub fn local_addresses(&self) -> Vec<SocketAddr> {
811        self.sockets.iter().map(|s| s.local).collect()
812    }
813
814    /// How many datagrams the connection wrote that were not sent: from a local address with
815    /// no open socket (one closed already), refused by the socket (an error, its send buffer
816    /// full among them: UDP drops them, as the wire would), or still waiting for a socket that
817    /// was not ready when it closed, or beyond the 64 such a socket holds. A socket that is
818    /// only not ready yet (the runtime's reactor has not reported it writable, as before the
819    /// first send after the bind) refuses nothing: the datagram waits for it. Counted so that
820    /// none is lost unseen.
821    pub fn unsent_datagrams(&self) -> u64 {
822        self.unsent
823    }
824
825    /// How many mDNS datagrams the driver sent for the connection (queries, probes,
826    /// announcements, answers, goodbyes), after the budget let them go.
827    pub fn mdns_datagrams_sent(&self) -> u64 {
828        self.mdns_sent
829    }
830
831    /// How many datagrams the driver's mDNS sockets received and handed to the connection
832    /// (its own looped back by the host included).
833    pub fn mdns_datagrams_received(&self) -> u64 {
834        self.mdns_received
835    }
836
837    /// How many mDNS sends the system refused (to a group or an asker): a host without a
838    /// multicast route, a Mac application without the Local Network permission.
839    pub fn mdns_send_failures(&self) -> u64 {
840        self.mdns_send_failures
841    }
842
843    /// How many times an mDNS socket could not be bound or joined.
844    pub fn mdns_bind_failures(&self) -> u64 {
845        self.mdns_bind_failures
846    }
847
848    /// How many received mDNS datagrams were dropped because the driver was not stepped fast
849    /// enough (the oldest go first; at most 256 wait).
850    pub fn mdns_datagrams_dropped(&self) -> u64 {
851        self.mdns_dropped.load(Ordering::Relaxed)
852    }
853
854    /// Whether the driver can send mDNS for a family now: its socket is bound and its sends
855    /// have not been refused since (see [`PeerDriverEvent::MdnsUnavailable`]).
856    pub fn mdns_available(&self, ipv6: bool) -> bool {
857        self.mdns_sockets.as_ref().is_some_and(|m| {
858            let family = if ipv6 { &m.v6 } else { &m.v4 };
859            family.socket.is_some() && !family.unavailable
860        })
861    }
862
863    /// The next event of the driver itself (mDNS that cannot be sent, and that works again).
864    pub fn poll_driver_event(&mut self) -> Option<PeerDriverEvent> {
865        self.driver_events.pop_front()
866    }
867
868    /// How many sockets the platform refused a TOS / Traffic Class on: their datagrams leave
869    /// without the DSCP the engine asked for (Windows without qWAVE, an IPv6 socket where the
870    /// platform has no `IPV6_TCLASS`; see [`sockets::set_traffic_class`]).
871    pub fn unmarked_sockets(&self) -> u64 {
872        self.unmarked_sockets
873    }
874
875    /// How many datagrams were sent with each TOS / Traffic Class byte set on their socket
876    /// (a socket the platform refused counts under 0).
877    pub fn sent_by_traffic_class(&self) -> &std::collections::BTreeMap<u8, u64> {
878        &self.sent_by_traffic_class
879    }
880
881    /// The TOS / Traffic Class byte the operating system reports for the UDP socket bound to
882    /// `local` (`getsockopt` of `IP_TOS` / `IPV6_TCLASS`): what its next datagram carries.
883    /// `None` without such a socket.
884    pub fn socket_traffic_class(&self, local: SocketAddr) -> Option<io::Result<u32>> {
885        let host = self.sockets.iter().find(|s| s.local == local)?;
886        Some(host.socket.traffic_class())
887    }
888
889    /// The next event of the connection. The driver has already done what is its to do
890    /// (gathering on `OnLocalCandidatesNeeded` and when a transport begins gathering, closing
891    /// the previous sockets on a new selected pair, ending each generation's gathering with
892    /// its end-of-candidates); the application signals the candidates of
893    /// `OnIceCandidateEvent` to the peer, the end-of-candidates candidate included (W3C
894    /// webrtc-pc 5.6.4: the peer's transport is "failed" only once it has it, "disconnected"
895    /// until then), and handles the rest. The driver tears nothing down on "failed" or
896    /// "disconnected": an application that does not relay the end-of-candidates candidate, or
897    /// whose peer never sends its own, needs a timer of its own to restart or close.
898    pub fn poll_event(&mut self) -> Option<RTCPeerConnectionEvent> {
899        self.events.pop_front()
900    }
901
902    /// Hands what the connection wants to send to the sockets and the stream driver, and
903    /// reacts to its events, until nothing is left.
904    ///
905    /// # Errors
906    ///
907    /// A socket that cannot be bound for a transport that needs one, or a candidate the
908    /// connection refuses.
909    pub fn flush(&mut self) -> Result<()> {
910        self.send_waiting();
911        loop {
912            let mut progress = false;
913            while let Some(command) = self.pc.poll_stream_command() {
914                self.streams.execute(command);
915                progress = true;
916            }
917            while let Some(transmit) = self.pc.poll_stream_transmit() {
918                self.streams.write(transmit);
919                progress = true;
920            }
921            while let Some(datagram) = self.pc.poll_write() {
922                self.send(datagram);
923                progress = true;
924            }
925            while let Some(event) = self.pc.poll_event() {
926                self.on_event(&event)?;
927                self.events.push_back(event);
928                progress = true;
929            }
930            if !progress {
931                self.send_mdns(self.runtime.now());
932                return Ok(());
933            }
934        }
935    }
936
937    /// Ends the connection and the driver in order: closes the connection, sends what it
938    /// writes on closing (the mDNS goodbyes of its published names, RFC 6762 section 10.1:
939    /// records with TTL 0, so that the link's caches drop them at once instead of holding them
940    /// for their 120 s; draft-ietf-mmusic-mdns-ice-candidates section 7.1; and the deletion of
941    /// each of the engine's TURN allocations over UDP, a Refresh of LIFETIME 0, RFC 8656
942    /// section 8), waiting up to `linger` for the mDNS budget to let the goodbyes go and for
943    /// the TURN releases to be answered (the closed connection retransmits them, RFC 8489
944    /// section 6.2.1, and reads their answers from the driver's sockets:
945    /// `OnTurnAllocationReleased` for each, in [`poll_event`](Self::poll_event)), then closes
946    /// every socket of the driver, which leaves the mDNS groups. A server whose allocation is
947    /// deleted at once accepts a new one from the same address and port at once (RFC 8656
948    /// section 7.2: a live allocation on a 5-tuple refuses another with 437). An application
949    /// that ends on a signal (SIGTERM, SIGINT) calls this from its handler. The driver is not
950    /// to be stepped afterwards.
951    ///
952    /// Dropping a driver that was not shut down does what can be done without waiting (see
953    /// [`Drop`](#impl-Drop-for-PeerDriver)).
954    ///
955    /// # Errors
956    ///
957    /// As [`flush`](Self::flush).
958    pub async fn shutdown(&mut self, linger: Duration) -> Result<()> {
959        // The connection may be closed already: the application's own `close()`.
960        let _ = self.pc.close();
961        self.shut_down = true;
962        let until = self.runtime.now() + linger;
963        loop {
964            self.flush()?;
965            let now = self.runtime.now();
966            let mdns_waiting = self.mdns_egress.next_ready(now).is_some();
967            // The closed connection keeps a timer exactly while a TURN transaction is left.
968            let turn_waiting = self.pc.poll_timeout().is_some()
969                && !self.pc.turn_local_addresses_in_use().is_empty();
970            // Datagrams a socket was not ready for yet (a TURN release among them).
971            let sends_waiting = self.sockets.iter().any(|s| !s.waiting.is_empty());
972            if now >= until || !(mdns_waiting || turn_waiting || sends_waiting) {
973                break;
974            }
975            // Reads the sockets (the releases' answers), runs the timers (their
976            // retransmissions), and lets the budget's goodbyes go.
977            self.step(until - now).await?;
978        }
979        // Closing a socket leaves its groups (the system drops its memberships).
980        self.mdns_sockets = None;
981        self.unsent += self
982            .sockets
983            .iter()
984            .map(|s| s.waiting.len() as u64)
985            .sum::<u64>();
986        self.sockets.clear();
987        Ok(())
988    }
989
990    /// One round: flushes, then waits up to `wait` (less when a timer of the connection is due
991    /// first) for a datagram, a stream input, a socket ready for a datagram that waited for it
992    /// (one not ready when the connection wrote it, as before the first send after the bind)
993    /// or the timer, hands it over, and flushes again.
994    ///
995    /// # Errors
996    ///
997    /// As [`flush`](Self::flush).
998    pub async fn step(&mut self, wait: Duration) -> Result<()> {
999        self.flush()?;
1000        let now = self.runtime.now();
1001        let deadline = self
1002            .pc
1003            .poll_timeout()
1004            .into_iter()
1005            .chain(self.mdns_egress.next_ready(now))
1006            .chain(self.next_interface_check)
1007            .fold(now + wait, Instant::min)
1008            .max(now);
1009        let woke = {
1010            let mut datagram = std::pin::pin!(self.datagrams.recv());
1011            let mut mdns = std::pin::pin!(self.mdns_rx.recv());
1012            let mut input = std::pin::pin!(self.streams.next());
1013            let mut timer = self.runtime.sleep_until(deadline);
1014            let sockets = &mut self.sockets;
1015            std::future::poll_fn(|cx| {
1016                // A socket that was not ready for a datagram: polled with this task's waker,
1017                // so that its readiness wakes the step.
1018                for (index, host) in sockets.iter_mut().enumerate() {
1019                    if let Poll::Ready((waiting, result)) = host.poll_waiting(cx) {
1020                        return Poll::Ready(Woke::Sent(index, waiting, result));
1021                    }
1022                }
1023                if let Poll::Ready(Ok(received)) = datagram.as_mut().poll(cx) {
1024                    return Poll::Ready(Woke::Datagram(received));
1025                }
1026                if let Poll::Ready(Ok(received)) = mdns.as_mut().poll(cx) {
1027                    return Poll::Ready(Woke::Mdns(received));
1028                }
1029                if let Poll::Ready(input) = input.as_mut().poll(cx) {
1030                    return Poll::Ready(Woke::Stream(input));
1031                }
1032                timer.as_mut().poll(cx).map(|()| Woke::Timer)
1033            })
1034            .await
1035        };
1036        match woke {
1037            Woke::Datagram(received) => {
1038                self.feed(received);
1039                while let Ok(received) = self.datagrams.try_recv() {
1040                    self.feed(received);
1041                }
1042            }
1043            Woke::Mdns(received) => {
1044                self.mdns_received += 1;
1045                self.feed(received);
1046                while let Ok(received) = self.mdns_rx.try_recv() {
1047                    self.mdns_received += 1;
1048                    self.feed(received);
1049                }
1050            }
1051            Woke::Stream(input) => self.feed_stream(input),
1052            Woke::Sent(index, waiting, result) => {
1053                self.book_send(index, &waiting, result);
1054                self.send_waiting();
1055            }
1056            Woke::Timer => {}
1057        }
1058        // The engine's timers; one that fails is the connection's to report (its states).
1059        let now = self.runtime.now();
1060        self.engine_time = self.engine_time.max(now);
1061        let _ = self.pc.handle_timeout(now);
1062        self.close_due_sockets(now);
1063        self.check_interfaces(now, false);
1064        self.flush()
1065    }
1066
1067    /// Hands a received datagram to the engine, with the time the reader took it off the
1068    /// socket (RFC 8888 section 3: arrival "recorded at the earliest available opportunity",
1069    /// not when the application next steps the driver) and the ECN codepoint the socket
1070    /// reported (RFC 6679 section 7.2.1: receivers "listen for ECT/CE"). The time is never
1071    /// earlier than one the engine was already given: a datagram that waited in the queue
1072    /// while the previous step ran is stamped with that step's time.
1073    fn feed(&mut self, received: Received) {
1074        let now = received.at.max(self.engine_time);
1075        self.engine_time = now;
1076        // A datagram the engine cannot take (a stray, a late one) is its business, not the
1077        // driver's: it goes on.
1078        let _ = self.pc.handle_read(tagged(&received, now));
1079    }
1080
1081    fn feed_stream(&mut self, input: DriverInput) {
1082        let now = self.runtime.now();
1083        match input {
1084            DriverInput::Event(event) => {
1085                let _ = self.pc.handle_stream_event(now, event);
1086            }
1087            DriverInput::Read { id, data } => {
1088                let _ = self.pc.handle_stream_read(now, id, &data);
1089            }
1090            DriverInput::Accepted(accepted) => {
1091                if let Some(id) = self.pc.handle_stream_accepted(
1092                    now,
1093                    accepted.listener,
1094                    accepted.local,
1095                    accepted.remote,
1096                ) {
1097                    self.streams.adopt(id, accepted);
1098                }
1099            }
1100        }
1101    }
1102
1103    /// Sends a datagram of the engine on the socket of its local address, marked with the
1104    /// DSCP and ECN codepoint the engine gives it (`RTCPeerConnection::traffic_class`: RFC 8837
1105    /// Table 1 by flow and priority, RFC 8835 section 4.2): the socket's `IP_TOS` /
1106    /// `IPV6_TCLASS` is set before the datagram when it differs from the last one set.
1107    fn send(&mut self, datagram: TaggedBytesMut) {
1108        if datagram.transport.transport_protocol != TransportProtocol::UDP {
1109            return;
1110        }
1111        let local = datagram.transport.local_addr;
1112        if local.port() == MDNS_PORT && !self.sockets.iter().any(|s| s.local == local) {
1113            if !self.mdns_egress.push(datagram) {
1114                self.unsent += 1;
1115            }
1116            return;
1117        }
1118        let traffic_class = self.pc.traffic_class(&datagram);
1119        let Some(index) = self.sockets.iter().position(|s| s.local == local) else {
1120            self.unsent += 1;
1121            return;
1122        };
1123        let dont_fragment = self.pc.dont_fragment(&datagram);
1124        let waiting = WaitingSend {
1125            datagram,
1126            traffic_class,
1127            dont_fragment,
1128        };
1129        let host = &mut self.sockets[index];
1130        // Behind the datagrams already waiting for the socket, in order.
1131        if !host.waiting.is_empty() {
1132            if host.waiting.len() < MAX_WAITING_SENDS {
1133                host.waiting.push_back(waiting);
1134            } else {
1135                // UDP: a datagram the socket cannot take is lost, as on the wire.
1136                self.book_send(index, &waiting, Err(io::ErrorKind::WouldBlock.into()));
1137            }
1138            return;
1139        }
1140        // A socket that is not ready yet (`Pending`: its reactor has not reported it writable,
1141        // as before the first send after the bind) refuses nothing: the datagram waits for it
1142        // ([`Self::step`]). An error, `WouldBlock` included, is the system's refusal.
1143        let mut cx = Context::from_waker(Waker::noop());
1144        match host.poll_transmit(&mut cx, &waiting) {
1145            Poll::Ready(result) => self.book_send(index, &waiting, result),
1146            Poll::Pending => host.waiting.push_back(waiting),
1147        }
1148    }
1149
1150    /// Sends what waits for the sockets that are ready now, in order, until each socket is
1151    /// not ready again or has nothing waiting.
1152    fn send_waiting(&mut self) {
1153        let mut cx = Context::from_waker(Waker::noop());
1154        for index in 0..self.sockets.len() {
1155            while let Poll::Ready((waiting, result)) = self.sockets[index].poll_waiting(&mut cx) {
1156                self.book_send(index, &waiting, result);
1157            }
1158        }
1159    }
1160
1161    /// Counts the end of a send on `self.sockets[index]`: sent (by its marking), or refused
1162    /// (unsent, and discarded on the pair; a refusal for its size told to the engine).
1163    fn book_send(&mut self, index: usize, waiting: &WaitingSend, result: io::Result<usize>) {
1164        let datagram = &waiting.datagram;
1165        let traffic_class = waiting.traffic_class;
1166        let host = &mut self.sockets[index];
1167        let sent = result.is_ok();
1168        // A send refused for its size is the one transport indication of RFC 6347 4.1.1.1 /
1169        // RFC 9147 section 4.4 these sockets observe: they do not read the ICMP error queue
1170        // (no IP_RECVERR), so an ICMP Packet Too Big never reaches the driver; a datagram
1171        // with DF that exceeds the path MTU the system knows is refused (EMSGSIZE), one
1172        // without it is fragmented by the system. A refusal names no MTU.
1173        let too_big = result.as_ref().is_err_and(refused_for_size);
1174        // The platform does not mark (RFC 8835 4.2: "appropriate to depart ... on platforms
1175        // where QoS marking is not implemented"): counted once per socket.
1176        let unmarked = host.socket.unmarked();
1177        if unmarked && !host.counted_unmarked {
1178            host.counted_unmarked = true;
1179            self.unmarked_sockets += 1;
1180        }
1181        if sent {
1182            let applied = if unmarked { 0 } else { traffic_class };
1183            *self.sent_by_traffic_class.entry(applied).or_default() += 1;
1184        } else {
1185            self.unsent += 1;
1186            // W3C webrtc-stats 8.20: `packetsDiscardedOnSend` / `bytesDiscardedOnSend` count
1187            // the pair's packets "discarded due to socket errors". What the engine sends on
1188            // other candidate pairs is STUN only (connectivity checks; RFC 7983 first byte 0
1189            // to 3); everything else (DTLS, SRTP / SRTCP, SCTP) is on the selected pair, which
1190            // `on_send_discarded` charges. A discard before a pair is selected counts nowhere.
1191            if !is_stun(&datagram.message) {
1192                self.pc.on_send_discarded(datagram.message.len());
1193            }
1194        }
1195        if too_big {
1196            let now = self.runtime.now();
1197            self.pc
1198                .handle_datagram_too_big(now, datagram.transport, None, Some(&datagram.message));
1199        }
1200    }
1201
1202    /// Sends the held mDNS datagrams the budget lets go at `now`, binding the mDNS sockets at
1203    /// the first, each on the interface of the address the engine names for it
1204    /// ([`MdnsSockets::routes`]). A datagram no socket could send is unsent; a send the system
1205    /// refuses counts against its family ([`Self::mdns_send_result`]).
1206    fn send_mdns(&mut self, now: Instant) {
1207        while let Some(datagram) = self.mdns_egress.pop_ready(now) {
1208            self.ensure_mdns(now, false);
1209            let Some(sockets) = self.mdns_sockets.as_ref() else {
1210                self.unsent += 1;
1211                continue;
1212            };
1213            let routes = sockets.routes(
1214                datagram.transport.local_addr.ip(),
1215                datagram.transport.peer_addr,
1216            );
1217            let mut results = Vec::new();
1218            for (destination, source) in routes {
1219                let family = if destination.is_ipv6() {
1220                    &sockets.v6
1221                } else {
1222                    &sockets.v4
1223                };
1224                if let Some((socket, _)) = &family.socket {
1225                    let result = socket.try_send(&Transmit {
1226                        destination,
1227                        contents: &datagram.message,
1228                        traffic_class: 0,
1229                        segment_size: None,
1230                        source,
1231                    });
1232                    results.push((destination.is_ipv6(), result));
1233                }
1234            }
1235            let mut sent = false;
1236            for (ipv6, result) in results {
1237                sent |= self.mdns_send_result(ipv6, result, now);
1238            }
1239            if sent {
1240                self.mdns_sent += 1;
1241            } else {
1242                self.unsent += 1;
1243            }
1244        }
1245    }
1246
1247    /// Books one mDNS send of a family: a success makes the family available again (told
1248    /// once); a refusal counts, and declares the family unavailable at once when the error
1249    /// says there is no route or no permission, or after a few in a row. A full send buffer
1250    /// (`WouldBlock`) is a lost datagram, as on the wire, not a failure.
1251    fn mdns_send_result(&mut self, ipv6: bool, result: io::Result<usize>, now: Instant) -> bool {
1252        let Some(sockets) = self.mdns_sockets.as_mut() else {
1253            return false;
1254        };
1255        let family = if ipv6 {
1256            &mut sockets.v6
1257        } else {
1258            &mut sockets.v4
1259        };
1260        match result {
1261            Ok(_) => {
1262                family.failures = 0;
1263                if family.unavailable {
1264                    family.unavailable = false;
1265                    family.backoff = MDNS_RETRY_FIRST;
1266                    self.driver_events
1267                        .push_back(PeerDriverEvent::MdnsAvailable { ipv6 });
1268                    self.refresh_mdns_publishing();
1269                }
1270                true
1271            }
1272            Err(e) if e.kind() == io::ErrorKind::WouldBlock => false,
1273            Err(e) => {
1274                self.mdns_send_failures += 1;
1275                family.failures += 1;
1276                if decisive(&e) || family.failures >= MDNS_FAILURES_BEFORE_UNAVAILABLE {
1277                    self.mdns_unavailable(ipv6, MdnsStage::Send, &e, now);
1278                }
1279                false
1280            }
1281        }
1282    }
1283
1284    /// A family's mDNS cannot be used: its socket is closed (bound again at the next try),
1285    /// the next try waits a back-off, the application is told (once until it works again),
1286    /// and the connection learns that the family's names cannot be published.
1287    fn mdns_unavailable(&mut self, ipv6: bool, stage: MdnsStage, error: &io::Error, now: Instant) {
1288        let Some(sockets) = self.mdns_sockets.as_mut() else {
1289            return;
1290        };
1291        let family = if ipv6 {
1292            &mut sockets.v6
1293        } else {
1294            &mut sockets.v4
1295        };
1296        family.close();
1297        family.failures = 0;
1298        family.retry_at = Some(now + family.backoff);
1299        family.backoff = (family.backoff * 2).min(MDNS_RETRY_MAX);
1300        if !family.unavailable {
1301            family.unavailable = true;
1302            self.driver_events
1303                .push_back(PeerDriverEvent::MdnsUnavailable(MdnsFailure::new(
1304                    ipv6, stage, error,
1305                )));
1306        }
1307        self.refresh_mdns_publishing();
1308    }
1309
1310    /// The host's mDNS sockets (none with [`PeerDriverConfig::mdns_sockets`] off): each family
1311    /// without a socket is bound now when it never was, when `force` (a gathering), or when
1312    /// its back-off has passed. Each socket is joined to its group on the interface of every
1313    /// configured address of its family (RFC 6762 section 14: a name is answered, and a peer's
1314    /// asked for, on the link of its address). A bind that fails is reported
1315    /// ([`PeerDriverEvent::MdnsUnavailable`]) and tried again later.
1316    fn ensure_mdns(&mut self, now: Instant, force: bool) {
1317        let skips_loopback_v4 = self.config.skips_loopback_mdns_v4();
1318        let addresses = mdns_addresses(&self.config.addresses, skips_loopback_v4);
1319        if self.mdns_sockets.is_none() {
1320            let mut v4 = MdnsFamily::new(one_per_interface(&addresses, true));
1321            if addresses.len() < self.config.addresses.len() {
1322                note_loopback_mdns_skipped();
1323                // Only loopback IPv4 addresses: no IPv4 socket at all (one with no interface
1324                // would join and send on the system's default one).
1325                v4.off = !addresses.iter().any(IpAddr::is_ipv4);
1326            }
1327            let v6 = MdnsFamily::new(one_per_interface(&addresses, false));
1328            let companions = v6
1329                .links
1330                .iter()
1331                .filter_map(|ip6| {
1332                    let name = runtime::interface_name(*ip6)?;
1333                    let ip4 = v4
1334                        .links
1335                        .iter()
1336                        .find(|ip4| runtime::interface_name(**ip4).as_deref() == Some(&name))?;
1337                    Some((*ip6, *ip4))
1338                })
1339                .collect();
1340            self.mdns_sockets = Some(MdnsSockets {
1341                v4,
1342                v6,
1343                companions,
1344                skips_loopback_v4,
1345            });
1346        }
1347        if !self.config.mdns_sockets {
1348            return;
1349        }
1350        for ipv6 in [false, true] {
1351            let Some(sockets) = self.mdns_sockets.as_ref() else {
1352                return;
1353            };
1354            let family = if ipv6 { &sockets.v6 } else { &sockets.v4 };
1355            if family.off
1356                || family.socket.is_some()
1357                || !(force || family.retry_at.is_none_or(|at| now >= at))
1358            {
1359                continue;
1360            }
1361            let config = if ipv6 {
1362                mdns_v6(addresses.clone())
1363            } else {
1364                mdns_v4(addresses.clone())
1365            };
1366            let bound = self
1367                .runtime
1368                .bind_udp_multicast(&config)
1369                .and_then(|socket| Ok((socket.local_addr()?, socket)));
1370            match bound {
1371                Ok((local, socket)) => {
1372                    let tx = self.mdns_tx.clone();
1373                    let dropped = self.mdns_dropped.clone();
1374                    let reader = self.runtime.spawn(Box::pin(read_loop(
1375                        self.runtime.clone(),
1376                        socket.clone(),
1377                        local,
1378                        true,
1379                        move |received| match tx.force_send(received) {
1380                            Ok(None) => true,
1381                            Ok(Some(_)) => {
1382                                dropped.fetch_add(1, Ordering::Relaxed);
1383                                true
1384                            }
1385                            Err(_) => false,
1386                        },
1387                        MDNS_MAX_DATAGRAM,
1388                    )));
1389                    if let Some(sockets) = self.mdns_sockets.as_mut() {
1390                        let family = if ipv6 {
1391                            &mut sockets.v6
1392                        } else {
1393                            &mut sockets.v4
1394                        };
1395                        family.socket = Some((socket, reader));
1396                    }
1397                }
1398                Err(e) => {
1399                    self.mdns_bind_failures += 1;
1400                    self.mdns_unavailable(ipv6, MdnsStage::Bind, &e, now);
1401                }
1402            }
1403        }
1404        self.refresh_mdns_publishing();
1405    }
1406
1407    /// Before the connection's host candidates, with `QueryAndGather`: binds the mDNS sockets
1408    /// (again, for a family that failed) and tells the connection for which address families
1409    /// its names can be published (draft-ietf-mmusic-mdns-ice-candidates section 3.1.1 step 4).
1410    fn prepare_mdns_publishing(&mut self) {
1411        if self.pc.multicast_dns_mode() != MulticastDnsMode::QueryAndGather {
1412            return;
1413        }
1414        let now = self.runtime.now();
1415        self.ensure_mdns(now, true);
1416        if self.mdns_publishing_told.is_none() {
1417            let publishing = self.mdns_publishing();
1418            self.mdns_publishing_told = Some(publishing);
1419            self.pc.set_multicast_dns_publishing(publishing);
1420        }
1421    }
1422
1423    /// What is actually sent: an IPv4 record's messages need the IPv4 socket; an IPv6 record's
1424    /// leave on the IPv6 group, or on the IPv4 group of its interface.
1425    fn mdns_publishing(&self) -> MulticastDnsPublishing {
1426        let usable = |f: &MdnsFamily| f.socket.is_some() && !f.unavailable;
1427        self.mdns_sockets.as_ref().map_or(
1428            MulticastDnsPublishing {
1429                ipv4: false,
1430                ipv6: false,
1431            },
1432            |m| MulticastDnsPublishing {
1433                ipv4: usable(&m.v4),
1434                ipv6: usable(&m.v6) || (usable(&m.v4) && !m.companions.is_empty()),
1435            },
1436        )
1437    }
1438
1439    /// Tells the connection again when what can be published changed, once it was told.
1440    fn refresh_mdns_publishing(&mut self) {
1441        let Some(told) = self.mdns_publishing_told else {
1442            return;
1443        };
1444        let now = self.mdns_publishing();
1445        if now != told {
1446            self.mdns_publishing_told = Some(now);
1447            self.pc.set_multicast_dns_publishing(now);
1448        }
1449    }
1450
1451    /// With `QueryAndGather`, tells the connection which of the addresses it gathers on the
1452    /// operating system flags as RFC 4941 temporary IPv6 addresses
1453    /// (`RTCPeerConnection::set_temporary_ipv6_addresses`), so that
1454    /// `with_multicast_dns_expose_temporary_ipv6_addresses` can leave those unwrapped
1455    /// (draft-ietf-mmusic-mdns-ice-candidates section 3.1.2.3). Read from the interface list
1456    /// at each gathering (`shared::ifaces::temporary_ipv6_addresses`: Linux, Android, macOS
1457    /// and iOS report the flag; Windows and other systems mark nothing); where it cannot be
1458    /// read, nothing is marked and every address stays hidden.
1459    fn mark_temporary_addresses(&mut self) {
1460        if self.pc.multicast_dns_mode() != MulticastDnsMode::QueryAndGather {
1461            return;
1462        }
1463        let temporary: Vec<std::net::Ipv6Addr> = shared::ifaces::temporary_ipv6_addresses()
1464            .unwrap_or_default()
1465            .into_iter()
1466            .filter(|t| self.config.addresses.contains(&IpAddr::V6(*t)))
1467            .collect();
1468        self.pc.set_temporary_ipv6_addresses(temporary);
1469    }
1470
1471    fn on_event(&mut self, event: &RTCPeerConnectionEvent) -> Result<()> {
1472        match event {
1473            RTCPeerConnectionEvent::OnLocalCandidatesNeeded(needed) => {
1474                self.on_candidates_needed(needed)
1475            }
1476            RTCPeerConnectionEvent::OnSignalingStateChangeEvent(RTCSignalingState::Stable) => {
1477                self.match_sockets_to_candidates();
1478                Ok(())
1479            }
1480            RTCPeerConnectionEvent::OnTransportEvent(event) => match &event.event {
1481                RTCTransportEventKind::GatheringStateChange(RTCIceGatheringState::Gathering) => {
1482                    self.on_gathering_begins(event.ice_transport, event.dtls_transport)
1483                }
1484                RTCTransportEventKind::SelectedCandidatePairChange(pair) => {
1485                    let local = pair.local();
1486                    let udp = local.protocol == RTCIceProtocol::Udp;
1487                    for host in self.sockets.iter_mut() {
1488                        if udp && names_socket(&local.address, local.port, host.local) {
1489                            host.selected_by = Some(event.ice_transport);
1490                        } else if host.selected_by == Some(event.ice_transport) {
1491                            host.selected_by = None;
1492                        }
1493                    }
1494                    let on_retired = self.sockets.iter().any(|s| {
1495                        s.retired_for.is_some() && names_socket(&local.address, local.port, s.local)
1496                    });
1497                    if !on_retired {
1498                        self.release_after_linger(event.ice_transport);
1499                    }
1500                    Ok(())
1501                }
1502                RTCTransportEventKind::IceStateChange(RTCIceTransportState::Closed) => {
1503                    // A closed transport sends on no pair any more.
1504                    for host in self.sockets.iter_mut() {
1505                        if host.selected_by == Some(event.ice_transport) {
1506                            host.selected_by = None;
1507                        }
1508                    }
1509                    self.release(event.ice_transport);
1510                    Ok(())
1511                }
1512                _ => Ok(()),
1513            },
1514            _ => Ok(()),
1515        }
1516    }
1517
1518    /// `OnLocalCandidatesNeeded`: new sockets for the transport, or (`DiscardedBySetting`,
1519    /// no address refused) the same sockets' candidates again.
1520    fn on_candidates_needed(&mut self, needed: &RTCLocalCandidatesNeededEvent) -> Result<()> {
1521        let Some(mid) = needed.mids.first().cloned() else {
1522            return Ok(());
1523        };
1524        let index = needed.sdp_mline_index;
1525        self.gathered.insert(needed.ice_transport);
1526        self.mark_temporary_addresses();
1527        if !needed.reason.needs_new_addresses() {
1528            // The candidates were discarded (`DiscardedBySetting`): the generation gathers on
1529            // the addresses the host has now (RFC 8445 section 5.1.1.1). The sockets of
1530            // addresses no longer selected are retired for the transport (closed once a pair
1531            // on a new one is selected); the others give their candidates again, and new
1532            // addresses get sockets.
1533            self.reselect_addresses();
1534            let addresses = self.config.addresses.clone();
1535            for host in self.sockets.iter_mut().filter(|s| {
1536                s.serves() && needed.mids.contains(&s.mid) && !addresses.contains(&s.local.ip())
1537            }) {
1538                host.retired_for = Some(needed.ice_transport);
1539            }
1540            let on: Vec<SocketAddr> = self
1541                .sockets
1542                .iter()
1543                .filter(|s| s.serves() && needed.mids.contains(&s.mid))
1544                .map(|s| s.local)
1545                .collect();
1546            if !on.is_empty() {
1547                for local in &on {
1548                    self.pc
1549                        .add_local_candidate(host_candidate(*local, &mid, index)?)?;
1550                }
1551                for ip in addresses {
1552                    if !on.iter().any(|local| local.ip() == ip) {
1553                        self.open_host_socket(ip, &mid, index)?;
1554                    }
1555                }
1556                return self.end_of_candidates(&mid, index);
1557            }
1558            return self.gather_section(&mid, index);
1559        }
1560        for host in self
1561            .sockets
1562            .iter_mut()
1563            .filter(|s| needed.refused_addresses.contains(&s.local))
1564        {
1565            host.retired_for = Some(needed.ice_transport);
1566        }
1567        if needed.reason == RTCLocalCandidatesNeededReason::TransportReplaced {
1568            // The transport they served is closed: nothing travels over them any more.
1569            self.release(needed.ice_transport);
1570        }
1571        self.gather_section(&mid, index)
1572    }
1573
1574    /// Back in the stable state, the sockets are matched against the candidates the
1575    /// transports hold. A local offer that is rolled back takes its ICE restart back (RFC
1576    /// 9429 section 5.7: "any resources or candidates that were allocated by the abandoned
1577    /// local description are discarded"), the `OnLocalCandidatesNeeded` it fired included: a
1578    /// socket retired for it whose candidate the transport holds again carries the
1579    /// transport's packets as before (it is no longer retired), and a socket bound for the
1580    /// abandoned generation, whose candidate the transport dropped, is closed. The answer to
1581    /// the peer's colliding offer, if it sets up a new association, fires its own event. A
1582    /// socket whose candidate the transport dropped but which is still its selected pair's
1583    /// base (an answer's ICE restart for a new association: the stable state comes before its
1584    /// `OnLocalCandidatesNeeded`) is retired, not closed: the transport sends on that pair
1585    /// until the restart selects one.
1586    fn match_sockets_to_candidates(&mut self) {
1587        let held: Vec<(String, u16)> = self
1588            .pc
1589            .dtls_transports()
1590            .iter()
1591            .flat_map(|t| t.ice_transport().get_local_candidates())
1592            .filter(|c| c.protocol == RTCIceProtocol::Udp)
1593            .map(|c| (c.address, c.port))
1594            .collect();
1595        let holds = |local: &SocketAddr| {
1596            held.iter()
1597                .any(|(address, port)| names_socket(address, *port, *local))
1598        };
1599        let in_use = self.pc.turn_local_addresses_in_use();
1600        let now = self.runtime.now();
1601        for host in self.sockets.iter_mut() {
1602            if host.retired_for.is_some() && holds(&host.local) {
1603                host.retired_for = None;
1604                host.close_at = None;
1605            } else if host.retired_for.is_none()
1606                && !holds(&host.local)
1607                && let Some(transport) = host.selected_by
1608            {
1609                // The base of the pair its transport still sends on: an ICE restart that
1610                // dropped the candidate keeps that pair for data until the restart selects one
1611                // (RFC 8445 section 9: "during the restart, data can continue to be sent using
1612                // existing data sessions"). An answer that sets up a new association reaches the
1613                // stable state before its `OnLocalCandidatesNeeded` retires the socket: it is
1614                // retired here, and closes once the new pair is selected plus the linger, as
1615                // every retired socket does.
1616                host.retired_for = Some(transport);
1617            } else if host.retired_for.is_none()
1618                && !holds(&host.local)
1619                && in_use.contains(&host.local)
1620            {
1621                // The abandoned generation's socket carries a TURN release (or an Allocate the
1622                // engine deletes) of the rollback: it closes once that is done.
1623                host.close_at = Some(now);
1624            }
1625        }
1626        let unsent = &mut self.unsent;
1627        self.sockets.retain(|s| {
1628            let keep = s.retired_for.is_some() || holds(&s.local) || s.close_at.is_some();
1629            if !keep {
1630                // What still waited for the socket is not sent.
1631                *unsent += s.waiting.len() as u64;
1632            }
1633            keep
1634        });
1635    }
1636
1637    /// A transport begins gathering an ICE generation the driver was not told about: the
1638    /// first one (no socket of the transport yet: every section without one gets them), or a
1639    /// restart that kept the candidates (each is given to the new generation again).
1640    fn on_gathering_begins(
1641        &mut self,
1642        ice_transport: RTCTransportId,
1643        dtls_transport: RTCTransportId,
1644    ) -> Result<()> {
1645        if self.gathered.remove(&ice_transport) {
1646            return Ok(());
1647        }
1648        let Some(held) = self.pc.dtls_transport_by_id(dtls_transport).and_then(|t| {
1649            let ice = t.ice_transport();
1650            (ice.gathering_state() == RTCIceGatheringState::Gathering)
1651                .then(|| ice.get_local_candidates())
1652        }) else {
1653            return Ok(());
1654        };
1655        // With an address selection, the restart gathers on the addresses the host has now:
1656        // the sockets of addresses no longer selected are retired for the transport (closed
1657        // once a pair on a new one is selected, as on `OnLocalCandidatesNeeded`), and new
1658        // addresses get sockets.
1659        self.reselect_addresses();
1660        let addresses = self.config.addresses.clone();
1661        let mut gone = Vec::new();
1662        for host in self.sockets.iter_mut().filter(|s| {
1663            s.retired_for.is_none()
1664                && !addresses.contains(&s.local.ip())
1665                && held
1666                    .iter()
1667                    .any(|c| names_socket(&c.address, c.port, s.local))
1668        }) {
1669            host.retired_for = Some(ice_transport);
1670            gone.push(host.local);
1671        }
1672        // The restart kept their candidates (RFC 8445 section 9 with the default of
1673        // `with_discard_local_candidates_during_ice_restart`): the host no longer has those
1674        // addresses, so the new generation does not signal or pair them (section 5.1.1.4).
1675        // The selected pair, if on one, carries data until the restart selects another.
1676        for local in gone {
1677            self.pc.withdraw_local_candidates_of_base(local);
1678        }
1679        let kept: Vec<(SocketAddr, String)> = self
1680            .sockets
1681            .iter()
1682            .filter(|s| s.serves())
1683            .filter(|s| {
1684                held.iter()
1685                    .any(|c| names_socket(&c.address, c.port, s.local))
1686            })
1687            .map(|s| (s.local, s.mid.clone()))
1688            .collect();
1689        if kept.is_empty() {
1690            return self.gather();
1691        }
1692        let mid = kept[0].1.clone();
1693        for (local, _) in &kept {
1694            self.pc
1695                .add_local_candidate(host_candidate(*local, &mid, None)?)?;
1696        }
1697        for ip in addresses {
1698            if !kept.iter().any(|(local, _)| local.ip() == ip) {
1699                self.open_host_socket(ip, &mid, None)?;
1700            }
1701        }
1702        self.end_of_candidates(&mid, None)
1703    }
1704
1705    /// Host candidates for every transport section (`ice_transport_sections`) that has no
1706    /// socket of its own yet, each ended with the end of its generation.
1707    ///
1708    /// # Errors
1709    ///
1710    /// As [`flush`](Self::flush).
1711    pub fn gather(&mut self) -> Result<()> {
1712        for (mid, index) in self.pc.ice_transport_sections() {
1713            if self.sockets.iter().any(|s| s.serves() && s.mid == mid) {
1714                continue;
1715            }
1716            self.gather_section(&mid, Some(index))?;
1717        }
1718        Ok(())
1719    }
1720
1721    /// New sockets, one per configured address, for the transport of section `mid`: their
1722    /// host candidates, then the end of the generation.
1723    fn gather_section(&mut self, mid: &str, index: Option<u16>) -> Result<()> {
1724        self.reselect_addresses();
1725        self.prepare_mdns_publishing();
1726        self.mark_temporary_addresses();
1727        for ip in self.config.addresses.clone() {
1728            self.open_host_socket(ip, mid, index)?;
1729        }
1730        self.end_of_candidates(mid, index)
1731    }
1732
1733    /// A new UDP socket on `ip` for the transport of section `mid`, and its host candidate.
1734    fn open_host_socket(&mut self, ip: IpAddr, mid: &str, index: Option<u16>) -> Result<()> {
1735        let (socket, local) = self.bind_unique_port(ip).map_err(io_error)?;
1736        let tx = self.datagrams_tx.clone();
1737        let reader = self.runtime.spawn(Box::pin(read_loop(
1738            self.runtime.clone(),
1739            socket.clone(),
1740            local,
1741            false,
1742            move |received| tx.try_send(received).is_ok(),
1743            2048,
1744        )));
1745        self.sockets.push(HostSocket {
1746            socket,
1747            local,
1748            mid: mid.to_owned(),
1749            retired_for: None,
1750            close_at: None,
1751            selected_by: None,
1752            counted_unmarked: false,
1753            dont_fragment: None,
1754            dont_fragment_refused: false,
1755            waiting: VecDeque::new(),
1756            reader,
1757        });
1758        self.pc
1759            .add_local_candidate(host_candidate(local, mid, index)?)
1760    }
1761
1762    /// With [`PeerDriverConfig::address_selection`]: the addresses the host has now. When they
1763    /// changed, the mDNS sockets (joined on the previous addresses' interfaces) are bound again
1764    /// at their next use. No address found, or no list: the previous addresses stay.
1765    fn reselect_addresses(&mut self) {
1766        let Some(selection) = self.effective_selection() else {
1767            return;
1768        };
1769        match selection.select(self.runtime.as_ref(), &self.config.addresses) {
1770            Ok(addresses) if !addresses.is_empty() => {
1771                if addresses != self.config.addresses {
1772                    log::debug!("addresses now {addresses:?}");
1773                    self.config.addresses = addresses;
1774                    self.mdns_sockets = None;
1775                }
1776            }
1777            Ok(_) => log::debug!("address selection found no address; keeping the previous ones"),
1778            Err(e) => log::debug!("interfaces not listed ({e}); keeping the previous addresses"),
1779        }
1780        self.monitored = Some(self.config.addresses.clone());
1781    }
1782
1783    /// [`PeerDriverConfig::address_selection`] with what the connection itself says: the IP
1784    /// addresses of its `turn:` / `turns:` servers as routes for Mode 2 (RFC 8828 section 5.2:
1785    /// "the preferred route MUST be through this TURN server"), and one address per family
1786    /// for a lite connection (RFC 8445 section 5.2).
1787    fn effective_selection(&self) -> Option<AddressSelection> {
1788        let mut selection = self.config.address_selection.clone()?;
1789        for server in self.pc.get_configuration().ice_servers() {
1790            for ip in server.urls.iter().filter_map(|url| turn_server_ip(url)) {
1791                if !selection.route_via.contains(&ip) {
1792                    selection.route_via.push(ip);
1793                }
1794            }
1795        }
1796        if self.pc.is_ice_lite() {
1797            selection.one_per_family = true;
1798        }
1799        Some(selection)
1800    }
1801
1802    /// Gives the user's consent to Mode 1 (every interface, RFC 8828 section 5.2), or takes it
1803    /// back ([`AddressSelection::user_consent`]): from the next gathering on (an ICE restart's;
1804    /// the interface monitor does not restart ICE for it). Without an address selection it
1805    /// changes nothing.
1806    pub fn set_user_consent(&mut self, consent: bool) {
1807        if let Some(selection) = self.config.address_selection.as_mut() {
1808            selection.user_consent = consent;
1809            // The monitor takes the new mode's addresses as the base line.
1810            self.monitored = None;
1811        }
1812    }
1813
1814    /// The application learnt that the network may have changed (an operating system
1815    /// notification: wake, link up, address change): the driver reads the interfaces now, as
1816    /// the monitor does ([`PeerDriverConfig::interface_check_interval`]), and tells the
1817    /// connection (`RTCPeerConnection::network_changed`) even when the addresses are the same.
1818    pub fn network_changed(&mut self) {
1819        let now = self.runtime.now();
1820        self.check_interfaces(now, true);
1821    }
1822
1823    /// The interface monitor ([`PeerDriverConfig::interface_check_interval`]): `forced`, a
1824    /// check on the application's word.
1825    fn check_interfaces(&mut self, now: Instant, forced: bool) {
1826        let interval = self.config.interface_check_interval;
1827        if !forced {
1828            let Some(interval) = interval else {
1829                return;
1830            };
1831            if self.next_interface_check.is_some_and(|at| now < at) {
1832                return;
1833            }
1834            self.next_interface_check = Some(now + interval);
1835        }
1836        let woke = self.woke_from_sleep(now);
1837        let changed = match (self.effective_selection(), self.monitored.clone()) {
1838            // Before the first gathering there is nothing to change.
1839            (Some(selection), Some(previous)) if !self.sockets.is_empty() => {
1840                match selection.select(self.runtime.as_ref(), &self.config.addresses) {
1841                    Ok(current) if !current.is_empty() && current != previous => {
1842                        Some((previous, current))
1843                    }
1844                    _ => None,
1845                }
1846            }
1847            (Some(selection), None) => {
1848                if let Ok(current) = selection.select(self.runtime.as_ref(), &self.config.addresses)
1849                {
1850                    self.monitored = Some(current);
1851                }
1852                None
1853            }
1854            _ => None,
1855        };
1856        if let Some((previous, current)) = changed {
1857            let added: Vec<IpAddr> = current
1858                .iter()
1859                .copied()
1860                .filter(|ip| !previous.contains(ip))
1861                .collect();
1862            let removed: Vec<IpAddr> = previous
1863                .iter()
1864                .copied()
1865                .filter(|ip| !current.contains(ip))
1866                .collect();
1867            self.monitored = Some(current);
1868            // RFC 8445 section 5.1.1.4: candidates whose base went are invalid: withdrawn, so
1869            // that the restart below does not carry them into its generation; their sockets
1870            // close (once the engine's TURN client is done with them).
1871            let mut gone = Vec::new();
1872            for host in self
1873                .sockets
1874                .iter_mut()
1875                .filter(|s| removed.contains(&s.local.ip()) && s.close_at.is_none())
1876            {
1877                host.close_at = Some(now);
1878                gone.push(host.local);
1879            }
1880            for local in gone {
1881                self.pc.withdraw_local_candidates_of_base(local);
1882            }
1883            self.close_due_sockets(now);
1884            // A new generation gathers on the addresses the host has now.
1885            self.pc.restart_ice();
1886            self.pc.network_changed();
1887            self.driver_events
1888                .push_back(PeerDriverEvent::AddressesChanged { added, removed });
1889        } else if woke || forced {
1890            self.pc.network_changed();
1891            self.driver_events
1892                .push_back(PeerDriverEvent::NetworkChanged);
1893        }
1894    }
1895
1896    /// Whether the host slept since the monitor's last look: the wall clock moved at least 5
1897    /// seconds further than the runtime's monotonic one (which stops in suspend on Linux and
1898    /// macOS). Never on a virtual clock.
1899    fn woke_from_sleep(&mut self, now: Instant) -> bool {
1900        if self.runtime.virtual_clock() {
1901            return false;
1902        }
1903        let wall = std::time::SystemTime::now();
1904        let woke = self.wall_mark.is_some_and(|(then, wall_then)| {
1905            let monotonic = now.saturating_duration_since(then);
1906            let walked = wall.duration_since(wall_then).unwrap_or_default();
1907            walked.saturating_sub(monotonic) >= Duration::from_secs(5)
1908        });
1909        self.wall_mark = Some((now, wall));
1910        woke
1911    }
1912
1913    /// A UDP socket on `ip`; with `QueryAndGather`, one whose port no other socket of the
1914    /// driver has: a `.local` candidate names its socket by port alone ([`names_socket`]), so
1915    /// ports are kept unique across the driver's addresses (the system gives each address its
1916    /// own ports, and a port-range cursor comes round again). Where the range has no such port
1917    /// left after [`MAX_PORT_ATTEMPTS`] binds, the last one is taken: two sockets then share a
1918    /// port, and a retired one may stay open until its transport closes.
1919    fn bind_unique_port(&self, ip: IpAddr) -> io::Result<(Arc<dyn AsyncUdpSocket>, SocketAddr)> {
1920        let unique = self.pc.multicast_dns_mode() == MulticastDnsMode::QueryAndGather;
1921        // Sockets refused for their port stay bound until the end, so that the next bind
1922        // cannot be given the same port again.
1923        let mut refused = Vec::new();
1924        for _ in 0..MAX_PORT_ATTEMPTS {
1925            let socket = match self.config.udp_port_range {
1926                Some(range) => sockets::bind_runtime_udp_in_range(self.runtime.as_ref(), ip, range),
1927                None => self.runtime.bind_udp(SocketAddr::new(ip, 0)),
1928            };
1929            let socket = match socket {
1930                Ok(socket) => socket,
1931                // The range is full now that the refused sockets hold their ports.
1932                Err(e) if !refused.is_empty() && e.kind() == io::ErrorKind::AddrInUse => break,
1933                Err(e) => return Err(e),
1934            };
1935            let local = socket.local_addr()?;
1936            if !unique || !self.sockets.iter().any(|s| s.local.port() == local.port()) {
1937                return Ok((socket, local));
1938            }
1939            refused.push((socket, local));
1940        }
1941        refused
1942            .pop()
1943            .ok_or_else(|| io::Error::from(io::ErrorKind::AddrInUse))
1944    }
1945
1946    fn end_of_candidates(&mut self, mid: &str, index: Option<u16>) -> Result<()> {
1947        self.pc.add_local_candidate(RTCIceCandidateInit {
1948            sdp_mid: Some(mid.to_owned()),
1949            sdp_mline_index: index,
1950            ..Default::default()
1951        })
1952    }
1953
1954    /// Closes the sockets retired for `transport` (it is closed: nothing of ICE travels over
1955    /// them), except those the engine's TURN client still uses
1956    /// (`RTCPeerConnection::turn_local_addresses_in_use`: a release under way, RFC 8656
1957    /// section 8): those are closed by [`step`](Self::step) once it is done.
1958    fn release(&mut self, transport: RTCTransportId) {
1959        let in_use = self.pc.turn_local_addresses_in_use();
1960        let now = self.runtime.now();
1961        let unsent = &mut self.unsent;
1962        self.sockets.retain_mut(|s| {
1963            if s.retired_for != Some(transport) {
1964                return true;
1965            }
1966            if in_use.contains(&s.local) {
1967                s.close_at = Some(now);
1968                return true;
1969            }
1970            // What still waited for the socket is not sent.
1971            *unsent += s.waiting.len() as u64;
1972            false
1973        });
1974    }
1975
1976    /// Closes the sockets whose time has come ([`HostSocket::close_at`]) and that the engine's
1977    /// TURN client no longer uses.
1978    fn close_due_sockets(&mut self, now: Instant) {
1979        if !self
1980            .sockets
1981            .iter()
1982            .any(|s| s.close_at.is_some_and(|at| at <= now))
1983        {
1984            return;
1985        }
1986        let in_use = self.pc.turn_local_addresses_in_use();
1987        let unsent = &mut self.unsent;
1988        self.sockets.retain(|s| {
1989            let keep = s.close_at.is_none_or(|at| at > now) || in_use.contains(&s.local);
1990            if !keep {
1991                *unsent += s.waiting.len() as u64;
1992            }
1993            keep
1994        });
1995    }
1996
1997    /// `transport` selected a pair on a new socket: its retired sockets are closed after
1998    /// [`PeerDriverConfig::retired_socket_linger`], for what the peer still sends to them.
1999    fn release_after_linger(&mut self, transport: RTCTransportId) {
2000        let close_at = self.runtime.now() + self.config.retired_socket_linger;
2001        for host in self
2002            .sockets
2003            .iter_mut()
2004            .filter(|s| s.retired_for == Some(transport) && s.close_at.is_none())
2005        {
2006            host.close_at = Some(close_at);
2007        }
2008    }
2009}
2010
2011/// What a driver dropped without [`PeerDriver::shutdown`] can do: an async driver on a runtime
2012/// of the application's choice cannot wait in `drop` (no runtime may be blocked there, and
2013/// none may be running any more), so it closes the connection and sends at once, without
2014/// waiting, what the connection then writes: the mDNS goodbyes the budget lets go now (the
2015/// rest is lost, and the neighbours' caches hold those names until their TTL ends), each
2016/// socket's last datagrams if the system takes them. The sockets close as the driver goes,
2017/// leaving the mDNS groups. Use `shutdown` to have every goodbye sent.
2018impl Drop for PeerDriver {
2019    fn drop(&mut self) {
2020        if self.shut_down {
2021            return;
2022        }
2023        let _ = self.pc.close();
2024        while let Some(datagram) = self.pc.poll_write() {
2025            self.send(datagram);
2026        }
2027        if self.mdns_sockets.is_some() {
2028            self.send_mdns(self.runtime.now());
2029        }
2030    }
2031}
2032
2033/// How many binds [`PeerDriver::bind_unique_port`] tries for a port no other socket has.
2034const MAX_PORT_ATTEMPTS: usize = 16;
2035
2036/// Whether a local candidate of `address` and `port` is the one of the socket at `local`. With
2037/// mDNS (`QueryAndGather`) the engine has replaced the candidate's address with a `.local` name
2038/// (draft-ietf-mmusic-mdns-ice-candidates section 3.1.1): the port tells the socket then, and
2039/// it tells exactly one, because no two sockets of a driver share a port
2040/// ([`PeerDriver::bind_unique_port`]).
2041fn names_socket(address: &str, port: u16, local: SocketAddr) -> bool {
2042    port == local.port()
2043        && (address == local.ip().to_string() || address.to_ascii_lowercase().ends_with(".local"))
2044}
2045
2046fn io_error(e: io::Error) -> Error {
2047    Error::Io(IoError(e))
2048}
2049
2050/// The host candidate of `local` for section `mid`.
2051fn host_candidate(local: SocketAddr, mid: &str, index: Option<u16>) -> Result<RTCIceCandidateInit> {
2052    let candidate = CandidateHostConfig {
2053        base_config: CandidateConfig {
2054            network: "udp".to_owned(),
2055            address: local.ip().to_string(),
2056            port: local.port(),
2057            component: 1,
2058            ..Default::default()
2059        },
2060        ..Default::default()
2061    }
2062    .new_candidate_host()?;
2063    let mut init = RTCIceCandidate::from(&candidate).to_json()?;
2064    init.sdp_mid = Some(mid.to_owned());
2065    init.sdp_mline_index = index;
2066    Ok(init)
2067}
2068
2069/// The IP address of a `turn:` / `turns:` URL's host, when the host is one (RFC 7065:
2070/// `turn:host[:port][?transport=...]`, an IPv6 address in brackets).
2071fn turn_server_ip(url: &str) -> Option<IpAddr> {
2072    let rest = url
2073        .strip_prefix("turn:")
2074        .or_else(|| url.strip_prefix("turns:"))?;
2075    let authority = rest.split('?').next()?;
2076    if let Some(v6) = authority.strip_prefix('[') {
2077        return v6.split(']').next()?.parse().ok();
2078    }
2079    authority.split(':').next()?.parse().ok()
2080}
2081
2082/// What woke a [`PeerDriver::step`].
2083enum Woke {
2084    Datagram(Received),
2085    Mdns(Received),
2086    Stream(DriverInput),
2087    /// A socket that was not ready took or refused its first waiting datagram.
2088    Sent(usize, WaitingSend, io::Result<usize>),
2089    Timer,
2090}
2091
2092/// What the engine is given for a received datagram at `now`: its addresses, its bytes and the
2093/// ECN codepoint the socket reported (Not-ECT and an unreported field are both `None`).
2094fn tagged(received: &Received, now: Instant) -> TaggedBytesMut {
2095    TaggedBytesMut {
2096        now,
2097        transport: TransportContext {
2098            local_addr: received.local,
2099            peer_addr: received.peer,
2100            ecn: received.ecn.and_then(EcnCodepoint::from_bits),
2101            transport_protocol: TransportProtocol::UDP,
2102        },
2103        message: BytesMut::from(&received.data[..]),
2104    }
2105}
2106
2107/// Whether a datagram is a STUN message by its first byte (RFC 7983 section 7: 0 to 3).
2108fn is_stun(datagram: &[u8]) -> bool {
2109    datagram.first().is_some_and(|b| *b <= 3)
2110}
2111
2112/// Whether a send was refused because the datagram is larger than the system sends
2113/// (`EMSGSIZE`, Windows `WSAEMSGSIZE`).
2114fn refused_for_size(e: &io::Error) -> bool {
2115    #[cfg(unix)]
2116    let code = libc::EMSGSIZE;
2117    #[cfg(windows)]
2118    let code = 10040;
2119    #[cfg(not(any(unix, windows)))]
2120    let code = -1;
2121    e.raw_os_error() == Some(code)
2122}
2123
2124/// Whether an mDNS send error says sending cannot work (no route to the group, no
2125/// permission): the family is unavailable at once, without waiting for more failures.
2126fn decisive(e: &io::Error) -> bool {
2127    matches!(
2128        e.kind(),
2129        io::ErrorKind::HostUnreachable
2130            | io::ErrorKind::NetworkUnreachable
2131            | io::ErrorKind::PermissionDenied
2132            | io::ErrorKind::AddrNotAvailable
2133            | io::ErrorKind::NetworkDown
2134    )
2135}
2136
2137/// Reads `socket` and hands each datagram to `deliver` (`false`: the driver is gone), with
2138/// `local` as its local address, or, with `destination`, the destination address of its IP
2139/// header where the socket reports it (else `local`'s: a socket bound to the mDNS group
2140/// receives only what was sent to the group).
2141async fn read_loop(
2142    runtime: Arc<dyn Runtime>,
2143    socket: Arc<dyn AsyncUdpSocket>,
2144    local: SocketAddr,
2145    destination: bool,
2146    mut deliver: impl FnMut(Received) -> bool + Send + 'static,
2147    max_datagram: usize,
2148) {
2149    let mut buf = vec![0u8; max_datagram];
2150    loop {
2151        let received = std::future::poll_fn(|cx| {
2152            let mut meta = [runtime::RecvMeta::default()];
2153            let mut bufs = [std::io::IoSliceMut::new(&mut buf)];
2154            socket
2155                .poll_recv(cx, &mut bufs, &mut meta)
2156                .map_ok(|_| meta[0])
2157        })
2158        .await;
2159        match received {
2160            Ok(meta) => {
2161                let to = match meta.dst_ip {
2162                    Some(ip) if destination && !ip.is_unspecified() => {
2163                        SocketAddr::new(ip, local.port())
2164                    }
2165                    _ => local,
2166                };
2167                let received = Received {
2168                    local: to,
2169                    peer: meta.addr,
2170                    data: buf[..meta.len].to_vec(),
2171                    at: runtime.now(),
2172                    ecn: meta.ecn,
2173                };
2174                if !deliver(received) {
2175                    return;
2176                }
2177            }
2178            // An ICMP error reported on the socket (Windows: a port unreachable) is not the
2179            // end of it.
2180            Err(_) => runtime::yield_now().await,
2181        }
2182    }
2183}
2184
2185#[cfg(test)]
2186mod tests {
2187    use super::*;
2188    use std::net::{Ipv4Addr, Ipv6Addr};
2189
2190    /// RFC 8888 section 3 ("the arrival time at the receiver needs to be recorded at the
2191    /// earliest available opportunity") and RFC 6679 section 7.2.1 (receivers "listen for
2192    /// ECT/CE"), the reader's part: a datagram is stamped with the runtime's time when the
2193    /// reader takes it off the socket, not later, and keeps the ECN field the socket reports.
2194    #[cfg(feature = "runtime-mock")]
2195    #[test]
2196    fn the_reader_stamps_each_datagram_on_receipt_and_keeps_its_ecn_field() {
2197        use crate::runtime::MockRuntime;
2198        let runtime = MockRuntime::new();
2199        let shared: Arc<dyn Runtime> = Arc::new(runtime.clone());
2200        let a: SocketAddr = "10.0.0.1:4000".parse().unwrap();
2201        let b: SocketAddr = "10.0.0.2:4000".parse().unwrap();
2202        let sender = shared.bind_udp(a).unwrap();
2203        let receiver = shared.bind_udp(b).unwrap();
2204        let got = Arc::new(std::sync::Mutex::new(Vec::new()));
2205        let sink = got.clone();
2206        let _reader = shared.spawn(Box::pin(read_loop(
2207            shared.clone(),
2208            receiver,
2209            b,
2210            false,
2211            move |received| {
2212                sink.lock().unwrap().push(received);
2213                true
2214            },
2215            2048,
2216        )));
2217        let sent_at = runtime.now();
2218        sender
2219            .try_send(&Transmit {
2220                destination: b,
2221                contents: b"ect1",
2222                // AF41 with ECT(1).
2223                traffic_class: (34 << 2) | 0b01,
2224                segment_size: None,
2225                source: None,
2226            })
2227            .unwrap();
2228        runtime.run_until_idle();
2229        runtime.clock().advance(Duration::from_millis(300));
2230        runtime.run_until_idle();
2231        let got = got.lock().unwrap();
2232        assert_eq!(got.len(), 1);
2233        assert_eq!(got[0].at, sent_at, "stamped when taken off the socket");
2234        assert_eq!(got[0].ecn, Some(0b01), "ECT(1) as sent");
2235        assert_eq!(got[0].peer, a);
2236        assert_eq!(got[0].data, b"ect1");
2237    }
2238
2239    /// RFC 6679 section 7.2.1, the driver's hand-over: the ECN field the socket reported
2240    /// reaches the engine's `TransportContext::ecn` (ECT(0), ECT(1), CE); Not-ECT and an
2241    /// unreported field are none.
2242    #[test]
2243    fn a_received_datagrams_ecn_field_reaches_the_engine() {
2244        let now = Instant::now();
2245        let mut received = Received {
2246            local: "10.0.0.2:4000".parse().unwrap(),
2247            peer: "10.0.0.1:4000".parse().unwrap(),
2248            data: vec![0x80, 0, 0, 1],
2249            at: now,
2250            ecn: None,
2251        };
2252        for (field, expected) in [
2253            (Some(0b10), Some(EcnCodepoint::Ect0)),
2254            (Some(0b01), Some(EcnCodepoint::Ect1)),
2255            (Some(0b11), Some(EcnCodepoint::Ce)),
2256            (Some(0b00), None),
2257            (None, None),
2258        ] {
2259            received.ecn = field;
2260            let tagged = tagged(&received, now);
2261            assert_eq!(tagged.transport.ecn, expected, "{field:?}");
2262            assert_eq!(tagged.transport.peer_addr, received.peer);
2263            assert_eq!(&tagged.message[..], &received.data[..]);
2264        }
2265    }
2266
2267    const NIC: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
2268    const LO: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
2269
2270    fn sockets(addresses: &[IpAddr], skips_loopback_v4: bool) -> MdnsSockets {
2271        let addresses = mdns_addresses(addresses, skips_loopback_v4);
2272        MdnsSockets {
2273            v4: MdnsFamily::new(one_per_interface(&addresses, true)),
2274            v6: MdnsFamily::new(one_per_interface(&addresses, false)),
2275            companions: vec![],
2276            skips_loopback_v4,
2277        }
2278    }
2279
2280    // The 0.3.0 default on Windows: IPv4 loopback addresses get no mDNS interface; the others,
2281    // IPv6 loopback included (not measured to leave a route), keep theirs. With the setting (and
2282    // on other systems) nothing is taken out.
2283    #[test]
2284    fn ipv4_loopback_addresses_get_no_mdns_interface_when_skipped() {
2285        let all = [NIC, LO, IpAddr::V6(Ipv6Addr::LOCALHOST)];
2286        assert_eq!(
2287            mdns_addresses(&all, true),
2288            vec![NIC, IpAddr::V6(Ipv6Addr::LOCALHOST)]
2289        );
2290        assert_eq!(mdns_addresses(&all, false), all.to_vec());
2291    }
2292
2293    // A message about the loopback address's name is sent nowhere on the group when skipped, and
2294    // on the loopback interface otherwise; a query leaves on the other interfaces only.
2295    #[test]
2296    fn a_loopback_record_leaves_on_no_group_when_skipped() {
2297        let group = SocketAddr::new(MDNS_MULTICAST_IPV4.into(), MDNS_PORT);
2298        let skipped = sockets(&[NIC, LO], true);
2299        assert!(skipped.routes(LO, group).is_empty());
2300        assert_eq!(skipped.routes(NIC, group), vec![(group, Some(NIC))]);
2301        assert_eq!(
2302            skipped.routes(Ipv4Addr::UNSPECIFIED.into(), group),
2303            vec![(group, Some(NIC))],
2304            "the query leaves on the network interface only"
2305        );
2306        let asked = sockets(&[NIC, LO], false);
2307        assert_eq!(asked.routes(LO, group), vec![(group, Some(LO))]);
2308    }
2309
2310    // The default decides on Windows only; the setting turns it off there.
2311    #[test]
2312    fn loopback_mdns_is_skipped_by_default_on_windows_only() {
2313        let config = PeerDriverConfig::on(vec![LO]);
2314        assert!(!config.mdns_on_loopback_on_windows, "the default");
2315        assert_eq!(config.skips_loopback_mdns_v4(), cfg!(windows));
2316        let asked = PeerDriverConfig {
2317            mdns_on_loopback_on_windows: true,
2318            ..config
2319        };
2320        assert!(!asked.skips_loopback_mdns_v4());
2321    }
2322}