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//! With `SettingEngineBuilder::with_dtls_new_association_on_previous_addresses(true)` the
22//! engine keeps the candidates and fires no event: the driver keeps its sockets and gives their
23//! candidates to each new ICE generation again.
24//!
25//! # mDNS
26//!
27//! A connection with mDNS on (`SettingEngineBuilder::with_multicast_dns_mode`) publishes its
28//! host addresses behind `.local` names and resolves the peer's: its ICE agents write their
29//! mDNS datagrams from local port 5353. At the first one the driver binds the host's mDNS
30//! sockets, port 5353 joined to 224.0.0.251 and, where the host has IPv6, to ff02::fb (shared
31//! with other mDNS responders of the host through address reuse), on the interface of every
32//! address of [`PeerDriverConfig::addresses`]; it sends the connection's queries, probes and
33//! answers there and hands what arrives back to the connection. A connection without mDNS
34//! writes none, and the driver binds nothing.
35//!
36//! RFC 6762 section 14: a host on several links takes part in mDNS on each, and an answer
37//! carries only addresses valid on the interface it leaves by. The engine names, for each
38//! message, the address it is about (its record's); the driver sends it by that address's
39//! interface (`Transmit::source`: `IP_MULTICAST_IF` / `IPV6_MULTICAST_IF`), an IPv6 record's
40//! on the IPv6 group (and on the IPv4 group of the same interface where the driver has an IPv4
41//! address there), and a query once on each interface.
42//!
43//! On Windows, a process that joins the IPv4 mDNS group on the loopback interface (a driver
44//! given 127.0.0.1) and sends to the group there leaves a stale route for the group behind
45//! it: the system's destination cache holds 224.0.0.251 with source 127.0.0.1 on the
46//! "Loopback Pseudo-Interface" after the process has exited (`netsh interface ipv4 show
47//! destinationcache address=224.0.0.251`), and from then on any process that asks which
48//! address reaches the group (a UDP socket connected to it) gets 127.0.0.1. Measured on
49//! Windows 11 and on GitHub's Windows image; the joins table entry for the group on the
50//! loopback interface that the join also leaves (`show joins`, references 0) is not what moves
51//! the answer. A later join, send and leave on the network interface does not clear the
52//! entry; deleting it does, at once: `netsh interface ipv4 delete destinationcache
53//! interface=<the loopback interface's index> address=224.0.0.251`, from an administrator
54//! prompt (measured on Windows 11 and on GitHub's Windows image). The same may hold for IPv6's
55//! ff02::fb; that was not measured. So on Windows the driver, by default, takes no part in
56//! IPv4 mDNS on loopback: it does not join 224.0.0.251 on the loopback interface and sends
57//! nothing to the group from a loopback address (the messages about a loopback address's name
58//! are dropped, counted in [`PeerDriver::unsent_datagrams`]); a driver whose only IPv4
59//! addresses are loopback binds no IPv4 mDNS socket and tells the connection that its IPv4
60//! names cannot be published ([`PeerDriver::mdns_available`] is `false`). Loopback candidates
61//! are for local use only (RFC 8445 section 5.1.1.1: "Addresses from a loopback interface MUST
62//! NOT be included in the candidate addresses"), and RFC 6762 asks no mDNS on loopback.
63//! [`PeerDriverConfig::mdns_on_loopback_on_windows`] turns it back on, as on other systems;
64//! the driver then logs a warning when it makes such a join, and an application or test host
65//! that does so cleans the entry as above when it is done. The driver changes no host routing
66//! state itself.
67//!
68//! Where mDNS cannot be sent (a socket that cannot be bound, or a system that refuses every
69//! send to the group: no multicast route, or a Mac application without the Local Network
70//! permission) the driver tells the application with
71//! [`PeerDriverEvent::MdnsUnavailable`] ([`PeerDriver::poll_driver_event`]), with the system's
72//! error, counts it ([`PeerDriver::mdns_send_failures`], [`PeerDriver::mdns_bind_failures`]),
73//! and tells the connection that the family's names cannot be published. It tries again at the
74//! next gathering and, while mDNS datagrams wait, after a back-off; the first send that works
75//! is reported as [`PeerDriverEvent::MdnsAvailable`]. The connection itself goes on over its
76//! other candidates, or fails as ICE does.
77//!
78//! With `QueryAndGather` the driver binds the mDNS sockets before it adds the first host
79//! candidates and tells the connection for which address families it has one
80//! (`RTCPeerConnection::set_multicast_dns_publishing`): a host address of a family without one
81//! cannot have its name published (draft-ietf-mmusic-mdns-ice-candidates section 3.1.1 step
82//! 4), and its candidates go out under a `.local` name that is not published, or not at all
83//! when the connection fails closed (`SettingEngineBuilder::with_multicast_dns_fail_closed`).
84//! [`PeerDriverConfig::mdns_sockets`] `false` binds none.
85//!
86//! Every mDNS datagram takes one message from a budget shared by every driver of the process
87//! ([`process_mdns_rate_limit`], unless [`PeerDriverConfig::mdns_rate_limit`] names another):
88//! draft-ietf-mmusic-mdns-ice-candidates section 7.1 requires "an implementation-wide rate
89//! limit" over the mDNS queries and responses of all connections. A datagram the budget refuses
90//! waits in the driver and leaves, in order, when the budget has room.
91//!
92//! # The loop
93//!
94//! ```text
95//! let mut driver = PeerDriver::new(pc, PeerDriverConfig::on(vec![ip]));
96//! // offer / answer through the application's signalling, on driver.pc_mut();
97//! // after the first local description, the driver gathers by itself;
98//! loop {
99//!     driver.step(Duration::from_millis(20)).await?;
100//!     while let Some(event) = driver.poll_event() {
101//!         // signal OnIceCandidateEvent candidates to the peer (the end-of-candidates one
102//!         // too: without it the peer's transport is "disconnected", never "failed", when
103//!         // the path is lost), answer negotiation-needed, ...
104//!     }
105//!     while let Some(read) = driver.pc_mut().poll_read() { /* media, data channels */ }
106//! }
107//! ```
108
109use crate::mdns_io::{MDNS_MAX_DATAGRAM, MdnsEgress, mdns_v4, mdns_v6};
110pub use crate::mdns_io::{
111    MDNS_MULTICAST_IPV6, process_mdns_rate_limit, set_process_mdns_rate_limit,
112};
113use crate::runtime::{self, AsyncUdpSocket, JoinHandle, Runtime, Transmit};
114use crate::sockets::{self, PortRange};
115use crate::{DriverConfig, DriverInput, StreamDriver};
116use bytes::BytesMut;
117use rtci::ice::mdns::{MulticastDnsMode, MulticastDnsPublishing};
118use rtci::mdns::{MDNS_MULTICAST_IPV4, MDNS_PORT, MdnsRateLimit};
119use rtci::peer_connection::RTCPeerConnection;
120use rtci::peer_connection::event::{
121    RTCLocalCandidatesNeededEvent, RTCLocalCandidatesNeededReason, RTCPeerConnectionEvent,
122    RTCTransportEventKind,
123};
124use rtci::peer_connection::state::{RTCIceGatheringState, RTCSignalingState};
125use rtci::peer_connection::transport::{
126    CandidateConfig, CandidateHostConfig, RTCIceCandidate, RTCIceCandidateInit, RTCIceProtocol,
127    RTCIceTransportState, RTCTransportId,
128};
129use rtci::sansio::Protocol;
130use rtci::shared::error::{Error, IoError, Result};
131use rtci::shared::{TaggedBytesMut, TransportContext, TransportProtocol};
132use std::collections::{HashSet, VecDeque};
133use std::future::Future;
134use std::io;
135use std::net::{IpAddr, SocketAddr};
136use std::sync::Arc;
137use std::sync::atomic::{AtomicU64, Ordering};
138use std::task::Poll;
139use std::time::{Duration, Instant};
140
141/// A datagram a socket of the driver received: its local address, the sender, the bytes.
142type Received = (SocketAddr, SocketAddr, Vec<u8>);
143
144/// What a [`PeerDriver`] binds.
145#[derive(Debug, Clone)]
146pub struct PeerDriverConfig {
147    /// The local addresses that get a host candidate: one UDP socket per address for each
148    /// transport.
149    pub addresses: Vec<IpAddr>,
150    /// The UDP sockets take a port of this range (any free port without one). A port the
151    /// host refuses to applications is skipped like a port in use
152    /// ([`sockets::bind_udp_in_range`]).
153    pub udp_port_range: Option<PortRange>,
154    /// The engine's TCP sockets (ICE-TCP, TURN over TCP and TLS), with their port range.
155    pub streams: DriverConfig,
156    /// How long a previous socket stays open after its transport selected a pair on a new one:
157    /// the peer may still send to the previous address until its own selection switches
158    /// (each side selects on its own), and those packets must not be lost. 5 seconds by
159    /// default.
160    pub retired_socket_linger: Duration,
161    /// The budget the connection's mDNS datagrams take from
162    /// (draft-ietf-mmusic-mdns-ice-candidates section 7.1). `None`, the default: the one of
163    /// the process, [`process_mdns_rate_limit`], shared by every driver that has none named
164    /// (on a runtime with a virtual clock, [`Runtime::virtual_clock`], one of the driver's own).
165    /// A limit given here is shared by the drivers given clones of it.
166    pub mdns_rate_limit: Option<MdnsRateLimit>,
167    /// Whether the driver binds the host's mDNS sockets (`true` by default). `false`: it
168    /// binds none, its connection's mDNS datagrams are unsent, and the connection is told it
169    /// can publish no name (`RTCPeerConnection::set_multicast_dns_publishing`), as when the
170    /// host refuses the sockets.
171    pub mdns_sockets: bool,
172    /// On Windows, whether the driver takes part in IPv4 mDNS on loopback addresses of
173    /// [`addresses`](Self::addresses): joins 224.0.0.251 on the loopback interface and sends the
174    /// messages about a loopback address's name there. `false` by default: on Windows mDNS sent
175    /// on loopback leaves the group's destination-cache route on loopback for every process of
176    /// the host after this one has exited (see the [module documentation](self)), so loopback
177    /// addresses get no mDNS and their `.local` names are not published. `true` does what other
178    /// systems always do, with one warning per process. Ignored on other systems.
179    pub mdns_on_loopback_on_windows: bool,
180}
181
182impl PeerDriverConfig {
183    /// Host candidates on `addresses`, any free port. With a loopback address and mDNS on
184    /// Windows, see the module documentation: mDNS sent on loopback leaves a stale
185    /// destination-cache route for the group after the process, so by default the driver sends
186    /// none there ([`mdns_on_loopback_on_windows`](Self::mdns_on_loopback_on_windows)).
187    pub fn on(addresses: Vec<IpAddr>) -> Self {
188        Self {
189            addresses,
190            udp_port_range: None,
191            streams: DriverConfig::default(),
192            retired_socket_linger: Duration::from_secs(5),
193            mdns_rate_limit: None,
194            mdns_sockets: true,
195            mdns_on_loopback_on_windows: false,
196        }
197    }
198
199    /// Whether this configuration keeps IPv4 mDNS off loopback addresses on this system: on
200    /// Windows unless [`mdns_on_loopback_on_windows`](Self::mdns_on_loopback_on_windows).
201    fn skips_loopback_mdns_v4(&self) -> bool {
202        cfg!(windows) && !self.mdns_on_loopback_on_windows
203    }
204
205    /// The budget this configuration's mDNS takes from: the one named, or the process's.
206    pub fn mdns_rate_limit(&self) -> MdnsRateLimit {
207        self.mdns_rate_limit
208            .clone()
209            .unwrap_or_else(process_mdns_rate_limit)
210    }
211}
212
213/// Why the driver's mDNS of one address family stopped: what [`PeerDriverEvent::MdnsUnavailable`]
214/// tells the application.
215#[derive(Debug, Clone, PartialEq, Eq)]
216pub struct MdnsFailure {
217    /// The family: IPv6 (`true`) or IPv4.
218    pub ipv6: bool,
219    /// What failed.
220    pub stage: MdnsStage,
221    /// The operating system's error.
222    pub kind: io::ErrorKind,
223    /// Its code, where it has one (`EHOSTUNREACH`, `WSAENETUNREACH`, ...).
224    pub os_error: Option<i32>,
225    /// Its text.
226    pub message: String,
227}
228
229impl MdnsFailure {
230    fn new(ipv6: bool, stage: MdnsStage, error: &io::Error) -> Self {
231        Self {
232            ipv6,
233            stage,
234            kind: error.kind(),
235            os_error: error.raw_os_error(),
236            message: error.to_string(),
237        }
238    }
239}
240
241/// What failed in a [`MdnsFailure`].
242#[derive(Debug, Clone, Copy, PartialEq, Eq)]
243pub enum MdnsStage {
244    /// The mDNS socket could not be bound or joined to the group.
245    Bind,
246    /// The socket is bound but the system refuses to send to the group (no multicast route;
247    /// on a Mac, an application without the Local Network permission).
248    Send,
249}
250
251/// Something the driver itself reports to the application ([`PeerDriver::poll_driver_event`]),
252/// beside the connection's own events.
253#[derive(Debug, Clone, PartialEq, Eq)]
254pub enum PeerDriverEvent {
255    /// The driver cannot send mDNS for a family: the socket could not be bound, or the system
256    /// refused its sends. Told once until it works again. Its names are no longer published
257    /// (`RTCPeerConnection::set_multicast_dns_publishing`) for the candidates gathered next,
258    /// and the peer's `.local` names of that family will not resolve: the connection goes on
259    /// over its other candidates, or fails as ICE does. The driver tries again at the next
260    /// gathering and, while datagrams wait, after a back-off (1 s, doubling to 60 s).
261    MdnsUnavailable(MdnsFailure),
262    /// mDNS of the family works again (a datagram was sent after a failure).
263    MdnsAvailable {
264        /// The family: IPv6 (`true`) or IPv4.
265        ipv6: bool,
266    },
267}
268
269/// The first wait before the driver tries an mDNS socket again after a failure.
270const MDNS_RETRY_FIRST: Duration = Duration::from_secs(1);
271/// The longest wait between two tries.
272const MDNS_RETRY_MAX: Duration = Duration::from_secs(60);
273/// How many sends in a row may fail before the family is declared unavailable (an error that
274/// says there is no route, or no permission, does it at once).
275const MDNS_FAILURES_BEFORE_UNAVAILABLE: u32 = 3;
276/// How many received mDNS datagrams wait for the driver at most; past it the oldest is
277/// dropped ([`PeerDriver::mdns_datagrams_dropped`]): any host on the link can send mDNS, and a
278/// driver that is not stepped must not grow with it.
279const MAX_QUEUED_MDNS_RECEIVED: usize = 256;
280
281/// One family's mDNS socket, and what the driver knows of it.
282struct MdnsFamily {
283    socket: Option<(Arc<dyn AsyncUdpSocket>, Box<dyn JoinHandle>)>,
284    /// One configured address per interface: what a message that names no address of its
285    /// own (a query) leaves from, once on each interface (RFC 6762 section 14).
286    links: Vec<IpAddr>,
287    /// Sends that failed in a row.
288    failures: u32,
289    /// Reported unavailable ([`PeerDriverEvent::MdnsUnavailable`]) and not yet working again.
290    unavailable: bool,
291    /// Not tried again before.
292    retry_at: Option<Instant>,
293    backoff: Duration,
294    /// Never bound: every configured address of the family is a loopback one the driver keeps
295    /// mDNS off ([`PeerDriverConfig::mdns_on_loopback_on_windows`]).
296    off: bool,
297}
298
299impl MdnsFamily {
300    fn new(links: Vec<IpAddr>) -> Self {
301        Self {
302            off: false,
303            socket: None,
304            links,
305            failures: 0,
306            unavailable: false,
307            retry_at: None,
308            backoff: MDNS_RETRY_FIRST,
309        }
310    }
311
312    fn close(&mut self) {
313        if let Some((_, reader)) = self.socket.take() {
314            reader.abort();
315        }
316    }
317}
318
319impl Drop for MdnsFamily {
320    fn drop(&mut self) {
321        self.close();
322    }
323}
324
325/// The host's mDNS sockets of a driver, bound at the connection's first mDNS datagram.
326struct MdnsSockets {
327    v4: MdnsFamily,
328    v6: MdnsFamily,
329    /// For an IPv6 address, the configured IPv4 address of the same interface: an IPv6
330    /// record's messages also leave on the IPv4 group of its own interface.
331    companions: Vec<(IpAddr, IpAddr)>,
332    /// IPv4 mDNS is kept off loopback addresses: a message about one is sent nowhere
333    /// ([`PeerDriverConfig::mdns_on_loopback_on_windows`]).
334    skips_loopback_v4: bool,
335}
336
337impl MdnsSockets {
338    /// Where one mDNS datagram of the engine goes: (destination, address it leaves from).
339    /// The engine names the address of the record a message is about (its own interface's,
340    /// RFC 6762 section 14), or the unspecified address for a query; it addresses every
341    /// multicast message to the IPv4 group. An IPv4 record's message leaves from its address
342    /// on the IPv4 group; an IPv6 record's from its address on the IPv6 group, and from the
343    /// IPv4 address of its interface on the IPv4 group where the driver has one (resolvers
344    /// that listen on one family); a query once from each interface, on each family's group.
345    /// A multicast message about an IPv4 loopback address goes nowhere when
346    /// [`skips_loopback_v4`](Self::skips_loopback_v4).
347    fn routes(&self, from: IpAddr, to: SocketAddr) -> Vec<(SocketAddr, Option<IpAddr>)> {
348        let group_v4 = SocketAddr::new(MDNS_MULTICAST_IPV4.into(), MDNS_PORT);
349        let group_v6 = SocketAddr::new(MDNS_MULTICAST_IPV6.into(), MDNS_PORT);
350        if !to.ip().is_multicast() {
351            // A unicast reply to an asker (RFC 6762 sections 5.5, 6.7).
352            let source = (!from.is_unspecified() && from.is_ipv4() == to.is_ipv4()).then_some(from);
353            return vec![(to, source)];
354        }
355        if self.skips_loopback_v4 && from.is_loopback() && from.is_ipv4() {
356            // Not on the group from loopback (Windows: the destination-cache route it leaves).
357            return vec![];
358        }
359        if from.is_unspecified() {
360            let routes: Vec<_> = (self.v4.links.iter().map(|ip| (group_v4, Some(*ip))))
361                .chain(self.v6.links.iter().map(|ip| (group_v6, Some(*ip))))
362                .collect();
363            if routes.is_empty() {
364                return vec![(to, None)];
365            }
366            return routes;
367        }
368        match from {
369            IpAddr::V4(_) => vec![(group_v4, Some(from))],
370            IpAddr::V6(_) => std::iter::once((group_v6, Some(from)))
371                .chain(
372                    self.companions
373                        .iter()
374                        .filter(|(v6, _)| *v6 == from)
375                        .map(|(_, v4)| (group_v4, Some(*v4))),
376                )
377                .collect(),
378        }
379    }
380}
381
382/// `addresses` with one per interface (the first of each), of one family. An address on no
383/// interface the host lists (a mock network's) counts as an interface of its own.
384fn one_per_interface(addresses: &[IpAddr], ipv4: bool) -> Vec<IpAddr> {
385    let mut seen = HashSet::new();
386    addresses
387        .iter()
388        .copied()
389        .filter(|ip| ip.is_ipv4() == ipv4 && !ip.is_unspecified())
390        .filter(|ip| seen.insert(runtime::interface_name(*ip).unwrap_or_else(|| ip.to_string())))
391        .collect()
392}
393
394/// The addresses whose interfaces get mDNS: `addresses` without the IPv4 loopback ones when
395/// `skips_loopback_v4` ([`PeerDriverConfig::mdns_on_loopback_on_windows`]).
396fn mdns_addresses(addresses: &[IpAddr], skips_loopback_v4: bool) -> Vec<IpAddr> {
397    addresses
398        .iter()
399        .copied()
400        .filter(|ip| !(skips_loopback_v4 && ip.is_ipv4() && ip.is_loopback()))
401        .collect()
402}
403
404/// Says once per process that IPv4 mDNS is kept off loopback on Windows.
405fn note_loopback_mdns_skipped() {
406    static ONCE: std::sync::Once = std::sync::Once::new();
407    ONCE.call_once(|| {
408        log::info!(
409            "no IPv4 mDNS on loopback on Windows: it would leave the group's destination-cache \
410             route on loopback for the whole host (PeerDriverConfig::mdns_on_loopback_on_windows)"
411        );
412    });
413}
414
415/// One UDP socket of the connection, with the reader that hands its datagrams to the driver.
416struct HostSocket {
417    socket: Arc<dyn AsyncUdpSocket>,
418    local: SocketAddr,
419    /// The section its candidate was added for.
420    mid: String,
421    /// Set when the engine refused its address for `transport` (`OnLocalCandidatesNeeded`):
422    /// it is closed once that transport has selected a pair on another socket, or closed.
423    retired_for: Option<RTCTransportId>,
424    /// Once its transport selected a pair on another socket: when it is closed.
425    close_at: Option<Instant>,
426    /// Counted in [`PeerDriver::unmarked_sockets`] (the platform refused to mark it: its
427    /// datagrams leave unmarked).
428    counted_unmarked: bool,
429    reader: Box<dyn JoinHandle>,
430}
431
432impl Drop for HostSocket {
433    fn drop(&mut self) {
434        self.reader.abort();
435    }
436}
437
438/// Drives an `RTCPeerConnection` over sockets of its own (see the [module documentation](self)).
439pub struct PeerDriver {
440    runtime: Arc<dyn Runtime>,
441    pc: RTCPeerConnection,
442    streams: StreamDriver,
443    config: PeerDriverConfig,
444    sockets: Vec<HostSocket>,
445    datagrams_tx: async_channel::Sender<Received>,
446    datagrams: async_channel::Receiver<Received>,
447    /// What the mDNS sockets received: bounded, the oldest dropped.
448    mdns_tx: async_channel::Sender<Received>,
449    mdns_rx: async_channel::Receiver<Received>,
450    /// Received mDNS datagrams dropped from a full queue ([`Self::mdns_datagrams_dropped`]).
451    mdns_dropped: Arc<AtomicU64>,
452    /// The driver's own events ([`Self::poll_driver_event`]).
453    driver_events: VecDeque<PeerDriverEvent>,
454    /// mDNS sends the system refused ([`Self::mdns_send_failures`]).
455    mdns_send_failures: u64,
456    /// mDNS socket binds that failed ([`Self::mdns_bind_failures`]).
457    mdns_bind_failures: u64,
458    /// [`Self::shutdown`] ran: nothing is left for `Drop` to do.
459    shut_down: bool,
460    /// The engine's events, for the application, after the driver had its look.
461    events: VecDeque<RTCPeerConnectionEvent>,
462    /// The transports whose generation the driver gathered for on an
463    /// `OnLocalCandidatesNeeded`: their `gatheringstatechange` that follows needs nothing.
464    gathered: HashSet<RTCTransportId>,
465    /// Datagrams the engine wrote that no socket sent ([`Self::unsent_datagrams`]).
466    unsent: u64,
467    /// The connection's mDNS datagrams, held to the budget.
468    mdns_egress: MdnsEgress,
469    /// `None` until the connection writes its first mDNS datagram, or, with
470    /// `QueryAndGather`, until it gathers.
471    mdns_sockets: Option<MdnsSockets>,
472    /// What the connection was last told about the families its names can be published for.
473    mdns_publishing_told: Option<MulticastDnsPublishing>,
474    /// mDNS datagrams sent ([`Self::mdns_datagrams_sent`]).
475    mdns_sent: u64,
476    /// mDNS datagrams received ([`Self::mdns_datagrams_received`]).
477    mdns_received: u64,
478    /// Sockets on which the platform refused a TOS / Traffic Class ([`Self::unmarked_sockets`]).
479    unmarked_sockets: u64,
480    /// Datagrams sent, by the TOS / Traffic Class their socket had ([`Self::sent_by_traffic_class`]).
481    sent_by_traffic_class: std::collections::BTreeMap<u8, u64>,
482}
483
484impl PeerDriver {
485    /// A driver for `pc` on tokio ([`runtime::TokioRuntime::new`]: it must be used inside a
486    /// tokio runtime), with no socket yet: it binds when the connection's first local
487    /// description begins gathering. Feature `runtime-tokio` (on by default).
488    #[cfg(feature = "runtime-tokio")]
489    pub fn new(pc: RTCPeerConnection, config: PeerDriverConfig) -> Self {
490        Self::with_runtime(Arc::new(runtime::TokioRuntime::new()), pc, config)
491    }
492
493    /// A driver for `pc` on `runtime`, with no socket yet: it binds when the connection's first
494    /// local description begins gathering. Every time it gives the connection is the
495    /// runtime's ([`Runtime::now`]).
496    pub fn with_runtime(
497        runtime: Arc<dyn Runtime>,
498        pc: RTCPeerConnection,
499        config: PeerDriverConfig,
500    ) -> Self {
501        // The driver hands each mDNS datagram over with its destination (the group's where it
502        // knows the datagram arrived there: RFC 6762 section 11 then deems it on the link).
503        let mut pc = pc;
504        pc.set_multicast_dns_destination_reported(true);
505        let virtual_clock = runtime.virtual_clock();
506        let (datagrams_tx, datagrams) = async_channel::unbounded();
507        let (mdns_tx, mdns_rx) = async_channel::bounded(MAX_QUEUED_MDNS_RECEIVED);
508        Self {
509            streams: StreamDriver::with_runtime(runtime.clone(), config.streams),
510            runtime,
511            pc,
512            sockets: Vec::new(),
513            datagrams_tx,
514            datagrams,
515            mdns_tx,
516            mdns_rx,
517            mdns_dropped: Arc::new(AtomicU64::new(0)),
518            driver_events: VecDeque::new(),
519            mdns_send_failures: 0,
520            mdns_bind_failures: 0,
521            shut_down: false,
522            events: VecDeque::new(),
523            gathered: HashSet::new(),
524            unsent: 0,
525            // A driver on a virtual clock does not share the process's budget, whose times
526            // are the wall clock's: a mock clock ahead would leave it empty for real drivers,
527            // one behind would never see it refill.
528            mdns_egress: MdnsEgress::new(match &config.mdns_rate_limit {
529                None if virtual_clock => MdnsRateLimit::default(),
530                _ => config.mdns_rate_limit(),
531            }),
532            mdns_sockets: None,
533            mdns_publishing_told: None,
534            mdns_sent: 0,
535            mdns_received: 0,
536            config,
537            unmarked_sockets: 0,
538            sent_by_traffic_class: std::collections::BTreeMap::new(),
539        }
540    }
541
542    /// The runtime the driver runs on.
543    pub fn runtime(&self) -> &Arc<dyn Runtime> {
544        &self.runtime
545    }
546
547    /// The peer connection.
548    pub fn pc(&self) -> &RTCPeerConnection {
549        &self.pc
550    }
551
552    /// The peer connection, for signalling, media and data channels. Call
553    /// [`flush`](Self::flush) (or [`step`](Self::step)) after changing it, so that what it
554    /// wants to send leaves and the driver sees its events.
555    pub fn pc_mut(&mut self) -> &mut RTCPeerConnection {
556        &mut self.pc
557    }
558
559    /// The local addresses of the UDP sockets open, the previous ones still waiting for a new
560    /// pair included.
561    pub fn local_addresses(&self) -> Vec<SocketAddr> {
562        self.sockets.iter().map(|s| s.local).collect()
563    }
564
565    /// How many datagrams the connection wrote that were not sent: from a local address with
566    /// no open socket (one closed already), or refused by the socket (its send buffer full:
567    /// UDP drops them, as the wire would). Counted so that none is lost unseen.
568    pub fn unsent_datagrams(&self) -> u64 {
569        self.unsent
570    }
571
572    /// How many mDNS datagrams the driver sent for the connection (queries, probes,
573    /// announcements, answers, goodbyes), after the budget let them go.
574    pub fn mdns_datagrams_sent(&self) -> u64 {
575        self.mdns_sent
576    }
577
578    /// How many datagrams the driver's mDNS sockets received and handed to the connection
579    /// (its own looped back by the host included).
580    pub fn mdns_datagrams_received(&self) -> u64 {
581        self.mdns_received
582    }
583
584    /// How many mDNS sends the system refused (to a group or an asker): a host without a
585    /// multicast route, a Mac application without the Local Network permission.
586    pub fn mdns_send_failures(&self) -> u64 {
587        self.mdns_send_failures
588    }
589
590    /// How many times an mDNS socket could not be bound or joined.
591    pub fn mdns_bind_failures(&self) -> u64 {
592        self.mdns_bind_failures
593    }
594
595    /// How many received mDNS datagrams were dropped because the driver was not stepped fast
596    /// enough (the oldest go first; at most 256 wait).
597    pub fn mdns_datagrams_dropped(&self) -> u64 {
598        self.mdns_dropped.load(Ordering::Relaxed)
599    }
600
601    /// Whether the driver can send mDNS for a family now: its socket is bound and its sends
602    /// have not been refused since (see [`PeerDriverEvent::MdnsUnavailable`]).
603    pub fn mdns_available(&self, ipv6: bool) -> bool {
604        self.mdns_sockets.as_ref().is_some_and(|m| {
605            let family = if ipv6 { &m.v6 } else { &m.v4 };
606            family.socket.is_some() && !family.unavailable
607        })
608    }
609
610    /// The next event of the driver itself (mDNS that cannot be sent, and that works again).
611    pub fn poll_driver_event(&mut self) -> Option<PeerDriverEvent> {
612        self.driver_events.pop_front()
613    }
614
615    /// How many sockets the platform refused a TOS / Traffic Class on: their datagrams leave
616    /// without the DSCP the engine asked for (Windows without qWAVE, an IPv6 socket where the
617    /// platform has no `IPV6_TCLASS`; see [`sockets::set_traffic_class`]).
618    pub fn unmarked_sockets(&self) -> u64 {
619        self.unmarked_sockets
620    }
621
622    /// How many datagrams were sent with each TOS / Traffic Class byte set on their socket
623    /// (a socket the platform refused counts under 0).
624    pub fn sent_by_traffic_class(&self) -> &std::collections::BTreeMap<u8, u64> {
625        &self.sent_by_traffic_class
626    }
627
628    /// The TOS / Traffic Class byte the operating system reports for the UDP socket bound to
629    /// `local` (`getsockopt` of `IP_TOS` / `IPV6_TCLASS`): what its next datagram carries.
630    /// `None` without such a socket.
631    pub fn socket_traffic_class(&self, local: SocketAddr) -> Option<io::Result<u32>> {
632        let host = self.sockets.iter().find(|s| s.local == local)?;
633        Some(host.socket.traffic_class())
634    }
635
636    /// The next event of the connection. The driver has already done what is its to do
637    /// (gathering on `OnLocalCandidatesNeeded` and when a transport begins gathering, closing
638    /// the previous sockets on a new selected pair, ending each generation's gathering with
639    /// its end-of-candidates); the application signals the candidates of
640    /// `OnIceCandidateEvent` to the peer, the end-of-candidates candidate included (W3C
641    /// webrtc-pc 5.6.4: the peer's transport is "failed" only once it has it, "disconnected"
642    /// until then), and handles the rest. The driver tears nothing down on "failed" or
643    /// "disconnected": an application that does not relay the end-of-candidates candidate, or
644    /// whose peer never sends its own, needs a timer of its own to restart or close.
645    pub fn poll_event(&mut self) -> Option<RTCPeerConnectionEvent> {
646        self.events.pop_front()
647    }
648
649    /// Hands what the connection wants to send to the sockets and the stream driver, and
650    /// reacts to its events, until nothing is left.
651    ///
652    /// # Errors
653    ///
654    /// A socket that cannot be bound for a transport that needs one, or a candidate the
655    /// connection refuses.
656    pub fn flush(&mut self) -> Result<()> {
657        loop {
658            let mut progress = false;
659            while let Some(command) = self.pc.poll_stream_command() {
660                self.streams.execute(command);
661                progress = true;
662            }
663            while let Some(transmit) = self.pc.poll_stream_transmit() {
664                self.streams.write(transmit);
665                progress = true;
666            }
667            while let Some(datagram) = self.pc.poll_write() {
668                self.send(datagram);
669                progress = true;
670            }
671            while let Some(event) = self.pc.poll_event() {
672                self.on_event(&event)?;
673                self.events.push_back(event);
674                progress = true;
675            }
676            if !progress {
677                self.send_mdns(self.runtime.now());
678                return Ok(());
679            }
680        }
681    }
682
683    /// Ends the connection and the driver in order: closes the connection, sends what it
684    /// writes on closing (the mDNS goodbyes of its published names, RFC 6762 section 10.1:
685    /// records with TTL 0, so that the link's caches drop them at once instead of holding them
686    /// for their 120 s; draft-ietf-mmusic-mdns-ice-candidates section 7.1), waiting up to
687    /// `linger` for the mDNS budget to let them go, then closes every socket of the driver,
688    /// which leaves the mDNS groups. The driver is not to be stepped afterwards.
689    ///
690    /// Dropping a driver that was not shut down does what can be done without waiting (see
691    /// [`Drop`](#impl-Drop-for-PeerDriver)).
692    ///
693    /// # Errors
694    ///
695    /// As [`flush`](Self::flush).
696    pub async fn shutdown(&mut self, linger: Duration) -> Result<()> {
697        // The connection may be closed already: the application's own `close()`.
698        let _ = self.pc.close();
699        self.shut_down = true;
700        let until = self.runtime.now() + linger;
701        loop {
702            self.flush()?;
703            let now = self.runtime.now();
704            let Some(next) = self.mdns_egress.next_ready(now) else {
705                break;
706            };
707            if now >= until {
708                break;
709            }
710            self.runtime.sleep_until(next.min(until)).await;
711        }
712        // Closing a socket leaves its groups (the system drops its memberships).
713        self.mdns_sockets = None;
714        self.sockets.clear();
715        Ok(())
716    }
717
718    /// One round: flushes, then waits up to `wait` (less when a timer of the connection is due
719    /// first) for a datagram, a stream input or the timer, hands it over, and flushes again.
720    ///
721    /// # Errors
722    ///
723    /// As [`flush`](Self::flush).
724    pub async fn step(&mut self, wait: Duration) -> Result<()> {
725        self.flush()?;
726        let now = self.runtime.now();
727        let deadline = self
728            .pc
729            .poll_timeout()
730            .into_iter()
731            .chain(self.mdns_egress.next_ready(now))
732            .fold(now + wait, Instant::min)
733            .max(now);
734        let woke = {
735            let mut datagram = std::pin::pin!(self.datagrams.recv());
736            let mut mdns = std::pin::pin!(self.mdns_rx.recv());
737            let mut input = std::pin::pin!(self.streams.next());
738            let mut timer = self.runtime.sleep_until(deadline);
739            std::future::poll_fn(|cx| {
740                if let Poll::Ready(Ok(received)) = datagram.as_mut().poll(cx) {
741                    return Poll::Ready(Woke::Datagram(received));
742                }
743                if let Poll::Ready(Ok(received)) = mdns.as_mut().poll(cx) {
744                    return Poll::Ready(Woke::Mdns(received));
745                }
746                if let Poll::Ready(input) = input.as_mut().poll(cx) {
747                    return Poll::Ready(Woke::Stream(input));
748                }
749                timer.as_mut().poll(cx).map(|()| Woke::Timer)
750            })
751            .await
752        };
753        match woke {
754            Woke::Datagram((local, peer, data)) => {
755                self.feed(local, peer, data);
756                while let Ok((local, peer, data)) = self.datagrams.try_recv() {
757                    self.feed(local, peer, data);
758                }
759            }
760            Woke::Mdns((local, peer, data)) => {
761                self.mdns_received += 1;
762                self.feed(local, peer, data);
763                while let Ok((local, peer, data)) = self.mdns_rx.try_recv() {
764                    self.mdns_received += 1;
765                    self.feed(local, peer, data);
766                }
767            }
768            Woke::Stream(input) => self.feed_stream(input),
769            Woke::Timer => {}
770        }
771        // The engine's timers; one that fails is the connection's to report (its states).
772        let now = self.runtime.now();
773        let _ = self.pc.handle_timeout(now);
774        self.sockets
775            .retain(|s| s.close_at.is_none_or(|close_at| close_at > now));
776        self.flush()
777    }
778
779    fn feed(&mut self, local: SocketAddr, peer: SocketAddr, data: Vec<u8>) {
780        // A datagram the engine cannot take (a stray, a late one) is its business, not the
781        // driver's: it goes on.
782        let _ = self.pc.handle_read(TaggedBytesMut {
783            now: self.runtime.now(),
784            transport: TransportContext {
785                local_addr: local,
786                peer_addr: peer,
787                ecn: None,
788                transport_protocol: TransportProtocol::UDP,
789            },
790            message: BytesMut::from(&data[..]),
791        });
792    }
793
794    fn feed_stream(&mut self, input: DriverInput) {
795        let now = self.runtime.now();
796        match input {
797            DriverInput::Event(event) => {
798                let _ = self.pc.handle_stream_event(now, event);
799            }
800            DriverInput::Read { id, data } => {
801                let _ = self.pc.handle_stream_read(now, id, &data);
802            }
803            DriverInput::Accepted(accepted) => {
804                if let Some(id) = self.pc.handle_stream_accepted(
805                    now,
806                    accepted.listener,
807                    accepted.local,
808                    accepted.remote,
809                ) {
810                    self.streams.adopt(id, accepted);
811                }
812            }
813        }
814    }
815
816    /// Sends a datagram of the engine on the socket of its local address, marked with the
817    /// DSCP and ECN codepoint the engine gives it (`RTCPeerConnection::traffic_class`: RFC 8837
818    /// Table 1 by flow and priority, RFC 8835 section 4.2): the socket's `IP_TOS` /
819    /// `IPV6_TCLASS` is set before the datagram when it differs from the last one set.
820    fn send(&mut self, datagram: TaggedBytesMut) {
821        if datagram.transport.transport_protocol != TransportProtocol::UDP {
822            return;
823        }
824        let local = datagram.transport.local_addr;
825        if local.port() == MDNS_PORT && !self.sockets.iter().any(|s| s.local == local) {
826            if !self.mdns_egress.push(datagram) {
827                self.unsent += 1;
828            }
829            return;
830        }
831        let traffic_class = self.pc.traffic_class(&datagram);
832        let Some(host) = self.sockets.iter_mut().find(|s| s.local == local) else {
833            self.unsent += 1;
834            return;
835        };
836        // UDP: a datagram the socket cannot take now is lost, as on the wire.
837        let sent = host
838            .socket
839            .try_send(&Transmit {
840                destination: datagram.transport.peer_addr,
841                contents: &datagram.message,
842                traffic_class,
843                segment_size: None,
844                source: None,
845            })
846            .is_ok();
847        // The platform does not mark (RFC 8835 4.2: "appropriate to depart ... on platforms
848        // where QoS marking is not implemented"): counted once per socket.
849        let unmarked = host.socket.unmarked();
850        if unmarked && !host.counted_unmarked {
851            host.counted_unmarked = true;
852            self.unmarked_sockets += 1;
853        }
854        if sent {
855            let applied = if unmarked { 0 } else { traffic_class };
856            *self.sent_by_traffic_class.entry(applied).or_default() += 1;
857        } else {
858            self.unsent += 1;
859        }
860    }
861
862    /// Sends the held mDNS datagrams the budget lets go at `now`, binding the mDNS sockets at
863    /// the first, each on the interface of the address the engine names for it
864    /// ([`MdnsSockets::routes`]). A datagram no socket could send is unsent; a send the system
865    /// refuses counts against its family ([`Self::mdns_send_result`]).
866    fn send_mdns(&mut self, now: Instant) {
867        while let Some(datagram) = self.mdns_egress.pop_ready(now) {
868            self.ensure_mdns(now, false);
869            let Some(sockets) = self.mdns_sockets.as_ref() else {
870                self.unsent += 1;
871                continue;
872            };
873            let routes = sockets.routes(
874                datagram.transport.local_addr.ip(),
875                datagram.transport.peer_addr,
876            );
877            let mut results = Vec::new();
878            for (destination, source) in routes {
879                let family = if destination.is_ipv6() {
880                    &sockets.v6
881                } else {
882                    &sockets.v4
883                };
884                if let Some((socket, _)) = &family.socket {
885                    let result = socket.try_send(&Transmit {
886                        destination,
887                        contents: &datagram.message,
888                        traffic_class: 0,
889                        segment_size: None,
890                        source,
891                    });
892                    results.push((destination.is_ipv6(), result));
893                }
894            }
895            let mut sent = false;
896            for (ipv6, result) in results {
897                sent |= self.mdns_send_result(ipv6, result, now);
898            }
899            if sent {
900                self.mdns_sent += 1;
901            } else {
902                self.unsent += 1;
903            }
904        }
905    }
906
907    /// Books one mDNS send of a family: a success makes the family available again (told
908    /// once); a refusal counts, and declares the family unavailable at once when the error
909    /// says there is no route or no permission, or after a few in a row. A full send buffer
910    /// (`WouldBlock`) is a lost datagram, as on the wire, not a failure.
911    fn mdns_send_result(&mut self, ipv6: bool, result: io::Result<usize>, now: Instant) -> bool {
912        let Some(sockets) = self.mdns_sockets.as_mut() else {
913            return false;
914        };
915        let family = if ipv6 {
916            &mut sockets.v6
917        } else {
918            &mut sockets.v4
919        };
920        match result {
921            Ok(_) => {
922                family.failures = 0;
923                if family.unavailable {
924                    family.unavailable = false;
925                    family.backoff = MDNS_RETRY_FIRST;
926                    self.driver_events
927                        .push_back(PeerDriverEvent::MdnsAvailable { ipv6 });
928                    self.refresh_mdns_publishing();
929                }
930                true
931            }
932            Err(e) if e.kind() == io::ErrorKind::WouldBlock => false,
933            Err(e) => {
934                self.mdns_send_failures += 1;
935                family.failures += 1;
936                if decisive(&e) || family.failures >= MDNS_FAILURES_BEFORE_UNAVAILABLE {
937                    self.mdns_unavailable(ipv6, MdnsStage::Send, &e, now);
938                }
939                false
940            }
941        }
942    }
943
944    /// A family's mDNS cannot be used: its socket is closed (bound again at the next try),
945    /// the next try waits a back-off, the application is told (once until it works again),
946    /// and the connection learns that the family's names cannot be published.
947    fn mdns_unavailable(&mut self, ipv6: bool, stage: MdnsStage, error: &io::Error, now: Instant) {
948        let Some(sockets) = self.mdns_sockets.as_mut() else {
949            return;
950        };
951        let family = if ipv6 {
952            &mut sockets.v6
953        } else {
954            &mut sockets.v4
955        };
956        family.close();
957        family.failures = 0;
958        family.retry_at = Some(now + family.backoff);
959        family.backoff = (family.backoff * 2).min(MDNS_RETRY_MAX);
960        if !family.unavailable {
961            family.unavailable = true;
962            self.driver_events
963                .push_back(PeerDriverEvent::MdnsUnavailable(MdnsFailure::new(
964                    ipv6, stage, error,
965                )));
966        }
967        self.refresh_mdns_publishing();
968    }
969
970    /// The host's mDNS sockets (none with [`PeerDriverConfig::mdns_sockets`] off): each family
971    /// without a socket is bound now when it never was, when `force` (a gathering), or when
972    /// its back-off has passed. Each socket is joined to its group on the interface of every
973    /// configured address of its family (RFC 6762 section 14: a name is answered, and a peer's
974    /// asked for, on the link of its address). A bind that fails is reported
975    /// ([`PeerDriverEvent::MdnsUnavailable`]) and tried again later.
976    fn ensure_mdns(&mut self, now: Instant, force: bool) {
977        let skips_loopback_v4 = self.config.skips_loopback_mdns_v4();
978        let addresses = mdns_addresses(&self.config.addresses, skips_loopback_v4);
979        if self.mdns_sockets.is_none() {
980            let mut v4 = MdnsFamily::new(one_per_interface(&addresses, true));
981            if addresses.len() < self.config.addresses.len() {
982                note_loopback_mdns_skipped();
983                // Only loopback IPv4 addresses: no IPv4 socket at all (one with no interface
984                // would join and send on the system's default one).
985                v4.off = !addresses.iter().any(IpAddr::is_ipv4);
986            }
987            let v6 = MdnsFamily::new(one_per_interface(&addresses, false));
988            let companions = v6
989                .links
990                .iter()
991                .filter_map(|ip6| {
992                    let name = runtime::interface_name(*ip6)?;
993                    let ip4 = v4
994                        .links
995                        .iter()
996                        .find(|ip4| runtime::interface_name(**ip4).as_deref() == Some(&name))?;
997                    Some((*ip6, *ip4))
998                })
999                .collect();
1000            self.mdns_sockets = Some(MdnsSockets {
1001                v4,
1002                v6,
1003                companions,
1004                skips_loopback_v4,
1005            });
1006        }
1007        if !self.config.mdns_sockets {
1008            return;
1009        }
1010        for ipv6 in [false, true] {
1011            let Some(sockets) = self.mdns_sockets.as_ref() else {
1012                return;
1013            };
1014            let family = if ipv6 { &sockets.v6 } else { &sockets.v4 };
1015            if family.off
1016                || family.socket.is_some()
1017                || !(force || family.retry_at.is_none_or(|at| now >= at))
1018            {
1019                continue;
1020            }
1021            let config = if ipv6 {
1022                mdns_v6(addresses.clone())
1023            } else {
1024                mdns_v4(addresses.clone())
1025            };
1026            let bound = self
1027                .runtime
1028                .bind_udp_multicast(&config)
1029                .and_then(|socket| Ok((socket.local_addr()?, socket)));
1030            match bound {
1031                Ok((local, socket)) => {
1032                    let tx = self.mdns_tx.clone();
1033                    let dropped = self.mdns_dropped.clone();
1034                    let reader = self.runtime.spawn(Box::pin(read_loop(
1035                        socket.clone(),
1036                        local,
1037                        true,
1038                        move |received| match tx.force_send(received) {
1039                            Ok(None) => true,
1040                            Ok(Some(_)) => {
1041                                dropped.fetch_add(1, Ordering::Relaxed);
1042                                true
1043                            }
1044                            Err(_) => false,
1045                        },
1046                        MDNS_MAX_DATAGRAM,
1047                    )));
1048                    if let Some(sockets) = self.mdns_sockets.as_mut() {
1049                        let family = if ipv6 {
1050                            &mut sockets.v6
1051                        } else {
1052                            &mut sockets.v4
1053                        };
1054                        family.socket = Some((socket, reader));
1055                    }
1056                }
1057                Err(e) => {
1058                    self.mdns_bind_failures += 1;
1059                    self.mdns_unavailable(ipv6, MdnsStage::Bind, &e, now);
1060                }
1061            }
1062        }
1063        self.refresh_mdns_publishing();
1064    }
1065
1066    /// Before the connection's host candidates, with `QueryAndGather`: binds the mDNS sockets
1067    /// (again, for a family that failed) and tells the connection for which address families
1068    /// its names can be published (draft-ietf-mmusic-mdns-ice-candidates section 3.1.1 step 4).
1069    fn prepare_mdns_publishing(&mut self) {
1070        if self.pc.multicast_dns_mode() != MulticastDnsMode::QueryAndGather {
1071            return;
1072        }
1073        let now = self.runtime.now();
1074        self.ensure_mdns(now, true);
1075        if self.mdns_publishing_told.is_none() {
1076            let publishing = self.mdns_publishing();
1077            self.mdns_publishing_told = Some(publishing);
1078            self.pc.set_multicast_dns_publishing(publishing);
1079        }
1080    }
1081
1082    /// What is actually sent: an IPv4 record's messages need the IPv4 socket; an IPv6 record's
1083    /// leave on the IPv6 group, or on the IPv4 group of its interface.
1084    fn mdns_publishing(&self) -> MulticastDnsPublishing {
1085        let usable = |f: &MdnsFamily| f.socket.is_some() && !f.unavailable;
1086        self.mdns_sockets.as_ref().map_or(
1087            MulticastDnsPublishing {
1088                ipv4: false,
1089                ipv6: false,
1090            },
1091            |m| MulticastDnsPublishing {
1092                ipv4: usable(&m.v4),
1093                ipv6: usable(&m.v6) || (usable(&m.v4) && !m.companions.is_empty()),
1094            },
1095        )
1096    }
1097
1098    /// Tells the connection again when what can be published changed, once it was told.
1099    fn refresh_mdns_publishing(&mut self) {
1100        let Some(told) = self.mdns_publishing_told else {
1101            return;
1102        };
1103        let now = self.mdns_publishing();
1104        if now != told {
1105            self.mdns_publishing_told = Some(now);
1106            self.pc.set_multicast_dns_publishing(now);
1107        }
1108    }
1109
1110    /// With `QueryAndGather`, tells the connection which of the addresses it gathers on the
1111    /// operating system flags as RFC 4941 temporary IPv6 addresses
1112    /// (`RTCPeerConnection::set_temporary_ipv6_addresses`), so that
1113    /// `with_multicast_dns_expose_temporary_ipv6_addresses` can leave those unwrapped
1114    /// (draft-ietf-mmusic-mdns-ice-candidates section 3.1.2.3). Read from the interface list
1115    /// at each gathering (`shared::ifaces::temporary_ipv6_addresses`: Linux, Android, macOS
1116    /// and iOS report the flag; Windows and other systems mark nothing); where it cannot be
1117    /// read, nothing is marked and every address stays hidden.
1118    fn mark_temporary_addresses(&mut self) {
1119        if self.pc.multicast_dns_mode() != MulticastDnsMode::QueryAndGather {
1120            return;
1121        }
1122        let temporary: Vec<std::net::Ipv6Addr> = shared::ifaces::temporary_ipv6_addresses()
1123            .unwrap_or_default()
1124            .into_iter()
1125            .filter(|t| self.config.addresses.contains(&IpAddr::V6(*t)))
1126            .collect();
1127        self.pc.set_temporary_ipv6_addresses(temporary);
1128    }
1129
1130    fn on_event(&mut self, event: &RTCPeerConnectionEvent) -> Result<()> {
1131        match event {
1132            RTCPeerConnectionEvent::OnLocalCandidatesNeeded(needed) => {
1133                self.on_candidates_needed(needed)
1134            }
1135            RTCPeerConnectionEvent::OnSignalingStateChangeEvent(RTCSignalingState::Stable) => {
1136                self.match_sockets_to_candidates();
1137                Ok(())
1138            }
1139            RTCPeerConnectionEvent::OnTransportEvent(event) => match &event.event {
1140                RTCTransportEventKind::GatheringStateChange(RTCIceGatheringState::Gathering) => {
1141                    self.on_gathering_begins(event.ice_transport, event.dtls_transport)
1142                }
1143                RTCTransportEventKind::SelectedCandidatePairChange(pair) => {
1144                    let local = pair.local();
1145                    let on_retired = self.sockets.iter().any(|s| {
1146                        s.retired_for.is_some() && names_socket(&local.address, local.port, s.local)
1147                    });
1148                    if !on_retired {
1149                        self.release_after_linger(event.ice_transport);
1150                    }
1151                    Ok(())
1152                }
1153                RTCTransportEventKind::IceStateChange(RTCIceTransportState::Closed) => {
1154                    self.release(event.ice_transport);
1155                    Ok(())
1156                }
1157                _ => Ok(()),
1158            },
1159            _ => Ok(()),
1160        }
1161    }
1162
1163    /// `OnLocalCandidatesNeeded`: new sockets for the transport, or (`DiscardedBySetting`,
1164    /// no address refused) the same sockets' candidates again.
1165    fn on_candidates_needed(&mut self, needed: &RTCLocalCandidatesNeededEvent) -> Result<()> {
1166        let Some(mid) = needed.mids.first().cloned() else {
1167            return Ok(());
1168        };
1169        let index = needed.sdp_mline_index;
1170        self.gathered.insert(needed.ice_transport);
1171        self.mark_temporary_addresses();
1172        if !needed.reason.needs_new_addresses() {
1173            let on: Vec<SocketAddr> = self
1174                .sockets
1175                .iter()
1176                .filter(|s| s.retired_for.is_none() && needed.mids.contains(&s.mid))
1177                .map(|s| s.local)
1178                .collect();
1179            if !on.is_empty() {
1180                for local in on {
1181                    self.pc
1182                        .add_local_candidate(host_candidate(local, &mid, index)?)?;
1183                }
1184                return self.end_of_candidates(&mid, index);
1185            }
1186            return self.gather_section(&mid, index);
1187        }
1188        for host in self
1189            .sockets
1190            .iter_mut()
1191            .filter(|s| needed.refused_addresses.contains(&s.local))
1192        {
1193            host.retired_for = Some(needed.ice_transport);
1194        }
1195        if needed.reason == RTCLocalCandidatesNeededReason::TransportReplaced {
1196            // The transport they served is closed: nothing travels over them any more.
1197            self.release(needed.ice_transport);
1198        }
1199        self.gather_section(&mid, index)
1200    }
1201
1202    /// Back in the stable state, the sockets are matched against the candidates the
1203    /// transports hold. A local offer that is rolled back takes its ICE restart back (RFC
1204    /// 9429 section 5.7: "any resources or candidates that were allocated by the abandoned
1205    /// local description are discarded"), the `OnLocalCandidatesNeeded` it fired included: a
1206    /// socket retired for it whose candidate the transport holds again carries the
1207    /// transport's packets as before (it is no longer retired), and a socket bound for the
1208    /// abandoned generation, whose candidate the transport dropped, is closed. The answer to
1209    /// the peer's colliding offer, if it sets up a new association, fires its own event.
1210    fn match_sockets_to_candidates(&mut self) {
1211        let held: Vec<(String, u16)> = self
1212            .pc
1213            .dtls_transports()
1214            .iter()
1215            .flat_map(|t| t.ice_transport().get_local_candidates())
1216            .filter(|c| c.protocol == RTCIceProtocol::Udp)
1217            .map(|c| (c.address, c.port))
1218            .collect();
1219        let holds = |local: &SocketAddr| {
1220            held.iter()
1221                .any(|(address, port)| names_socket(address, *port, *local))
1222        };
1223        for host in self.sockets.iter_mut() {
1224            if host.retired_for.is_some() && holds(&host.local) {
1225                host.retired_for = None;
1226                host.close_at = None;
1227            }
1228        }
1229        self.sockets
1230            .retain(|s| s.retired_for.is_some() || holds(&s.local));
1231    }
1232
1233    /// A transport begins gathering an ICE generation the driver was not told about: the
1234    /// first one (no socket of the transport yet: every section without one gets them), or a
1235    /// restart that kept the candidates (each is given to the new generation again).
1236    fn on_gathering_begins(
1237        &mut self,
1238        ice_transport: RTCTransportId,
1239        dtls_transport: RTCTransportId,
1240    ) -> Result<()> {
1241        if self.gathered.remove(&ice_transport) {
1242            return Ok(());
1243        }
1244        let Some(held) = self.pc.dtls_transport_by_id(dtls_transport).and_then(|t| {
1245            let ice = t.ice_transport();
1246            (ice.gathering_state() == RTCIceGatheringState::Gathering)
1247                .then(|| ice.get_local_candidates())
1248        }) else {
1249            return Ok(());
1250        };
1251        let kept: Vec<(SocketAddr, String)> = self
1252            .sockets
1253            .iter()
1254            .filter(|s| s.retired_for.is_none())
1255            .filter(|s| {
1256                held.iter()
1257                    .any(|c| names_socket(&c.address, c.port, s.local))
1258            })
1259            .map(|s| (s.local, s.mid.clone()))
1260            .collect();
1261        if kept.is_empty() {
1262            return self.gather();
1263        }
1264        let mid = kept[0].1.clone();
1265        for (local, _) in &kept {
1266            self.pc
1267                .add_local_candidate(host_candidate(*local, &mid, None)?)?;
1268        }
1269        self.end_of_candidates(&mid, None)
1270    }
1271
1272    /// Host candidates for every transport section (`ice_transport_sections`) that has no
1273    /// socket of its own yet, each ended with the end of its generation.
1274    ///
1275    /// # Errors
1276    ///
1277    /// As [`flush`](Self::flush).
1278    pub fn gather(&mut self) -> Result<()> {
1279        for (mid, index) in self.pc.ice_transport_sections() {
1280            if self
1281                .sockets
1282                .iter()
1283                .any(|s| s.retired_for.is_none() && s.mid == mid)
1284            {
1285                continue;
1286            }
1287            self.gather_section(&mid, Some(index))?;
1288        }
1289        Ok(())
1290    }
1291
1292    /// New sockets, one per configured address, for the transport of section `mid`: their
1293    /// host candidates, then the end of the generation.
1294    fn gather_section(&mut self, mid: &str, index: Option<u16>) -> Result<()> {
1295        self.prepare_mdns_publishing();
1296        self.mark_temporary_addresses();
1297        for ip in self.config.addresses.clone() {
1298            let (socket, local) = self.bind_unique_port(ip).map_err(io_error)?;
1299            let tx = self.datagrams_tx.clone();
1300            let reader = self.runtime.spawn(Box::pin(read_loop(
1301                socket.clone(),
1302                local,
1303                false,
1304                move |received| tx.try_send(received).is_ok(),
1305                2048,
1306            )));
1307            self.sockets.push(HostSocket {
1308                socket,
1309                local,
1310                mid: mid.to_owned(),
1311                retired_for: None,
1312                close_at: None,
1313                counted_unmarked: false,
1314                reader,
1315            });
1316            self.pc
1317                .add_local_candidate(host_candidate(local, mid, index)?)?;
1318        }
1319        self.end_of_candidates(mid, index)
1320    }
1321
1322    /// A UDP socket on `ip`; with `QueryAndGather`, one whose port no other socket of the
1323    /// driver has: a `.local` candidate names its socket by port alone ([`names_socket`]), so
1324    /// ports are kept unique across the driver's addresses (the system gives each address its
1325    /// own ports, and a port-range cursor comes round again). Where the range has no such port
1326    /// left after [`MAX_PORT_ATTEMPTS`] binds, the last one is taken: two sockets then share a
1327    /// port, and a retired one may stay open until its transport closes.
1328    fn bind_unique_port(&self, ip: IpAddr) -> io::Result<(Arc<dyn AsyncUdpSocket>, SocketAddr)> {
1329        let unique = self.pc.multicast_dns_mode() == MulticastDnsMode::QueryAndGather;
1330        // Sockets refused for their port stay bound until the end, so that the next bind
1331        // cannot be given the same port again.
1332        let mut refused = Vec::new();
1333        for _ in 0..MAX_PORT_ATTEMPTS {
1334            let socket = match self.config.udp_port_range {
1335                Some(range) => sockets::bind_runtime_udp_in_range(self.runtime.as_ref(), ip, range),
1336                None => self.runtime.bind_udp(SocketAddr::new(ip, 0)),
1337            };
1338            let socket = match socket {
1339                Ok(socket) => socket,
1340                // The range is full now that the refused sockets hold their ports.
1341                Err(e) if !refused.is_empty() && e.kind() == io::ErrorKind::AddrInUse => break,
1342                Err(e) => return Err(e),
1343            };
1344            let local = socket.local_addr()?;
1345            if !unique || !self.sockets.iter().any(|s| s.local.port() == local.port()) {
1346                return Ok((socket, local));
1347            }
1348            refused.push((socket, local));
1349        }
1350        refused
1351            .pop()
1352            .ok_or_else(|| io::Error::from(io::ErrorKind::AddrInUse))
1353    }
1354
1355    fn end_of_candidates(&mut self, mid: &str, index: Option<u16>) -> Result<()> {
1356        self.pc.add_local_candidate(RTCIceCandidateInit {
1357            sdp_mid: Some(mid.to_owned()),
1358            sdp_mline_index: index,
1359            ..Default::default()
1360        })
1361    }
1362
1363    /// Closes the sockets retired for `transport` (it is closed: nothing travels over them).
1364    fn release(&mut self, transport: RTCTransportId) {
1365        self.sockets.retain(|s| s.retired_for != Some(transport));
1366    }
1367
1368    /// `transport` selected a pair on a new socket: its retired sockets are closed after
1369    /// [`PeerDriverConfig::retired_socket_linger`], for what the peer still sends to them.
1370    fn release_after_linger(&mut self, transport: RTCTransportId) {
1371        let close_at = self.runtime.now() + self.config.retired_socket_linger;
1372        for host in self
1373            .sockets
1374            .iter_mut()
1375            .filter(|s| s.retired_for == Some(transport) && s.close_at.is_none())
1376        {
1377            host.close_at = Some(close_at);
1378        }
1379    }
1380}
1381
1382/// What a driver dropped without [`PeerDriver::shutdown`] can do: an async driver on a runtime
1383/// of the application's choice cannot wait in `drop` (no runtime may be blocked there, and
1384/// none may be running any more), so it closes the connection and sends at once, without
1385/// waiting, what the connection then writes: the mDNS goodbyes the budget lets go now (the
1386/// rest is lost, and the neighbours' caches hold those names until their TTL ends), each
1387/// socket's last datagrams if the system takes them. The sockets close as the driver goes,
1388/// leaving the mDNS groups. Use `shutdown` to have every goodbye sent.
1389impl Drop for PeerDriver {
1390    fn drop(&mut self) {
1391        if self.shut_down {
1392            return;
1393        }
1394        let _ = self.pc.close();
1395        while let Some(datagram) = self.pc.poll_write() {
1396            self.send(datagram);
1397        }
1398        if self.mdns_sockets.is_some() {
1399            self.send_mdns(self.runtime.now());
1400        }
1401    }
1402}
1403
1404/// How many binds [`PeerDriver::bind_unique_port`] tries for a port no other socket has.
1405const MAX_PORT_ATTEMPTS: usize = 16;
1406
1407/// Whether a local candidate of `address` and `port` is the one of the socket at `local`. With
1408/// mDNS (`QueryAndGather`) the engine has replaced the candidate's address with a `.local` name
1409/// (draft-ietf-mmusic-mdns-ice-candidates section 3.1.1): the port tells the socket then, and
1410/// it tells exactly one, because no two sockets of a driver share a port
1411/// ([`PeerDriver::bind_unique_port`]).
1412fn names_socket(address: &str, port: u16, local: SocketAddr) -> bool {
1413    port == local.port()
1414        && (address == local.ip().to_string() || address.to_ascii_lowercase().ends_with(".local"))
1415}
1416
1417fn io_error(e: io::Error) -> Error {
1418    Error::Io(IoError(e))
1419}
1420
1421/// The host candidate of `local` for section `mid`.
1422fn host_candidate(local: SocketAddr, mid: &str, index: Option<u16>) -> Result<RTCIceCandidateInit> {
1423    let candidate = CandidateHostConfig {
1424        base_config: CandidateConfig {
1425            network: "udp".to_owned(),
1426            address: local.ip().to_string(),
1427            port: local.port(),
1428            component: 1,
1429            ..Default::default()
1430        },
1431        ..Default::default()
1432    }
1433    .new_candidate_host()?;
1434    let mut init = RTCIceCandidate::from(&candidate).to_json()?;
1435    init.sdp_mid = Some(mid.to_owned());
1436    init.sdp_mline_index = index;
1437    Ok(init)
1438}
1439
1440/// What woke a [`PeerDriver::step`].
1441enum Woke {
1442    Datagram(Received),
1443    Mdns(Received),
1444    Stream(DriverInput),
1445    Timer,
1446}
1447
1448/// Whether an mDNS send error says sending cannot work (no route to the group, no
1449/// permission): the family is unavailable at once, without waiting for more failures.
1450fn decisive(e: &io::Error) -> bool {
1451    matches!(
1452        e.kind(),
1453        io::ErrorKind::HostUnreachable
1454            | io::ErrorKind::NetworkUnreachable
1455            | io::ErrorKind::PermissionDenied
1456            | io::ErrorKind::AddrNotAvailable
1457            | io::ErrorKind::NetworkDown
1458    )
1459}
1460
1461/// Reads `socket` and hands each datagram to `deliver` (`false`: the driver is gone), with
1462/// `local` as its local address, or, with `destination`, the destination address of its IP
1463/// header where the socket reports it (else `local`'s: a socket bound to the mDNS group
1464/// receives only what was sent to the group).
1465async fn read_loop(
1466    socket: Arc<dyn AsyncUdpSocket>,
1467    local: SocketAddr,
1468    destination: bool,
1469    mut deliver: impl FnMut(Received) -> bool + Send + 'static,
1470    max_datagram: usize,
1471) {
1472    let mut buf = vec![0u8; max_datagram];
1473    loop {
1474        let received = std::future::poll_fn(|cx| {
1475            let mut meta = [runtime::RecvMeta::default()];
1476            let mut bufs = [std::io::IoSliceMut::new(&mut buf)];
1477            socket
1478                .poll_recv(cx, &mut bufs, &mut meta)
1479                .map_ok(|_| meta[0])
1480        })
1481        .await;
1482        match received {
1483            Ok(meta) => {
1484                let to = match meta.dst_ip {
1485                    Some(ip) if destination && !ip.is_unspecified() => {
1486                        SocketAddr::new(ip, local.port())
1487                    }
1488                    _ => local,
1489                };
1490                if !deliver((to, meta.addr, buf[..meta.len].to_vec())) {
1491                    return;
1492                }
1493            }
1494            // An ICMP error reported on the socket (Windows: a port unreachable) is not the
1495            // end of it.
1496            Err(_) => runtime::yield_now().await,
1497        }
1498    }
1499}
1500
1501#[cfg(test)]
1502mod tests {
1503    use super::*;
1504    use std::net::{Ipv4Addr, Ipv6Addr};
1505
1506    const NIC: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
1507    const LO: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
1508
1509    fn sockets(addresses: &[IpAddr], skips_loopback_v4: bool) -> MdnsSockets {
1510        let addresses = mdns_addresses(addresses, skips_loopback_v4);
1511        MdnsSockets {
1512            v4: MdnsFamily::new(one_per_interface(&addresses, true)),
1513            v6: MdnsFamily::new(one_per_interface(&addresses, false)),
1514            companions: vec![],
1515            skips_loopback_v4,
1516        }
1517    }
1518
1519    // The 0.3.0 default on Windows: IPv4 loopback addresses get no mDNS interface; the others,
1520    // IPv6 loopback included (not measured to leave a route), keep theirs. With the setting (and
1521    // on other systems) nothing is taken out.
1522    #[test]
1523    fn ipv4_loopback_addresses_get_no_mdns_interface_when_skipped() {
1524        let all = [NIC, LO, IpAddr::V6(Ipv6Addr::LOCALHOST)];
1525        assert_eq!(
1526            mdns_addresses(&all, true),
1527            vec![NIC, IpAddr::V6(Ipv6Addr::LOCALHOST)]
1528        );
1529        assert_eq!(mdns_addresses(&all, false), all.to_vec());
1530    }
1531
1532    // A message about the loopback address's name is sent nowhere on the group when skipped, and
1533    // on the loopback interface otherwise; a query leaves on the other interfaces only.
1534    #[test]
1535    fn a_loopback_record_leaves_on_no_group_when_skipped() {
1536        let group = SocketAddr::new(MDNS_MULTICAST_IPV4.into(), MDNS_PORT);
1537        let skipped = sockets(&[NIC, LO], true);
1538        assert!(skipped.routes(LO, group).is_empty());
1539        assert_eq!(skipped.routes(NIC, group), vec![(group, Some(NIC))]);
1540        assert_eq!(
1541            skipped.routes(Ipv4Addr::UNSPECIFIED.into(), group),
1542            vec![(group, Some(NIC))],
1543            "the query leaves on the network interface only"
1544        );
1545        let asked = sockets(&[NIC, LO], false);
1546        assert_eq!(asked.routes(LO, group), vec![(group, Some(LO))]);
1547    }
1548
1549    // The default decides on Windows only; the setting turns it off there.
1550    #[test]
1551    fn loopback_mdns_is_skipped_by_default_on_windows_only() {
1552        let config = PeerDriverConfig::on(vec![LO]);
1553        assert!(!config.mdns_on_loopback_on_windows, "the default");
1554        assert_eq!(config.skips_loopback_mdns_v4(), cfg!(windows));
1555        let asked = PeerDriverConfig {
1556            mdns_on_loopback_on_windows: true,
1557            ..config
1558        };
1559        assert!(!asked.skips_loopback_mdns_v4());
1560    }
1561}