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 result = host.socket.try_send(&Transmit {
838            destination: datagram.transport.peer_addr,
839            contents: &datagram.message,
840            traffic_class,
841            segment_size: None,
842            source: None,
843        });
844        let sent = result.is_ok();
845        // A send refused for its size is the one transport indication of RFC 6347 4.1.1.1 /
846        // RFC 9147 section 4.4 these sockets observe: they leave DF to the system's default
847        // and do not read the ICMP error queue (no IP_RECVERR), so an ICMP Packet Too Big
848        // never reaches the driver, and the system fragments locally what exceeds the path
849        // MTU it knows. A refusal names no MTU.
850        let too_big = result.as_ref().is_err_and(refused_for_size);
851        // The platform does not mark (RFC 8835 4.2: "appropriate to depart ... on platforms
852        // where QoS marking is not implemented"): counted once per socket.
853        let unmarked = host.socket.unmarked();
854        if unmarked && !host.counted_unmarked {
855            host.counted_unmarked = true;
856            self.unmarked_sockets += 1;
857        }
858        if sent {
859            let applied = if unmarked { 0 } else { traffic_class };
860            *self.sent_by_traffic_class.entry(applied).or_default() += 1;
861        } else {
862            self.unsent += 1;
863        }
864        if too_big {
865            let now = self.runtime.now();
866            self.pc
867                .handle_datagram_too_big(now, datagram.transport, None, Some(&datagram.message));
868        }
869    }
870
871    /// Sends the held mDNS datagrams the budget lets go at `now`, binding the mDNS sockets at
872    /// the first, each on the interface of the address the engine names for it
873    /// ([`MdnsSockets::routes`]). A datagram no socket could send is unsent; a send the system
874    /// refuses counts against its family ([`Self::mdns_send_result`]).
875    fn send_mdns(&mut self, now: Instant) {
876        while let Some(datagram) = self.mdns_egress.pop_ready(now) {
877            self.ensure_mdns(now, false);
878            let Some(sockets) = self.mdns_sockets.as_ref() else {
879                self.unsent += 1;
880                continue;
881            };
882            let routes = sockets.routes(
883                datagram.transport.local_addr.ip(),
884                datagram.transport.peer_addr,
885            );
886            let mut results = Vec::new();
887            for (destination, source) in routes {
888                let family = if destination.is_ipv6() {
889                    &sockets.v6
890                } else {
891                    &sockets.v4
892                };
893                if let Some((socket, _)) = &family.socket {
894                    let result = socket.try_send(&Transmit {
895                        destination,
896                        contents: &datagram.message,
897                        traffic_class: 0,
898                        segment_size: None,
899                        source,
900                    });
901                    results.push((destination.is_ipv6(), result));
902                }
903            }
904            let mut sent = false;
905            for (ipv6, result) in results {
906                sent |= self.mdns_send_result(ipv6, result, now);
907            }
908            if sent {
909                self.mdns_sent += 1;
910            } else {
911                self.unsent += 1;
912            }
913        }
914    }
915
916    /// Books one mDNS send of a family: a success makes the family available again (told
917    /// once); a refusal counts, and declares the family unavailable at once when the error
918    /// says there is no route or no permission, or after a few in a row. A full send buffer
919    /// (`WouldBlock`) is a lost datagram, as on the wire, not a failure.
920    fn mdns_send_result(&mut self, ipv6: bool, result: io::Result<usize>, now: Instant) -> bool {
921        let Some(sockets) = self.mdns_sockets.as_mut() else {
922            return false;
923        };
924        let family = if ipv6 {
925            &mut sockets.v6
926        } else {
927            &mut sockets.v4
928        };
929        match result {
930            Ok(_) => {
931                family.failures = 0;
932                if family.unavailable {
933                    family.unavailable = false;
934                    family.backoff = MDNS_RETRY_FIRST;
935                    self.driver_events
936                        .push_back(PeerDriverEvent::MdnsAvailable { ipv6 });
937                    self.refresh_mdns_publishing();
938                }
939                true
940            }
941            Err(e) if e.kind() == io::ErrorKind::WouldBlock => false,
942            Err(e) => {
943                self.mdns_send_failures += 1;
944                family.failures += 1;
945                if decisive(&e) || family.failures >= MDNS_FAILURES_BEFORE_UNAVAILABLE {
946                    self.mdns_unavailable(ipv6, MdnsStage::Send, &e, now);
947                }
948                false
949            }
950        }
951    }
952
953    /// A family's mDNS cannot be used: its socket is closed (bound again at the next try),
954    /// the next try waits a back-off, the application is told (once until it works again),
955    /// and the connection learns that the family's names cannot be published.
956    fn mdns_unavailable(&mut self, ipv6: bool, stage: MdnsStage, error: &io::Error, now: Instant) {
957        let Some(sockets) = self.mdns_sockets.as_mut() else {
958            return;
959        };
960        let family = if ipv6 {
961            &mut sockets.v6
962        } else {
963            &mut sockets.v4
964        };
965        family.close();
966        family.failures = 0;
967        family.retry_at = Some(now + family.backoff);
968        family.backoff = (family.backoff * 2).min(MDNS_RETRY_MAX);
969        if !family.unavailable {
970            family.unavailable = true;
971            self.driver_events
972                .push_back(PeerDriverEvent::MdnsUnavailable(MdnsFailure::new(
973                    ipv6, stage, error,
974                )));
975        }
976        self.refresh_mdns_publishing();
977    }
978
979    /// The host's mDNS sockets (none with [`PeerDriverConfig::mdns_sockets`] off): each family
980    /// without a socket is bound now when it never was, when `force` (a gathering), or when
981    /// its back-off has passed. Each socket is joined to its group on the interface of every
982    /// configured address of its family (RFC 6762 section 14: a name is answered, and a peer's
983    /// asked for, on the link of its address). A bind that fails is reported
984    /// ([`PeerDriverEvent::MdnsUnavailable`]) and tried again later.
985    fn ensure_mdns(&mut self, now: Instant, force: bool) {
986        let skips_loopback_v4 = self.config.skips_loopback_mdns_v4();
987        let addresses = mdns_addresses(&self.config.addresses, skips_loopback_v4);
988        if self.mdns_sockets.is_none() {
989            let mut v4 = MdnsFamily::new(one_per_interface(&addresses, true));
990            if addresses.len() < self.config.addresses.len() {
991                note_loopback_mdns_skipped();
992                // Only loopback IPv4 addresses: no IPv4 socket at all (one with no interface
993                // would join and send on the system's default one).
994                v4.off = !addresses.iter().any(IpAddr::is_ipv4);
995            }
996            let v6 = MdnsFamily::new(one_per_interface(&addresses, false));
997            let companions = v6
998                .links
999                .iter()
1000                .filter_map(|ip6| {
1001                    let name = runtime::interface_name(*ip6)?;
1002                    let ip4 = v4
1003                        .links
1004                        .iter()
1005                        .find(|ip4| runtime::interface_name(**ip4).as_deref() == Some(&name))?;
1006                    Some((*ip6, *ip4))
1007                })
1008                .collect();
1009            self.mdns_sockets = Some(MdnsSockets {
1010                v4,
1011                v6,
1012                companions,
1013                skips_loopback_v4,
1014            });
1015        }
1016        if !self.config.mdns_sockets {
1017            return;
1018        }
1019        for ipv6 in [false, true] {
1020            let Some(sockets) = self.mdns_sockets.as_ref() else {
1021                return;
1022            };
1023            let family = if ipv6 { &sockets.v6 } else { &sockets.v4 };
1024            if family.off
1025                || family.socket.is_some()
1026                || !(force || family.retry_at.is_none_or(|at| now >= at))
1027            {
1028                continue;
1029            }
1030            let config = if ipv6 {
1031                mdns_v6(addresses.clone())
1032            } else {
1033                mdns_v4(addresses.clone())
1034            };
1035            let bound = self
1036                .runtime
1037                .bind_udp_multicast(&config)
1038                .and_then(|socket| Ok((socket.local_addr()?, socket)));
1039            match bound {
1040                Ok((local, socket)) => {
1041                    let tx = self.mdns_tx.clone();
1042                    let dropped = self.mdns_dropped.clone();
1043                    let reader = self.runtime.spawn(Box::pin(read_loop(
1044                        socket.clone(),
1045                        local,
1046                        true,
1047                        move |received| match tx.force_send(received) {
1048                            Ok(None) => true,
1049                            Ok(Some(_)) => {
1050                                dropped.fetch_add(1, Ordering::Relaxed);
1051                                true
1052                            }
1053                            Err(_) => false,
1054                        },
1055                        MDNS_MAX_DATAGRAM,
1056                    )));
1057                    if let Some(sockets) = self.mdns_sockets.as_mut() {
1058                        let family = if ipv6 {
1059                            &mut sockets.v6
1060                        } else {
1061                            &mut sockets.v4
1062                        };
1063                        family.socket = Some((socket, reader));
1064                    }
1065                }
1066                Err(e) => {
1067                    self.mdns_bind_failures += 1;
1068                    self.mdns_unavailable(ipv6, MdnsStage::Bind, &e, now);
1069                }
1070            }
1071        }
1072        self.refresh_mdns_publishing();
1073    }
1074
1075    /// Before the connection's host candidates, with `QueryAndGather`: binds the mDNS sockets
1076    /// (again, for a family that failed) and tells the connection for which address families
1077    /// its names can be published (draft-ietf-mmusic-mdns-ice-candidates section 3.1.1 step 4).
1078    fn prepare_mdns_publishing(&mut self) {
1079        if self.pc.multicast_dns_mode() != MulticastDnsMode::QueryAndGather {
1080            return;
1081        }
1082        let now = self.runtime.now();
1083        self.ensure_mdns(now, true);
1084        if self.mdns_publishing_told.is_none() {
1085            let publishing = self.mdns_publishing();
1086            self.mdns_publishing_told = Some(publishing);
1087            self.pc.set_multicast_dns_publishing(publishing);
1088        }
1089    }
1090
1091    /// What is actually sent: an IPv4 record's messages need the IPv4 socket; an IPv6 record's
1092    /// leave on the IPv6 group, or on the IPv4 group of its interface.
1093    fn mdns_publishing(&self) -> MulticastDnsPublishing {
1094        let usable = |f: &MdnsFamily| f.socket.is_some() && !f.unavailable;
1095        self.mdns_sockets.as_ref().map_or(
1096            MulticastDnsPublishing {
1097                ipv4: false,
1098                ipv6: false,
1099            },
1100            |m| MulticastDnsPublishing {
1101                ipv4: usable(&m.v4),
1102                ipv6: usable(&m.v6) || (usable(&m.v4) && !m.companions.is_empty()),
1103            },
1104        )
1105    }
1106
1107    /// Tells the connection again when what can be published changed, once it was told.
1108    fn refresh_mdns_publishing(&mut self) {
1109        let Some(told) = self.mdns_publishing_told else {
1110            return;
1111        };
1112        let now = self.mdns_publishing();
1113        if now != told {
1114            self.mdns_publishing_told = Some(now);
1115            self.pc.set_multicast_dns_publishing(now);
1116        }
1117    }
1118
1119    /// With `QueryAndGather`, tells the connection which of the addresses it gathers on the
1120    /// operating system flags as RFC 4941 temporary IPv6 addresses
1121    /// (`RTCPeerConnection::set_temporary_ipv6_addresses`), so that
1122    /// `with_multicast_dns_expose_temporary_ipv6_addresses` can leave those unwrapped
1123    /// (draft-ietf-mmusic-mdns-ice-candidates section 3.1.2.3). Read from the interface list
1124    /// at each gathering (`shared::ifaces::temporary_ipv6_addresses`: Linux, Android, macOS
1125    /// and iOS report the flag; Windows and other systems mark nothing); where it cannot be
1126    /// read, nothing is marked and every address stays hidden.
1127    fn mark_temporary_addresses(&mut self) {
1128        if self.pc.multicast_dns_mode() != MulticastDnsMode::QueryAndGather {
1129            return;
1130        }
1131        let temporary: Vec<std::net::Ipv6Addr> = shared::ifaces::temporary_ipv6_addresses()
1132            .unwrap_or_default()
1133            .into_iter()
1134            .filter(|t| self.config.addresses.contains(&IpAddr::V6(*t)))
1135            .collect();
1136        self.pc.set_temporary_ipv6_addresses(temporary);
1137    }
1138
1139    fn on_event(&mut self, event: &RTCPeerConnectionEvent) -> Result<()> {
1140        match event {
1141            RTCPeerConnectionEvent::OnLocalCandidatesNeeded(needed) => {
1142                self.on_candidates_needed(needed)
1143            }
1144            RTCPeerConnectionEvent::OnSignalingStateChangeEvent(RTCSignalingState::Stable) => {
1145                self.match_sockets_to_candidates();
1146                Ok(())
1147            }
1148            RTCPeerConnectionEvent::OnTransportEvent(event) => match &event.event {
1149                RTCTransportEventKind::GatheringStateChange(RTCIceGatheringState::Gathering) => {
1150                    self.on_gathering_begins(event.ice_transport, event.dtls_transport)
1151                }
1152                RTCTransportEventKind::SelectedCandidatePairChange(pair) => {
1153                    let local = pair.local();
1154                    let on_retired = self.sockets.iter().any(|s| {
1155                        s.retired_for.is_some() && names_socket(&local.address, local.port, s.local)
1156                    });
1157                    if !on_retired {
1158                        self.release_after_linger(event.ice_transport);
1159                    }
1160                    Ok(())
1161                }
1162                RTCTransportEventKind::IceStateChange(RTCIceTransportState::Closed) => {
1163                    self.release(event.ice_transport);
1164                    Ok(())
1165                }
1166                _ => Ok(()),
1167            },
1168            _ => Ok(()),
1169        }
1170    }
1171
1172    /// `OnLocalCandidatesNeeded`: new sockets for the transport, or (`DiscardedBySetting`,
1173    /// no address refused) the same sockets' candidates again.
1174    fn on_candidates_needed(&mut self, needed: &RTCLocalCandidatesNeededEvent) -> Result<()> {
1175        let Some(mid) = needed.mids.first().cloned() else {
1176            return Ok(());
1177        };
1178        let index = needed.sdp_mline_index;
1179        self.gathered.insert(needed.ice_transport);
1180        self.mark_temporary_addresses();
1181        if !needed.reason.needs_new_addresses() {
1182            let on: Vec<SocketAddr> = self
1183                .sockets
1184                .iter()
1185                .filter(|s| s.retired_for.is_none() && needed.mids.contains(&s.mid))
1186                .map(|s| s.local)
1187                .collect();
1188            if !on.is_empty() {
1189                for local in on {
1190                    self.pc
1191                        .add_local_candidate(host_candidate(local, &mid, index)?)?;
1192                }
1193                return self.end_of_candidates(&mid, index);
1194            }
1195            return self.gather_section(&mid, index);
1196        }
1197        for host in self
1198            .sockets
1199            .iter_mut()
1200            .filter(|s| needed.refused_addresses.contains(&s.local))
1201        {
1202            host.retired_for = Some(needed.ice_transport);
1203        }
1204        if needed.reason == RTCLocalCandidatesNeededReason::TransportReplaced {
1205            // The transport they served is closed: nothing travels over them any more.
1206            self.release(needed.ice_transport);
1207        }
1208        self.gather_section(&mid, index)
1209    }
1210
1211    /// Back in the stable state, the sockets are matched against the candidates the
1212    /// transports hold. A local offer that is rolled back takes its ICE restart back (RFC
1213    /// 9429 section 5.7: "any resources or candidates that were allocated by the abandoned
1214    /// local description are discarded"), the `OnLocalCandidatesNeeded` it fired included: a
1215    /// socket retired for it whose candidate the transport holds again carries the
1216    /// transport's packets as before (it is no longer retired), and a socket bound for the
1217    /// abandoned generation, whose candidate the transport dropped, is closed. The answer to
1218    /// the peer's colliding offer, if it sets up a new association, fires its own event.
1219    fn match_sockets_to_candidates(&mut self) {
1220        let held: Vec<(String, u16)> = self
1221            .pc
1222            .dtls_transports()
1223            .iter()
1224            .flat_map(|t| t.ice_transport().get_local_candidates())
1225            .filter(|c| c.protocol == RTCIceProtocol::Udp)
1226            .map(|c| (c.address, c.port))
1227            .collect();
1228        let holds = |local: &SocketAddr| {
1229            held.iter()
1230                .any(|(address, port)| names_socket(address, *port, *local))
1231        };
1232        for host in self.sockets.iter_mut() {
1233            if host.retired_for.is_some() && holds(&host.local) {
1234                host.retired_for = None;
1235                host.close_at = None;
1236            }
1237        }
1238        self.sockets
1239            .retain(|s| s.retired_for.is_some() || holds(&s.local));
1240    }
1241
1242    /// A transport begins gathering an ICE generation the driver was not told about: the
1243    /// first one (no socket of the transport yet: every section without one gets them), or a
1244    /// restart that kept the candidates (each is given to the new generation again).
1245    fn on_gathering_begins(
1246        &mut self,
1247        ice_transport: RTCTransportId,
1248        dtls_transport: RTCTransportId,
1249    ) -> Result<()> {
1250        if self.gathered.remove(&ice_transport) {
1251            return Ok(());
1252        }
1253        let Some(held) = self.pc.dtls_transport_by_id(dtls_transport).and_then(|t| {
1254            let ice = t.ice_transport();
1255            (ice.gathering_state() == RTCIceGatheringState::Gathering)
1256                .then(|| ice.get_local_candidates())
1257        }) else {
1258            return Ok(());
1259        };
1260        let kept: Vec<(SocketAddr, String)> = self
1261            .sockets
1262            .iter()
1263            .filter(|s| s.retired_for.is_none())
1264            .filter(|s| {
1265                held.iter()
1266                    .any(|c| names_socket(&c.address, c.port, s.local))
1267            })
1268            .map(|s| (s.local, s.mid.clone()))
1269            .collect();
1270        if kept.is_empty() {
1271            return self.gather();
1272        }
1273        let mid = kept[0].1.clone();
1274        for (local, _) in &kept {
1275            self.pc
1276                .add_local_candidate(host_candidate(*local, &mid, None)?)?;
1277        }
1278        self.end_of_candidates(&mid, None)
1279    }
1280
1281    /// Host candidates for every transport section (`ice_transport_sections`) that has no
1282    /// socket of its own yet, each ended with the end of its generation.
1283    ///
1284    /// # Errors
1285    ///
1286    /// As [`flush`](Self::flush).
1287    pub fn gather(&mut self) -> Result<()> {
1288        for (mid, index) in self.pc.ice_transport_sections() {
1289            if self
1290                .sockets
1291                .iter()
1292                .any(|s| s.retired_for.is_none() && s.mid == mid)
1293            {
1294                continue;
1295            }
1296            self.gather_section(&mid, Some(index))?;
1297        }
1298        Ok(())
1299    }
1300
1301    /// New sockets, one per configured address, for the transport of section `mid`: their
1302    /// host candidates, then the end of the generation.
1303    fn gather_section(&mut self, mid: &str, index: Option<u16>) -> Result<()> {
1304        self.prepare_mdns_publishing();
1305        self.mark_temporary_addresses();
1306        for ip in self.config.addresses.clone() {
1307            let (socket, local) = self.bind_unique_port(ip).map_err(io_error)?;
1308            let tx = self.datagrams_tx.clone();
1309            let reader = self.runtime.spawn(Box::pin(read_loop(
1310                socket.clone(),
1311                local,
1312                false,
1313                move |received| tx.try_send(received).is_ok(),
1314                2048,
1315            )));
1316            self.sockets.push(HostSocket {
1317                socket,
1318                local,
1319                mid: mid.to_owned(),
1320                retired_for: None,
1321                close_at: None,
1322                counted_unmarked: false,
1323                reader,
1324            });
1325            self.pc
1326                .add_local_candidate(host_candidate(local, mid, index)?)?;
1327        }
1328        self.end_of_candidates(mid, index)
1329    }
1330
1331    /// A UDP socket on `ip`; with `QueryAndGather`, one whose port no other socket of the
1332    /// driver has: a `.local` candidate names its socket by port alone ([`names_socket`]), so
1333    /// ports are kept unique across the driver's addresses (the system gives each address its
1334    /// own ports, and a port-range cursor comes round again). Where the range has no such port
1335    /// left after [`MAX_PORT_ATTEMPTS`] binds, the last one is taken: two sockets then share a
1336    /// port, and a retired one may stay open until its transport closes.
1337    fn bind_unique_port(&self, ip: IpAddr) -> io::Result<(Arc<dyn AsyncUdpSocket>, SocketAddr)> {
1338        let unique = self.pc.multicast_dns_mode() == MulticastDnsMode::QueryAndGather;
1339        // Sockets refused for their port stay bound until the end, so that the next bind
1340        // cannot be given the same port again.
1341        let mut refused = Vec::new();
1342        for _ in 0..MAX_PORT_ATTEMPTS {
1343            let socket = match self.config.udp_port_range {
1344                Some(range) => sockets::bind_runtime_udp_in_range(self.runtime.as_ref(), ip, range),
1345                None => self.runtime.bind_udp(SocketAddr::new(ip, 0)),
1346            };
1347            let socket = match socket {
1348                Ok(socket) => socket,
1349                // The range is full now that the refused sockets hold their ports.
1350                Err(e) if !refused.is_empty() && e.kind() == io::ErrorKind::AddrInUse => break,
1351                Err(e) => return Err(e),
1352            };
1353            let local = socket.local_addr()?;
1354            if !unique || !self.sockets.iter().any(|s| s.local.port() == local.port()) {
1355                return Ok((socket, local));
1356            }
1357            refused.push((socket, local));
1358        }
1359        refused
1360            .pop()
1361            .ok_or_else(|| io::Error::from(io::ErrorKind::AddrInUse))
1362    }
1363
1364    fn end_of_candidates(&mut self, mid: &str, index: Option<u16>) -> Result<()> {
1365        self.pc.add_local_candidate(RTCIceCandidateInit {
1366            sdp_mid: Some(mid.to_owned()),
1367            sdp_mline_index: index,
1368            ..Default::default()
1369        })
1370    }
1371
1372    /// Closes the sockets retired for `transport` (it is closed: nothing travels over them).
1373    fn release(&mut self, transport: RTCTransportId) {
1374        self.sockets.retain(|s| s.retired_for != Some(transport));
1375    }
1376
1377    /// `transport` selected a pair on a new socket: its retired sockets are closed after
1378    /// [`PeerDriverConfig::retired_socket_linger`], for what the peer still sends to them.
1379    fn release_after_linger(&mut self, transport: RTCTransportId) {
1380        let close_at = self.runtime.now() + self.config.retired_socket_linger;
1381        for host in self
1382            .sockets
1383            .iter_mut()
1384            .filter(|s| s.retired_for == Some(transport) && s.close_at.is_none())
1385        {
1386            host.close_at = Some(close_at);
1387        }
1388    }
1389}
1390
1391/// What a driver dropped without [`PeerDriver::shutdown`] can do: an async driver on a runtime
1392/// of the application's choice cannot wait in `drop` (no runtime may be blocked there, and
1393/// none may be running any more), so it closes the connection and sends at once, without
1394/// waiting, what the connection then writes: the mDNS goodbyes the budget lets go now (the
1395/// rest is lost, and the neighbours' caches hold those names until their TTL ends), each
1396/// socket's last datagrams if the system takes them. The sockets close as the driver goes,
1397/// leaving the mDNS groups. Use `shutdown` to have every goodbye sent.
1398impl Drop for PeerDriver {
1399    fn drop(&mut self) {
1400        if self.shut_down {
1401            return;
1402        }
1403        let _ = self.pc.close();
1404        while let Some(datagram) = self.pc.poll_write() {
1405            self.send(datagram);
1406        }
1407        if self.mdns_sockets.is_some() {
1408            self.send_mdns(self.runtime.now());
1409        }
1410    }
1411}
1412
1413/// How many binds [`PeerDriver::bind_unique_port`] tries for a port no other socket has.
1414const MAX_PORT_ATTEMPTS: usize = 16;
1415
1416/// Whether a local candidate of `address` and `port` is the one of the socket at `local`. With
1417/// mDNS (`QueryAndGather`) the engine has replaced the candidate's address with a `.local` name
1418/// (draft-ietf-mmusic-mdns-ice-candidates section 3.1.1): the port tells the socket then, and
1419/// it tells exactly one, because no two sockets of a driver share a port
1420/// ([`PeerDriver::bind_unique_port`]).
1421fn names_socket(address: &str, port: u16, local: SocketAddr) -> bool {
1422    port == local.port()
1423        && (address == local.ip().to_string() || address.to_ascii_lowercase().ends_with(".local"))
1424}
1425
1426fn io_error(e: io::Error) -> Error {
1427    Error::Io(IoError(e))
1428}
1429
1430/// The host candidate of `local` for section `mid`.
1431fn host_candidate(local: SocketAddr, mid: &str, index: Option<u16>) -> Result<RTCIceCandidateInit> {
1432    let candidate = CandidateHostConfig {
1433        base_config: CandidateConfig {
1434            network: "udp".to_owned(),
1435            address: local.ip().to_string(),
1436            port: local.port(),
1437            component: 1,
1438            ..Default::default()
1439        },
1440        ..Default::default()
1441    }
1442    .new_candidate_host()?;
1443    let mut init = RTCIceCandidate::from(&candidate).to_json()?;
1444    init.sdp_mid = Some(mid.to_owned());
1445    init.sdp_mline_index = index;
1446    Ok(init)
1447}
1448
1449/// What woke a [`PeerDriver::step`].
1450enum Woke {
1451    Datagram(Received),
1452    Mdns(Received),
1453    Stream(DriverInput),
1454    Timer,
1455}
1456
1457/// Whether a send was refused because the datagram is larger than the system sends
1458/// (`EMSGSIZE`, Windows `WSAEMSGSIZE`).
1459fn refused_for_size(e: &io::Error) -> bool {
1460    #[cfg(unix)]
1461    let code = libc::EMSGSIZE;
1462    #[cfg(windows)]
1463    let code = 10040;
1464    #[cfg(not(any(unix, windows)))]
1465    let code = -1;
1466    e.raw_os_error() == Some(code)
1467}
1468
1469/// Whether an mDNS send error says sending cannot work (no route to the group, no
1470/// permission): the family is unavailable at once, without waiting for more failures.
1471fn decisive(e: &io::Error) -> bool {
1472    matches!(
1473        e.kind(),
1474        io::ErrorKind::HostUnreachable
1475            | io::ErrorKind::NetworkUnreachable
1476            | io::ErrorKind::PermissionDenied
1477            | io::ErrorKind::AddrNotAvailable
1478            | io::ErrorKind::NetworkDown
1479    )
1480}
1481
1482/// Reads `socket` and hands each datagram to `deliver` (`false`: the driver is gone), with
1483/// `local` as its local address, or, with `destination`, the destination address of its IP
1484/// header where the socket reports it (else `local`'s: a socket bound to the mDNS group
1485/// receives only what was sent to the group).
1486async fn read_loop(
1487    socket: Arc<dyn AsyncUdpSocket>,
1488    local: SocketAddr,
1489    destination: bool,
1490    mut deliver: impl FnMut(Received) -> bool + Send + 'static,
1491    max_datagram: usize,
1492) {
1493    let mut buf = vec![0u8; max_datagram];
1494    loop {
1495        let received = std::future::poll_fn(|cx| {
1496            let mut meta = [runtime::RecvMeta::default()];
1497            let mut bufs = [std::io::IoSliceMut::new(&mut buf)];
1498            socket
1499                .poll_recv(cx, &mut bufs, &mut meta)
1500                .map_ok(|_| meta[0])
1501        })
1502        .await;
1503        match received {
1504            Ok(meta) => {
1505                let to = match meta.dst_ip {
1506                    Some(ip) if destination && !ip.is_unspecified() => {
1507                        SocketAddr::new(ip, local.port())
1508                    }
1509                    _ => local,
1510                };
1511                if !deliver((to, meta.addr, buf[..meta.len].to_vec())) {
1512                    return;
1513                }
1514            }
1515            // An ICMP error reported on the socket (Windows: a port unreachable) is not the
1516            // end of it.
1517            Err(_) => runtime::yield_now().await,
1518        }
1519    }
1520}
1521
1522#[cfg(test)]
1523mod tests {
1524    use super::*;
1525    use std::net::{Ipv4Addr, Ipv6Addr};
1526
1527    const NIC: IpAddr = IpAddr::V4(Ipv4Addr::new(192, 168, 1, 1));
1528    const LO: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
1529
1530    fn sockets(addresses: &[IpAddr], skips_loopback_v4: bool) -> MdnsSockets {
1531        let addresses = mdns_addresses(addresses, skips_loopback_v4);
1532        MdnsSockets {
1533            v4: MdnsFamily::new(one_per_interface(&addresses, true)),
1534            v6: MdnsFamily::new(one_per_interface(&addresses, false)),
1535            companions: vec![],
1536            skips_loopback_v4,
1537        }
1538    }
1539
1540    // The 0.3.0 default on Windows: IPv4 loopback addresses get no mDNS interface; the others,
1541    // IPv6 loopback included (not measured to leave a route), keep theirs. With the setting (and
1542    // on other systems) nothing is taken out.
1543    #[test]
1544    fn ipv4_loopback_addresses_get_no_mdns_interface_when_skipped() {
1545        let all = [NIC, LO, IpAddr::V6(Ipv6Addr::LOCALHOST)];
1546        assert_eq!(
1547            mdns_addresses(&all, true),
1548            vec![NIC, IpAddr::V6(Ipv6Addr::LOCALHOST)]
1549        );
1550        assert_eq!(mdns_addresses(&all, false), all.to_vec());
1551    }
1552
1553    // A message about the loopback address's name is sent nowhere on the group when skipped, and
1554    // on the loopback interface otherwise; a query leaves on the other interfaces only.
1555    #[test]
1556    fn a_loopback_record_leaves_on_no_group_when_skipped() {
1557        let group = SocketAddr::new(MDNS_MULTICAST_IPV4.into(), MDNS_PORT);
1558        let skipped = sockets(&[NIC, LO], true);
1559        assert!(skipped.routes(LO, group).is_empty());
1560        assert_eq!(skipped.routes(NIC, group), vec![(group, Some(NIC))]);
1561        assert_eq!(
1562            skipped.routes(Ipv4Addr::UNSPECIFIED.into(), group),
1563            vec![(group, Some(NIC))],
1564            "the query leaves on the network interface only"
1565        );
1566        let asked = sockets(&[NIC, LO], false);
1567        assert_eq!(asked.routes(LO, group), vec![(group, Some(LO))]);
1568    }
1569
1570    // The default decides on Windows only; the setting turns it off there.
1571    #[test]
1572    fn loopback_mdns_is_skipped_by_default_on_windows_only() {
1573        let config = PeerDriverConfig::on(vec![LO]);
1574        assert!(!config.mdns_on_loopback_on_windows, "the default");
1575        assert_eq!(config.skips_loopback_mdns_v4(), cfg!(windows));
1576        let asked = PeerDriverConfig {
1577            mdns_on_loopback_on_windows: true,
1578            ..config
1579        };
1580        assert!(!asked.skips_loopback_mdns_v4());
1581    }
1582}