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