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