Skip to main content

rtci_ice/agent/
mod.rs

1//! The Sans-I/O ICE agent.
2//!
3//! An [`Agent`] is given local and remote candidates and inbound datagrams; it produces the
4//! connectivity checks to send, the state transitions to report, and eventually a selected
5//! candidate pair. It owns no sockets and no clock — the caller drives time with
6//! `handle_timeout`.
7//!
8//! Two roles exist: the controlling agent nominates the pair that will carry media, the
9//! controlled agent accepts that choice. Which side controls is decided by which offered, and the
10//! two must not agree — see [`Credentials`] and [`Agent::set_role`].
11#[cfg(test)]
12mod agent_candidate_pair_test;
13#[cfg(test)]
14mod agent_checklist_test;
15#[cfg(test)]
16mod agent_consent_delay_test;
17#[cfg(test)]
18mod agent_consent_test;
19#[cfg(test)]
20mod agent_mdns_exposure_test;
21#[cfg(test)]
22mod agent_nat_1to1_test;
23#[cfg(test)]
24mod agent_nomination_test;
25#[cfg(test)]
26mod agent_open_rows_test;
27#[cfg(test)]
28mod agent_ported_test;
29#[cfg(test)]
30mod agent_relay_policy_restart_test;
31#[cfg(test)]
32mod agent_rfc6544_mdns_test;
33#[cfg(test)]
34mod agent_rfc7675_test;
35#[cfg(test)]
36mod agent_rfc8445_test;
37#[cfg(test)]
38mod agent_stun_rows_test;
39#[cfg(test)]
40mod agent_tcp_integrity_test;
41#[cfg(test)]
42mod agent_test;
43#[cfg(test)]
44mod agent_trickle_test;
45
46#[cfg(test)]
47mod address_policy_test;
48/// Configuration for a new [`Agent`]: servers, timeouts and role.
49pub mod agent_config;
50mod agent_proto;
51/// Pair selection and nomination — which candidate pair becomes the selected one.
52pub mod agent_selector;
53/// Snapshot statistics for an agent's candidates and pairs.
54pub mod agent_stats;
55pub mod remote_policy;
56#[cfg(test)]
57mod remote_policy_test;
58mod restart_undo;
59
60use agent_config::*;
61use bytes::BytesMut;
62use crypto::{RTCCrypto, RTCCryptoProvider};
63use log::{debug, error, info, trace, warn};
64use mdns::{Mdns, QueryId};
65use sansio::Protocol;
66use std::collections::{HashMap, VecDeque};
67use std::net::{IpAddr, Ipv6Addr, SocketAddr};
68use std::sync::Arc;
69use std::time::{Duration, Instant};
70use stun::attributes::*;
71use stun::fingerprint::*;
72use stun::integrity::*;
73use stun::message::*;
74use stun::textattrs::*;
75use stun::xoraddr::*;
76
77use crate::candidate::candidate_peer_reflexive::CandidatePeerReflexiveConfig;
78use crate::candidate::candidate_server_reflexive::CandidateServerReflexiveConfig;
79use crate::candidate::{candidate_pair::*, *};
80use crate::external_ip_mapper::ExternalIpMapper;
81use crate::mdns::exposure::KnownPublicAddresses;
82use crate::mdns::{
83    MdnsOptions, MulticastDnsMode, MulticastDnsPublishing, create_multicast_dns,
84    generate_multicast_dns_name, is_ice_mdns_name, is_valid_local_mdns_name,
85};
86use crate::network_type::NetworkType;
87use crate::rand::*;
88use crate::state::*;
89use crate::tcp_type::TcpType;
90use crate::url::*;
91use remote_policy::{AddressPurpose, RemotePolicy};
92use shared::error::*;
93use shared::{TaggedBytesMut, TransportContext, TransportProtocol};
94
95const ZERO_DURATION: Duration = Duration::from_secs(0);
96
97#[derive(Debug, Clone)]
98pub(crate) struct BindingRequest {
99    pub(crate) timestamp: Instant,
100    pub(crate) transaction_id: TransactionId,
101    pub(crate) destination: SocketAddr,
102    pub(crate) is_use_candidate: bool,
103    /// The pair the request was sent on.
104    pub(crate) local_index: usize,
105    pub(crate) remote_index: usize,
106    /// The role attribute the request carried: ICE-CONTROLLING (true) or ICE-CONTROLLED. A 487
107    /// answer switches the role away from this one (RFC 8445 Section 7.2.5.1).
108    pub(crate) sent_as_controlling: bool,
109    /// The request as sent: a retransmission is the same message, transaction id included.
110    pub(crate) raw: BytesMut,
111    /// The RTO the transaction started with (RFC 8445 Section 14.3).
112    pub(crate) rto: Duration,
113    /// The wait before the next retransmission; doubles each time (RFC 8489 Section 6.2.1).
114    pub(crate) interval: Duration,
115    /// Requests sent so far, the first included.
116    pub(crate) transmissions: u16,
117    /// When the next retransmission is due, or, after the last one, when the transaction ends
118    /// without a response.
119    pub(crate) next_event: Instant,
120    /// Whether the request is retransmitted: not over TCP, not a consent request.
121    pub(crate) retransmit: bool,
122    /// Cancelled (RFC 8445 Section 7.3.1.4): no retransmission, no failure when it times out,
123    /// but a response is still taken.
124    pub(crate) cancelled: bool,
125    /// A consent request on the selected pair (RFC 7675), sent once.
126    pub(crate) consent: bool,
127    /// The PRIORITY the request carried: the priority of a local peer-reflexive candidate its
128    /// response may reveal (RFC 8445 Section 7.2.5.3.1).
129    pub(crate) priority: u32,
130    /// A response to it arrived and was discarded because its integrity check failed: if
131    /// the transaction ends without one that passes, that is an integrity violation, not a
132    /// timeout (RFC 8489 Section 9.1.4).
133    pub(crate) unauthentic_response: bool,
134}
135
136/// How long a consent request sent on a pair whose RTO is `rto` waits for its response, the
137/// consent expiry being `expiry`: see [`ConsentResponseWait`].
138pub(crate) fn consent_response_wait(
139    setting: ConsentResponseWait,
140    rto: Duration,
141    expiry: Duration,
142) -> Duration {
143    match setting {
144        // RFC 8489 Section 6.2.1: "If, after the last request, a duration equal to Rm times
145        // the RTO has passed without a response [...], the client SHOULD consider the
146        // transaction to have failed." A consent request is the first and the last of its
147        // transaction. Past the consent expiry consent has either been renewed by a later
148        // response or is lost, and then every transaction is discarded (RFC 7675 Section
149        // 5.1): no transaction is kept longer.
150        ConsentResponseWait::Rto => rto.saturating_mul(STUN_RM).min(expiry),
151        ConsentResponseWait::Fixed(wait) => wait,
152    }
153}
154
155impl BindingRequest {
156    /// A consent-style transaction (sent once) to `destination`, waiting until `timeout`.
157    #[cfg(test)]
158    pub(crate) fn sent_once(
159        now: Instant,
160        transaction_id: TransactionId,
161        destination: SocketAddr,
162        timeout: Duration,
163    ) -> Self {
164        Self {
165            timestamp: now,
166            transaction_id,
167            destination,
168            is_use_candidate: false,
169            local_index: 0,
170            remote_index: 0,
171            sent_as_controlling: true,
172            raw: BytesMut::new(),
173            rto: timeout,
174            interval: timeout,
175            transmissions: 1,
176            next_event: now + timeout,
177            retransmit: false,
178            cancelled: false,
179            consent: true,
180            priority: 0,
181            unauthentic_response: false,
182        }
183    }
184}
185
186/// A Binding request that arrived, authenticated, before the peer's credentials were known
187/// (RFC 8445 Section 7.3). It was answered at once; the rest of its processing (Sections
188/// 7.3.1.3 to 7.3.1.5) waits for the credentials.
189#[derive(Debug, Clone)]
190pub(crate) struct EarlyRequest {
191    pub(crate) message: Message,
192    pub(crate) local_addr: SocketAddr,
193    pub(crate) transport_protocol: TransportProtocol,
194    pub(crate) remote_addr: SocketAddr,
195}
196
197/// A candidate the peer signalled that the agent holds no pair for, but whose own checks can
198/// still reach the agent and teach it a peer-reflexive candidate (RFC 8445 Section 7.3.1.3): a
199/// `tcptype active` candidate (RFC 6544 Section 7.2: "STUN requests received on a passive TCP
200/// candidate will typically produce a remote peer reflexive candidate"), or a `.local` name
201/// the agent did not resolve (draft-ietf-mmusic-mdns-ice-candidates Section 5.3: "Through the
202/// process of learning peer-reflexive candidates [...] allowing ICE to succeed even though the
203/// legacy endpoint cannot resolve the mDNS names"). What the checklist's failure looks at.
204#[derive(Debug, Clone, Copy, PartialEq, Eq)]
205pub(crate) struct UnpairedRemote {
206    /// The candidate's network type; its address family is known only when `family_known`.
207    pub(crate) network_type: NetworkType,
208    /// The candidate's address is an IP address (not an unresolved name).
209    pub(crate) family_known: bool,
210    pub(crate) tcp_type: TcpType,
211}
212
213impl UnpairedRemote {
214    fn of(c: &Candidate) -> Self {
215        Self {
216            network_type: c.network_type(),
217            family_known: c.address().parse::<IpAddr>().is_ok(),
218            tcp_type: c.tcp_type(),
219        }
220    }
221
222    /// Adds `c`'s kind to `list` unless it is there already (the list stays a handful long).
223    fn note(list: &mut Vec<Self>, c: &Candidate) {
224        let kind = Self::of(c);
225        if !list.contains(&kind) {
226            list.push(kind);
227        }
228    }
229
230    /// Whether this remote candidate's checks can arrive on `local`: same transport (and
231    /// family, when known), and over TCP a candidate that dials one that listens (RFC 6544
232    /// Section 6.2: an active candidate pairs with a passive one, S-O with S-O).
233    fn can_reach(&self, local: &Candidate) -> bool {
234        let local_type = local.network_type();
235        local_type.to_protocol() == self.network_type.to_protocol()
236            && (!self.family_known || local_type == self.network_type)
237            && matches!(
238                (self.tcp_type, local.tcp_type()),
239                (TcpType::Unspecified, TcpType::Unspecified)
240                    | (TcpType::Active, TcpType::Passive)
241                    | (TcpType::SimultaneousOpen, TcpType::SimultaneousOpen)
242            )
243    }
244}
245
246/// What an ICE restart keeps of the generation it replaces, for as long as data still flows on
247/// that generation's selected pair ([`Agent::media_path`]).
248///
249/// RFC 7675 Section 5.1: "an endpoint that continues to send traffic on the previously
250/// validated candidate pair during ICE restart MUST continue to perform consent freshness on
251/// that candidate pair". Consent on that pair is asked for, and given to the peer, with the
252/// credentials the pair was validated with: the old ones, on both sides.
253#[derive(Clone)]
254pub(crate) struct PreviousGeneration {
255    /// The local credentials of the replaced generation: the peer's consent requests on the
256    /// old pair name this fragment and are signed with this password.
257    pub(crate) local_credentials: ErasedCredentials,
258    /// The peer's credentials of the replaced generation, for our own consent requests.
259    pub(crate) remote_credentials: ErasedCredentials,
260    /// The PRIORITY attribute of the consent requests.
261    pub(crate) priority: u32,
262    /// When the peer last consented (a lite agent: when it last sent an authenticated request).
263    pub(crate) last_consent: Instant,
264    pub(crate) next_consent_at: Instant,
265    /// Consent requests sent on the old pair that may still be answered: those the restart
266    /// found open on the selected pair, and those sent since.
267    pub(crate) pending: Vec<PreviousConsentRequest>,
268    /// The old pair's RTO (RFC 6298), as the pair had it at the restart and as the responses
269    /// since made it: what the wait of each request is based on.
270    pub(crate) rto: stun::timer::RtoEstimator,
271}
272
273/// One open consent transaction of a replaced generation.
274#[derive(Clone, Copy, Debug)]
275pub(crate) struct PreviousConsentRequest {
276    pub(crate) transaction_id: TransactionId,
277    /// When the request was sent.
278    pub(crate) sent: Instant,
279    /// When the transaction ends without a response: a response from then on is for a
280    /// transaction that is no longer in progress (RFC 8489 Section 6.3).
281    pub(crate) until: Instant,
282}
283
284/// Most consent transactions of a replaced generation kept open at a time: more than the
285/// requests of one consent expiry (at least 4 seconds apart, 30 seconds), and those of
286/// libwebrtc's 60 seconds ([`ConsentResponseWait::Fixed`]).
287pub(crate) const MAX_PREVIOUS_GENERATION_TRANSACTIONS: usize = 16;
288
289/// How long data is still taken on the path an ICE restart replaced, once the restart's pair
290/// is selected: each side selects on its own (the controlled agent at the nomination request,
291/// the controlling one at its response), so the peer may send on the previous path until its
292/// own selection switches. A datagram on that path, from that peer address, is the peer's (the
293/// previous generation's checks established it).
294pub(crate) const RETIRED_MEDIA_PATH_GRACE: Duration = Duration::from_secs(5);
295
296/// Most early requests remembered: one per (local, remote) address pair, so this bounds how
297/// many paths a peer can have probed before its description arrives.
298pub(crate) const MAX_EARLY_REQUESTS: usize = 16;
299
300#[derive(Default, Clone)]
301/// The ICE credentials for one side of a session, exchanged in SDP.
302pub struct Credentials {
303    /// The username fragment, echoed in every STUN check so a receiver can demultiplex.
304    pub ufrag: String,
305    /// The password, used as the `MESSAGE-INTEGRITY` key.
306    pub pwd: String,
307}
308
309/// [`Credentials`] as the agent keeps them: the password (the `MESSAGE-INTEGRITY` key) is
310/// overwritten when the value is dropped or replaced, so no copy the agent held is freed with
311/// it (the crate's key-erasure rule, docs/key-erasure.md). The public [`Credentials`] keeps its
312/// public fields; this wrapper is how the agent stores them.
313#[derive(Default, Clone)]
314pub(crate) struct ErasedCredentials(Credentials);
315
316impl From<Credentials> for ErasedCredentials {
317    fn from(credentials: Credentials) -> Self {
318        Self(credentials)
319    }
320}
321
322impl std::ops::Deref for ErasedCredentials {
323    type Target = Credentials;
324    fn deref(&self) -> &Credentials {
325        &self.0
326    }
327}
328
329/// Overwrites the passwords (TURN credentials) of `urls` in place, before they are freed.
330pub(crate) fn erase_url_passwords(urls: &mut [Url]) {
331    for url in urls {
332        zeroize::Zeroize::zeroize(&mut url.password);
333    }
334}
335
336/// The agent's copies of the TURN passwords are overwritten when it is dropped (its ICE
337/// passwords are in [`ErasedCredentials`]).
338impl Drop for Agent {
339    fn drop(&mut self) {
340        erase_url_passwords(&mut self.urls);
341    }
342}
343
344/// Tests set a field in place; the agent itself replaces whole values, which erases the old.
345#[cfg(test)]
346impl std::ops::DerefMut for ErasedCredentials {
347    fn deref_mut(&mut self) -> &mut Credentials {
348        &mut self.0
349    }
350}
351
352impl Drop for ErasedCredentials {
353    fn drop(&mut self) {
354        zeroize::Zeroize::zeroize(&mut self.0.pwd);
355    }
356}
357
358#[derive(Default, Clone)]
359pub(crate) struct UfragPwd {
360    pub(crate) local_credentials: ErasedCredentials,
361    pub(crate) remote_credentials: Option<ErasedCredentials>,
362    /// Credentials generated for an ICE restart that has not been applied yet.
363    ///
364    /// JSEP requires `createOffer` to be free of side effects, so the offer advertises these
365    /// while the live session keeps authenticating with `local_credentials`. They are installed
366    /// by [`Agent::apply_restart`] when the local description is set. If the offer is discarded,
367    /// they are simply dropped and the existing session is undisturbed.
368    pub(crate) pending_local_credentials: Option<ErasedCredentials>,
369}
370
371/// RFC 8445 Section 7.3: "the agent MUST consider the username to be valid if it consists of
372/// two values separated by a colon, where the first value is equal to the username fragment
373/// generated by the agent".
374fn assert_inbound_username(m: &Message, local_ufrag: &str) -> Result<()> {
375    let mut username = Username::new(ATTR_USERNAME, String::new());
376    username.get_from(m)?;
377
378    let text = username.to_string();
379    match text.split_once(':') {
380        Some((first, _)) if first == local_ufrag => Ok(()),
381        _ => Err(Error::Other(format!(
382            "{:?} expected({}:<remote fragment>) actual({})",
383            Error::ErrMismatchUsername,
384            local_ufrag,
385            username,
386        ))),
387    }
388}
389
390/// The comprehension-required attributes the ICE usage understands: STUN's own and ICE's
391/// (RFC 8445 Section 16.1). A request with another one is answered 420 (Unknown Attribute), a
392/// response with one is discarded (RFC 8489 Section 6.3). ICE-CONTROLLED, ICE-CONTROLLING and
393/// libwebrtc's NOMINATION are comprehension-optional.
394fn ice_known_attributes() -> Vec<AttrType> {
395    let mut known = stun::attributes::STUN_ATTRIBUTES.to_vec();
396    known.extend([ATTR_PRIORITY, ATTR_USE_CANDIDATE]);
397    known
398}
399
400/// What a received message is refused with, as the error the agent reports.
401fn rejection_error(rejection: &stun::validated::Rejection) -> Error {
402    use stun::validated::Rejection;
403    match rejection {
404        Rejection::IntegrityMismatch => Error::ErrIntegrityMismatch,
405        Rejection::IntegrityMissing => Error::ErrAttributeNotFound,
406        Rejection::FingerprintMissing | Rejection::FingerprintMismatch => {
407            Error::ErrFingerprintMismatch
408        }
409        other => Error::Other(other.to_string()),
410    }
411}
412
413/// Most remote candidates an agent holds. Browsers signal a few dozen at most; each one is paired
414/// with every local candidate, so an unbounded list is quadratic work for whoever sends it.
415pub(crate) const MAX_REMOTE_CANDIDATES: usize = 256;
416
417/// Most mDNS (`.local`) remote candidates waiting on a query at once.
418pub(crate) const MAX_PENDING_MDNS_QUERIES: usize = 32;
419
420fn assert_inbound_message_integrity(
421    m: &mut Message,
422    key: &[u8],
423    crypto: &dyn RTCCrypto,
424) -> Result<()> {
425    MessageIntegrity::check(m, key, crypto)
426}
427
428/// The SOFTWARE attribute the agent sends unless configured otherwise
429/// ([`AgentConfig::software`]).
430pub const DEFAULT_SOFTWARE: &str = concat!("rtci-ice ", env!("CARGO_PKG_VERSION"));
431
432/// What the agent reports to its caller.
433#[non_exhaustive]
434pub enum Event {
435    /// The agent's connection state changed.
436    ConnectionStateChange(ConnectionState),
437    /// A new pair was selected, carrying the local and remote candidates.
438    ///
439    /// Media should be sent on this pair from now on.
440    SelectedCandidatePairChange(Box<Candidate>, Box<Candidate>),
441    /// Emitted when the ICE role switches due to a role conflict (RFC 8445 §7.3.1.1).
442    /// The bool is `true` if the agent is now controlling, `false` if now controlled.
443    RoleChange(bool),
444    /// A local candidate is signalled differently from now on and has to be conveyed to the
445    /// peer again: its mDNS name was lost to another host (RFC 6762 Section 9) and it has a
446    /// new one. The candidate keeps its id.
447    LocalCandidateRenamed(Box<Candidate>),
448    /// Two lite agents, this one controlling, and more than one candidate pair: the agent
449    /// chose this pair (local, remote), and RFC 8445 Section 8.2 has the controlling agent
450    /// "send an updated candidate list to reconcile different agents selecting different
451    /// candidate pairs": an updated candidate exchange with these two candidates only.
452    LiteCandidateUpdate(Box<Candidate>, Box<Candidate>),
453    /// A candidate pair (local, remote) was put on the agent's list of pairs: formed from a
454    /// local and a remote candidate, from a peer's request, or as the valid pair a response
455    /// produced (webrtc-extensions 7, `icecandidatepairadd`).
456    CandidatePairAdded(Box<Candidate>, Box<Candidate>),
457    /// A candidate pair (local, remote) left the agent's list: another pair took its place
458    /// on a full checklist, an ICE restart dropped the pairs, or the application removed it
459    /// with [`Agent::remove_candidate_pair`] (webrtc-extensions 7, `icecandidatepairremove`).
460    CandidatePairRemoved(Box<Candidate>, Box<Candidate>),
461    /// With [`AgentConfig::candidate_pair_proposals`]: the controlling agent picked this pair
462    /// (local, remote) to nominate and waits for [`Agent::resolve_nomination_proposal`]
463    /// (webrtc-extensions 7, `icecandidatepairnominate`).
464    CandidatePairNominationProposed(Box<Candidate>, Box<Candidate>),
465    /// A check (or consent request) on this pair (local, remote) ended without a response
466    /// that passed its integrity check, and at least one response arrived that failed it:
467    /// RFC 8489 Section 9.1.4 has the transaction signal "an integrity protection violation"
468    /// instead of a timeout. The pair fails as it would on a timeout; the event says why.
469    IntegrityViolation(Box<Candidate>, Box<Candidate>),
470}
471
472/// An [`Event`] together with the instant its condition was observed at.
473///
474/// The agent's events are produced inside `handle_read` / `handle_timeout` / `close`, all of
475/// which know the time, but they are consumed from `poll_event`, which does not. Carrying the
476/// instant in the payload means the consumer is *told* when the condition happened rather than
477/// having to retain an instant of its own and guess — the same channel `TaggedBytesMut` already
478/// provides on the read path.
479pub struct TaggedEvent {
480    /// When the condition this event reports was observed.
481    pub now: Instant,
482    /// The event itself.
483    pub event: Event,
484}
485
486/// What ended the checks of an agent that reports `Disconnected` instead of `Failed` because
487/// the indication that there are no more candidates is missing (W3C webrtc-pc 5.6.4: "failed"
488/// needs the transport to have "finished gathering, received an indication that there are no
489/// more remote candidates"; until then, "disconnected": it "has finished checking all
490/// existing candidates pairs and not found a connection (or consent checks [RFC7675] once
491/// successful, have now failed), but it is still gathering and/or waiting for additional
492/// remote candidates"). See [`Agent::set_failed_without_end_of_candidates`].
493#[derive(Debug, Clone, Copy, PartialEq, Eq)]
494pub(crate) enum HeldFailure {
495    /// The checking timeout (`disconnected_timeout + failed_timeout`) passed with nothing left
496    /// that could produce a selected pair.
497    CheckingTimeout,
498    /// Consent expired on the selected pair (RFC 7675 Section 5.1) and no pair is left to
499    /// check.
500    ConsentExpired,
501    /// The nomination failed (RFC 8445 Section 7.2.5.3.4, `FailedNomination::FailChecklist`):
502    /// the checklist is Failed.
503    NominationFailed,
504}
505
506/// The addresses and transport data is sent on and accepted from. See [`Agent::media_path`].
507#[derive(Debug, Clone, Copy, PartialEq, Eq)]
508pub struct MediaPath {
509    /// The bound local address (a candidate's base).
510    pub local_addr: SocketAddr,
511    /// The remote candidate's address.
512    pub peer_addr: SocketAddr,
513    /// UDP or TCP.
514    pub transport_protocol: TransportProtocol,
515}
516
517/// The pair data arrived on. See [`Agent::data_path`].
518#[derive(Debug, Clone, Copy)]
519pub enum DataPath<'a> {
520    /// The path data is sent on: the selected pair's ([`Agent::media_path`]).
521    InUse,
522    /// Another valid pair: its local and remote candidates.
523    Valid(&'a Candidate, &'a Candidate),
524}
525
526/// Represents the ICE agent.
527pub struct Agent {
528    pub(crate) crypto_provider: Arc<dyn RTCCryptoProvider>,
529    pub(crate) tie_breaker: u64,
530    /// [`AgentConfig::new_tie_breaker_on_restart`].
531    pub(crate) new_tie_breaker_on_restart: bool,
532    pub(crate) is_controlling: bool,
533    pub(crate) lite: bool,
534
535    pub(crate) start_time: Instant,
536
537    pub(crate) connection_state: ConnectionState,
538    pub(crate) last_connection_state: ConnectionState,
539
540    //pub(crate) started_ch_tx: Mutex<Option<broadcast::Sender<()>>>,
541    pub(crate) ufrag_pwd: UfragPwd,
542
543    pub(crate) local_candidates: Vec<Candidate>,
544    pub(crate) remote_candidates: Vec<Candidate>,
545    pub(crate) candidate_pairs: Vec<CandidatePair>,
546    pub(crate) nominated_pair: Option<usize>,
547    /// [`AgentConfig::candidate_pair_proposals`].
548    pub(crate) candidate_pair_proposals: bool,
549    /// The pair proposed for nomination, waiting for the application's decision.
550    pub(crate) nomination_proposal: Option<usize>,
551    /// Pairs whose nomination the application declined (this ICE session).
552    pub(crate) declined_nominations: Vec<usize>,
553    /// When the controlling agent nominated `nominated_pair`.
554    pub(crate) nomination_started: Option<Instant>,
555    pub(crate) selected_pair: Option<usize>,
556    /// The selected pair's path at the moment an ICE restart was applied, kept until the
557    /// restart selects a pair (or the agent fails or closes). See [`Agent::media_path`].
558    pub(crate) previous_media_path: Option<MediaPath>,
559    /// `previous_media_path` once the restart selected a pair, with until when data is still
560    /// taken on it ([`RETIRED_MEDIA_PATH_GRACE`]). Nothing is sent on it.
561    pub(crate) retired_media_path: Option<(MediaPath, Instant)>,
562    /// The credentials and consent state that go with `previous_media_path`.
563    pub(crate) previous_generation: Option<PreviousGeneration>,
564    /// The type of the local candidate `previous_media_path` leaves from (a learned one's: its
565    /// base's), so that a later restart can tell whether the candidate types then allowed
566    /// still allow it ([`Agent::set_candidate_types`]).
567    pub(crate) previous_media_path_type: Option<CandidateType>,
568    /// The same for `retired_media_path`.
569    pub(crate) retired_media_path_type: Option<CandidateType>,
570    /// The session an ICE restart replaced, while that restart can be taken back
571    /// ([`Agent::apply_restart_revertible`]).
572    pub(crate) restart_undo: Option<Box<restart_undo::RestartUndo>>,
573
574    /// The open STUN transactions: one per check in flight, the consent requests, and the
575    /// cancelled ones still waiting out their timeout.
576    pub(crate) pending_binding_requests: Vec<BindingRequest>,
577    /// The triggered-check queue (RFC 8445 Section 6.1.4.1), FIFO, a pair named by its local
578    /// and remote candidate.
579    pub(crate) triggered_queue: VecDeque<(usize, usize)>,
580    /// Ta, the pacing of checks (Section 6.1.4.2), and when the next check may start.
581    pub(crate) ta: Duration,
582    pub(crate) next_check_at: Instant,
583    /// The most pairs on the checklist (Section 6.1.2.5).
584    pub(crate) max_candidate_pairs: usize,
585    /// The peer signalled end-of-candidates for this generation (RFC 8838 Section 14).
586    pub(crate) remote_end_of_candidates: bool,
587    /// Local gathering is complete for this generation (RFC 8838 Section 13).
588    pub(crate) local_gathering_complete: bool,
589    /// The peer's descriptions say it can trickle candidates (`a=ice-options:trickle`). When
590    /// they do not, its description held every candidate it has (W3C webrtc-pc 5.6.4: the
591    /// indication that there are no more remote candidates can be given "by
592    /// canTrickleIceCandidates being set to false"). See [`Agent::set_remote_trickles`].
593    pub(crate) remote_trickles: bool,
594    /// See [`Agent::set_failed_without_end_of_candidates`]. Off by default.
595    pub(crate) failed_without_end_of_candidates: bool,
596    /// The checks have failed, but without the indications [`Agent::may_report_failed`]
597    /// needs the agent reports `Disconnected`, not `Failed`: what ended them. Cleared by any
598    /// other state (a new pair makes the agent check again).
599    pub(crate) failure_held: Option<HeldFailure>,
600    /// The peer's signalled candidates of this generation that are not paired but whose
601    /// checks can still create a pair (each kind once).
602    pub(crate) unpaired_remotes: Vec<UnpairedRemote>,
603    /// Requests answered before the peer's credentials arrived, to finish processing then.
604    pub(crate) early_requests: Vec<EarlyRequest>,
605
606    // the following variables won't be changed after init_with_defaults()
607    pub(crate) max_binding_requests: u16,
608    pub(crate) host_acceptance_min_wait: Duration,
609    pub(crate) srflx_acceptance_min_wait: Duration,
610    pub(crate) prflx_acceptance_min_wait: Duration,
611    pub(crate) relay_acceptance_min_wait: Duration,
612    // How long connectivity checks can fail before the ICE Agent
613    // goes to disconnected
614    pub(crate) disconnected_timeout: Duration,
615    // How long connectivity checks can fail before the ICE Agent
616    // goes to failed
617    pub(crate) failed_timeout: Duration,
618    // The basic period of the consent checks (RFC 7675 Section 5.1), at least 5 seconds.
619    // 0 means never
620    pub(crate) keepalive_interval: Duration,
621    /// When the next consent request goes out on the selected pair: the last one plus an
622    /// interval drawn from 0.8 to 1.2 times the period. `None` until a pair is selected.
623    pub(crate) next_consent_at: Option<Instant>,
624    /// When the oldest consent request that no response has followed was sent. `None` while
625    /// the peer answers. The agent is `Disconnected` once this is `disconnected_timeout` old.
626    pub(crate) consent_unanswered_since: Option<Instant>,
627    // How often should we run our internal taskLoop to check for state changes when connecting
628    pub(crate) check_interval: Duration,
629    pub(crate) checking_duration: Instant,
630    pub(crate) last_checking_time: Instant,
631    /// The latest instant the agent was given (construction, `handle_read`, `handle_timeout`):
632    /// what the candidate-pair events of a call that is not given one are tagged with.
633    pub(crate) clock: Instant,
634    // When set, a connectivity check has been requested and must be run on the next
635    // `handle_timeout`. Checks are deferred (rather than run inline) so that adding a
636    // candidate can never re-enter `contact()` and mutate agent state - e.g. transition
637    // to `Failed` and drop candidates - while a caller still holds indices into the
638    // candidate vectors. See issue #88.
639    pub(crate) force_candidate_contact: bool,
640
641    pub(crate) mdns: Option<Mdns>,
642    pub(crate) mdns_queries: HashMap<QueryId, Candidate>,
643
644    pub(crate) mdns_mode: MulticastDnsMode,
645    pub(crate) mdns_local_name: String,
646    pub(crate) mdns_local_ip: Option<IpAddr>,
647    /// `QueryAndGather` without a fixed `mdns_local_ip`: the `<uuid>.local` name each local
648    /// address is published under, one per address, made when its first host candidate is added.
649    pub(crate) mdns_local_names: Vec<(IpAddr, String)>,
650    /// mDNS names lost to another host (RFC 6762 section 9) after this session's candidates
651    /// could no longer be conveyed (end-of-candidates, or a nominated pair; RFC 8838 section
652    /// 13): the lost name and its replacement. The session's candidates keep the name they
653    /// were conveyed with; the next ICE restart gives the kept ones the new name.
654    pub(crate) mdns_deferred_renames: Vec<(String, String)>,
655    /// `QueryAndGather`: the `<uuid>.local` name each local address whose name could not be
656    /// registered goes out under (never published), reused for its other candidates.
657    pub(crate) mdns_unpublished_names: Vec<(IpAddr, String)>,
658    /// [`AgentConfig::multicast_dns_fail_closed`].
659    pub(crate) mdns_fail_closed: bool,
660    /// [`AgentConfig::multicast_dns_publishing`], or what [`Agent::set_multicast_dns_publishing`]
661    /// set since.
662    pub(crate) mdns_publishing: MulticastDnsPublishing,
663    /// `QueryAndGather` with [`AgentConfig::multicast_dns_fail_closed`]: the local addresses
664    /// whose host candidates the agent withheld (their name could not be registered).
665    pub(crate) mdns_withheld: Vec<IpAddr>,
666    /// [`AgentConfig::multicast_dns_expose_known_public_addresses`].
667    pub(crate) mdns_expose_known_public: bool,
668    /// The local addresses gatherings showed to be public (draft Section 3.1.2.2), for
669    /// `mdns_expose_known_public`.
670    pub(crate) mdns_known_public: KnownPublicAddresses,
671    /// [`AgentConfig::multicast_dns_expose_temporary_ipv6_addresses`].
672    pub(crate) mdns_expose_temporary_ipv6: bool,
673    /// The addresses the application marked as RFC 4941 temporary
674    /// ([`Agent::set_temporary_ipv6_addresses`]).
675    pub(crate) temporary_ipv6_addresses: Vec<Ipv6Addr>,
676    /// Which ICE generation the agent is in: one more at each applied restart (the first one
677    /// made by `new`).
678    pub(crate) ice_generation: u64,
679
680    pub(crate) candidate_types: Vec<CandidateType>,
681    pub(crate) network_types: Vec<NetworkType>,
682    pub(crate) urls: Vec<Url>,
683
684    /// Which remote addresses checks may be sent to. See [`remote_policy`].
685    pub(crate) remote_policy: RemotePolicy,
686
687    /// The peer is a lite implementation (RFC 8445 Section 6.1.1; set by the using protocol).
688    pub(crate) remote_lite: bool,
689    /// The `LiteCandidateUpdate` event of this generation was raised.
690    pub(crate) lite_update_raised: bool,
691    /// Two lite agents, controlled: the updated candidate exchange of this generation was
692    /// taken ([`Agent::replace_remote_candidates`]).
693    pub(crate) lite_update_taken: bool,
694    /// Two lite agents, controlled: the local transport address an updated candidate
695    /// exchange named in `a=remote-candidates` (RFC 8839 Section 4.4.2.2), which the pair
696    /// takes as its local candidate. See [`Agent::replace_remote_candidates_pinning`].
697    pub(crate) pinned_local_addr: Option<SocketAddr>,
698    /// Ta as configured, before the peer's proposal (Section 14.2).
699    pub(crate) configured_ta: Option<Duration>,
700    /// Which of several nominations the controlled agent uses.
701    pub(crate) nomination_acceptance: NominationAcceptance,
702    /// What a nomination that times out leads to.
703    pub(crate) failed_nomination: FailedNomination,
704    pub(crate) pacing_group: Option<Arc<PacingGroup>>,
705    /// The controlling agent's consent checks carry USE-CANDIDATE (libwebrtc).
706    pub(crate) nominate_on_consent_checks: bool,
707    /// How long a consent request waits for its response.
708    pub(crate) consent_response_wait: ConsentResponseWait,
709    /// Error responses to unauthenticated requests, or nothing.
710    pub(crate) unauthenticated_requests: UnauthenticatedRequests,
711    /// The token bucket of those error responses: tokens left, and when it was last filled.
712    pub(crate) unauthenticated_response_tokens: u32,
713    pub(crate) unauthenticated_response_refill: Instant,
714    /// The integrity attribute of the request being answered: its responses carry the same one
715    /// and no other (RFC 8489 Section 9.1.3).
716    pub(crate) answer_integrity: IntegrityAlgorithm,
717    /// Data only from the selected pair's remote address (not RFC 8445 Section 12.2).
718    pub(crate) data_from_selected_pair_only: bool,
719    /// Data on the best valid pair before a pair is selected (RFC 8445 Section 12.1).
720    pub(crate) send_data_before_nomination: bool,
721    /// [`AgentConfig::hold_local_candidates_until_conveyed`].
722    pub(crate) hold_local_candidates_until_conveyed: bool,
723    /// [`AgentConfig::path_mtu`].
724    pub(crate) path_mtu: Option<usize>,
725    /// [`AgentConfig::software`], resolved: `None` sends no SOFTWARE attribute.
726    pub(crate) software: Option<String>,
727
728    /// The 1:1 NAT mapping applied to the host candidates the application adds.
729    pub(crate) ext_ip_mapper: Option<ExternalIpMapper>,
730
731    pub(crate) write_outs: VecDeque<TaggedBytesMut>,
732    pub(crate) event_outs: VecDeque<TaggedEvent>,
733}
734
735/// What [`Agent::mdns_name_for`] decided for a host candidate.
736enum MdnsHostName {
737    /// Publish it under this name.
738    Hide(String),
739    /// Keep its address.
740    Literal,
741    /// The name cannot be registered (no mDNS for the address's family, or too many names
742    /// are published already): the candidate takes this name, which is not published, and so
743    /// keeps its address private.
744    Unpublished(String),
745    /// The name cannot be registered and the agent fails closed
746    /// ([`AgentConfig::multicast_dns_fail_closed`]): no candidate.
747    Withhold,
748}
749
750/// RFC 8839 section 5.4: `ice-ufrag` is 4 to 256 `ice-char`s and `ice-pwd` 22 to 256, with
751/// "at least 24 bits" and "at least 128 bits of randomness"; an agent "MUST NOT send" a ufrag
752/// longer than 32 characters. Credentials the application supplies are held to that (the
753/// generated ones are 16 and 32 letters): too short is too few bits, other characters or a
754/// longer value are invalid.
755pub(crate) fn check_local_credentials(ufrag: &str, pwd: &str) -> Result<()> {
756    let ice_chars = |value: &str| {
757        value
758            .bytes()
759            .all(|b| b.is_ascii_alphanumeric() || b == b'+' || b == b'/')
760    };
761    if ufrag.len() < 4 || ufrag.len() * 8 < 24 {
762        return Err(Error::ErrLocalUfragInsufficientBits);
763    }
764    if pwd.len() < 22 || pwd.len() * 8 < 128 {
765        return Err(Error::ErrLocalPwdInsufficientBits);
766    }
767    if ufrag.len() > 32 || !ice_chars(ufrag) {
768        return Err(Error::ErrLocalUfragInvalid);
769    }
770    if pwd.len() > 256 || !ice_chars(pwd) {
771        return Err(Error::ErrLocalPwdInvalid);
772    }
773    Ok(())
774}
775
776impl Agent {
777    /// Creates a new Agent.
778    ///
779    /// The crypto provider is supplied by the caller; this crate never resolves a default.
780    /// Builds an agent whose clock starts at `now`.
781    ///
782    /// `now` is a constructor argument rather than an `AgentConfig` field because it is a value
783    /// consumed once at construction, not a setting that persists for the agent's lifetime — and
784    /// because `Instant` has no `Default`, so a config field would force `AgentConfig` to drop
785    /// `#[derive(Default)]` and break every `..Default::default()` in its 31 call sites.
786    pub fn new(
787        now: Instant,
788        config: Arc<AgentConfig>,
789        crypto_provider: Arc<dyn RTCCryptoProvider>,
790    ) -> Result<Self> {
791        let tie_breaker = match config.tie_breaker {
792            Some(tie_breaker) => tie_breaker,
793            None => generate_tie_breaker(crypto_provider.random())?,
794        };
795
796        let mut mdns_local_name = config.multicast_dns_local_name.clone();
797        if mdns_local_name.is_empty() {
798            mdns_local_name = generate_multicast_dns_name();
799        }
800
801        if !is_valid_local_mdns_name(&mdns_local_name) {
802            return Err(Error::ErrInvalidMulticastDnshostName);
803        }
804
805        let mdns_mode = config.multicast_dns_mode;
806        let mdns = create_multicast_dns(
807            now,
808            mdns_mode,
809            &mdns_local_name,
810            &config.multicast_dns_local_ip,
811            &config.multicast_dns_query_timeout,
812            MdnsOptions {
813                first_query_delay: config.multicast_dns_first_query_delay.unwrap_or(true),
814                multi_question_delay: config.multicast_dns_multi_question_delay.unwrap_or(true),
815                destination_reported: config.multicast_dns_destination_reported,
816                unicast_response: config.multicast_dns_unicast_response,
817                rate_limit: config.multicast_dns_rate_limit.clone(),
818            },
819        )
820        .unwrap_or_else(|err| {
821            // Opportunistic mDNS: If we can't open the connection, that's ok: we
822            // can continue without it.
823            warn!("Failed to initialize mDNS {mdns_local_name}: {err}");
824            None
825        });
826
827        let candidate_types = if config.candidate_types.is_empty() {
828            default_candidate_types()
829        } else {
830            config.candidate_types.clone()
831        };
832
833        if config.lite && (candidate_types.len() != 1 || candidate_types[0] != CandidateType::Host)
834        {
835            return Err(Error::ErrLiteUsingNonHostCandidates);
836        }
837
838        if !config.urls.is_empty()
839            && !contains_candidate_type(CandidateType::ServerReflexive, &candidate_types)
840            && !contains_candidate_type(CandidateType::Relay, &candidate_types)
841        {
842            return Err(Error::ErrUselessUrlsProvided);
843        }
844
845        let ext_ip_mapper = config.init_ext_ip_mapping(mdns_mode, &candidate_types)?;
846
847        let mut agent = Self {
848            crypto_provider,
849            tie_breaker,
850            // Set once the first `restart` below has initialised the agent: that one is not
851            // an ICE restart, and the configured tiebreaker must survive it.
852            new_tie_breaker_on_restart: false,
853            is_controlling: config.is_controlling,
854            lite: config.lite,
855
856            start_time: now,
857
858            nominated_pair: None,
859            candidate_pair_proposals: config.candidate_pair_proposals,
860            nomination_proposal: None,
861            declined_nominations: Vec::new(),
862            nomination_started: None,
863            selected_pair: None,
864            previous_media_path: None,
865            retired_media_path: None,
866            previous_generation: None,
867            previous_media_path_type: None,
868            retired_media_path_type: None,
869            restart_undo: None,
870            candidate_pairs: vec![],
871
872            connection_state: ConnectionState::New,
873
874            //started_ch_tx: MuteSome(started_ch_tx)),
875
876            //won't change after init_with_defaults()
877            max_binding_requests: if let Some(max_binding_requests) = config.max_binding_requests {
878                max_binding_requests
879            } else {
880                DEFAULT_MAX_BINDING_REQUESTS
881            },
882            host_acceptance_min_wait: if let Some(host_acceptance_min_wait) =
883                config.host_acceptance_min_wait
884            {
885                host_acceptance_min_wait
886            } else {
887                DEFAULT_HOST_ACCEPTANCE_MIN_WAIT
888            },
889            srflx_acceptance_min_wait: if let Some(srflx_acceptance_min_wait) =
890                config.srflx_acceptance_min_wait
891            {
892                srflx_acceptance_min_wait
893            } else {
894                DEFAULT_SRFLX_ACCEPTANCE_MIN_WAIT
895            },
896            prflx_acceptance_min_wait: if let Some(prflx_acceptance_min_wait) =
897                config.prflx_acceptance_min_wait
898            {
899                prflx_acceptance_min_wait
900            } else {
901                DEFAULT_PRFLX_ACCEPTANCE_MIN_WAIT
902            },
903            relay_acceptance_min_wait: if let Some(relay_acceptance_min_wait) =
904                config.relay_acceptance_min_wait
905            {
906                relay_acceptance_min_wait
907            } else {
908                DEFAULT_RELAY_ACCEPTANCE_MIN_WAIT
909            },
910
911            // How long connectivity checks can fail before the ICE Agent
912            // goes to disconnected
913            disconnected_timeout: if let Some(disconnected_timeout) = config.disconnected_timeout {
914                disconnected_timeout
915            } else {
916                DEFAULT_DISCONNECTED_TIMEOUT
917            },
918
919            // How long connectivity checks can fail before the ICE Agent
920            // goes to failed
921            failed_timeout: if let Some(failed_timeout) = config.failed_timeout {
922                failed_timeout
923            } else {
924                DEFAULT_FAILED_TIMEOUT
925            },
926
927            // The basic period of the consent checks; 0 means never. RFC 7675 Section 5.1:
928            // "Implementations MUST NOT set the period between checks to less than 4 seconds",
929            // and each interval is 0.8 to 1.2 times the basic period, so the basic period is
930            // at least 5 seconds.
931            keepalive_interval: match config.keepalive_interval {
932                Some(ZERO_DURATION) => ZERO_DURATION,
933                Some(keepalive_interval) => keepalive_interval.max(DEFAULT_KEEPALIVE_INTERVAL),
934                None => DEFAULT_KEEPALIVE_INTERVAL,
935            },
936
937            // How often should we run our internal taskLoop to check for state changes when connecting
938            check_interval: if config.check_interval == Duration::from_secs(0) {
939                DEFAULT_CHECK_INTERVAL
940            } else {
941                config.check_interval
942            },
943            next_consent_at: None,
944            consent_unanswered_since: None,
945            checking_duration: now,
946            last_checking_time: now,
947            clock: now,
948            force_candidate_contact: false,
949            last_connection_state: ConnectionState::Unspecified,
950
951            mdns,
952            mdns_queries: HashMap::new(),
953
954            mdns_mode,
955            mdns_local_name,
956            mdns_local_ip: config.multicast_dns_local_ip,
957            mdns_local_names: Vec::new(),
958            mdns_deferred_renames: Vec::new(),
959            mdns_unpublished_names: Vec::new(),
960            mdns_fail_closed: config.multicast_dns_fail_closed,
961            mdns_publishing: config.multicast_dns_publishing,
962            mdns_withheld: Vec::new(),
963            mdns_expose_known_public: config.multicast_dns_expose_known_public_addresses,
964            mdns_known_public: KnownPublicAddresses::default(),
965            mdns_expose_temporary_ipv6: config.multicast_dns_expose_temporary_ipv6_addresses,
966            temporary_ipv6_addresses: Vec::new(),
967            ice_generation: 0,
968
969            ufrag_pwd: UfragPwd::default(),
970
971            local_candidates: vec![],
972            remote_candidates: vec![],
973
974            pending_binding_requests: vec![],
975            triggered_queue: VecDeque::new(),
976            // RFC 8445 Section 14.2: 50 ms by default, never under 5 ms.
977            ta: config.ta.unwrap_or(DEFAULT_TA).max(MIN_TA),
978            next_check_at: now,
979            max_candidate_pairs: config
980                .max_candidate_pairs
981                .unwrap_or(DEFAULT_MAX_CANDIDATE_PAIRS)
982                .max(1),
983            remote_end_of_candidates: false,
984            local_gathering_complete: false,
985            remote_trickles: true,
986            failed_without_end_of_candidates: false,
987            failure_held: None,
988            unpaired_remotes: vec![],
989            early_requests: vec![],
990
991            candidate_types,
992            network_types: config.network_types.clone(),
993            urls: config.urls.clone(),
994
995            remote_policy: RemotePolicy {
996                allow_loopback: config.allow_loopback_remote_candidates,
997                allow_link_local: config.allow_link_local_remote_candidates,
998                filter: config.remote_address_filter.clone(),
999                address: config.address_policy.clone(),
1000            },
1001            ext_ip_mapper,
1002
1003            remote_lite: false,
1004            lite_update_raised: false,
1005            lite_update_taken: false,
1006            pinned_local_addr: None,
1007            configured_ta: config.ta,
1008            nomination_acceptance: config.nomination_acceptance,
1009            failed_nomination: config.failed_nomination,
1010            pacing_group: config.pacing_group.clone(),
1011            nominate_on_consent_checks: config.nominate_on_consent_checks,
1012            consent_response_wait: config.consent_response_wait,
1013            unauthenticated_requests: config.unauthenticated_requests,
1014            unauthenticated_response_tokens: MAX_UNAUTHENTICATED_RESPONSE_BURST,
1015            unauthenticated_response_refill: now,
1016            answer_integrity: IntegrityAlgorithm::Sha1,
1017            data_from_selected_pair_only: config.data_from_selected_pair_only,
1018            send_data_before_nomination: config.send_data_before_nomination,
1019            hold_local_candidates_until_conveyed: config.hold_local_candidates_until_conveyed,
1020            path_mtu: config.path_mtu,
1021            software: match &config.software {
1022                None => Some(DEFAULT_SOFTWARE.to_owned()),
1023                Some(s) if s.is_empty() => None,
1024                Some(s) => Some(s.clone()),
1025            },
1026
1027            write_outs: VecDeque::new(),
1028            event_outs: VecDeque::new(),
1029        };
1030
1031        // Restart is also used to initialize the agent for the first time
1032        if let Err(err) = agent.restart(
1033            now,
1034            config.local_ufrag.clone(),
1035            config.local_pwd.clone(),
1036            false,
1037        ) {
1038            let _ = agent.close();
1039            return Err(err);
1040        }
1041        agent.new_tie_breaker_on_restart = config.new_tie_breaker_on_restart;
1042
1043        Ok(agent)
1044    }
1045
1046    /// Adds a new local candidate that the caller conveys to the peer with this call (trickles
1047    /// it, or writes it into the description it sends): the agent pairs it at once.
1048    ///
1049    /// RFC 8838 Section 10: "A Trickle ICE agent MUST NOT pair a local candidate until it has
1050    /// been trickled to the remote party." A caller that gathers a candidate before it can
1051    /// convey it adds it with [`Agent::add_unconveyed_local_candidate`] and tells the agent
1052    /// with [`Agent::local_candidate_conveyed`] when it has.
1053    ///
1054    /// With [`AgentConfig::hold_local_candidates_until_conveyed`] this is
1055    /// [`Agent::add_unconveyed_local_candidate`].
1056    pub fn add_local_candidate(&mut self, c: Candidate) -> Result<bool> {
1057        let hold = self.hold_local_candidates_until_conveyed;
1058        self.add_gathered_local_candidate(c, hold)
1059    }
1060
1061    /// Adds a new local candidate that is not conveyed to the peer yet: the agent holds it,
1062    /// answers checks that reach it, and pairs it once [`Agent::local_candidate_conveyed`]
1063    /// (or [`Agent::all_local_candidates_conveyed`]) says it has been trickled (RFC 8838
1064    /// Section 10). Otherwise as [`Agent::add_local_candidate`]; a server-reflexive candidate
1065    /// the agent adds next to it for a 1:1 NAT mapping is held too.
1066    pub fn add_unconveyed_local_candidate(&mut self, c: Candidate) -> Result<bool> {
1067        self.add_gathered_local_candidate(c, true)
1068    }
1069
1070    /// The local candidate `id` has been conveyed to the peer: it is paired now with the
1071    /// remote candidates known (RFC 8838 Section 10, steps 2 and 3). Returns whether the
1072    /// agent held such a candidate unconveyed.
1073    pub fn local_candidate_conveyed(&mut self, id: &str) -> bool {
1074        let Some(local_index) = self
1075            .local_candidates
1076            .iter()
1077            .position(|c| c.unconveyed && c.id() == id)
1078        else {
1079            return false;
1080        };
1081        self.convey_local_candidate(local_index);
1082        true
1083    }
1084
1085    /// Every local candidate the agent holds has been conveyed to the peer (a description
1086    /// listing them was applied, say): each one held unconveyed is paired now.
1087    pub fn all_local_candidates_conveyed(&mut self) {
1088        for local_index in 0..self.local_candidates.len() {
1089            if self.local_candidates[local_index].unconveyed {
1090                self.convey_local_candidate(local_index);
1091            }
1092        }
1093    }
1094
1095    /// RFC 8839 Sections 4.2.5, 4.3.3 and 5.3: the answer carries `a=ice-mismatch` for the
1096    /// data stream this agent serves (the offer arrived at the peer with a default destination
1097    /// that no candidate matched), so "ICE procedures MUST NOT be used for this data stream".
1098    /// The agent stops: no more checks or consent requests, no candidates, state `Failed`.
1099    /// The RFC 3264 fallback the RFC then calls for (media to the `m=` / `c=` destination
1100    /// without checks) is not taken: a WebRTC endpoint sends nothing without consent (RFC
1101    /// 7675 Section 5.1), so the stream ends with the agent. Returns whether the agent was
1102    /// running.
1103    pub fn stop_for_ice_mismatch(&mut self, now: Instant) -> bool {
1104        if matches!(
1105            self.connection_state,
1106            ConnectionState::Failed | ConnectionState::Closed
1107        ) {
1108            return false;
1109        }
1110        warn!(
1111            "[{}]: the answer says ice-mismatch: ICE is not used for this stream",
1112            self.get_name()
1113        );
1114        self.update_connection_state(Some(now), ConnectionState::Failed);
1115        true
1116    }
1117
1118    /// Whether the local candidate `id` is held unconveyed (and so unpaired).
1119    pub fn is_local_candidate_unconveyed(&self, id: &str) -> bool {
1120        self.local_candidates
1121            .iter()
1122            .any(|c| c.unconveyed && c.id() == id)
1123    }
1124
1125    fn convey_local_candidate(&mut self, local_index: usize) {
1126        self.local_candidates[local_index].unconveyed = false;
1127        self.pair_local_candidate(local_index);
1128    }
1129
1130    /// Pairs a conveyed local candidate with every remote candidate it can be paired with.
1131    fn pair_local_candidate(&mut self, local_index: usize) {
1132        if self.local_candidates[local_index].held_from_pairing() {
1133            return;
1134        }
1135        for remote_index in 0..self.remote_candidates.len() {
1136            if self.local_candidates[local_index]
1137                .can_pair_with(&self.remote_candidates[remote_index])
1138            {
1139                self.add_pair(local_index, remote_index);
1140            }
1141        }
1142        self.request_connectivity_check();
1143    }
1144
1145    fn add_gathered_local_candidate(&mut self, c: Candidate, unconveyed: bool) -> Result<bool> {
1146        self.note_public_address(&c);
1147        self.take_local_candidate(c, unconveyed)
1148    }
1149
1150    /// The ICE generation a local candidate added now belongs to: the next one while a
1151    /// restart is staged (see `add_gathered_local_candidate`'s `staged`).
1152    fn local_candidate_generation(&self) -> u64 {
1153        self.ice_generation + u64::from(self.has_pending_restart())
1154    }
1155
1156    /// draft-ietf-mmusic-mdns-ice-candidates Section 3.1.2.2: "If the STUN response returns
1157    /// the same value as the local IP address, this indicates the address is in fact public".
1158    /// With [`AgentConfig::multicast_dns_expose_known_public_addresses`] in `QueryAndGather`,
1159    /// a server-reflexive candidate the application adds whose address is its base's records
1160    /// that base as public for this generation, when the base is the address of a host
1161    /// candidate the agent holds (its own interface: a STUN server cannot name another) and
1162    /// a global unicast address.
1163    fn note_public_address(&mut self, c: &Candidate) {
1164        if !self.mdns_expose_known_public
1165            || self.mdns_mode != MulticastDnsMode::QueryAndGather
1166            || c.candidate_type() != CandidateType::ServerReflexive
1167        {
1168            return;
1169        }
1170        let Some(base) = c
1171            .related_address()
1172            .and_then(|related| related.address.parse::<IpAddr>().ok())
1173        else {
1174            return;
1175        };
1176        if c.addr().ip() != base || !crate::mdns::is_global_unicast(base) {
1177            return;
1178        }
1179        let own_interface = self
1180            .local_candidates
1181            .iter()
1182            .any(|h| h.candidate_type() == CandidateType::Host && h.addr().ip() == base);
1183        if !own_interface {
1184            return;
1185        }
1186        let generation = self.local_candidate_generation();
1187        debug!(
1188            "[{}]: {} shown public by a server-reflexive candidate (generation {})",
1189            self.get_name(),
1190            base,
1191            generation
1192        );
1193        self.mdns_known_public.record(base, generation);
1194    }
1195
1196    /// draft-ietf-mmusic-mdns-ice-candidates Section 3.1.1 step 1: whether the host candidate
1197    /// `c` is "safe to expose" under one of the two opt-in settings, and so keeps its
1198    /// address in `QueryAndGather`: a global unicast address (never anything
1199    /// [`crate::mdns::is_global_unicast`] refuses) that the gathering before this generation
1200    /// showed public ([`AgentConfig::multicast_dns_expose_known_public_addresses`]), or that
1201    /// the application marked as an RFC 4941 temporary IPv6 address
1202    /// ([`AgentConfig::multicast_dns_expose_temporary_ipv6_addresses`]).
1203    fn exposes_host_address(&self, c: &Candidate) -> bool {
1204        self.exposes_address(c.addr().ip(), self.local_candidate_generation())
1205    }
1206
1207    /// [`Agent::exposes_host_address`] for an address and a generation.
1208    fn exposes_address(&self, ip: IpAddr, generation: u64) -> bool {
1209        if !crate::mdns::is_global_unicast(ip) {
1210            return false;
1211        }
1212        let known_public =
1213            self.mdns_expose_known_public && self.mdns_known_public.exposes(ip, generation);
1214        let temporary = self.mdns_expose_temporary_ipv6
1215            && matches!(ip, IpAddr::V6(v6) if self.temporary_ipv6_addresses.contains(&v6));
1216        known_public || temporary
1217    }
1218
1219    /// A restart that keeps the local candidates hands them to the new generation, which is
1220    /// a new gathering phase (draft-ietf-mmusic-mdns-ice-candidates Section 3.1.2.2): with
1221    /// one of the exposure settings in `QueryAndGather`, each kept host candidate takes the
1222    /// form the new generation gives its address (its address, or its name again), as one
1223    /// gathered anew would. A kept server-reflexive candidate that becomes redundant with an
1224    /// unwrapped host candidate (RFC 8445 Section 5.1.3), or a kept candidate equal to one
1225    /// gathered while the restart was staged, is dropped; one whose name can no longer be
1226    /// registered under `multicast_dns_fail_closed` is withheld.
1227    fn reevaluate_kept_host_candidates(&mut self) {
1228        if self.mdns_mode != MulticastDnsMode::QueryAndGather
1229            || !(self.mdns_expose_known_public || self.mdns_expose_temporary_ipv6)
1230        {
1231            return;
1232        }
1233        let generation = self.ice_generation;
1234        let mut index = 0;
1235        while index < self.local_candidates.len() {
1236            let c = &self.local_candidates[index];
1237            if c.candidate_type() != CandidateType::Host {
1238                index += 1;
1239                continue;
1240            }
1241            let (ip, network_type) = (c.addr().ip(), c.network_type());
1242            let named = c.address().ends_with(".local");
1243            let address = if self.exposes_address(ip, generation) {
1244                (named).then(|| ip.to_string())
1245            } else if !named {
1246                match self.mdns_name_for(ip, network_type) {
1247                    MdnsHostName::Hide(name) | MdnsHostName::Unpublished(name) => Some(name),
1248                    MdnsHostName::Literal => None,
1249                    MdnsHostName::Withhold => {
1250                        if !self.mdns_withheld.contains(&ip) {
1251                            self.mdns_withheld.push(ip);
1252                        }
1253                        self.local_candidates.remove(index);
1254                        continue;
1255                    }
1256                }
1257            } else {
1258                None
1259            };
1260            let Some(address) = address else {
1261                index += 1;
1262                continue;
1263            };
1264            self.local_candidates[index].address = address;
1265            let c = &self.local_candidates[index];
1266            let duplicate = self
1267                .local_candidates
1268                .iter()
1269                .enumerate()
1270                .any(|(other, o)| other != index && o.equal(c));
1271            if duplicate {
1272                self.local_candidates.remove(index);
1273                continue;
1274            }
1275            if !c.address().ends_with(".local") {
1276                let (addr, tcp_type) = (c.addr(), c.tcp_type());
1277                let redundant = |o: &Candidate| {
1278                    o.candidate_type() == CandidateType::ServerReflexive
1279                        && o.network_type() == network_type
1280                        && o.tcp_type() == tcp_type
1281                        && o.addr() == addr
1282                        && o.base_addr() == addr
1283                };
1284                let before = self.local_candidates[..index]
1285                    .iter()
1286                    .filter(|o| redundant(o))
1287                    .count();
1288                self.local_candidates.retain(|o| !redundant(o));
1289                index -= before;
1290            }
1291            index += 1;
1292        }
1293    }
1294
1295    /// Marks the local addresses that are RFC 4941 temporary IPv6 addresses (replacing what
1296    /// was marked before). The operating system knows which they are, the engine cannot tell
1297    /// from the bits: the application (`rtci-stream-driver`'s `PeerDriver` does it from the
1298    /// interface list) says so before it adds their host candidates. Only with
1299    /// [`AgentConfig::multicast_dns_expose_temporary_ipv6_addresses`] in `QueryAndGather`
1300    /// does it change anything: host candidates added afterwards on a marked address that is
1301    /// a global unicast address keep the address (draft-ietf-mmusic-mdns-ice-candidates
1302    /// Section 3.1.2.3). Candidates added before keep their form.
1303    pub fn set_temporary_ipv6_addresses(&mut self, addresses: Vec<Ipv6Addr>) {
1304        self.temporary_ipv6_addresses = addresses;
1305    }
1306
1307    /// The STUN / TURN servers the application gathers with now (`AgentConfig::urls` at
1308    /// first). When the set differs from the one before (credentials aside), what gatherings
1309    /// showed about public addresses is discarded (draft-ietf-mmusic-mdns-ice-candidates
1310    /// Section 3.1.2.2: "if the set of STUN servers changes, any cached information SHOULD be
1311    /// discarded, as the new set may return different results").
1312    pub fn set_ice_servers(&mut self, urls: Vec<Url>) {
1313        fn key(url: &Url) -> (String, String, u16, String) {
1314            (
1315                url.scheme.to_string(),
1316                url.host.to_ascii_lowercase(),
1317                url.port,
1318                url.proto.to_string(),
1319            )
1320        }
1321        let mut before: Vec<_> = self.urls.iter().map(key).collect();
1322        let mut after: Vec<_> = urls.iter().map(key).collect();
1323        before.sort();
1324        before.dedup();
1325        after.sort();
1326        after.dedup();
1327        if before != after && !self.mdns_known_public.is_empty() {
1328            debug!(
1329                "[{}]: the STUN / TURN servers changed: public addresses forgotten",
1330                self.get_name()
1331            );
1332            self.mdns_known_public.clear();
1333        }
1334        erase_url_passwords(&mut self.urls);
1335        self.urls = urls;
1336    }
1337
1338    fn take_local_candidate(&mut self, mut c: Candidate, unconveyed: bool) -> Result<bool> {
1339        // Filter by network type if network_types is configured
1340        if !self.network_types.is_empty() {
1341            let candidate_network_type = c.network_type();
1342            if !self.network_types.contains(&candidate_network_type) {
1343                debug!(
1344                    "Ignoring local candidate with network type {:?} (not in configured network types: {:?})",
1345                    candidate_network_type, self.network_types
1346                );
1347                return Ok(false);
1348            }
1349        }
1350
1351        // Filter by candidate type if candidate_types is configured.
1352        let candidate_type = c.candidate_type();
1353        if !self.candidate_types.is_empty() && !self.candidate_types.contains(&candidate_type) {
1354            debug!(
1355                "Ignoring local candidate with type {:?} (not in configured candidate types: {:?})",
1356                candidate_type, self.candidate_types
1357            );
1358            return Ok(false);
1359        }
1360
1361        // RFC 8839 section 5.1: "rel-addr and rel-port ... MUST be present for server
1362        // reflexive, peer-reflexive and relayed candidates". A local one given without its
1363        // related address would be signalled as `raddr  rport 0`: it is refused.
1364        if matches!(
1365            candidate_type,
1366            CandidateType::ServerReflexive | CandidateType::Relay | CandidateType::PeerReflexive
1367        ) && c
1368            .related_address()
1369            .is_none_or(|related| related.address.is_empty())
1370        {
1371            return Err(Error::ErrLocalCandidateWithoutRelatedAddress);
1372        }
1373
1374        if c.candidate_type() == CandidateType::Host
1375            && self.mdns_mode == MulticastDnsMode::QueryAndGather
1376            && !c.address.ends_with(".local")
1377            && !self.exposes_host_address(&c)
1378        {
1379            match self.mdns_name_for(c.addr().ip(), c.network_type()) {
1380                MdnsHostName::Hide(name) => {
1381                    trace!("mDNS hides local ip {} with local name {}", c.address, name);
1382                    c.address = name;
1383                }
1384                MdnsHostName::Literal => {}
1385                MdnsHostName::Unpublished(name) => {
1386                    // draft-ietf-mmusic-mdns-ice-candidates Section 3.1.1: "the ICE agent
1387                    // SHOULD still provide mDNS candidates in step 6 even if [...] mDNS
1388                    // registration fails in step 4": the candidate goes out under a name
1389                    // that is never published (it does not resolve), so neither its address
1390                    // nor the failure shows.
1391                    warn!(
1392                        "[{}]: local host candidate {} goes out under an unpublished mDNS name: no mDNS for its address family, or {} names already published (the cap)",
1393                        self.get_name(),
1394                        c.address,
1395                        mdns::MAX_LOCAL_NAMES
1396                    );
1397                    c.address = name;
1398                }
1399                MdnsHostName::Withhold => {
1400                    // `multicast_dns_fail_closed`: the address is never written, and no
1401                    // candidate the peer cannot resolve is offered either.
1402                    warn!(
1403                        "[{}]: local host candidate {} withheld: its mDNS name cannot be registered (fail closed)",
1404                        self.get_name(),
1405                        c.address
1406                    );
1407                    let ip = c.addr().ip();
1408                    if !self.mdns_withheld.contains(&ip) {
1409                        self.mdns_withheld.push(ip);
1410                    }
1411                    return Ok(false);
1412                }
1413            }
1414        }
1415
1416        // 1:1 NAT (`nat_1to1_ips`): the host candidate is advertised on, or joined by a
1417        // server-reflexive candidate on, the external address of its local one.
1418        let nat_srflx = self.apply_nat_1to1(&mut c);
1419
1420        // A candidate gathered while an ICE restart is staged (the remote restart offer is
1421        // applied, the answer not yet; or the restart offer is created, not yet applied) is
1422        // the new generation's: the peer connection announces it with the new credentials
1423        // (W3C webrtc-pc 5.6: a candidate gathered for a generation whose description is not
1424        // applied yet waits for it, it is not dropped). The rules below that bind the current
1425        // session do not apply to it, and the restart keeps it (`apply_restart`).
1426        let staged = self.has_pending_restart();
1427
1428        // RFC 8838 Section 13: no candidate follows the end-of-candidates indication of its
1429        // generation.
1430        if self.local_gathering_complete && !staged {
1431            warn!(
1432                "[{}]: ignoring local candidate {}: gathering was declared complete",
1433                self.get_name(),
1434                c
1435            );
1436            return Ok(false);
1437        }
1438        // RFC 8838 Section 13: "In all cases, an agent MUST NOT trickle any new candidates
1439        // within an ICE session after nomination of a candidate pair". A candidate gathered
1440        // after it is not taken (so not announced either); an ICE restart takes it. One
1441        // gathered for a staged restart is taken but not paired before the restart.
1442        let awaiting_restart = self.selected_pair.is_some();
1443        if awaiting_restart && !staged {
1444            debug!(
1445                "[{}]: ignoring local candidate {}: a pair has been nominated",
1446                self.get_name(),
1447                c
1448            );
1449            return Ok(false);
1450        }
1451
1452        // RFC 8445 Section 5.2: a lite implementation has only host candidates, "zero or one
1453        // candidate per IP address": another type, or a second candidate on an address it
1454        // already has a candidate on, is not taken. RFC 6544 Section 4.4 adds TCP to it: "In
1455        // the lite mode, for TCP candidates, only passive host candidates are gathered, unless
1456        // active candidates are needed as the default candidates. Otherwise, the procedures
1457        // described for lite mode ... also apply to TCP candidates": one candidate per IP
1458        // address for each of UDP, passive TCP and active TCP (the active one is the default
1459        // candidate of the updated offer of two lite agents whose offerer connects, Section
1460        // 6.1, and a lite agent cannot add it later without a restart, RFC 8839 Section
1461        // 4.4.1.3); no simultaneous-open candidate.
1462        if self.lite
1463            && (c.candidate_type() != CandidateType::Host
1464                || c.tcp_type() == TcpType::SimultaneousOpen
1465                || self.local_candidates.iter().any(|cand| {
1466                    cand.addr().ip() == c.addr().ip()
1467                        && cand.network_type().is_tcp() == c.network_type().is_tcp()
1468                        && cand.tcp_type() == c.tcp_type()
1469                }))
1470        {
1471            warn!(
1472                "[{}]: ignoring local candidate {}: a lite agent has one host candidate per IP address",
1473                self.get_name(),
1474                c
1475            );
1476            return Ok(false);
1477        }
1478
1479        for index in 0..self.local_candidates.len() {
1480            let cand = &self.local_candidates[index];
1481            let equal = cand.equal(&c);
1482            // RFC 8445 Section 5.1.3: "A candidate is redundant if and only if its transport
1483            // address and base equal those of another candidate" (a server-reflexive candidate
1484            // equal to its host candidate, a relayed one identical to a host candidate). An
1485            // mDNS host candidate hides its address: a reflexive candidate on that address is
1486            // not redundant with it (draft-ietf-mmusic-mdns-ice-candidates Section 3.1.2.2).
1487            let redundant = !equal
1488                && cand.network_type() == c.network_type()
1489                && cand.tcp_type() == c.tcp_type()
1490                && cand.addr() == c.addr()
1491                && cand.base_addr() == c.base_addr()
1492                && !cand.addr().ip().is_unspecified()
1493                && !cand.address().ends_with(".local")
1494                && !c.address().ends_with(".local")
1495                && cand.address() == c.address();
1496            if equal || redundant {
1497                if redundant {
1498                    debug!(
1499                        "[{}]: ignoring redundant local candidate {} (same address and base as {})",
1500                        self.get_name(),
1501                        c,
1502                        cand
1503                    );
1504                }
1505                // Gathered again for a staged restart: the candidate held is the new
1506                // generation's too.
1507                if staged {
1508                    self.local_candidates[index].restart_generation = true;
1509                }
1510                return Ok(false);
1511            }
1512        }
1513
1514        self.rank_local_candidate(&mut c);
1515
1516        // With host addresses hidden behind mDNS names, a reflexive or relayed candidate does
1517        // not give its base away in raddr / rport (mDNS draft Section 3.1.2.2). Nor does a
1518        // relayed candidate when only relayed candidates are gathered (the W3C "relay" ICE
1519        // transport policy): RFC 8827 section 6.4, the mechanism that keeps the local
1520        // addresses from the peer "MUST also suppress the related address".
1521        let relay_only = self.candidate_types == [CandidateType::Relay];
1522        if (self.mdns_mode == MulticastDnsMode::QueryAndGather || relay_only)
1523            && c.candidate_type() != CandidateType::Host
1524            && c.related_address().is_some()
1525        {
1526            c.hide_related_address = true;
1527        }
1528
1529        c.unconveyed = unconveyed;
1530        c.restart_generation = staged;
1531        c.awaiting_restart = staged && awaiting_restart;
1532        self.local_candidates.push(c);
1533        let local_index = self.local_candidates.len() - 1;
1534
1535        // RFC 8838 Section 10: a candidate not yet conveyed to the peer is not paired.
1536        self.pair_local_candidate(local_index);
1537
1538        if let Some(srflx) = nat_srflx {
1539            self.take_local_candidate(srflx, unconveyed)?;
1540        }
1541
1542        Ok(true)
1543    }
1544
1545    /// Adds local candidates gathered together: those without a priority or a rank of their
1546    /// own are ranked first as RFC 8421 Section 4 recommends for a dual-stack host (an IPv6
1547    /// head start, then the families alternating; see
1548    /// [`rank_local_candidates`]), around the ranks
1549    /// of the candidates the agent holds, and then each is added as by
1550    /// [`Agent::add_local_candidate`], whose results are returned in order.
1551    pub fn add_local_candidates(&mut self, mut candidates: Vec<Candidate>) -> Result<Vec<bool>> {
1552        crate::candidate::assign_dual_stack_ranks(&self.local_candidates, &mut candidates);
1553        candidates
1554            .into_iter()
1555            .map(|c| self.add_local_candidate(c))
1556            .collect()
1557    }
1558
1559    /// Gives a local candidate that has neither a priority nor a rank of its own a local
1560    /// preference no other local candidate of its type has (RFC 8445 Section 5.1.2.1: "If
1561    /// there are multiple candidates for a particular component for a particular data stream
1562    /// that have the same type, the local preference MUST be unique for each one"; RFC 6544
1563    /// Section 4.2 says the same of a TCP candidate's other-pref).
1564    ///
1565    /// Candidates are ranked in the order they are added, the two address families
1566    /// interleaved (RFC 8421 Section 4): the family of the first candidate of a type takes the
1567    /// even ranks, the other family the odd ones, so neither family's candidates are all
1568    /// checked before the other's. The first candidate keeps the largest value (65535), as
1569    /// Section 5.1.2.1 asks of an agent with one address. A priority that has been signalled
1570    /// never changes, which is why a later candidate cannot go ahead of an earlier one: an
1571    /// application that wants IPv6 first adds its candidates together with
1572    /// [`Agent::add_local_candidates`] (RFC 8421's IPv6 head start), adds an IPv6 candidate
1573    /// first, or ranks candidates itself with [`Candidate::set_local_preference_rank`].
1574    fn rank_local_candidate(&self, c: &mut Candidate) {
1575        if c.priority_override != 0 || c.local_preference_rank.is_some() {
1576            return;
1577        }
1578        let same_group = |other: &&Candidate| {
1579            other.candidate_type() == c.candidate_type()
1580                && other.component() == c.component()
1581                && other.network_type().is_tcp() == c.network_type().is_tcp()
1582                && other.tcp_type() == c.tcp_type()
1583                // (A lite agent's ranked candidates carry their priority as an override.)
1584                && (other.priority_override == 0 || other.local_preference_rank.is_some())
1585        };
1586        let ranked: Vec<&Candidate> = self.local_candidates.iter().filter(same_group).collect();
1587        let is_v6 = |x: &Candidate| x.network_type().is_ipv6();
1588        let parity = match ranked.first() {
1589            Some(first) if is_v6(first) != is_v6(c) => 1u16,
1590            _ => 0,
1591        };
1592        let mut rank = parity;
1593        while ranked
1594            .iter()
1595            .any(|other| other.local_preference_rank.unwrap_or(0) == rank)
1596        {
1597            match rank.checked_add(2) {
1598                Some(next) => rank = next,
1599                None => break,
1600            }
1601        }
1602        c.local_preference_rank = Some(rank);
1603
1604        // RFC 8445 Section 5.2: "If an ICE lite agent is dual-stack or IPv6-only, the local
1605        // preference SHOULD be set to the precedence value for IP addresses described in [RFC
1606        // 6724]" (an IPv4-only lite agent keeps 65535). The precedence takes the high byte, so
1607        // it orders the candidates, and the rank the low one, so that two candidates of one
1608        // precedence still have unique priorities (Section 5.2: "each candidate MUST have a
1609        // unique priority").
1610        //
1611        // A TCP candidate keeps RFC 6544 section 4.2's form, "local preference = (2^13) *
1612        // direction-pref + other-pref", the precedence going into other-pref ("the preference
1613        // for the particular IP address from which the candidate was obtained"), followed by
1614        // the rank: an active and a passive candidate on one address must not share a priority
1615        // (two lite agents pick their pair by it, RFC 8445 Section 8.2, and the controlling
1616        // one opens the connection of an active-to-passive pair, RFC 6544 Section 6.1).
1617        if self.lite && self.is_dual_stack_or_ipv6(c) {
1618            let precedence = rfc6724_precedence(c.addr().ip());
1619            let local_preference = if c.network_type().is_tcp() {
1620                (1u16 << 13) * c.tcp_direction_pref()
1621                    + ((u16::from(precedence) << 7) | (127 - rank.min(127)))
1622            } else {
1623                (u16::from(precedence) << 8) | (255 - rank.min(255))
1624            };
1625            c.priority_override = (u32::from(c.type_preference(c.candidate_type())) << 24)
1626                + (u32::from(local_preference) << 8)
1627                + 256u32.saturating_sub(u32::from(c.component()));
1628        }
1629    }
1630
1631    /// RFC 8445 Section 5.2: "If a host is IPv6 or dual stack, the local preference value
1632    /// SHOULD be set to the precedence value for IP addresses ... If a host is IPv4 only, the
1633    /// local preference value SHOULD be set to 65535." Whether the host is IPv6 or dual stack
1634    /// is judged from the candidates the agent holds when `c` is ranked, `c` included (not
1635    /// from the configured network types, which by default allow IPv6 on any host): an
1636    /// IPv6 candidate, or an IPv4 one beside held IPv6 ones.
1637    ///
1638    /// Candidates come one at a time, and a signalled priority does not change (re-ranking
1639    /// would need the candidates conveyed again): an IPv4-only host's candidates keep 65535
1640    /// (less their rank) after an IPv6 candidate comes; that candidate, and every one after
1641    /// it, take the precedence form. Priorities stay unique ("each candidate MUST be assigned a
1642    /// unique priority"): the IPv4-only forms (65535 less the rank for UDP; other-pref 8191
1643    /// less the rank for TCP) lie above the precedence forms of the same kind (at most
1644    /// `50 << 8 | 255`; other-pref at most `50 << 7 | 127`).
1645    fn is_dual_stack_or_ipv6(&self, c: &Candidate) -> bool {
1646        c.network_type().is_ipv6()
1647            || self
1648                .local_candidates
1649                .iter()
1650                .any(|other| other.network_type().is_ipv6())
1651    }
1652
1653    /// Applies the 1:1 NAT mapping to a host candidate the application adds. With a `Host`
1654    /// mapping the candidate's advertised address becomes the external one (its base, the
1655    /// socket it is bound to, is kept, as an mDNS name keeps it); with a `ServerReflexive`
1656    /// mapping the server-reflexive candidate to add beside it is returned.
1657    fn apply_nat_1to1(&self, c: &mut Candidate) -> Option<Candidate> {
1658        let mapper = self.ext_ip_mapper.as_ref()?;
1659        // An application-added `.local` candidate has no resolved address to map.
1660        if c.candidate_type() != CandidateType::Host || c.addr().ip().is_unspecified() {
1661            return None;
1662        }
1663        let local_ip = c.addr().ip();
1664        let external_ip = match mapper.find_external(local_ip) {
1665            Ok(ip) => ip,
1666            Err(_) => {
1667                warn!(
1668                    "[{}]: 1:1 NAT mapping is enabled but no external IP is found for {}",
1669                    self.get_name(),
1670                    local_ip
1671                );
1672                return None;
1673            }
1674        };
1675        if mapper.candidate_type == CandidateType::Host {
1676            c.address = external_ip.to_string();
1677            return None;
1678        }
1679        let mut srflx = match (CandidateServerReflexiveConfig {
1680            base_config: CandidateConfig {
1681                network: c.network.clone(),
1682                address: external_ip.to_string(),
1683                port: c.port(),
1684                component: c.component(),
1685                ..CandidateConfig::default()
1686            },
1687            rel_addr: local_ip.to_string(),
1688            rel_port: c.port(),
1689            url: None,
1690        })
1691        .new_candidate_server_reflexive()
1692        {
1693            Ok(srflx) => srflx,
1694            Err(err) => {
1695                warn!(
1696                    "[{}]: cannot make the 1:1 NAT server-reflexive candidate for {}: {}",
1697                    self.get_name(),
1698                    c,
1699                    err
1700                );
1701                return None;
1702            }
1703        };
1704        srflx.tcp_type = c.tcp_type();
1705        Some(srflx)
1706    }
1707
1708    /// The name a host candidate on `ip` is published under in `QueryAndGather` mode.
1709    ///
1710    /// With a fixed `mdns_local_ip` (the original behaviour), only that IPv4 address is hidden,
1711    /// behind `mdns_local_name`, for UDP and TCP alike. Without one, every local address gets its
1712    /// own `<uuid>.local` name, IPv4 and IPv6, as browsers publish host candidates: made when its
1713    /// first candidate is added, registered with the mDNS responder, reused for the address's
1714    /// other candidates (and across ICE restarts).
1715    /// The `.local` name this agent gave the host address `ip` (published or not), if it hid
1716    /// it behind one.
1717    pub(crate) fn mdns_name_of_hidden(&self, ip: IpAddr) -> Option<String> {
1718        if self.mdns_local_ip == Some(ip) {
1719            return Some(self.mdns_local_name.clone());
1720        }
1721        self.mdns_local_names
1722            .iter()
1723            .chain(self.mdns_unpublished_names.iter())
1724            .find(|(i, _)| *i == ip)
1725            .map(|(_, name)| name.clone())
1726    }
1727
1728    fn mdns_name_for(&mut self, ip: IpAddr, network_type: NetworkType) -> MdnsHostName {
1729        if let Some(local_ip) = self.mdns_local_ip {
1730            let v4 = matches!(network_type, NetworkType::Udp4 | NetworkType::Tcp4);
1731            return if v4 && local_ip == ip {
1732                MdnsHostName::Hide(self.mdns_local_name.clone())
1733            } else {
1734                MdnsHostName::Literal
1735            };
1736        }
1737        if let Some((_, name)) = self.mdns_local_names.iter().find(|(i, _)| *i == ip) {
1738            return MdnsHostName::Hide(name.clone());
1739        }
1740        let name = generate_multicast_dns_name();
1741        // Section 3.1.1 step 4, register the name: on the network only where the application
1742        // can send mDNS for the address's family, in a responder that has room for it.
1743        let registered = self.mdns_publishing.covers(ip)
1744            && self
1745                .mdns
1746                .as_mut()
1747                .is_some_and(|mdns_conn| mdns_conn.add_local_name(&name, ip));
1748        if registered {
1749            self.mdns_local_names.push((ip, name.clone()));
1750            return MdnsHostName::Hide(name);
1751        }
1752        if self.mdns_fail_closed {
1753            return MdnsHostName::Withhold;
1754        }
1755        if let Some((_, name)) = self.mdns_unpublished_names.iter().find(|(i, _)| *i == ip) {
1756            return MdnsHostName::Unpublished(name.clone());
1757        }
1758        self.mdns_unpublished_names.push((ip, name.clone()));
1759        MdnsHostName::Unpublished(name)
1760    }
1761
1762    /// Tells the agent for which address families the application can send mDNS (an mDNS
1763    /// socket is open; both by default, [`AgentConfig::multicast_dns_publishing`]). In
1764    /// `QueryAndGather`, the name of a host candidate added afterwards on an address of a
1765    /// family it cannot send on is not registered (draft-ietf-mmusic-mdns-ice-candidates
1766    /// Section 3.1.1 step 4 fails): the candidate goes out under an unpublished name, or not
1767    /// at all with [`AgentConfig::multicast_dns_fail_closed`]. Names registered before stay.
1768    pub fn set_multicast_dns_publishing(&mut self, publishing: MulticastDnsPublishing) {
1769        self.mdns_publishing = publishing;
1770    }
1771
1772    /// Declares, from now on, whether the application hands each mDNS datagram to
1773    /// `handle_read` with its destination address in `local_addr` (as
1774    /// [`AgentConfig::multicast_dns_destination_reported`]): the mDNS group's for one that
1775    /// arrived by multicast (on the link whatever its source, RFC 6762 section 11), the host's
1776    /// own for a unicast one, the unspecified address when it does not know.
1777    pub fn set_multicast_dns_destination_reported(&mut self, reported: bool) {
1778        if let Some(mdns_conn) = self.mdns.as_mut() {
1779            mdns_conn.set_destination_reported(reported);
1780        }
1781    }
1782
1783    /// Feeds a datagram received on the host's mDNS socket (local port 5353) together with
1784    /// the destination address of its IP header, as the driver read it (`IP_PKTINFO`,
1785    /// `IPV6_PKTINFO`, `IP_RECVDSTADDR`): `224.0.0.251` or `ff02::fb` for one that arrived on
1786    /// the group, the host's own address for one sent to it by unicast. Otherwise as
1787    /// `handle_read`, and a datagram that is not the mDNS socket's (its local address is a
1788    /// local candidate's, or not on port 5353) is read as `handle_read` reads it.
1789    ///
1790    /// With the destination known, the mDNS connection applies the RFC 6762 rules that turn
1791    /// on it, whatever [`AgentConfig::multicast_dns_destination_reported`] says: a query
1792    /// received by direct unicast is answered as a "QU" question, and only when its source is
1793    /// on the link (section 5.5); a unicast response is taken only for a recent question that
1794    /// asked for one (section 6); a response that arrived on the group is on the link whatever
1795    /// its source (section 11). The link is the one
1796    /// [`set_multicast_dns_on_link_subnets`](Self::set_multicast_dns_on_link_subnets) gives,
1797    /// else the scope of the source address.
1798    pub fn handle_mdns_datagram(&mut self, msg: TaggedBytesMut, destination: IpAddr) -> Result<()> {
1799        let mdns_socket = msg.transport.local_addr.port() == mdns::MDNS_PORT
1800            && self
1801                .find_local_candidate(msg.transport.local_addr, msg.transport.transport_protocol)
1802                .is_none();
1803        self.read_datagram(msg, mdns_socket.then_some(destination))
1804    }
1805
1806    /// The host's network may have changed: it woke from sleep, a link came up or changed, an
1807    /// address changed. The agent's mDNS responder and resolver start over
1808    /// (`Mdns::network_changed` of rtci-mdns): the address cache is
1809    /// emptied (RFC 6762 section 10.3, "cache flush on topology change"), and every published
1810    /// name is probed for again and announced (section 8: "whenever a Multicast DNS responder
1811    /// starts up, wakes up from sleep, receives an indication of a network interface 'Link
1812    /// Change' event, or has any other reason to believe that its network connectivity may
1813    /// have changed in some relevant way, it MUST perform the two startup steps"; section
1814    /// 10.2: the announcements after reconnection). A no-op without mDNS.
1815    pub fn multicast_dns_network_changed(&mut self) {
1816        if let Some(mdns) = self.mdns.as_mut() {
1817            mdns.network_changed();
1818        }
1819    }
1820
1821    /// Sets the subnets of the link the mDNS socket is on, as (address, prefix length) pairs
1822    /// (the driver enumerates the interfaces; the agent cannot know their prefixes). RFC 6762
1823    /// section 5.5: a responder checks "that the source address in the query packet matches
1824    /// the local subnet for that link (or, in the case of IPv6, the source address has an
1825    /// on-link prefix) and silently ignore[s] the packet if not"; section 11 holds the senders
1826    /// of answers to the same test. Empty (the default): the scope of the source address
1827    /// decides (private, shared, link-local and loopback IPv4; link-local, unique-local and
1828    /// loopback IPv6).
1829    pub fn set_multicast_dns_on_link_subnets(&mut self, subnets: Vec<(IpAddr, u8)>) {
1830        if let Some(mdns_conn) = self.mdns.as_mut() {
1831            mdns_conn.set_on_link_subnets(subnets);
1832        }
1833    }
1834
1835    /// Whether the agent withheld the host candidates of `ip` because their mDNS name could
1836    /// not be registered ([`AgentConfig::multicast_dns_fail_closed`]). The application may
1837    /// still gather server-reflexive and relayed candidates from that address: they do not
1838    /// carry it (Section 3.1.2.2).
1839    pub fn multicast_dns_withholds(&self, ip: IpAddr) -> bool {
1840        self.mdns_withheld.contains(&ip)
1841    }
1842
1843    /// Adds a new remote candidate.
1844    pub fn add_remote_candidate(&mut self, c: Candidate) -> Result<bool> {
1845        // RFC 8838 Section 14: "After an agent has received an end-of-candidates indication,
1846        // it MUST ignore any newly received candidates for that data stream".
1847        if self.remote_end_of_candidates {
1848            warn!(
1849                "[{}]: ignoring remote candidate {}: it follows end-of-candidates",
1850                self.get_name(),
1851                c.address()
1852            );
1853            return Ok(false);
1854        }
1855        // Bound what the remote description (or a stream of peer-reflexive checks) can make us
1856        // hold: every remote candidate is paired with every local one, and each `.local` name
1857        // is an mDNS query kept until it resolves.
1858        if self.remote_candidates.len() >= MAX_REMOTE_CANDIDATES {
1859            warn!(
1860                "[{}]: ignoring remote candidate {}: already holding {} (the cap)",
1861                self.get_name(),
1862                c.address(),
1863                MAX_REMOTE_CANDIDATES
1864            );
1865            return Ok(false);
1866        }
1867
1868        // The agent has one component (RTP; the engine is rtcp-mux only), and candidates are
1869        // paired within a component (RFC 8445 Section 6.1.2.2). A peer that also signals each
1870        // candidate for the RTCP component (pion and webrtc-rs do, with the same address)
1871        // gets those ignored: held, they could never be paired, and they would stand in the
1872        // way of the RTP candidate with the same transport address.
1873        if c.component() != COMPONENT_RTP {
1874            debug!(
1875                "[{}]: ignoring remote candidate {} of component {}",
1876                self.get_name(),
1877                c.address(),
1878                c.component()
1879            );
1880            return Ok(false);
1881        }
1882
1883        // Filter by network type if network_types is configured
1884        if !self.network_types.is_empty() {
1885            let candidate_network_type = c.network_type();
1886            if !self.network_types.contains(&candidate_network_type) {
1887                debug!(
1888                    "Ignoring remote candidate with network type {:?} (not in configured network types: {:?})",
1889                    candidate_network_type, self.network_types
1890                );
1891                return Ok(false);
1892            }
1893        }
1894
1895        // A signalled TCP active candidate has no listening port (RFC 6544 §4.5: port 9): it
1896        // initiates connections and is reached as the peer-reflexive candidate its checks
1897        // create on one of our passive candidates. That peer-reflexive one, which carries the
1898        // connection's real source port, is kept. (RFC 6544 Section 6.2 pairs it with a passive
1899        // candidate and then prunes "any pair for which the local candidate is a passive TCP
1900        // candidate".) The agent notes that the peer may dial: its checklist does not fail
1901        // while that connection may still come. Two lite agents send no checks (RFC 8445
1902        // Section 6.1.1) and pair without them (Section 8.2): there the active candidate is
1903        // the remote side of a pair, whose connection the peer opens itself (RFC 6544 Section
1904        // 6.1); it is taken as a remote candidate, not noted as one only checks could pair.
1905        if c.tcp_type() == TcpType::Active
1906            && c.candidate_type() != CandidateType::PeerReflexive
1907            && !(self.lite && self.remote_lite)
1908        {
1909            debug!(
1910                "Ignoring remote candidate with tcptype active: {}",
1911                c.address()
1912            );
1913            self.note_unpaired_remote(&c);
1914            return Ok(false);
1915        }
1916
1917        // If we have a mDNS Candidate lets fully resolve it before adding it locally
1918        if c.candidate_type() == CandidateType::Host && c.address().ends_with(".local") {
1919            if self.mdns_mode == MulticastDnsMode::Disabled {
1920                // What the application asked for (`MulticastDnsMode::Disabled`), not a fault:
1921                // debug, like an unresolved name.
1922                debug!(
1923                    "[{}]: ignoring remote mDNS candidate {}: mDNS is disabled",
1924                    self.get_name(),
1925                    c.address()
1926                );
1927                // Ignored (draft Section 3.2.1, step 5), but the peer's checks from behind
1928                // the name still teach a peer-reflexive candidate (Section 5.3). (Not with
1929                // the relay-only policy: see below.)
1930                if self.candidate_types != [CandidateType::Relay] {
1931                    self.note_unpaired_remote(&c);
1932                }
1933                return Ok(false);
1934            }
1935
1936            // draft-ietf-mmusic-mdns-ice-candidates Section 3.2.1, step 2: "If the ICE
1937            // candidate policy is 'relay', as defined in [RFC8829], ignore the candidate":
1938            // it could only be paired with a relayed candidate, which Section 3.3.2 forbids,
1939            // and resolving it would tell the local network who is being called.
1940            if self.candidate_types == [CandidateType::Relay] {
1941                debug!(
1942                    "[{}]: ignoring mDNS candidate {}: relay-only policy",
1943                    self.get_name(),
1944                    c.address()
1945                );
1946                return Ok(false);
1947            }
1948
1949            if c.candidate_type() != CandidateType::Host {
1950                return Err(Error::ErrAddressParseFailed);
1951            }
1952
1953            if !is_ice_mdns_name(c.address()) {
1954                warn!(
1955                    "[{}]: ignoring mDNS candidate {}: not a <uuid>.local name",
1956                    self.get_name(),
1957                    c.address()
1958                );
1959                // Not resolved (Section 3.2.2), but its checks may come (Section 5.3).
1960                self.note_unpaired_remote(&c);
1961                return Ok(false);
1962            }
1963
1964            if self.mdns_queries.len() >= MAX_PENDING_MDNS_QUERIES {
1965                warn!(
1966                    "[{}]: ignoring mDNS candidate {}: {} queries already pending (the cap)",
1967                    self.get_name(),
1968                    c.address(),
1969                    MAX_PENDING_MDNS_QUERIES
1970                );
1971                self.note_unpaired_remote(&c);
1972                return Ok(false);
1973            }
1974
1975            if let Some(mdns_conn) = &mut self.mdns {
1976                let query_id = mdns_conn.schedule_query(c.address());
1977                self.mdns_queries.insert(query_id, c);
1978            } else {
1979                // No mDNS connection: the name is never resolved.
1980                self.note_unpaired_remote(&c);
1981            }
1982
1983            return Ok(false);
1984        }
1985
1986        Ok(self.trigger_request_connectivity_check(vec![c]) > 0)
1987    }
1988
1989    /// Takes remote candidates into the list and pairs them; returns how many are now held.
1990    fn trigger_request_connectivity_check(&mut self, remote_candidates: Vec<Candidate>) -> usize {
1991        let mut held = 0;
1992        for c in remote_candidates {
1993            // Every path that adds a remote candidate comes through here, mDNS-resolved ones
1994            // included (their query was capped, not the candidate list).
1995            if self.remote_candidates.len() >= MAX_REMOTE_CANDIDATES {
1996                warn!(
1997                    "[{}]: ignoring remote candidate {}: already holding {} (the cap)",
1998                    self.get_name(),
1999                    c.address(),
2000                    MAX_REMOTE_CANDIDATES
2001                );
2002                continue;
2003            }
2004            // RFC 8445 §5.1.1.1: a candidate is a unicast transport address. One that can't be
2005            // a destination, or that the application's filter or address policy refuses, is
2006            // never held or paired.
2007            if !self
2008                .remote_policy
2009                .allows_remote(c.addr(), AddressPurpose::RemoteCandidate)
2010            {
2011                warn!(
2012                    "[{}]: ignoring remote candidate {}: its address {} is not an allowed destination",
2013                    self.get_name(),
2014                    c.address(),
2015                    c.addr()
2016                );
2017                continue;
2018            }
2019            // One remote candidate per transport address: a second one could never be told
2020            // apart from the first by the source of what it sends.
2021            if let Some(known) = self
2022                .remote_candidates
2023                .iter()
2024                .position(|cand| cand.addr() == c.addr() && cand.network_type() == c.network_type())
2025            {
2026                if self.remote_candidates[known].candidate_type() == CandidateType::PeerReflexive
2027                    && c.candidate_type() != CandidateType::PeerReflexive
2028                {
2029                    self.replace_peer_reflexive_remote_candidate(known, c);
2030                    held += 1;
2031                }
2032                continue;
2033            }
2034            if !self.remote_candidates.iter().any(|cand| cand.equal(&c)) {
2035                held += 1;
2036                self.remote_candidates.push(c);
2037                let remote_index = self.remote_candidates.len() - 1;
2038
2039                for local_index in 0..self.local_candidates.len() {
2040                    if !self.local_candidates[local_index].held_from_pairing()
2041                        && self.local_candidates[local_index]
2042                            .can_pair_with(&self.remote_candidates[remote_index])
2043                    {
2044                        self.add_pair(local_index, remote_index);
2045                    }
2046                }
2047
2048                self.request_connectivity_check();
2049            }
2050        }
2051        held
2052    }
2053
2054    /// RFC 8838 Section 11: a signalled candidate with the address of a peer-reflexive one the
2055    /// agent learned from a check takes its place. The pairs that candidate is in are kept,
2056    /// with the signalled priority (and so their place in the checklist), and the candidate
2057    /// is now paired with the other local candidates too.
2058    fn replace_peer_reflexive_remote_candidate(&mut self, remote_index: usize, mut c: Candidate) {
2059        let learned = &self.remote_candidates[remote_index];
2060        c.last_sent = learned.last_sent;
2061        c.last_received = learned.last_received;
2062        c.last_authenticated = learned.last_authenticated;
2063        c.last_consent = learned.last_consent;
2064        // The candidate keeps the identity its pairs are known by: the statistics of a pair
2065        // (and its packet counters) are keyed by the two candidates' ids, and a pair that is
2066        // carrying data must not become another pair because its remote candidate was
2067        // signalled after all.
2068        c.id = learned.id.clone();
2069        if c.tcp_type() == TcpType::Unspecified {
2070            c.tcp_type = learned.tcp_type();
2071        }
2072        let priority = c.priority();
2073        self.remote_candidates[remote_index] = c;
2074        for index in 0..self.candidate_pairs.len() {
2075            if self.candidate_pairs[index].remote_index == remote_index {
2076                let local_index = self.candidate_pairs[index].local_index;
2077                let foundation = self.pair_foundation(local_index, remote_index);
2078                let p = &mut self.candidate_pairs[index];
2079                p.remote_priority = priority;
2080                p.foundation = foundation;
2081            }
2082        }
2083        for local_index in 0..self.local_candidates.len() {
2084            if !self.local_candidates[local_index].held_from_pairing()
2085                && self.local_candidates[local_index]
2086                    .can_pair_with(&self.remote_candidates[remote_index])
2087            {
2088                self.add_pair(local_index, remote_index);
2089            }
2090        }
2091        self.request_connectivity_check();
2092    }
2093
2094    /// Takes what the mDNS connection has to report: the remote candidates whose names
2095    /// resolved (returned), the queries that ended without an address, and the local names
2096    /// lost to another host, which are replaced.
2097    pub(crate) fn drain_mdns_events(&mut self, now: Instant) -> Vec<Candidate> {
2098        use mdns::MdnsEvent;
2099
2100        let mut resolved = vec![];
2101        let mut lost = vec![];
2102        if let Some(mdns_conn) = &mut self.mdns {
2103            while let Some(event) = mdns_conn.poll_event() {
2104                match event {
2105                    MdnsEvent::QueryAnswered(id, addr) => {
2106                        if let Some(mut c) = self.mdns_queries.remove(&id)
2107                            && c.set_ip(&addr).is_ok()
2108                        {
2109                            debug!(
2110                                "mDNS query id {} answered Candidate {} with resolved_addr {} is added into remote candidates",
2111                                id,
2112                                c,
2113                                c.addr()
2114                            );
2115                            resolved.push(c);
2116                        }
2117                    }
2118                    MdnsEvent::QueryTimeout(id) => {
2119                        if let Some(c) = self.mdns_queries.remove(&id) {
2120                            // An expected outcome, not an engine error: a browser hides its
2121                            // host addresses behind `<uuid>.local` names, and on many
2122                            // networks they do not resolve. Logged once per query (its
2123                            // retries log nothing), at debug.
2124                            debug!(
2125                                "mDNS query {} for {} ended without an address; the candidate is ignored",
2126                                id,
2127                                c.address()
2128                            );
2129                            // Unresolved, and ignored (draft Section 3.2.1, step 5); the
2130                            // peer's checks may still come (Section 5.3).
2131                            UnpairedRemote::note(&mut self.unpaired_remotes, &c);
2132                        }
2133                    }
2134                    MdnsEvent::LocalNameConflict(name) => lost.push(name),
2135                    _ => {}
2136                }
2137            }
2138        }
2139        for name in lost {
2140            self.replace_local_mdns_name(now, &name);
2141        }
2142        resolved
2143    }
2144
2145    /// RFC 6762 Section 9: a host that loses a name to another "MUST [...] choose a new
2146    /// name". The local candidates published under `lost` get a new `<uuid>.local` name,
2147    /// registered with the responder, and are reported with
2148    /// [`Event::LocalCandidateRenamed`] so that they are conveyed to the peer again: the
2149    /// name it holds resolves to the other host, or to nothing.
2150    fn replace_local_mdns_name(&mut self, now: Instant, lost: &str) {
2151        let ip = if self.mdns_local_name == lost {
2152            self.mdns_local_ip
2153        } else {
2154            self.mdns_local_names
2155                .iter()
2156                .find(|(_, name)| name == lost)
2157                .map(|(ip, _)| *ip)
2158        };
2159        let (Some(ip), Some(mdns_conn)) = (ip, &mut self.mdns) else {
2160            return;
2161        };
2162        let name = generate_multicast_dns_name();
2163        if !mdns_conn.add_local_name(&name, ip) {
2164            warn!(
2165                "[{}]: the mDNS name {} was lost to another host and no new one could be registered",
2166                self.get_name(),
2167                lost
2168            );
2169            return;
2170        }
2171        warn!(
2172            "[{}]: the mDNS name {} was lost to another host: its candidates are now {}",
2173            self.get_name(),
2174            lost,
2175            name
2176        );
2177        if self.mdns_local_name == lost {
2178            self.mdns_local_name = name.clone();
2179        }
2180        for (_, published) in &mut self.mdns_local_names {
2181            if published == lost {
2182                *published = name.clone();
2183            }
2184        }
2185        // RFC 8838 section 13: "an agent MUST NOT trickle any new candidates within an ICE
2186        // session after nomination of a candidate pair", nor after its end-of-candidates. A
2187        // renamed candidate is a candidate the peer does not have: in a session where none
2188        // may be conveyed any more, the candidates keep the name they were conveyed with (the
2189        // path runs on addresses, not names), and the next ICE restart, which conveys a new
2190        // set, gives them the new one. A candidate of a staged restart is the next session's.
2191        let conveying_closed = (self.local_gathering_complete || self.selected_pair.is_some())
2192            && !self.has_pending_restart();
2193        if conveying_closed {
2194            for (_, deferred) in &mut self.mdns_deferred_renames {
2195                if deferred == lost {
2196                    *deferred = name.clone();
2197                }
2198            }
2199            if self.local_candidates.iter().any(|c| c.address == lost) {
2200                warn!(
2201                    "[{}]: the candidates named {} keep that name until an ICE restart: none may be conveyed in this session any more",
2202                    self.get_name(),
2203                    lost
2204                );
2205                self.mdns_deferred_renames.push((lost.to_owned(), name));
2206            }
2207            return;
2208        }
2209        for c in &mut self.local_candidates {
2210            if c.address == lost {
2211                c.address = name.clone();
2212                self.event_outs.push_back(TaggedEvent {
2213                    now,
2214                    event: Event::LocalCandidateRenamed(Box::new(c.clone())),
2215                });
2216            }
2217        }
2218    }
2219
2220    /// The remote mDNS candidates whose names have not resolved yet. They are held by no
2221    /// pair, but they were submitted: statistics list them (mDNS draft Section 3.3.1).
2222    pub fn pending_mdns_candidates(&self) -> impl Iterator<Item = &Candidate> {
2223        self.mdns_queries.values()
2224    }
2225
2226    /// Notes a candidate the peer signalled that is not paired but whose checks may still
2227    /// arrive (see [`UnpairedRemote`]).
2228    fn note_unpaired_remote(&mut self, c: &Candidate) {
2229        UnpairedRemote::note(&mut self.unpaired_remotes, c);
2230    }
2231
2232    /// Whether a pair can still be formed by a check from the peer (RFC 8445 Section 7.3.1.3)
2233    /// although every signalled candidate is in: the peer signalled a candidate that is not
2234    /// paired but can reach one of the local candidates it knows, a `tcptype active` one that
2235    /// dials a local passive candidate, or a `.local` name the agent did not resolve. RFC 8838
2236    /// Section 8: "a Trickle ICE agent MUST keep each checklist in the Running state as long as
2237    /// it expects candidate pairs to be incrementally added to the checklist."
2238    pub(crate) fn pair_may_come_from_a_peer_check(&self) -> bool {
2239        self.unpaired_remotes.iter().any(|remote| {
2240            self.local_candidates
2241                .iter()
2242                .any(|local| !local.held_from_pairing() && remote.can_reach(local))
2243        })
2244    }
2245
2246    /// The peer has no more candidates for this generation (an end-of-candidates indication,
2247    /// RFC 8838 Section 14). Remote candidates signalled after it are ignored, and a checking
2248    /// agent whose pairs have all failed (or that has none) fails without waiting for its
2249    /// timeout, once local gathering is complete too and the PAC timer has expired (RFC 8863:
2250    /// 39.5 s after checking began, with the defaults), unless a check from the peer may still
2251    /// form a pair (a `tcptype active` candidate of the peer that dials ours, a `.local` name
2252    /// not resolved): then its timeout ends it. With local gathering complete it is also the
2253    /// indication W3C webrtc-pc 5.6.4 makes "failed" and "completed" wait for (see
2254    /// [`Agent::set_failed_without_end_of_candidates`]). An ICE restart starts a new generation.
2255    pub fn set_remote_end_of_candidates(&mut self) {
2256        self.remote_end_of_candidates = true;
2257        self.request_connectivity_check();
2258    }
2259
2260    /// RFC 9429 Section 5.7: the local description that began this agent's gathering was
2261    /// rolled back before any answer ("Any resources or candidates that were allocated by the
2262    /// abandoned local description are discarded"). Its local candidates go, with the pairs
2263    /// and what the checks taught; the credentials stay; local gathering starts again with
2264    /// the candidates added next.
2265    pub fn discard_gathering(&mut self) {
2266        self.delete_all_candidates(false);
2267        self.local_gathering_complete = false;
2268        self.remote_end_of_candidates = false;
2269        self.request_connectivity_check();
2270    }
2271
2272    /// Local gathering is complete for this generation (RFC 8838 Section 13): no local
2273    /// candidate is accepted after it. An ICE restart starts a new generation.
2274    pub fn set_local_gathering_complete(&mut self) {
2275        self.local_gathering_complete = true;
2276        self.request_connectivity_check();
2277    }
2278
2279    /// Whether the peer's description says it can trickle candidates (`a=ice-options:trickle`,
2280    /// RFC 9429 Sections 4.1.17 and 5.10), `true` until told otherwise. A peer that cannot
2281    /// trickle gave all its candidates in its description: W3C webrtc-pc 5.6.4 counts
2282    /// `canTrickleIceCandidates` false as the indication that there are no more remote
2283    /// candidates, which "failed" and "completed" need. (Candidates signalled later are still
2284    /// taken: only an end-of-candidates indication makes the agent ignore them, RFC 8838
2285    /// Section 14.)
2286    pub fn set_remote_trickles(&mut self, trickles: bool) {
2287        self.remote_trickles = trickles;
2288        self.request_connectivity_check();
2289    }
2290
2291    /// Whether the agent reports `Failed` without the indications W3C webrtc-pc 5.6.4 makes
2292    /// "failed" wait for, once the PAC timer (RFC 8863) has expired. Off by default.
2293    ///
2294    /// By default (off) the transport is "failed" only when it "has finished gathering,
2295    /// received an indication that there are no more remote candidates, finished checking all
2296    /// candidate pairs, and all pairs have either failed connectivity checks or lost consent":
2297    /// local gathering complete ([`Agent::set_local_gathering_complete`]) and the peer's
2298    /// end-of-candidates ([`Agent::set_remote_end_of_candidates`]) or a peer that cannot
2299    /// trickle ([`Agent::set_remote_trickles`]). Before that, checks that have all failed (the
2300    /// checking timeout, a failed nomination) or consent that expired make the agent
2301    /// `Disconnected` ("it is still gathering and/or waiting for additional remote
2302    /// candidates"); it fails as soon as the indications are in, checks again (`Checking`)
2303    /// when a new pair is formed, and an ICE restart starts it over. A peer that never sends
2304    /// its end-of-candidates leaves it `Disconnected` until the application restarts or closes.
2305    ///
2306    /// On, the PAC timer serves as the end-of-candidates fallback RFC 8863 Section 5 allows
2307    /// ("ICE agents MAY use the PAC timer to also serve as an end-of-candidates fallback"):
2308    /// once it has expired (39.5 s after the checks began, with the defaults; at once for a
2309    /// lite agent, which has none) those events fail the agent without the indications, as
2310    /// libwebrtc's transports do.
2311    pub fn set_failed_without_end_of_candidates(&mut self, enabled: bool) {
2312        self.failed_without_end_of_candidates = enabled;
2313        self.request_connectivity_check();
2314    }
2315
2316    /// See [`Agent::set_failed_without_end_of_candidates`].
2317    pub fn failed_without_end_of_candidates(&self) -> bool {
2318        self.failed_without_end_of_candidates
2319    }
2320
2321    /// The peer has no more candidates for this generation: its end-of-candidates indication,
2322    /// or a description that says it cannot trickle (W3C webrtc-pc 5.6.4).
2323    pub(crate) fn no_more_remote_candidates(&self) -> bool {
2324        self.remote_end_of_candidates || !self.remote_trickles
2325    }
2326
2327    /// Whether checks that have failed, or consent that was lost, may make the agent `Failed`
2328    /// at `now` (W3C webrtc-pc 5.6.4 "failed": the transport "has finished gathering, received
2329    /// an indication that there are no more remote candidates, [...] and either zero local
2330    /// candidates were gathered or the PAC timer has expired [RFC8863]"): local gathering is
2331    /// complete and the peer has no more candidates, or
2332    /// [`Agent::set_failed_without_end_of_candidates`]; and in both cases the PAC timer has
2333    /// expired or the agent has no local candidate. That holds for consent lost after a
2334    /// connection too: within the PAC timer the agent is `Disconnected` and fails as it
2335    /// expires. A lite agent has no PAC timer (RFC 8863 Section 4 is for full agents).
2336    pub(crate) fn may_report_failed(&self, now: Instant) -> bool {
2337        let pac_holds = self.pac_running(now) && !self.local_candidates.is_empty();
2338        !pac_holds
2339            && ((self.local_gathering_complete && self.no_more_remote_candidates())
2340                || self.failed_without_end_of_candidates)
2341    }
2342
2343    /// The checks have failed (`why`): `Failed` when [`Agent::may_report_failed`], else
2344    /// `Disconnected` until it does (W3C webrtc-pc 5.6.4).
2345    pub(crate) fn fail_or_hold(&mut self, now: Instant, why: HeldFailure) {
2346        if self.may_report_failed(now) {
2347            self.update_connection_state(Some(now), ConnectionState::Failed);
2348            return;
2349        }
2350        if self.failure_held.is_none() {
2351            info!(
2352                "[{}]: {why:?}, but the indication that there are no more candidates is missing (local gathering complete: {}, remote end-of-candidates: {}): disconnected, not failed",
2353                self.get_name(),
2354                self.local_gathering_complete,
2355                self.no_more_remote_candidates()
2356            );
2357        }
2358        self.update_connection_state(Some(now), ConnectionState::Disconnected);
2359        self.failure_held.get_or_insert(why);
2360    }
2361
2362    /// Whether this IP address is one the peer's signalling led to: the address of a candidate
2363    /// it signalled, or the address a `.local` name it signalled has been resolved to. A
2364    /// peer-reflexive remote candidate's address may be shown in statistics only then
2365    /// (draft-ietf-mmusic-mdns-ice-candidates Section 3.3.1: "a peer-reflexive remote
2366    /// candidate could be constructed from a remote host IP address as a result of an ICE
2367    /// connectivity check"; before the peer's name resolves, such a candidate would reveal
2368    /// what the name hides). Once the agent has resolved the name itself, the address is no
2369    /// news; the mDNS candidate's own entry still shows the name, never the address.
2370    pub fn is_signalled_remote_ip(&self, ip: IpAddr) -> bool {
2371        self.remote_candidates
2372            .iter()
2373            .any(|c| c.candidate_type() != CandidateType::PeerReflexive && c.addr().ip() == ip)
2374    }
2375
2376    /// The local candidates to signal to the peer: the ones the application added (with their
2377    /// 1:1 NAT companions), not the peer-reflexive ones the agent learned from the mapped
2378    /// address of a response (RFC 8445 Section 7.2.5.3.1), which need no signalling.
2379    pub fn get_local_candidates_to_signal(&self) -> Vec<Candidate> {
2380        self.local_candidates
2381            .iter()
2382            .filter(|c| c.candidate_type() != CandidateType::PeerReflexive && !c.withdrawn)
2383            .cloned()
2384            .collect()
2385    }
2386
2387    /// Sets the credentials of the remote agent.
2388    pub fn set_remote_credentials(
2389        &mut self,
2390        remote_ufrag: String,
2391        remote_pwd: String,
2392    ) -> Result<()> {
2393        if remote_ufrag.is_empty() {
2394            return Err(Error::ErrRemoteUfragEmpty);
2395        } else if remote_pwd.is_empty() {
2396            return Err(Error::ErrRemotePwdEmpty);
2397        }
2398
2399        self.ufrag_pwd.remote_credentials = Some(
2400            Credentials {
2401                ufrag: remote_ufrag,
2402                pwd: remote_pwd,
2403            }
2404            .into(),
2405        );
2406
2407        // Checks can start: the pairs formed so far get their initial states (RFC 8445
2408        // Section 6.1.2.6).
2409        self.compute_initial_pair_states();
2410
2411        // Requests answered before these credentials were known are processed on the next
2412        // `handle_timeout` (RFC 8445 Section 7.3), which is asked for at once.
2413        self.request_connectivity_check();
2414
2415        Ok(())
2416    }
2417
2418    /// Returns the remote credentials.
2419    pub fn get_remote_credentials(&self) -> Option<&Credentials> {
2420        self.ufrag_pwd.remote_credentials.as_deref()
2421    }
2422
2423    /// Returns the local credentials.
2424    /// The credentials to advertise, which is what SDP generation wants.
2425    ///
2426    /// Returns credentials staged by [`Agent::generate_restart_credentials`] when an ICE restart
2427    /// is pending, so an offer carries the new ufrag/pwd. Inbound STUN validation deliberately
2428    /// does *not* go through here — it reads `local_credentials` directly, so the live session
2429    /// keeps working until [`Agent::apply_restart`] installs the new pair.
2430    pub fn get_local_credentials(&self) -> &Credentials {
2431        self.ufrag_pwd
2432            .pending_local_credentials
2433            .as_ref()
2434            .unwrap_or(&self.ufrag_pwd.local_credentials)
2435    }
2436
2437    /// Queues `CandidatePairRemoved` for every listed pair, before the list is cleared.
2438    pub(crate) fn announce_all_pairs_removed(&mut self) {
2439        for index in 0..self.candidate_pairs.len() {
2440            self.announce_pair(index, false);
2441        }
2442    }
2443
2444    /// The candidate pairs on the agent's list (webrtc-extensions 7 `[[CandidatePairs]]`):
2445    /// (local, remote), in the order they were formed. A pair the application removed is not
2446    /// listed.
2447    pub fn get_candidate_pairs(&self) -> Vec<(Candidate, Candidate)> {
2448        self.candidate_pairs
2449            .iter()
2450            .filter(|p| !p.removed)
2451            .filter_map(|p| {
2452                Some((
2453                    self.local_candidates.get(p.local_index)?.clone(),
2454                    self.remote_candidates.get(p.remote_index)?.clone(),
2455                ))
2456            })
2457            .collect()
2458    }
2459
2460    fn listed_pair(&self, local: &Candidate, remote: &Candidate) -> Option<usize> {
2461        self.candidate_pairs.iter().position(|p| {
2462            !p.removed
2463                && self
2464                    .local_candidates
2465                    .get(p.local_index)
2466                    .is_some_and(|c| c.equal(local))
2467                && self
2468                    .remote_candidates
2469                    .get(p.remote_index)
2470                    .is_some_and(|c| c.equal(remote))
2471        })
2472    }
2473
2474    /// The InvalidStateError checks of `selectCandidatePair` / `removeCandidatePair`: the
2475    /// agent is closed, or its state is new or failed.
2476    fn check_pair_call_state(&self) -> Result<()> {
2477        if matches!(
2478            self.connection_state,
2479            ConnectionState::New | ConnectionState::Failed | ConnectionState::Closed
2480        ) {
2481            return Err(Error::InvalidStateError);
2482        }
2483        Ok(())
2484    }
2485
2486    /// Whether a nomination proposal waits for [`Self::resolve_nomination_proposal`]
2487    /// (webrtc-extensions 7 `[[ProposalPending]]`).
2488    pub fn proposal_pending(&self) -> bool {
2489        self.nomination_proposal.is_some()
2490    }
2491
2492    /// Answers the pending nomination proposal: `accept` nominates the pair (a check with
2493    /// USE-CANDIDATE); otherwise the pair is not nominated and the agent keeps checking
2494    /// (webrtc-extensions 7, a cancelled `icecandidatepairnominate`). Nothing when no
2495    /// proposal is pending.
2496    pub fn resolve_nomination_proposal(&mut self, now: Instant, accept: bool) {
2497        let Some(pair_index) = self.nomination_proposal.take() else {
2498            return;
2499        };
2500        if accept && self.selected_pair.is_none() && self.nominated_pair.is_none() {
2501            self.candidate_pairs[pair_index].nominate = true;
2502            self.nominated_pair = Some(pair_index);
2503            self.enqueue_triggered(pair_index);
2504        } else if !accept {
2505            self.declined_nominations.push(pair_index);
2506        }
2507        let _ = now;
2508    }
2509
2510    /// webrtc-extensions 7 `selectCandidatePair(pair)`: the agent sends data on the pair of
2511    /// `local` and `remote` from now on; the selected pair changes, with its
2512    /// `SelectedCandidatePairChange` event, and the state with its event when it was not
2513    /// connected. Connectivity checks on other pairs stop, as they do once a pair is
2514    /// selected; consent keeps being checked on this one.
2515    ///
2516    /// # Errors
2517    ///
2518    /// `InvalidStateError` when the agent is closed, or new or failed; `NotFoundError` when
2519    /// the pair is not on the list ([`Self::get_candidate_pairs`]).
2520    pub fn select_candidate_pair(
2521        &mut self,
2522        now: Instant,
2523        local: &Candidate,
2524        remote: &Candidate,
2525    ) -> Result<()> {
2526        self.check_pair_call_state()?;
2527        let index = self
2528            .listed_pair(local, remote)
2529            .ok_or(Error::NotFoundError)?;
2530        self.clock = self.clock.max(now);
2531        if self.selected_pair != Some(index) {
2532            self.nominated_pair = Some(index);
2533            self.set_selected_pair(Some(now), Some(index));
2534        }
2535        Ok(())
2536    }
2537
2538    /// webrtc-extensions 7 `removeCandidatePair(pair)`: the agent stops the checks on the
2539    /// pair of `local` and `remote` (an In-Progress transaction is cancelled, no check is
2540    /// sent or answered on it any more, data from it is not accepted through it), then
2541    /// queues `CandidatePairRemoved`. When it was the selected pair the best other valid pair
2542    /// takes its place, or none: the state then follows consent as for a lost path.
2543    ///
2544    /// # Errors
2545    ///
2546    /// As [`Self::select_candidate_pair`].
2547    pub fn remove_candidate_pair(
2548        &mut self,
2549        now: Instant,
2550        local: &Candidate,
2551        remote: &Candidate,
2552    ) -> Result<()> {
2553        self.check_pair_call_state()?;
2554        let index = self
2555            .listed_pair(local, remote)
2556            .ok_or(Error::NotFoundError)?;
2557        self.remove_pair_at(now, index, true);
2558        Ok(())
2559    }
2560
2561    /// webrtc-extensions 7, the accepted removal of a pair the agent's freeing proposed (a
2562    /// cancelable `icecandidatepairremove` the application did not cancel): as
2563    /// [`Self::remove_candidate_pair`], without a second `CandidatePairRemoved` (the proposal
2564    /// was the event).
2565    ///
2566    /// # Errors
2567    ///
2568    /// As [`Self::remove_candidate_pair`].
2569    pub fn remove_proposed_candidate_pair(
2570        &mut self,
2571        now: Instant,
2572        local: &Candidate,
2573        remote: &Candidate,
2574    ) -> Result<()> {
2575        self.check_pair_call_state()?;
2576        let index = self
2577            .listed_pair(local, remote)
2578            .ok_or(Error::NotFoundError)?;
2579        self.remove_pair_at(now, index, false);
2580        Ok(())
2581    }
2582
2583    /// Withdraws the local candidate whose transport address is `addr` (of `protocol`): no
2584    /// session after the current one has it, and the current one keeps of it only what carries
2585    /// its data. For a relayed candidate whose allocation is to be let go (its server left the
2586    /// configuration), which a restart that keeps the local candidates would otherwise carry
2587    /// into the next session. Returns whether such a candidate was there (and not withdrawn
2588    /// already).
2589    ///
2590    /// What each part of the agent sees, whether or not a restart is staged (credentials
2591    /// generated, not applied: `get_local_credentials` gives the staged ones):
2592    ///
2593    /// | | from the call | after the next `apply_restart` |
2594    /// |---|---|---|
2595    /// | the candidate | held, flagged withdrawn | dropped |
2596    /// | its selected (or nominated) pair in the current session | kept: data and consent go on | gone with the session; the restart's previous media path still runs on it |
2597    /// | its other pairs in the current session | removed (as `remove_candidate_pair`) | — |
2598    /// | new pairs with it (remote candidates, checks that reach it) | none | — |
2599    /// | `get_local_candidates_to_signal` | without it | without it |
2600    /// | `discard_restart_credentials` | flag kept: the next restart drops it | — |
2601    /// | `revert_restart` | the session restored as it was when the restart was applied (a withdrawal made after that is undone; the engine withdraws again) | — |
2602    /// | the candidate gathered again | stays withdrawn | — |
2603    pub fn withdraw_local_candidate(
2604        &mut self,
2605        now: Instant,
2606        addr: SocketAddr,
2607        protocol: TransportProtocol,
2608    ) -> bool {
2609        let Some(local_index) = self.local_candidates.iter().position(|c| {
2610            !c.withdrawn && c.addr() == addr && c.network_type().to_protocol() == protocol
2611        }) else {
2612            return false;
2613        };
2614        self.local_candidates[local_index].withdrawn = true;
2615        for index in 0..self.candidate_pairs.len() {
2616            let pair = &self.candidate_pairs[index];
2617            if pair.local_index != local_index
2618                || pair.removed
2619                || self.selected_pair == Some(index)
2620                || self.nominated_pair == Some(index)
2621            {
2622                continue;
2623            }
2624            self.remove_pair_at(now, index, true);
2625        }
2626        true
2627    }
2628
2629    /// Removes the pair `index` (`remove_candidate_pair`), announced with
2630    /// `CandidatePairRemoved` when `announce`.
2631    fn remove_pair_at(&mut self, now: Instant, index: usize, announce: bool) {
2632        self.clock = self.clock.max(now);
2633        let pair = self.candidate_pairs[index];
2634        self.cancel_pair_checks(pair.local_index, pair.remote_index);
2635        {
2636            let p = &mut self.candidate_pairs[index];
2637            p.state = CandidatePairState::Failed;
2638            p.valid = false;
2639            p.nominate = false;
2640            p.triggered = false;
2641            p.nomination_pending = false;
2642        }
2643        if announce {
2644            self.announce_pair(index, false);
2645        }
2646        self.candidate_pairs[index].removed = true;
2647        if self.nominated_pair == Some(index) {
2648            self.nominated_pair = None;
2649        }
2650        if self.selected_pair == Some(index) {
2651            let next = self
2652                .candidate_pairs
2653                .iter()
2654                .enumerate()
2655                .filter(|(_, p)| p.valid && !p.removed && p.state == CandidatePairState::Succeeded)
2656                .max_by_key(|(_, p)| p.priority())
2657                .map(|(i, _)| i);
2658            match next {
2659                Some(next) => {
2660                    self.nominated_pair = Some(next);
2661                    self.set_selected_pair(Some(now), Some(next));
2662                }
2663                None => {
2664                    self.selected_pair = None;
2665                    self.request_connectivity_check();
2666                }
2667            }
2668        }
2669    }
2670
2671    /// Whether this agent is the controlling one, which decides nomination.
2672    pub fn role(&self) -> bool {
2673        self.is_controlling
2674    }
2675
2676    /// Sets the role, when the roles are determined (RFC 8445 Section 6.1.1): the agent that
2677    /// started the ICE processing is controlling, unless exactly one of the two is lite (the
2678    /// full one is controlling then).
2679    ///
2680    /// "Once the roles are determined for a session, they persist throughout the lifetime of
2681    /// the session": an ICE restart keeps them (the agent does, by itself), and they are
2682    /// determined again at a restart only when an agent changed between full and lite. A role
2683    /// conflict is repaired by the agent (Section 7.3.1.1).
2684    ///
2685    /// The pairs the agent holds get the priority of the new role (Section 6.1.2.3), and a
2686    /// nomination that was being made is dropped: only the controlling agent nominates.
2687    pub fn set_role(&mut self, is_controlling: bool) {
2688        if self.is_controlling == is_controlling {
2689            return;
2690        }
2691        self.is_controlling = is_controlling;
2692        for pair in &mut self.candidate_pairs {
2693            pair.ice_role_controlling = is_controlling;
2694            pair.nominate = false;
2695        }
2696        self.nominated_pair = None;
2697        self.nomination_proposal = None;
2698        self.declined_nominations.clear();
2699    }
2700
2701    /// The tiebreaker the agent's checks carry (RFC 8445 Section 5.2).
2702    pub fn tie_breaker(&self) -> u64 {
2703        self.tie_breaker
2704    }
2705
2706    /// Whether this agent is a lite implementation.
2707    pub fn is_lite(&self) -> bool {
2708        self.lite
2709    }
2710
2711    /// Whether the peer is a lite implementation ([`Agent::set_remote_lite`]).
2712    pub fn is_remote_lite(&self) -> bool {
2713        self.remote_lite
2714    }
2715
2716    /// Two lite agents, this one controlled, with several pairs: the controlling agent's
2717    /// updated candidate exchange is still to come (RFC 8445 Section 8.2: "ICE processing is
2718    /// complete after and only after the updated candidate exchange is complete"), and with
2719    /// it the pair. A TCP connection the controlling agent opened in parallel with that
2720    /// exchange waits for it (RFC 6544 Section 6.1).
2721    pub fn awaits_lite_update(&self) -> bool {
2722        self.lite
2723            && self.remote_lite
2724            && !self.is_controlling
2725            && !self.lite_update_taken
2726            && self.candidate_pairs.len() > 1
2727    }
2728
2729    /// Tells the agent whether the peer is a lite implementation (in SDP, `a=ice-lite`).
2730    ///
2731    /// It matters to a lite agent: with a full peer it answers checks and waits for the
2732    /// nomination; with a lite peer "no connectivity checks are ever sent. Rather, once the
2733    /// candidates are exchanged, each agent performs the processing described in Section 8
2734    /// without connectivity checks" (RFC 8445 Section 6.1.1). See
2735    /// [`Event::LiteCandidateUpdate`] and [`Agent::replace_remote_candidates`].
2736    pub fn set_remote_lite(&mut self, lite: bool) {
2737        self.remote_lite = lite;
2738        self.request_connectivity_check();
2739    }
2740
2741    /// Ta, the pacing of connectivity checks in use (RFC 8445 Section 14.2).
2742    pub fn pacing(&self) -> Duration {
2743        self.ta
2744    }
2745
2746    /// The Ta this agent proposes to its peer, when it is not the default of 50 ms: "If an
2747    /// agent wants to use a Ta value other than the default value, the agent MUST indicate the
2748    /// proposed value to its peer during the establishment of the ICE session" (RFC 8445
2749    /// Section 14.2; in SDP, `a=ice-pacing`, RFC 8839 Section 5.5, in milliseconds).
2750    pub fn proposed_pacing(&self) -> Option<Duration> {
2751        self.configured_ta
2752            .map(|ta| ta.max(MIN_TA))
2753            .filter(|ta| *ta != DEFAULT_TA)
2754    }
2755
2756    /// The peer's proposal for Ta (`None`: it proposed nothing, which is the default, 50 ms).
2757    /// "Both agents MUST use the higher out of the two proposed values" (RFC 8445 Section
2758    /// 14.2): from now on Ta is the larger of this agent's own and the peer's.
2759    ///
2760    /// Until this is called the agent paces by its own configuration alone: it cannot know
2761    /// that the peer was told. An application that configures a Ta under 50 ms and never
2762    /// calls this is pacing faster than the peer agreed to.
2763    pub fn set_remote_pacing(&mut self, proposed: Option<Duration>) {
2764        let own = self.configured_ta.unwrap_or(DEFAULT_TA);
2765        self.ta = own.max(proposed.unwrap_or(DEFAULT_TA)).max(MIN_TA);
2766    }
2767
2768    /// Two lite agents: replaces the remote candidates with those of an updated candidate
2769    /// exchange (RFC 8445 Section 8.2: "the controlling agent MUST send an updated candidate
2770    /// list to reconcile different agents selecting different candidate pairs. ICE processing
2771    /// is complete after and only after the updated candidate exchange is complete"), and
2772    /// selects again. Returns `false`, and changes nothing, unless both agents are lite.
2773    pub fn replace_remote_candidates(&mut self, now: Instant, candidates: Vec<Candidate>) -> bool {
2774        self.replace_remote_candidates_pinning(now, candidates, None)
2775    }
2776
2777    /// [`Agent::replace_remote_candidates`], with the local side of the pair given: RFC 8839
2778    /// Section 4.4.2.2, a lite answerer offered `a=remote-candidates` forms the pair from the
2779    /// offer's default destination and, as its local candidate, the transport address the
2780    /// attribute names (the controlling agent's remote candidate is this agent's local one).
2781    /// A pair with a local candidate at `local` is chosen over any other; `None` (or an
2782    /// address no local candidate has) leaves the choice to the RFC 6724 preference.
2783    pub fn replace_remote_candidates_pinning(
2784        &mut self,
2785        now: Instant,
2786        candidates: Vec<Candidate>,
2787        local: Option<SocketAddr>,
2788    ) -> bool {
2789        if !(self.lite && self.remote_lite) {
2790            return false;
2791        }
2792        self.pinned_local_addr = local;
2793        self.lite_update_taken = true;
2794        self.set_selected_pair(Some(now), None);
2795        self.announce_all_pairs_removed();
2796        self.candidate_pairs = Vec::new();
2797        self.nominated_pair = None;
2798        self.nomination_proposal = None;
2799        self.declined_nominations.clear();
2800        self.triggered_queue.clear();
2801        self.remote_candidates.clear();
2802        self.unpaired_remotes.clear();
2803        self.remote_end_of_candidates = false;
2804        self.trigger_request_connectivity_check(candidates);
2805        self.request_connectivity_check();
2806        true
2807    }
2808
2809    /// Replaces the candidate types the agent accepts as local candidates from now on
2810    /// (`AgentConfig::candidate_types`; empty means the default set).
2811    ///
2812    /// Candidates already added stay, and so does the pair in use: a new ICE transport policy
2813    /// takes effect at the next gathering (RFC 9429, Section 4.1.18; W3C webrtc-pc "set the
2814    /// configuration": "no action will be taken until the next gathering phase. If a script
2815    /// wants this to happen immediately, it should do an ICE restart"). The next ICE restart
2816    /// ([`Agent::apply_restart`]) drops the local candidates of a type no longer allowed, and
2817    /// does not keep the path in use when its local candidate is of such a type (the W3C
2818    /// "relay" policy: "The ICE Agent uses only media relay candidates"). A lite agent keeps
2819    /// host candidates only.
2820    pub fn set_candidate_types(&mut self, candidate_types: Vec<CandidateType>) {
2821        if self.lite {
2822            return;
2823        }
2824        self.candidate_types = if candidate_types.is_empty() {
2825            default_candidate_types()
2826        } else {
2827            candidate_types
2828        };
2829    }
2830
2831    /// The agent's current connection state.
2832    pub fn state(&self) -> ConnectionState {
2833        self.connection_state
2834    }
2835
2836    /// Whether a non-STUN datagram on `transport` should be accepted as media.
2837    ///
2838    /// Guards against accepting media from an address that has not passed a connectivity check.
2839    pub fn is_valid_non_stun_traffic(&mut self, now: Instant, transport: TransportContext) -> bool {
2840        self.remote_policy.allows_source(transport.peer_addr)
2841            && self
2842                .find_local_candidate(transport.local_addr, transport.transport_protocol)
2843                .is_some()
2844            && self.validate_non_stun_traffic(now, transport.peer_addr)
2845    }
2846
2847    fn get_timeout_interval(&self) -> Duration {
2848        let (check_interval, keepalive_interval, disconnected_timeout, failed_timeout) = (
2849            self.check_interval,
2850            self.keepalive_interval,
2851            self.disconnected_timeout,
2852            self.failed_timeout,
2853        );
2854        let mut interval = DEFAULT_CHECK_INTERVAL;
2855
2856        let mut update_interval = |x: Duration| {
2857            if x != ZERO_DURATION && (interval == ZERO_DURATION || interval > x) {
2858                interval = x;
2859            }
2860        };
2861
2862        match self.last_connection_state {
2863            ConnectionState::New | ConnectionState::Checking => {
2864                // While connecting, check candidates more frequently
2865                update_interval(check_interval);
2866            }
2867            ConnectionState::Connected | ConnectionState::Disconnected => {
2868                update_interval(keepalive_interval);
2869            }
2870            _ => {}
2871        };
2872        // Ensure we run our task loop as quickly as the minimum of our various configured timeouts
2873        update_interval(disconnected_timeout);
2874        update_interval(failed_timeout);
2875        interval
2876    }
2877
2878    /// The path data (DTLS, SRTP) is sent on and accepted from: the selected pair's, and
2879    /// during an ICE restart, until the restart selects a pair, the one the session had when
2880    /// the restart was applied, if the candidate types allowed then still allow its local
2881    /// candidate ([`Agent::set_candidate_types`]).
2882    ///
2883    /// RFC 8445 Section 9: "during the restart, data can continue to be sent using existing
2884    /// data sessions". Without it every packet between
2885    /// `apply_restart` and the first nomination of the new generation was dropped, on both
2886    /// sides, for as long as the offer/answer exchange took.
2887    ///
2888    /// While the controlling agent's nomination is in flight, it is the nominated pair's. That
2889    /// pair is valid, so Section 12.1 allows it ("An ICE agent MAY send data on any valid pair
2890    /// before selected pairs have been produced for the data stream"), and it is the pair
2891    /// the controlled agent selected when the nomination's first request reached it: the peer
2892    /// sends on it from then on (its DTLS handshake starts), and Section 12.2 asks for that
2893    /// data to be received ("ICE implementations SHOULD by default be prepared to receive data
2894    /// on any of the candidates"). Without it, while the responses to the nomination were
2895    /// lost, the controlling agent dropped everything the peer sent and could answer nothing:
2896    /// the peer's DTLS retransmissions went unanswered and its timer backed off for nothing,
2897    /// so that after a few more losses at 10 % the data channel had not opened in 30 seconds.
2898    ///
2899    /// With [`AgentConfig::send_data_before_nomination`], and before the first pair is
2900    /// selected, it is the best valid pair's (Section 12.1).
2901    pub fn media_path(&self) -> Option<MediaPath> {
2902        self.selected_media_path()
2903            .or(self.previous_media_path)
2904            .or_else(|| self.nominating_media_path())
2905            .or_else(|| self.valid_media_path())
2906    }
2907
2908    /// The path an ICE restart replaced, while data on it is still taken after the restart's
2909    /// pair was selected (`RETIRED_MEDIA_PATH_GRACE`); nothing is sent on it.
2910    pub fn retired_media_path(&self) -> Option<MediaPath> {
2911        self.retired_media_path
2912            .filter(|(_, until)| self.clock < *until)
2913            .map(|(path, _)| path)
2914    }
2915
2916    /// The path of the valid pair the controlling agent is nominating, before any pair is
2917    /// selected, while consent on it is fresh: a Binding success response came from its
2918    /// remote candidate less than the consent expiry ago, as of the newest instant the agent
2919    /// was given (RFC 7675 Section 5.1: no data once consent has expired). A nomination's
2920    /// transaction lasts longer than that (39.5 seconds, RFC 8445 Section 14.3).
2921    fn nominating_media_path(&self) -> Option<MediaPath> {
2922        if !self.is_controlling || self.selected_pair.is_some() {
2923            return None;
2924        }
2925        let pair_index = self.nominated_pair?;
2926        let pair = self.candidate_pairs.get(pair_index)?;
2927        let consent = self.pair_consent(pair_index)?;
2928        (pair.valid
2929            && !pair.removed
2930            && pair.state != CandidatePairState::Failed
2931            && self.clock.saturating_duration_since(consent) < self.consent_expiry())
2932        .then(|| self.path_of(pair.local_index, pair.remote_index))
2933    }
2934
2935    /// The best valid pair's path, when data may be sent before a pair is selected. A lite
2936    /// agent has no valid pair before a nomination (Section 12.1.1).
2937    fn valid_media_path(&self) -> Option<MediaPath> {
2938        if !self.send_data_before_nomination {
2939            return None;
2940        }
2941        let pair = &self.candidate_pairs[self.get_best_valid_candidate_pair()?];
2942        Some(self.path_of(pair.local_index, pair.remote_index))
2943    }
2944
2945    /// The type of the local candidate [`Agent::media_path`] leaves from, found the way
2946    /// `media_path` finds the path. A learned (peer-reflexive) local candidate is of its base's
2947    /// type: its packets leave from that candidate's base (RFC 8445 Section 7.2.5.3.1).
2948    fn media_path_local_type(&self) -> Option<CandidateType> {
2949        if let Some(pair_index) = self.get_selected_pair() {
2950            return Some(self.path_local_type(self.candidate_pairs[pair_index].local_index));
2951        }
2952        if self.previous_media_path.is_some() {
2953            return self.previous_media_path_type;
2954        }
2955        if self.nominating_media_path().is_some() {
2956            let pair = self.candidate_pairs[self.nominated_pair?];
2957            return Some(self.path_local_type(pair.local_index));
2958        }
2959        if self.valid_media_path().is_some() {
2960            let pair = self.candidate_pairs[self.get_best_valid_candidate_pair()?];
2961            return Some(self.path_local_type(pair.local_index));
2962        }
2963        None
2964    }
2965
2966    /// The type of local candidate `local_index`, a learned one's being its base's (see
2967    /// `media_path_local_type`); a learned one whose base is gone stays peer-reflexive.
2968    fn path_local_type(&self, local_index: usize) -> CandidateType {
2969        let local = &self.local_candidates[local_index];
2970        if local.candidate_type() != CandidateType::PeerReflexive {
2971            return local.candidate_type();
2972        }
2973        let (base, network_type) = (local.base_addr(), local.network_type());
2974        self.local_candidates
2975            .iter()
2976            .find(|c| {
2977                c.candidate_type() != CandidateType::PeerReflexive
2978                    && c.network_type() == network_type
2979                    && c.base_addr() == base
2980            })
2981            .map_or(CandidateType::PeerReflexive, |c| c.candidate_type())
2982    }
2983
2984    fn path_of(&self, local_index: usize, remote_index: usize) -> MediaPath {
2985        let local = &self.local_candidates[local_index];
2986        MediaPath {
2987            local_addr: local.base_addr(),
2988            peer_addr: self.remote_candidates[remote_index].addr(),
2989            transport_protocol: local.network_type().to_protocol(),
2990        }
2991    }
2992
2993    /// Whether data (anything that is not STUN: DTLS, SRTP) that arrived on `transport` is
2994    /// accepted.
2995    ///
2996    /// RFC 8445 Section 12.2: "ICE implementations SHOULD by default be prepared to receive
2997    /// data on any of the candidates provided in the most recent candidate exchange with the
2998    /// peer", and "an agent will be able to determine that a data stream is from the same peer
2999    /// as a consequence of the STUN exchange that proceeds media data transmission". So, once
3000    /// there is a path to send on ([`Agent::media_path`]), data is accepted on any local
3001    /// candidate, from that path's remote address and from the remote candidate of any valid
3002    /// pair: an address one of the agent's own checks was answered from, by someone who holds
3003    /// the peer's password. A source that only sent requests, or that no check reached, is
3004    /// not accepted.
3005    ///
3006    /// With [`AgentConfig::data_from_selected_pair_only`] only the remote address of the path
3007    /// data is sent on is accepted.
3008    pub fn accepts_data(&self, transport: TransportContext) -> bool {
3009        self.data_path(transport).is_some()
3010    }
3011
3012    /// As [`Agent::accepts_data`], saying which pair the data arrived on: the one in use, or
3013    /// another valid pair (its local and remote candidates).
3014    pub fn data_path(&self, transport: TransportContext) -> Option<DataPath<'_>> {
3015        // Nothing from a source the embedder's address policy refuses.
3016        if !self.remote_policy.allows_source(transport.peer_addr) {
3017            return None;
3018        }
3019        let path = self.media_path()?;
3020        if self.data_from_selected_pair_only {
3021            // (The hardening compares the source only, as it always did.)
3022            return (transport.peer_addr == path.peer_addr).then_some(DataPath::InUse);
3023        }
3024        if transport.peer_addr == path.peer_addr
3025            && transport.local_addr == path.local_addr
3026            && transport.transport_protocol == path.transport_protocol
3027        {
3028            return Some(DataPath::InUse);
3029        }
3030        // The path an ICE restart replaced, for a while after the new pair was selected: the
3031        // peer's packets sent before its own selection switched.
3032        if self.retired_media_path.is_some_and(|(retired, until)| {
3033            self.clock < until
3034                && transport.peer_addr == retired.peer_addr
3035                && transport.local_addr == retired.local_addr
3036                && transport.transport_protocol == retired.transport_protocol
3037        }) {
3038            return Some(DataPath::InUse);
3039        }
3040        // "On any of the candidates provided": the datagram arrived on one of them.
3041        self.find_local_candidate(transport.local_addr, transport.transport_protocol)?;
3042        let valid = |p: &&CandidatePair| {
3043            p.valid
3044                && p.state == CandidatePairState::Succeeded
3045                && self.remote_candidates[p.remote_index].addr() == transport.peer_addr
3046                && self.local_candidates[p.local_index]
3047                    .network_type()
3048                    .to_protocol()
3049                    == transport.transport_protocol
3050        };
3051        // The valid pair it arrived on, when there is one for this local candidate too.
3052        let exact = self
3053            .candidate_pairs
3054            .iter()
3055            .filter(valid)
3056            .find(|p| self.local_candidates[p.local_index].base_addr() == transport.local_addr);
3057        if let Some(p) = exact.or_else(|| self.candidate_pairs.iter().find(valid)) {
3058            return Some(DataPath::Valid(
3059                &self.local_candidates[p.local_index],
3060                &self.remote_candidates[p.remote_index],
3061            ));
3062        }
3063        // From the remote address of the path in use, on another local candidate.
3064        (transport.peer_addr == path.peer_addr
3065            && transport.transport_protocol == path.transport_protocol)
3066            .then_some(DataPath::InUse)
3067    }
3068
3069    fn selected_media_path(&self) -> Option<MediaPath> {
3070        self.get_selected_candidate_pair()
3071            .map(|(local, remote)| MediaPath {
3072                // The local candidate's base: for a (server/peer-)reflexive candidate the
3073                // candidate address is the NAT mapping, not a bound local socket
3074                // (RFC 8445 Section 5.1.1).
3075                local_addr: local.base_addr(),
3076                peer_addr: remote.addr(),
3077                transport_protocol: local.network_type().to_protocol(),
3078            })
3079    }
3080
3081    /// Returns the selected pair (local_candidate, remote_candidate) or none
3082    pub fn get_selected_candidate_pair(&self) -> Option<(&Candidate, &Candidate)> {
3083        if let Some(pair_index) = self.get_selected_pair() {
3084            let candidate_pair = &self.candidate_pairs[pair_index];
3085            Some((
3086                &self.local_candidates[candidate_pair.local_index],
3087                &self.remote_candidates[candidate_pair.remote_index],
3088            ))
3089        } else {
3090            None
3091        }
3092    }
3093
3094    /// The highest-priority pair that is still usable, whether or not it has been nominated.
3095    pub fn get_best_available_candidate_pair(&self) -> Option<(&Candidate, &Candidate)> {
3096        if let Some(pair_index) = self.get_best_available_pair() {
3097            let candidate_pair = &self.candidate_pairs[pair_index];
3098            Some((
3099                &self.local_candidates[candidate_pair.local_index],
3100                &self.remote_candidates[candidate_pair.remote_index],
3101            ))
3102        } else {
3103            None
3104        }
3105    }
3106
3107    /// start connectivity checks
3108    pub fn start_connectivity_checks(
3109        &mut self,
3110        now: Instant,
3111        is_controlling: bool,
3112        remote_ufrag: String,
3113        remote_pwd: String,
3114    ) -> Result<()> {
3115        debug!(
3116            "Started agent: isControlling? {}, remoteUfrag: {}, remotePwd: {}",
3117            is_controlling, remote_ufrag, remote_pwd
3118        );
3119        self.set_remote_credentials(remote_ufrag, remote_pwd)?;
3120        self.is_controlling = is_controlling;
3121        self.start(now);
3122
3123        self.update_connection_state(Some(now), ConnectionState::Checking);
3124        self.request_connectivity_check();
3125
3126        Ok(())
3127    }
3128
3129    /// Restarts the ICE Agent with the provided ufrag/pwd
3130    /// If no ufrag/pwd is provided the Agent will generate one itself.
3131    /// Stages new local credentials for an ICE restart, without disturbing the live session.
3132    ///
3133    /// This is the half of an ICE restart that an offerer needs *before* generating SDP: the offer
3134    /// must carry the new ufrag/pwd. It deliberately does not touch `local_credentials`,
3135    /// candidate pairs, or connection state, because JSEP requires `createOffer` to be free of
3136    /// side effects — and because inbound STUN is still being validated against the current
3137    /// credentials until the local description is applied.
3138    ///
3139    /// Empty `ufrag` / `pwd` are filled from the crypto provider's RNG. Call
3140    /// [`Agent::apply_restart`] to install them.
3141    pub fn generate_restart_credentials(
3142        &mut self,
3143        mut ufrag: String,
3144        mut pwd: String,
3145    ) -> Result<()> {
3146        if ufrag.is_empty() {
3147            ufrag = generate_ufrag_with_random(self.crypto_provider.random())?;
3148        }
3149        if pwd.is_empty() {
3150            pwd = generate_pwd_with_random(self.crypto_provider.random())?;
3151        }
3152
3153        // RFC 8445 Section 9: an ICE restart changes both the fragment and the password. An
3154        // application that pins its credentials would otherwise offer the ones in use: the
3155        // peer sees no restart while this side has flushed its pairs. The pinned pair then
3156        // names the first generation only.
3157        let current = &self.ufrag_pwd.local_credentials;
3158        if !current.ufrag.is_empty() && (ufrag == current.ufrag || pwd == current.pwd) {
3159            warn!(
3160                "[{}]: an ICE restart was given the credentials in use; generating new ones",
3161                self.get_name()
3162            );
3163            ufrag = generate_ufrag_with_random(self.crypto_provider.random())?;
3164            pwd = generate_pwd_with_random(self.crypto_provider.random())?;
3165        }
3166
3167        check_local_credentials(&ufrag, &pwd)?;
3168
3169        self.ufrag_pwd.pending_local_credentials = Some(Credentials { ufrag, pwd }.into());
3170
3171        Ok(())
3172    }
3173
3174    /// Whether [`Agent::generate_restart_credentials`] has staged a restart that is not yet applied.
3175    pub fn has_pending_restart(&self) -> bool {
3176        self.ufrag_pwd.pending_local_credentials.is_some()
3177    }
3178
3179    /// Forgets the credentials [`Agent::generate_restart_credentials`] staged, so that no
3180    /// restart is pending: the description they were staged for was abandoned (a rolled-back
3181    /// remote offer, RFC 9429 section 5.7). The live session is untouched.
3182    pub fn discard_restart_credentials(&mut self) {
3183        self.ufrag_pwd.pending_local_credentials = None;
3184        // What was gathered for it belongs to no generation now; a candidate that could not
3185        // join the current session (it had nominated) still does not.
3186        for c in &mut self.local_candidates {
3187            c.restart_generation = false;
3188        }
3189    }
3190
3191    /// The local candidates gathered for the staged ICE restart (see
3192    /// [`Agent::generate_restart_credentials`]): added, or added again, since it was staged.
3193    /// The restart keeps them whether or not it keeps the others.
3194    pub fn get_restart_generation_local_candidates(&self) -> Vec<Candidate> {
3195        self.local_candidates
3196            .iter()
3197            .filter(|c| c.restart_generation)
3198            .cloned()
3199            .collect()
3200    }
3201
3202    /// Applies a staged ICE restart, tearing down the old session and starting a new one at `now`.
3203    ///
3204    /// Installs the credentials staged by [`Agent::generate_restart_credentials`], if any, then
3205    /// discards the remote credentials, pending binding requests, candidate pairs and selected
3206    /// pair, and restarts the agent's timers. With nothing staged, the current credentials are
3207    /// kept and only the session is restarted.
3208    pub fn apply_restart(&mut self, now: Instant, keep_local_candidates: bool) -> Result<()> {
3209        // A closed agent has shut its mDNS connection and dropped its candidates for good; a
3210        // restart must not bring it back to `Checking`.
3211        if self.connection_state == ConnectionState::Closed {
3212            return Err(Error::ErrClosed);
3213        }
3214        // A restart that is not revertible commits an earlier one.
3215        self.restart_undo = None;
3216        // RFC 8445 Section 16.1: "The agent MAY change the number when an ICE restart
3217        // occurs", when the application asked for it.
3218        if self.new_tie_breaker_on_restart {
3219            self.tie_breaker = generate_tie_breaker(self.crypto_provider.random())?;
3220        }
3221        // A new generation: what the gathering just before showed public is what it unwraps
3222        // (draft-ietf-mmusic-mdns-ice-candidates Section 3.1.2.2).
3223        self.ice_generation += 1;
3224        self.mdns_known_public.restarted(self.ice_generation);
3225        // Data keeps the path it has until the new generation selects a pair (RFC 8445
3226        // Section 9), whether or not the local candidates are kept: discarding them forgets
3227        // what was signalled, not the socket the path's packets leave from. An application
3228        // that closed that socket (a rebind) drops what is written to it, as before.
3229        let previous_media_path = self.media_path();
3230        // Consent goes on being checked on that path (RFC 7675 Section 5.1), with the
3231        // credentials of the generation that validated it. A second restart before the first
3232        // one selected a pair keeps what the first one kept.
3233        let previous_generation = match (self.selected_pair, &self.ufrag_pwd.remote_credentials) {
3234            (Some(pair_index), Some(remote_credentials)) => {
3235                let pair = self.candidate_pairs[pair_index];
3236                let remote = &self.remote_candidates[pair.remote_index];
3237                let last_consent = if self.lite {
3238                    remote.last_authenticated()
3239                } else {
3240                    self.pair_consent(pair_index)
3241                };
3242                Some(PreviousGeneration {
3243                    local_credentials: self.ufrag_pwd.local_credentials.clone(),
3244                    remote_credentials: remote_credentials.clone(),
3245                    priority: self.local_candidates[pair.local_index].peer_reflexive_priority(),
3246                    last_consent: last_consent.unwrap_or(now),
3247                    next_consent_at: self
3248                        .next_consent_at
3249                        .unwrap_or_else(|| now + self.next_consent_interval()),
3250                    // The consent requests still open on the pair stay open on the path: the
3251                    // peer answers them as it would have without the restart (RFC 7675
3252                    // Section 5.1: "a response might be for a previous request").
3253                    pending: self
3254                        .pending_binding_requests
3255                        .iter()
3256                        .filter(|r| {
3257                            r.consent
3258                                && r.local_index == pair.local_index
3259                                && r.remote_index == pair.remote_index
3260                                && r.next_event > now
3261                        })
3262                        .map(|r| PreviousConsentRequest {
3263                            transaction_id: r.transaction_id,
3264                            sent: r.timestamp,
3265                            until: r.next_event,
3266                        })
3267                        .collect(),
3268                    rto: pair.rto,
3269                })
3270            }
3271            _ => self.previous_generation.take(),
3272        };
3273        // The candidate types allowed now: a new ICE transport policy takes effect with the
3274        // restart (W3C webrtc-pc "set the configuration": "If a script wants this to happen
3275        // immediately, it should do an ICE restart"), and the "relay" policy allows the ICE
3276        // agent "only media relay candidates". RFC 8445 Section 9 lets data "continue to be
3277        // sent using existing data sessions" during a restart, a permission: a path whose local
3278        // candidate is of a type no longer allowed is not kept (the peer would go on learning
3279        // the address the policy hides, and receiving from it), so the agent checks until the
3280        // new generation selects a pair. Nor is a retired one.
3281        let previous_media_path_type = previous_media_path.and(self.media_path_local_type());
3282        let allowed =
3283            |t: Option<CandidateType>| t.is_some_and(|t| self.candidate_types.contains(&t));
3284        let (previous_media_path, previous_generation) = if allowed(previous_media_path_type) {
3285            (previous_media_path, previous_generation)
3286        } else {
3287            if let Some(path) = previous_media_path {
3288                debug!(
3289                    "[{}]: not keeping the path {} -> {} across the ICE restart: its local candidate ({:?}) is not of a type now allowed ({:?})",
3290                    self.get_name(),
3291                    path.local_addr,
3292                    path.peer_addr,
3293                    previous_media_path_type,
3294                    self.candidate_types
3295                );
3296            }
3297            (None, None)
3298        };
3299        if self.retired_media_path.is_some() && !allowed(self.retired_media_path_type) {
3300            self.retired_media_path = None;
3301            self.retired_media_path_type = None;
3302        }
3303
3304        if let Some(credentials) = self.ufrag_pwd.pending_local_credentials.take() {
3305            self.ufrag_pwd.local_credentials = credentials;
3306        }
3307        self.ufrag_pwd.remote_credentials = None;
3308
3309        self.pending_binding_requests = vec![];
3310        self.early_requests = vec![];
3311        self.triggered_queue.clear();
3312        // A new generation: its candidates and its end-of-candidates are still to come.
3313        self.lite_update_raised = false;
3314        self.lite_update_taken = false;
3315        self.pinned_local_addr = None;
3316        self.remote_end_of_candidates = false;
3317        self.local_gathering_complete = false;
3318
3319        self.announce_all_pairs_removed();
3320        self.candidate_pairs = Vec::new();
3321
3322        self.set_selected_pair(Some(now), None);
3323        // The local candidates gathered while the restart was staged are the new
3324        // generation's: they stay when the previous generation's are discarded.
3325        if !keep_local_candidates {
3326            self.local_candidates.retain(|c| c.restart_generation);
3327        }
3328        // A withdrawn candidate is not the new session's.
3329        self.local_candidates.retain(|c| !c.withdrawn);
3330        // Nor is a kept one of a type no longer allowed (`set_candidate_types`): the restart is
3331        // the next gathering phase, where a new ICE transport policy takes effect (RFC 9429
3332        // Section 4.1.18), and the "relay" policy allows "only media relay candidates" (W3C
3333        // webrtc-pc `RTCIceTransportPolicy`). Kept, the new generation would pair it, check it
3334        // and select the very path the policy rules out.
3335        let candidate_types = self.candidate_types.clone();
3336        self.local_candidates
3337            .retain(|c| candidate_types.contains(&c.candidate_type()));
3338        self.delete_all_candidates(true);
3339        for c in &mut self.local_candidates {
3340            c.restart_generation = false;
3341            c.awaiting_restart = false;
3342        }
3343        self.reevaluate_kept_host_candidates();
3344        // The names lost while the previous session could convey nothing: the new
3345        // generation's candidates take the new ones (`replace_local_mdns_name`).
3346        for (lost, name) in std::mem::take(&mut self.mdns_deferred_renames) {
3347            for c in &mut self.local_candidates {
3348                if c.address == lost {
3349                    c.address = name.clone();
3350                }
3351            }
3352        }
3353        self.previous_media_path = previous_media_path;
3354        self.previous_media_path_type = previous_media_path.and(previous_media_path_type);
3355        self.previous_generation = previous_media_path.and(previous_generation);
3356        self.start(now);
3357
3358        // Restart is used by NewAgent. Accept/Connect should be used to move to checking
3359        // for new Agents. W3C webrtc-pc 5.6.4: "An ICE restart [...] causing a transition to
3360        // connected if begun in the completed state. If begun in the transient disconnected
3361        // state, it causes a transition to checking": a connected or completed agent that keeps
3362        // its path (RFC 8445 Section 9) is connected; a disconnected or failed one, or one
3363        // without a path, checks.
3364        let was_connected = matches!(
3365            self.connection_state,
3366            ConnectionState::Connected | ConnectionState::Completed
3367        );
3368        if was_connected && self.previous_media_path.is_some() {
3369            self.update_connection_state(Some(now), ConnectionState::Connected);
3370        } else if self.connection_state != ConnectionState::New {
3371            self.update_connection_state(Some(now), ConnectionState::Checking);
3372        }
3373
3374        Ok(())
3375    }
3376
3377    /// Generates and immediately applies an ICE restart.
3378    ///
3379    /// Equivalent to [`Agent::generate_restart_credentials`] followed by
3380    /// [`Agent::apply_restart`]. A JSEP-conformant offerer wants the two halves separately —
3381    /// credentials at `createOffer`, application at `setLocalDescription` — but this remains the
3382    /// right call for anything that restarts in one step.
3383    pub fn restart(
3384        &mut self,
3385        now: Instant,
3386        ufrag: String,
3387        pwd: String,
3388        keep_local_candidates: bool,
3389    ) -> Result<()> {
3390        self.generate_restart_credentials(ufrag, pwd)?;
3391        self.apply_restart(now, keep_local_candidates)
3392    }
3393
3394    /// Returns the local candidates.
3395    pub fn get_local_candidates(&self) -> &[Candidate] {
3396        &self.local_candidates
3397    }
3398
3399    /// The remote candidates this agent has been given, in the order they were added.
3400    pub fn get_remote_candidates(&self) -> &[Candidate] {
3401        &self.remote_candidates
3402    }
3403
3404    /// One pass over everything the agent does on its own: retransmissions and timeouts, the
3405    /// selected pair's consent, nomination, the next check Ta allows, and the checklist's
3406    /// state.
3407    fn contact(&mut self, now: Instant) {
3408        // Consume any pending deferred-check request now that we are running one.
3409        // Reset before the early returns below so a failed/settled agent does not
3410        // keep asking `poll_timeout` for an immediate wake-up.
3411        self.force_candidate_contact = false;
3412
3413        if matches!(
3414            self.connection_state,
3415            ConnectionState::Failed | ConnectionState::Closed
3416        ) {
3417            // The connection is currently failed so don't send any checks
3418            // In the future it may be restarted though
3419            self.last_connection_state = self.connection_state;
3420            return;
3421        }
3422        // Checks that failed while the indications were missing: failed once they are in (W3C
3423        // webrtc-pc 5.6.4).
3424        if let Some(why) = self.failure_held
3425            && self.may_report_failed(now)
3426        {
3427            self.fail_or_hold(now, why);
3428            self.last_connection_state = self.connection_state;
3429            return;
3430        }
3431        if self.connection_state == ConnectionState::Checking {
3432            // We have just entered checking for the first time so update our checking timer
3433            if self.last_connection_state != self.connection_state {
3434                self.checking_duration = now;
3435            }
3436
3437            // A nomination the peer has not been heard from for the consent expiry ends: its
3438            // pair fails, and the next valid pair is nominated.
3439            self.expire_unanswered_nomination(now);
3440
3441            // Past `disconnected_timeout + failed_timeout` in checking, the agent fails, but
3442            // only once nothing is left that may still produce a selected pair (RFC 8445
3443            // Sections 6.1.4.2 and 8.1.2: the checklist fails when every pair has failed). A
3444            // pair that is still being checked fails by its own transaction (Section 14.3), a
3445            // nomination by `expire_unanswered_nomination`. Nor while the PAC timer runs (RFC
3446            // 8863 Section 4: no Failed checklist, no Failed session, before it expires). And
3447            // `Failed` only with the indications that no candidate is to come (W3C webrtc-pc
3448            // 5.6.4); without them `Disconnected`, and the checks go on (a triggered check, a
3449            // new pair).
3450            if self.failed_timeout != ZERO_DURATION
3451                && now
3452                    .checked_duration_since(self.checking_duration)
3453                    .unwrap_or_else(|| Duration::from_secs(0))
3454                    > self.disconnected_timeout + self.failed_timeout
3455                && !self.checks_in_progress(now)
3456                && !self.pac_running(now)
3457            {
3458                self.fail_or_hold(now, HeldFailure::CheckingTimeout);
3459                if self.connection_state == ConnectionState::Failed {
3460                    self.last_connection_state = self.connection_state;
3461                    return;
3462                }
3463            }
3464        }
3465
3466        self.run_transactions(now);
3467
3468        // Two lite agents: no checks, the pair comes from the candidate exchange (Section 8.2).
3469        if self.lite && self.remote_lite {
3470            self.conclude_lite_to_lite(now);
3471        }
3472
3473        if self.selected_pair.is_some() && self.validate_selected_pair(now) {
3474            if self.lite && (!self.is_controlling || self.remote_lite) {
3475                self.lite_keepalive(now);
3476            } else {
3477                self.check_keepalive(now);
3478            }
3479        }
3480
3481        if !matches!(
3482            self.connection_state,
3483            ConnectionState::Failed | ConnectionState::Closed
3484        ) {
3485            self.maybe_nominate(now);
3486            self.run_ta(now);
3487            self.update_checklist_failure(now);
3488        }
3489
3490        self.last_connection_state = self.connection_state;
3491        self.last_checking_time = now;
3492    }
3493
3494    /// When `contact` next has something to do. `None` when the agent has no peer credentials
3495    /// or is failed or closed.
3496    pub(crate) fn ice_deadline(&self) -> Option<Instant> {
3497        if self.ufrag_pwd.remote_credentials.is_none()
3498            || matches!(
3499                self.connection_state,
3500                ConnectionState::Failed | ConnectionState::Closed
3501            )
3502        {
3503            return None;
3504        }
3505        if self.force_candidate_contact {
3506            // A check or a look at the state was requested: as soon as possible.
3507            // `last_checking_time` is in the past, so the resulting deadline is immediate.
3508            return Some(self.last_checking_time);
3509        }
3510        let mut deadline: Option<Instant> = None;
3511        let mut by = |at: Instant| deadline = Some(deadline.map_or(at, |d| d.min(at)));
3512        // A retransmission, or a transaction that ends.
3513        for request in &self.pending_binding_requests {
3514            by(request.next_event);
3515        }
3516        // Connected: the next consent request, or the moment its silence counts.
3517        if let Some(at) = self.selected_pair_deadline() {
3518            by(at);
3519        }
3520        // Connecting (and a lite agent always): a periodic look at the state.
3521        if self.selected_pair.is_none() || self.lite {
3522            by(self.last_checking_time + self.get_timeout_interval());
3523        }
3524        // The next check, when Ta allows it.
3525        if self.has_check_to_start() {
3526            by(self.next_check_at);
3527        }
3528        deadline
3529    }
3530
3531    pub(crate) fn update_connection_state(
3532        &mut self,
3533        now: Option<Instant>,
3534        new_state: ConnectionState,
3535    ) {
3536        if new_state != ConnectionState::Disconnected {
3537            self.failure_held = None;
3538        }
3539        if self.connection_state != new_state {
3540            // Connection has gone to failed, release all gathered candidates
3541            if new_state == ConnectionState::Failed {
3542                self.set_selected_pair(now, None);
3543                self.delete_all_candidates(false);
3544            }
3545            // A failed or closed agent has no path, a restart's previous one included, and no
3546            // open transactions (RFC 7675 Section 5.1: "All outstanding STUN consent
3547            // transactions for a candidate pair MUST be discarded when consent expires").
3548            if matches!(new_state, ConnectionState::Failed | ConnectionState::Closed) {
3549                self.previous_media_path = None;
3550                self.retired_media_path = None;
3551                self.previous_generation = None;
3552                self.pending_binding_requests.clear();
3553                self.triggered_queue.clear();
3554                self.next_consent_at = None;
3555                self.consent_unanswered_since = None;
3556            }
3557
3558            info!(
3559                "[{}]: Setting new connection state: {}",
3560                self.get_name(),
3561                new_state
3562            );
3563            self.connection_state = new_state;
3564            if let Some(now) = now {
3565                self.event_outs.push_back(TaggedEvent {
3566                    now,
3567                    event: Event::ConnectionStateChange(new_state),
3568                });
3569            }
3570        }
3571    }
3572
3573    pub(crate) fn set_selected_pair(&mut self, now: Option<Instant>, selected_pair: Option<usize>) {
3574        if let Some(pair_index) = selected_pair {
3575            trace!(
3576                "[{}]: Set selected candidate pair: {:?}",
3577                self.get_name(),
3578                self.candidate_pairs[pair_index]
3579            );
3580
3581            self.candidate_pairs[pair_index].nominated = true;
3582            if self.selected_pair != Some(pair_index) {
3583                // Consent on the new pair was given by the response that validated it; the
3584                // first consent check follows one interval later. A pair the peer selects
3585                // long after that response (its nomination's responses were lost, so the
3586                // controlled agent waited) has less than 30 seconds of consent left (RFC 7675
3587                // section 5.1), and the check that validated it was sent at least as long
3588                // ago: the first consent check goes now, which keeps the period between
3589                // checks above the minimum.
3590                let interval = self.next_consent_interval();
3591                let last_consent = self.pair_consent(pair_index);
3592                self.next_consent_at = now.map(|now| match last_consent {
3593                    Some(at) if now.saturating_duration_since(at) >= interval => now,
3594                    _ => now + interval,
3595                });
3596                self.consent_unanswered_since = None;
3597            }
3598            self.selected_pair = Some(pair_index);
3599            // The restart (if any) has its pair: the previous generation's path is retired. The
3600            // peer may still send on it until its own selection switches: data on it is taken
3601            // a little longer (`RETIRED_MEDIA_PATH_GRACE`).
3602            if let Some(previous) = self.previous_media_path.take() {
3603                let now = now.unwrap_or(self.clock);
3604                self.retired_media_path = Some((previous, now + RETIRED_MEDIA_PATH_GRACE));
3605                self.retired_media_path_type = self.previous_media_path_type.take();
3606            }
3607            self.previous_generation = None;
3608
3609            if !matches!(
3610                self.connection_state,
3611                ConnectionState::Connected | ConnectionState::Completed
3612            ) {
3613                self.update_connection_state(now, ConnectionState::Connected);
3614            }
3615
3616            // Notify when the selected pair changes
3617            let candidate_pair = &self.candidate_pairs[pair_index];
3618            if let Some(now) = now {
3619                self.event_outs.push_back(TaggedEvent {
3620                    now,
3621                    event: Event::SelectedCandidatePairChange(
3622                        Box::new(self.local_candidates[candidate_pair.local_index].clone()),
3623                        Box::new(self.remote_candidates[candidate_pair.remote_index].clone()),
3624                    ),
3625                });
3626            }
3627        } else {
3628            self.selected_pair = None;
3629            self.next_consent_at = None;
3630            self.consent_unanswered_since = None;
3631        }
3632    }
3633
3634    /// The state of a connected agent whose consent is fresh: `Completed` once both sides
3635    /// have said they have no more candidates (W3C `RTCIceTransportState`: "finished
3636    /// gathering, received an indication that there are no more remote candidates, finished
3637    /// checking all candidate pairs and found a connection"; a peer that cannot trickle has
3638    /// none to come either), `Connected` until then.
3639    fn healthy_state(&self) -> ConnectionState {
3640        if self.no_more_remote_candidates() && self.local_gathering_complete {
3641            ConnectionState::Completed
3642        } else {
3643            ConnectionState::Connected
3644        }
3645    }
3646
3647    /// One interval between two consent checks: 0.8 to 1.2 times the basic period, drawn from
3648    /// the crypto provider's RNG, and never under 4 seconds (RFC 7675 Section 5.1: "To prevent
3649    /// synchronization of consent checks, each interval MUST be randomized from between 0.8
3650    /// and 1.2 times the basic period. [...] Implementations MUST NOT set the period between
3651    /// checks to less than 4 seconds").
3652    pub(crate) fn next_consent_interval(&self) -> Duration {
3653        let mut bytes = [0_u8; 4];
3654        // Without randomness the period itself is the interval.
3655        let r = match self.crypto_provider.random().fill(&mut bytes) {
3656            Ok(()) => u64::from(u32::from_be_bytes(bytes)),
3657            Err(_) => u64::from(u32::MAX / 2),
3658        };
3659        // 0.8 + 0.4 * r / (2^32 - 1), in millionths.
3660        let factor = 800_000 + (r * 400_000) / u64::from(u32::MAX);
3661        let nanos = self.keepalive_interval.as_nanos() * u128::from(factor) / 1_000_000;
3662        Duration::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX)).max(MIN_CONSENT_INTERVAL)
3663    }
3664
3665    /// How long after the last consent response the agent stops sending: the configured
3666    /// `disconnected_timeout + failed_timeout`, and 30 seconds at most (RFC 7675 Section 5.1:
3667    /// "Consent expires after 30 seconds. That is, if a valid STUN binding response has not
3668    /// been received from the remote peer's transport address in 30 seconds, the endpoint MUST
3669    /// cease transmission on that 5-tuple"). A `failed_timeout` of zero, which keeps a
3670    /// checking agent from failing, does not keep consent alive.
3671    pub(crate) fn consent_expiry(&self) -> Duration {
3672        if self.failed_timeout == ZERO_DURATION {
3673            CONSENT_EXPIRY
3674        } else {
3675            (self.disconnected_timeout + self.failed_timeout).min(CONSENT_EXPIRY)
3676        }
3677    }
3678
3679    /// Checks if the selected pair is (still) valid.
3680    /// Re-evaluates the selected pair's liveness as of `now`.
3681    ///
3682    /// `now` comes from the caller so that this decision and the keepalive decision below are
3683    /// made against the same instant as the `contact(now)` that reached them.
3684    pub(crate) fn validate_selected_pair(&mut self, now: Instant) -> bool {
3685        let Some(pair_index) = self.selected_pair else {
3686            return false;
3687        };
3688        let remote_index = self.candidate_pairs[pair_index].remote_index;
3689        let remote = &self.remote_candidates[remote_index];
3690
3691        if self.lite && self.remote_lite {
3692            // Two lite agents exchange no Binding requests at all (Section 6.1.1: "no
3693            // connectivity checks are ever sent"): ICE has no sign of life to judge by.
3694            self.update_connection_state(Some(now), self.healthy_state());
3695            return true;
3696        }
3697
3698        if self.lite {
3699            // A lite agent sends no checks (RFC 8445 §2.5), so for it an authenticated request
3700            // from the peer is the only sign of life, judged by the configured timeouts.
3701            let last_received = remote.last_authenticated().unwrap_or(self.start_time);
3702            let disconnected_time = now.saturating_duration_since(last_received);
3703
3704            // Only allow transitions to fail if a.failedTimeout is non-zero
3705            let mut total_time_to_failure = self.failed_timeout;
3706            if total_time_to_failure != ZERO_DURATION {
3707                total_time_to_failure += self.disconnected_timeout;
3708            }
3709
3710            // Failed only with the indications that no candidate is to come (W3C webrtc-pc
3711            // 5.6.4); until then the silence is a loss of connectivity: Disconnected.
3712            let failed =
3713                total_time_to_failure != ZERO_DURATION && disconnected_time > total_time_to_failure;
3714            if failed && self.may_report_failed(now) {
3715                self.update_connection_state(Some(now), ConnectionState::Failed);
3716            } else if failed
3717                || (self.disconnected_timeout != ZERO_DURATION
3718                    && disconnected_time > self.disconnected_timeout)
3719            {
3720                self.update_connection_state(Some(now), ConnectionState::Disconnected);
3721            } else {
3722                self.update_connection_state(Some(now), self.healthy_state());
3723            }
3724            return true;
3725        }
3726
3727        // Consent (RFC 7675 §5.1) is refreshed only by an authenticated success response to
3728        // one of our own checks: not by non-STUN datagrams, not by unauthenticated
3729        // indications, and not by the peer's own requests, which say the peer is there but not
3730        // that it still wants our traffic.
3731        let last_consent = self.pair_consent(pair_index).unwrap_or(self.start_time);
3732        let since_consent = now.saturating_duration_since(last_consent);
3733
3734        // Disconnected: a consent request has gone unanswered for `disconnected_timeout`.
3735        // (Consent requests are at least 4 seconds apart, so "no response for 5 seconds" alone
3736        // would be true between two answered requests.) With keepalives off nothing is ever
3737        // asked, and the time since the last response decides.
3738        let unanswered = if self.keepalive_interval == ZERO_DURATION {
3739            since_consent
3740        } else {
3741            self.consent_unanswered_since
3742                .map(|since| now.saturating_duration_since(since))
3743                .unwrap_or(ZERO_DURATION)
3744        };
3745
3746        if since_consent >= self.consent_expiry() {
3747            if self.may_report_failed(now) {
3748                self.update_connection_state(Some(now), ConnectionState::Failed);
3749            } else {
3750                self.lose_consent_waiting_for_candidates(now, pair_index);
3751            }
3752        } else if self.disconnected_timeout != ZERO_DURATION
3753            && unanswered >= self.disconnected_timeout
3754        {
3755            let was = self.connection_state;
3756            self.update_connection_state(Some(now), ConnectionState::Disconnected);
3757            if was != ConnectionState::Disconnected {
3758                self.fall_back_to_another_nominated_pair(now);
3759            }
3760        } else {
3761            self.update_connection_state(Some(now), self.healthy_state());
3762        }
3763
3764        true
3765    }
3766
3767    /// Consent expired on the selected pair `pair_index` (RFC 7675 Section 5.1) while the agent
3768    /// may not report `Failed` yet ([`Agent::may_report_failed`]): more candidates may still
3769    /// come (local gathering not complete, or no end-of-candidates from the peer), or the PAC
3770    /// timer runs. W3C webrtc-pc 5.6.4, "connected": "If consent checks [RFC7675] fail on the
3771    /// connection in use, and there are no other successful candidate pairs available, then
3772    /// the state transitions to "checking" (if there are candidate pairs remaining to be
3773    /// checked) or "disconnected" (if there are no candidate pairs to check, but the peer is
3774    /// still gathering and/or waiting for additional remote candidates)"; "completed": "If
3775    /// consent checks [RFC7675] subsequently fail on all successful candidate pairs, the state
3776    /// transitions to "failed"", which also waits for the PAC timer (`Disconnected` until
3777    /// then). The pairs the nomination took out of the checklist (RFC 8445 Section 8.1.2,
3778    /// Failed since) are not "remaining to be checked". The pair is no longer used: its consent transactions are discarded and it
3779    /// is removed, so that nothing is sent or answered on it again (RFC 7675 Section 5.1); no
3780    /// other valid pair takes over without a nomination. The agent keeps its candidates and
3781    /// the other pairs, and fails once the indications are in and the PAC timer has expired
3782    /// ([`Agent::fail_or_hold`]).
3783    fn lose_consent_waiting_for_candidates(&mut self, now: Instant, pair_index: usize) {
3784        let (local_index, remote_index) = (
3785            self.candidate_pairs[pair_index].local_index,
3786            self.candidate_pairs[pair_index].remote_index,
3787        );
3788        warn!(
3789            "[{}]: consent expired on the selected pair {}: no longer sending on it",
3790            self.get_name(),
3791            self.candidate_pairs[pair_index]
3792        );
3793        self.pending_binding_requests.retain(|r| {
3794            !(r.consent && r.local_index == local_index && r.remote_index == remote_index)
3795        });
3796        // "After consent is lost, the same ICE credentials MUST NOT be used on the affected
3797        // 5-tuple again" (RFC 7675 Section 5.1): the pair is removed, so that no check is
3798        // sent on it, and marked, so that no request on it is answered. No other pair takes
3799        // over: the pair in use changes only by a nomination (RFC 8445 Sections 8.1.1 and
3800        // 8.1.2) or an ICE restart, so the selection is cleared first and `remove_pair_at`
3801        // (whose fallback is for a pair the application removes) selects nothing.
3802        self.set_selected_pair(Some(now), None);
3803        self.remove_pair_at(now, pair_index, true);
3804        self.candidate_pairs[pair_index].consent_lost = true;
3805        // The pairs the nomination took out of the checklist are Failed (RFC 8445 Section
3806        // 8.1.2, `conclude`): not left to check, and none of them could be nominated in this
3807        // ICE session (Section 8.1.1: "the agent MUST NOT nominate another pair for same
3808        // component of the data stream within the ICE session. Doing so requires an ICE
3809        // restart").
3810        let to_check = !self.triggered_queue.is_empty()
3811            || self.candidate_pairs.iter().any(|p| {
3812                matches!(
3813                    p.state,
3814                    CandidatePairState::Frozen
3815                        | CandidatePairState::Waiting
3816                        | CandidatePairState::InProgress
3817                )
3818            });
3819        if to_check {
3820            self.update_connection_state(Some(now), ConnectionState::Checking);
3821            self.checking_duration = now;
3822        } else {
3823            self.fail_or_hold(now, HeldFailure::ConsentExpired);
3824        }
3825    }
3826
3827    /// Sends a STUN Binding request on the selected pair when the consent interval has run
3828    /// out (RFC 7675). Each one is a new transaction, sent once.
3829    pub(crate) fn check_keepalive(&mut self, now: Instant) {
3830        if self.keepalive_interval == ZERO_DURATION {
3831            return;
3832        }
3833        let Some(pair_index) = self.selected_pair else {
3834            return;
3835        };
3836        match self.next_consent_at {
3837            None => self.next_consent_at = Some(now + self.next_consent_interval()),
3838            Some(at) if now >= at => {
3839                self.next_consent_at = Some(now + self.next_consent_interval());
3840                self.consent_unanswered_since.get_or_insert(now);
3841                self.candidate_pairs[pair_index].on_consent_request_sent();
3842                // A consent check is a plain Binding request (RFC 7675 Section 5.1); RFC 8445
3843                // Section 7.1.2 asks for USE-CANDIDATE "in order to nominate a candidate
3844                // pair", which was done. libwebrtc's controlling agent repeats it on every
3845                // check of its selected pair: `nominate_on_consent_checks`.
3846                let use_candidate = self.is_controlling && self.nominate_on_consent_checks;
3847                self.send_check(now, pair_index, use_candidate, true);
3848            }
3849            Some(_) => {}
3850        }
3851    }
3852
3853    /// When the agent next has something to do for its selected pair: send a consent request,
3854    /// notice that one went unanswered, or let consent expire. `None` without a selected pair
3855    /// and for a lite agent, whose timer is the periodic one.
3856    pub(crate) fn selected_pair_deadline(&self) -> Option<Instant> {
3857        let pair_index = self.selected_pair?;
3858        if self.lite {
3859            return None;
3860        }
3861        let last_consent = self.pair_consent(pair_index).unwrap_or(self.start_time);
3862
3863        let mut deadline = last_consent + self.consent_expiry();
3864        if self.keepalive_interval != ZERO_DURATION {
3865            // Before the first `handle_timeout` after selection there is no schedule yet.
3866            deadline = deadline.min(self.next_consent_at.unwrap_or(self.last_checking_time));
3867        }
3868        if self.disconnected_timeout != ZERO_DURATION
3869            && self.connection_state != ConnectionState::Disconnected
3870        {
3871            let unanswered_since = if self.keepalive_interval == ZERO_DURATION {
3872                Some(last_consent)
3873            } else {
3874                self.consent_unanswered_since
3875            };
3876            if let Some(since) = unanswered_since {
3877                deadline = deadline.min(since + self.disconnected_timeout);
3878            }
3879        }
3880        Some(deadline)
3881    }
3882
3883    /// Consent on the path an ICE restart left in use (RFC 7675 Section 5.1): sends the consent
3884    /// requests of the replaced generation, and retires the path when its consent expires.
3885    pub(crate) fn maintain_previous_generation(&mut self, now: Instant) {
3886        let Some(path) = self.previous_media_path else {
3887            self.previous_generation = None;
3888            return;
3889        };
3890        let expiry = self.consent_expiry();
3891        let interval = self.next_consent_interval();
3892        let (lite, keepalive, controlling, tie_breaker, response_wait) = (
3893            self.lite,
3894            self.keepalive_interval != ZERO_DURATION,
3895            self.is_controlling,
3896            self.tie_breaker,
3897            self.consent_response_wait,
3898        );
3899        let Some(previous) = &mut self.previous_generation else {
3900            return;
3901        };
3902        // The transactions that ended without a response.
3903        previous.pending.retain(|r| r.until > now);
3904
3905        if now.saturating_duration_since(previous.last_consent) >= expiry {
3906            warn!(
3907                "consent expired on the path kept across the ICE restart ({} -> {}): no longer sending on it",
3908                path.local_addr, path.peer_addr
3909            );
3910            self.previous_media_path = None;
3911            self.previous_generation = None;
3912            // The kept path was what made the agent connected through the restart; without it
3913            // and with no pair of the new generation selected, the agent is checking.
3914            if self.selected_pair.is_none() && self.connection_state == ConnectionState::Connected {
3915                self.update_connection_state(Some(now), ConnectionState::Checking);
3916            }
3917            return;
3918        }
3919
3920        if lite || !keepalive || now < previous.next_consent_at {
3921            return;
3922        }
3923        previous.next_consent_at = now + interval;
3924
3925        let username = previous.remote_credentials.ufrag.clone()
3926            + ":"
3927            + previous.local_credentials.ufrag.as_str();
3928        let role: Box<dyn Setter> = if controlling {
3929            Box::new(crate::attributes::control::AttrControlling(tie_breaker))
3930        } else {
3931            Box::new(crate::attributes::control::AttrControlled(tie_breaker))
3932        };
3933        let mut msg = Message::new();
3934        if let Err(err) = msg.build(&[
3935            Box::new(BINDING_REQUEST),
3936            Box::new(TransactionId::new()),
3937            Box::new(Username::new(ATTR_USERNAME, username)),
3938            role,
3939            Box::new(crate::attributes::priority::PriorityAttr(previous.priority)),
3940            Box::new(MessageIntegrity::new_short_term_integrity_with_provider(
3941                previous.remote_credentials.pwd.clone(),
3942                self.crypto_provider.crypto(),
3943            )),
3944            Box::new(FINGERPRINT),
3945        ]) {
3946            error!("{}", err);
3947            return;
3948        }
3949        if previous.pending.len() >= MAX_PREVIOUS_GENERATION_TRANSACTIONS {
3950            previous.pending.remove(0);
3951        }
3952        let wait = consent_response_wait(response_wait, previous.rto.start(now), expiry);
3953        previous.pending.push(PreviousConsentRequest {
3954            transaction_id: msg.transaction_id,
3955            sent: now,
3956            until: now + wait,
3957        });
3958        self.write_outs.push_back(TaggedBytesMut {
3959            now,
3960            transport: TransportContext {
3961                local_addr: path.local_addr,
3962                peer_addr: path.peer_addr,
3963                ecn: None,
3964                transport_protocol: path.transport_protocol,
3965            },
3966            message: BytesMut::from(&msg.raw[..]),
3967        });
3968    }
3969
3970    /// When `maintain_previous_generation` next has something to do.
3971    pub(crate) fn previous_generation_deadline(&self) -> Option<Instant> {
3972        let previous = self.previous_generation.as_ref()?;
3973        self.previous_media_path?;
3974        let expires = previous.last_consent + self.consent_expiry();
3975        if self.lite || self.keepalive_interval == ZERO_DURATION {
3976            Some(expires)
3977        } else {
3978            Some(expires.min(previous.next_consent_at))
3979        }
3980    }
3981
3982    /// STUN on the path an ICE restart left in use that belongs to the replaced generation:
3983    /// the peer's consent requests, which name the old local fragment and are answered with
3984    /// the old password, and the responses to ours. Returns whether `msg` was one of them.
3985    pub(crate) fn handle_previous_generation(&mut self, msg: &TaggedBytesMut) -> bool {
3986        let (Some(path), Some(previous)) = (self.previous_media_path, &self.previous_generation)
3987        else {
3988            return false;
3989        };
3990        if msg.transport.local_addr != path.local_addr
3991            || msg.transport.peer_addr != path.peer_addr
3992            || msg.transport.transport_protocol != path.transport_protocol
3993            || !is_stun_message(&msg.message)
3994        {
3995            return false;
3996        }
3997        let mut m = Message {
3998            raw: msg.message.to_vec(),
3999            ..Message::default()
4000        };
4001        if m.decode().is_err() || m.typ.method != METHOD_BINDING {
4002            return false;
4003        }
4004
4005        if m.typ.class == CLASS_REQUEST {
4006            if assert_inbound_username(&m, &previous.local_credentials.ufrag).is_err()
4007                || assert_inbound_message_integrity(
4008                    &mut m,
4009                    previous.local_credentials.pwd.as_bytes(),
4010                    self.crypto_provider.crypto(),
4011                )
4012                .is_err()
4013            {
4014                return false;
4015            }
4016            let mut out = Message::new();
4017            if let Err(err) = out.build(&[
4018                Box::new(m.clone()),
4019                Box::new(BINDING_SUCCESS),
4020                Box::new(XorMappedAddress {
4021                    ip: path.peer_addr.ip(),
4022                    port: path.peer_addr.port(),
4023                }),
4024                Box::new(MessageIntegrity::new_short_term_integrity_with_provider(
4025                    previous.local_credentials.pwd.clone(),
4026                    self.crypto_provider.crypto(),
4027                )),
4028                Box::new(FINGERPRINT),
4029            ]) {
4030                error!("{}", err);
4031                return true;
4032            }
4033            self.write_outs.push_back(TaggedBytesMut {
4034                now: msg.now,
4035                transport: TransportContext {
4036                    local_addr: path.local_addr,
4037                    peer_addr: path.peer_addr,
4038                    ecn: None,
4039                    transport_protocol: path.transport_protocol,
4040                },
4041                message: BytesMut::from(&out.raw[..]),
4042            });
4043            if self.lite
4044                && let Some(previous) = &mut self.previous_generation
4045            {
4046                previous.last_consent = msg.now;
4047            }
4048            return true;
4049        }
4050
4051        if m.typ.class == CLASS_SUCCESS_RESPONSE || m.typ.class == CLASS_ERROR_RESPONSE {
4052            // Matched by transaction id, to a transaction that is still in progress (RFC
4053            // 8489 Section 6.3).
4054            let Some(position) = previous
4055                .pending
4056                .iter()
4057                .position(|r| r.transaction_id == m.transaction_id && r.until > msg.now)
4058            else {
4059                return false;
4060            };
4061            if assert_inbound_message_integrity(
4062                &mut m,
4063                previous.remote_credentials.pwd.as_bytes(),
4064                self.crypto_provider.crypto(),
4065            )
4066            .is_err()
4067            {
4068                // Claims to answer our transaction but is not signed by the peer: dropped.
4069                return true;
4070            }
4071            let is_success = m.typ.class == CLASS_SUCCESS_RESPONSE;
4072            if is_success && !m.contains(stun::attributes::ATTR_XORMAPPED_ADDRESS) {
4073                // RFC 8489 Section 6.3.3: a Binding success response without
4074                // XOR-MAPPED-ADDRESS fails the client's checks; discarded, no consent.
4075                return true;
4076            }
4077            if let Some(previous) = &mut self.previous_generation {
4078                let request = previous.pending.remove(position);
4079                if is_success {
4080                    previous.last_consent = msg.now;
4081                    // Each consent request is sent once: its response gives the round trip.
4082                    previous
4083                        .rto
4084                        .sample(msg.now.saturating_duration_since(request.sent), msg.now);
4085                }
4086            }
4087            return true;
4088        }
4089
4090        false
4091    }
4092
4093    pub(crate) fn request_connectivity_check(&mut self) {
4094        // Defer the connectivity check to `handle_timeout` instead of running it
4095        // inline. Running `contact()` here is re-entrant: it can advance the state
4096        // to `Failed`, which calls `delete_all_candidates()` and wipes the candidate
4097        // and pair vectors while a caller still holds indices into them (for example
4098        // `handle_inbound` while adding a peer-reflexive candidate). See issue #88.
4099        self.force_candidate_contact = true;
4100    }
4101
4102    /// Remove all candidates.
4103    /// This closes any listening sockets and removes both the local and remote candidate lists.
4104    ///
4105    /// This is used for restarts, failures and on close.
4106    pub(crate) fn delete_all_candidates(&mut self, keep_local_candidates: bool) {
4107        if !keep_local_candidates {
4108            self.local_candidates.clear();
4109        } else {
4110            // What the agent learned from the mapped addresses of the old generation's
4111            // responses goes with that generation.
4112            self.local_candidates
4113                .retain(|c| c.candidate_type() != CandidateType::PeerReflexive);
4114        }
4115        self.remote_candidates.clear();
4116        self.unpaired_remotes.clear();
4117        self.triggered_queue.clear();
4118
4119        // Candidate pairs reference candidates by index, so once the candidates are
4120        // removed every pair - and the `selected_pair`/`nominated_pair` indices into
4121        // the pair list - is dangling and must be dropped to avoid out-of-bounds
4122        // access. `remote_candidates` is always cleared here, so no pair can remain
4123        // valid even when the local candidates are kept. See issue #88.
4124        self.announce_all_pairs_removed();
4125        self.candidate_pairs = Vec::new();
4126        self.selected_pair = None;
4127        self.nominated_pair = None;
4128        self.nomination_proposal = None;
4129        self.declined_nominations.clear();
4130    }
4131
4132    pub(crate) fn find_remote_candidate(&self, addr: SocketAddr) -> Option<usize> {
4133        for (index, c) in self.remote_candidates.iter().enumerate() {
4134            if c.addr() == addr {
4135                return Some(index);
4136            }
4137        }
4138        None
4139    }
4140
4141    /// The local candidate a datagram that arrived on `addr` belongs to.
4142    ///
4143    /// RFC 8445 Section 7.3.1.4: "The local candidate will be either a host candidate [...] or
4144    /// a relayed candidate [...]. The local candidate can never be a server-reflexive
4145    /// candidate." A reflexive candidate is returned only when the application never added
4146    /// the host candidate that is its base.
4147    pub(crate) fn find_local_candidate(
4148        &self,
4149        addr: SocketAddr,
4150        transport_protocol: TransportProtocol,
4151    ) -> Option<usize> {
4152        // An exact address match wins over the TCP active candidates' IP-only match: a
4153        // connection accepted on a passive candidate arrives on that candidate's own address,
4154        // and must not be credited to an active candidate on the same IP that happens to be
4155        // listed first.
4156        let mut active_on_ip = None;
4157        let mut reflexive_on_base = None;
4158        for (index, c) in self.local_candidates.iter().enumerate() {
4159            if c.network_type().to_protocol() != transport_protocol {
4160                continue;
4161            }
4162            let reflexive = matches!(
4163                c.candidate_type(),
4164                CandidateType::ServerReflexive | CandidateType::PeerReflexive
4165            );
4166
4167            // TCP active candidates use port 9 as a placeholder in signalling, but each
4168            // connection they open has its own ephemeral port: they match by IP alone.
4169            if c.tcp_type() == TcpType::Active && transport_protocol == TransportProtocol::TCP {
4170                if active_on_ip.is_none() && !reflexive && c.addr().ip() == addr.ip() {
4171                    active_on_ip = Some(index);
4172                }
4173            } else if reflexive {
4174                if reflexive_on_base.is_none()
4175                    && c.candidate_type() == CandidateType::ServerReflexive
4176                    && c.related_address().is_some_and(|related| {
4177                        related.address == addr.ip().to_string() && related.port == addr.port()
4178                    })
4179                {
4180                    reflexive_on_base = Some(index);
4181                }
4182            } else if c.addr() == addr {
4183                return Some(index);
4184            }
4185        }
4186        active_on_ip.or(reflexive_on_base)
4187    }
4188
4189    /// Answers the Binding request `m`, which arrived on `local_index` from `remote_addr`, with
4190    /// a success response: XOR-MAPPED-ADDRESS is the request's source (RFC 8445 Section
4191    /// 7.3.1.2), MESSAGE-INTEGRITY uses the local password, FINGERPRINT closes it.
4192    pub(crate) fn send_binding_success(
4193        &mut self,
4194        now: Instant,
4195        m: &Message,
4196        local_index: usize,
4197        remote_addr: SocketAddr,
4198    ) {
4199        let (ip, port) = (remote_addr.ip(), remote_addr.port());
4200
4201        let (out, result) = {
4202            let mut out = Message::new();
4203            let result = self.answer_integrity_setter().and_then(|integrity| {
4204                let mut setters: Vec<Box<dyn Setter + '_>> = vec![
4205                    Box::new(m.clone()),
4206                    Box::new(BINDING_SUCCESS),
4207                    Box::new(XorMappedAddress { ip, port }),
4208                ];
4209                // RFC 8489 Section 6.3.1.1: a success response SHOULD carry SOFTWARE.
4210                if let Some(software) = &self.software {
4211                    setters.push(Box::new(Software::new(ATTR_SOFTWARE, software.clone())));
4212                }
4213                setters.push(integrity);
4214                setters.push(Box::new(FINGERPRINT));
4215                out.build(&setters)
4216            });
4217            (out, result)
4218        };
4219
4220        if let Err(err) = result {
4221            warn!(
4222                "[{}]: Failed to handle inbound ICE from: {} to: {} error: {}",
4223                self.get_name(),
4224                self.local_candidates[local_index],
4225                remote_addr,
4226                err
4227            );
4228        } else {
4229            // Track response sent on the candidate pair
4230            if let Some(remote_index) = self.find_remote_candidate(remote_addr)
4231                && let Some(pair_index) = self.find_pair(local_index, remote_index)
4232            {
4233                self.candidate_pairs[pair_index].on_response_sent();
4234            }
4235            self.send_stun_to(now, &out, local_index, remote_addr);
4236        }
4237    }
4238
4239    /// The integrity attribute of a response to the request being answered, with the local
4240    /// password: MESSAGE-INTEGRITY-SHA256 when the request was authenticated by one, else
4241    /// MESSAGE-INTEGRITY (RFC 8489 Section 9.1.3: "A response to a request that contains
4242    /// a MESSAGE-INTEGRITY-SHA256 attribute MUST include the MESSAGE-INTEGRITY-SHA256
4243    /// attribute [...] only one of these attributes can appear in a response").
4244    fn answer_integrity_setter(&self) -> Result<Box<dyn Setter + '_>> {
4245        let local_pwd = self.ufrag_pwd.local_credentials.pwd.clone();
4246        let crypto = self.crypto_provider.crypto();
4247        Ok(match self.answer_integrity {
4248            IntegrityAlgorithm::Sha1 => Box::new(
4249                MessageIntegrity::new_short_term_integrity_with_provider(local_pwd, crypto),
4250            ),
4251            IntegrityAlgorithm::Sha256 => {
4252                Box::new(MessageIntegritySha256::short_term(&local_pwd, crypto)?)
4253            }
4254        })
4255    }
4256
4257    /// Sends a 487 (Role Conflict) error response.
4258    /// RFC 8445 Section 7.3.1.1
4259    pub(crate) fn send_role_conflict_error(
4260        &mut self,
4261        now: Instant,
4262        m: &Message,
4263        local_index: usize,
4264        remote_addr: SocketAddr,
4265    ) {
4266        use stun::error_code::*;
4267
4268        let (out, result) = {
4269            let mut out = Message::new();
4270            let result = self.answer_integrity_setter().and_then(|integrity| {
4271                out.build(&[
4272                    Box::new(m.clone()),
4273                    Box::new(stun::message::BINDING_ERROR),
4274                    Box::new(CODE_ROLE_CONFLICT),
4275                    integrity,
4276                    Box::new(FINGERPRINT),
4277                ])
4278            });
4279            (out, result)
4280        };
4281
4282        if let Err(err) = result {
4283            warn!(
4284                "[{}]: Failed to send role conflict error from: {} to: {} error: {}",
4285                self.get_name(),
4286                self.local_candidates[local_index],
4287                remote_addr,
4288                err
4289            );
4290        } else {
4291            debug!(
4292                "[{}]: Sent 487 Role Conflict error from {} to {}",
4293                self.get_name(),
4294                self.local_candidates[local_index],
4295                remote_addr
4296            );
4297            self.send_stun_to(now, &out, local_index, remote_addr);
4298        }
4299    }
4300
4301    /// Answers a request that carries unknown comprehension-required attributes with a 420
4302    /// (Unknown Attribute) error response listing them (RFC 8489 Section 6.3.1), signed like
4303    /// every response.
4304    fn send_unknown_attributes_error(
4305        &mut self,
4306        now: Instant,
4307        m: &Message,
4308        unknown: &[AttrType],
4309        local_index: usize,
4310        remote_addr: SocketAddr,
4311    ) {
4312        let response = self.answer_integrity_setter().and_then(|integrity| {
4313            stun::validated::unknown_attributes_response(
4314                m,
4315                unknown,
4316                &[integrity, Box::new(FINGERPRINT)],
4317            )
4318        });
4319        match response {
4320            Ok(out) => self.send_stun_to(now, &out, local_index, remote_addr),
4321            Err(err) => warn!(
4322                "[{}]: cannot build the 420 response for {}: {}",
4323                self.get_name(),
4324                remote_addr,
4325                err
4326            ),
4327        }
4328    }
4329
4330    /// Switches the ICE agent role and recomputes all candidate pair priorities.
4331    /// RFC 8445 Section 7.3.1.1
4332    pub(crate) fn switch_role(&mut self, now: Instant) {
4333        self.is_controlling = !self.is_controlling;
4334
4335        // Recompute priorities for all candidate pairs
4336        // The priority calculation depends on ice_role_controlling
4337        for pair in &mut self.candidate_pairs {
4338            pair.ice_role_controlling = self.is_controlling;
4339        }
4340
4341        // Clear nominated pair when switching roles: only the controlling agent nominates.
4342        self.nominated_pair = None;
4343        self.nomination_proposal = None;
4344        self.declined_nominations.clear();
4345        for pair in &mut self.candidate_pairs {
4346            pair.nominate = false;
4347        }
4348
4349        info!(
4350            "[{}]: Role switched, recomputed {} candidate pair priorities",
4351            self.get_name(),
4352            self.candidate_pairs.len()
4353        );
4354
4355        self.event_outs.push_back(TaggedEvent {
4356            now,
4357            event: Event::RoleChange(self.is_controlling),
4358        });
4359    }
4360
4361    /// RFC 8445 Section 7.3.1.1, Detecting and Repairing Role Conflicts, for an authenticated
4362    /// Binding request. Returns `true` when the request must be answered with a 487 (Role
4363    /// Conflict) error response and nothing else; otherwise the agent has kept or switched its
4364    /// role and the request is processed as usual.
4365    fn detect_role_conflict(&mut self, now: Instant, m: &Message) -> Result<bool> {
4366        if self.is_controlling {
4367            if m.contains(ATTR_ICE_CONTROLLING) {
4368                let mut remote = crate::attributes::control::AttrControlling::default();
4369                remote.get_from(m)?;
4370                debug!(
4371                    "[{}]: Role conflict detected (both controlling), local tiebreaker: {}, remote tiebreaker: {}",
4372                    self.get_name(),
4373                    self.tie_breaker,
4374                    remote.0
4375                );
4376                // "If the agent's tiebreaker value is larger than or equal to the contents of
4377                // the ICE-CONTROLLING attribute, the agent generates a Binding error response
4378                // and includes an ERROR-CODE attribute with a value of 487 (Role Conflict) but
4379                // retains its role."
4380                if self.tie_breaker >= remote.0 {
4381                    return Ok(true);
4382                }
4383                // "If the agent's tiebreaker value is less than the contents of the
4384                // ICE-CONTROLLING attribute, the agent switches to the controlled role."
4385                self.switch_role(now);
4386            } else if m.contains(ATTR_USE_CANDIDATE) {
4387                // USE-CANDIDATE only has meaning on the controlled side (RFC 8445 7.3.1.5), and
4388                // role conflicts are decided by ICE-CONTROLLING/ICE-CONTROLLED alone. Like
4389                // libwebrtc, ignore it and answer the check.
4390                debug!(
4391                    "[{}]: USE-CANDIDATE without ICE-CONTROLLING while controlling; ignoring USE-CANDIDATE and answering the check",
4392                    self.get_name(),
4393                );
4394            }
4395        } else if m.contains(ATTR_ICE_CONTROLLED) {
4396            let mut remote = crate::attributes::control::AttrControlled::default();
4397            remote.get_from(m)?;
4398            debug!(
4399                "[{}]: Role conflict detected (both controlled), local tiebreaker: {}, remote tiebreaker: {}",
4400                self.get_name(),
4401                self.tie_breaker,
4402                remote.0
4403            );
4404            // "If the agent's tiebreaker value is larger than or equal to the contents of the
4405            // ICE-CONTROLLED attribute, the agent switches to the controlling role."
4406            if self.tie_breaker >= remote.0 {
4407                self.switch_role(now);
4408            } else {
4409                // "... less than ...: the agent generates a Binding error response and
4410                // includes an ERROR-CODE attribute with a value of 487 (Role Conflict) but
4411                // retains its role."
4412                return Ok(true);
4413            }
4414        }
4415
4416        Ok(false)
4417    }
4418
4419    pub(crate) fn handle_inbound(
4420        &mut self,
4421        now: Instant,
4422        m: &mut Message,
4423        local_index: usize,
4424        remote_addr: SocketAddr,
4425    ) -> Result<()> {
4426        if m.typ.method != METHOD_BINDING
4427            || !(m.typ.class == CLASS_SUCCESS_RESPONSE
4428                || m.typ.class == CLASS_ERROR_RESPONSE
4429                || m.typ.class == CLASS_REQUEST
4430                || m.typ.class == CLASS_INDICATION)
4431        {
4432            trace!(
4433                "[{}]: unhandled STUN from {} to {} class({}) method({})",
4434                self.get_name(),
4435                remote_addr,
4436                self.local_candidates[local_index],
4437                m.typ.class,
4438                m.typ.method
4439            );
4440            return Err(Error::ErrUnhandledStunpacket);
4441        }
4442
4443        if m.typ.class == CLASS_REQUEST {
4444            return self.handle_inbound_request(now, m, local_index, remote_addr);
4445        }
4446
4447        let Some(remote_credentials) = &self.ufrag_pwd.remote_credentials else {
4448            debug!(
4449                "[{}]: ufrag_pwd.remote_credentials.is_none",
4450                self.get_name(),
4451            );
4452            return Err(Error::ErrPasswordEmpty);
4453        };
4454
4455        let remote_candidate_index = self.find_remote_candidate(remote_addr);
4456        if m.typ.class == CLASS_SUCCESS_RESPONSE || m.typ.class == CLASS_ERROR_RESPONSE {
4457            // A response: FINGERPRINT when present, MESSAGE-INTEGRITY with the peer's
4458            // password, no unknown comprehension-required attribute, or it is discarded (RFC
4459            // 8489 Sections 6.3.3 and 9.1.4). Only what the integrity covers is read.
4460            //
4461            // The agent's requests carry MESSAGE-INTEGRITY only, so a response is checked by
4462            // that attribute only (RFC 8489 Section 9.1.4: "the algorithm in the response has
4463            // to match; otherwise, the response MUST be discarded"), and so is every later
4464            // transaction with the peer (Section 9.1.5).
4465            let known = ice_known_attributes();
4466            match stun::validated::Validator::new()
4467                .known_attributes(&known)
4468                .authenticate_with(
4469                    m,
4470                    IntegrityAlgorithm::Sha1,
4471                    remote_credentials.pwd.as_bytes(),
4472                    self.crypto_provider.crypto(),
4473                ) {
4474                Ok(valid) => *m = valid.into_message(),
4475                Err(rejection) => {
4476                    warn!(
4477                        "[{}]: discard message from ({}), {}",
4478                        self.get_name(),
4479                        remote_addr,
4480                        rejection
4481                    );
4482                    if !matches!(rejection, stun::validated::Rejection::UnknownAttributes(_)) {
4483                        self.note_unauthentic_response(m.transaction_id);
4484                    }
4485                    // RFC 8489 Section 6.3.4: an (authenticated) error response with unknown
4486                    // comprehension-required attributes means the transaction failed. (A
4487                    // success response with them is discarded, Section 6.3.3, and the
4488                    // transaction goes on.)
4489                    if m.typ.class == CLASS_ERROR_RESPONSE
4490                        && matches!(rejection, stun::validated::Rejection::UnknownAttributes(_))
4491                    {
4492                        self.handle_failed_transaction(now, m.transaction_id, remote_addr);
4493                    }
4494                    return Err(rejection_error(&rejection));
4495                }
4496            }
4497
4498            // A response is matched to its request by transaction id (RFC 8445 Section
4499            // 7.2.5); where it came from is then checked against where the request went.
4500            if m.typ.class == CLASS_SUCCESS_RESPONSE {
4501                self.handle_success_response(now, m, local_index, remote_addr);
4502            } else {
4503                self.handle_error_response(now, m, remote_addr);
4504            }
4505
4506            if remote_candidate_index.is_none() {
4507                warn!(
4508                    "[{}]: discard response from ({}), no such remote",
4509                    self.get_name(),
4510                    remote_addr
4511                );
4512                return Err(Error::ErrUnhandledStunpacket);
4513            }
4514        }
4515
4516        // RFC 8489 Section 6.3.2: an indication (a lite peer's keepalive) with unknown
4517        // comprehension-required attributes, or a wrong FINGERPRINT, is discarded.
4518        if m.typ.class == CLASS_INDICATION
4519            && let Err(rejection) = stun::validated::Validator::new()
4520                .known_attributes(&ice_known_attributes())
4521                .unauthenticated(m)
4522        {
4523            debug!(
4524                "[{}]: discard indication from ({}), {}",
4525                self.get_name(),
4526                remote_addr,
4527                rejection
4528            );
4529            return Err(rejection_error(&rejection));
4530        }
4531
4532        if let Some(remote) = remote_candidate_index.and_then(|i| self.remote_candidates.get_mut(i))
4533        {
4534            remote.seen(now, false);
4535            // Responses reaching here passed MESSAGE-INTEGRITY; indications did not and carry
4536            // none.
4537            if m.typ.class != CLASS_INDICATION {
4538                remote.last_authenticated = Some(now);
4539            }
4540        }
4541
4542        Ok(())
4543    }
4544
4545    /// A Binding request (RFC 8445 Section 7.3): authenticated with the short-term credential,
4546    /// then answered and processed, or, before the peer's credentials are known, answered and
4547    /// remembered.
4548    fn handle_inbound_request(
4549        &mut self,
4550        now: Instant,
4551        m: &mut Message,
4552        local_index: usize,
4553        remote_addr: SocketAddr,
4554    ) -> Result<()> {
4555        // RFC 8489 Sections 6.3 and 9.1.3, through `rtci-stun`'s validator: FINGERPRINT is
4556        // verified when present, MESSAGE-INTEGRITY with the local password, and from here on
4557        // only what the integrity covers is read: USERNAME, the role attributes, PRIORITY,
4558        // USE-CANDIDATE. An attribute appended after it does not exist for the agent.
4559        // The validator verifies MESSAGE-INTEGRITY-SHA256 when the request has it, and the
4560        // answers carry the attribute that was verified (Section 9.1.3).
4561        self.answer_integrity = if m.contains(ATTR_MESSAGE_INTEGRITY_SHA256) {
4562            IntegrityAlgorithm::Sha256
4563        } else {
4564            IntegrityAlgorithm::Sha1
4565        };
4566        let known = ice_known_attributes();
4567        let validated = stun::validated::Validator::new()
4568            .known_attributes(&known)
4569            .authenticate(
4570                m,
4571                self.ufrag_pwd.local_credentials.pwd.as_bytes(),
4572                self.crypto_provider.crypto(),
4573            );
4574        match validated {
4575            Ok(valid) => *m = valid.into_message(),
4576            Err(stun::validated::Rejection::UnknownAttributes(unknown)) => {
4577                // RFC 8489 Section 6.3.1: an authenticated request with a comprehension-
4578                // required attribute the agent does not know is answered 420 with the list.
4579                self.send_unknown_attributes_error(now, m, &unknown, local_index, remote_addr);
4580                return Err(Error::ErrUnhandledStunpacket);
4581            }
4582            Err(rejection) => {
4583                warn!(
4584                    "[{}]: discard message from ({}), {}",
4585                    self.get_name(),
4586                    remote_addr,
4587                    rejection
4588                );
4589                // RFC 8489 Section 9.1.3, in its order: no MESSAGE-INTEGRITY or no USERNAME
4590                // is 400; a username that is not valid here is 401; a MESSAGE-INTEGRITY that
4591                // does not match is 401. (A FINGERPRINT that does not match is not answered:
4592                // the datagram is not STUN for this agent, Section 7.3.)
4593                use stun::error_code::{CODE_BAD_REQUEST, CODE_UNAUTHENTICATED};
4594                use stun::validated::Rejection;
4595                let code = match rejection {
4596                    Rejection::IntegrityMissing => Some(CODE_BAD_REQUEST),
4597                    Rejection::IntegrityMismatch if !m.contains(ATTR_USERNAME) => {
4598                        Some(CODE_BAD_REQUEST)
4599                    }
4600                    Rejection::IntegrityMismatch => Some(CODE_UNAUTHENTICATED),
4601                    _ => None,
4602                };
4603                if let Some(code) = code {
4604                    self.reject_unauthenticated_request(now, m, code, local_index, remote_addr);
4605                }
4606                return Err(rejection_error(&rejection));
4607            }
4608        }
4609        if let Err(err) = assert_inbound_username(m, &self.ufrag_pwd.local_credentials.ufrag) {
4610            warn!(
4611                "[{}]: discard message from ({}), {}",
4612                self.get_name(),
4613                remote_addr,
4614                err
4615            );
4616            // The integrity matched, so the sender holds the password: the username is
4617            // absent (400) or not this agent's (401).
4618            let code = if m.contains(ATTR_USERNAME) {
4619                stun::error_code::CODE_UNAUTHENTICATED
4620            } else {
4621                stun::error_code::CODE_BAD_REQUEST
4622            };
4623            self.reject_unauthenticated_request(now, m, code, local_index, remote_addr);
4624            return Err(err);
4625        }
4626
4627        if self.ufrag_pwd.remote_credentials.is_none() {
4628            // RFC 8445 Section 7.3: "it is possible (and in fact very likely) that the
4629            // initiating agent will receive a Binding request prior to receiving the candidates
4630            // from its peer. If this happens, the agent MUST immediately generate a response
4631            // [...] Once the answer is received, it MUST proceed with the remaining steps."
4632            // A source the destination policy refuses is not answered, now or later. Nor is
4633            // one the embedder's address policy would refuse as a peer-reflexive candidate
4634            // (what the source of a request from no known candidate becomes, Section 7.3.1.3,
4635            // once the credentials are here): answered now, it would have its answer, and its
4636            // reflexive address in it, before the policy was ever asked about it.
4637            if !self.remote_policy.allows_candidate(remote_addr)
4638                || (self.find_remote_candidate(remote_addr).is_none()
4639                    && !self
4640                        .remote_policy
4641                        .address
4642                        .allows(remote_addr, AddressPurpose::PeerReflexiveSource))
4643            {
4644                return Err(Error::ErrUnhandledStunpacket);
4645            }
4646            self.send_binding_success(now, m, local_index, remote_addr);
4647            self.remember_early_request(m, local_index, remote_addr);
4648            return Ok(());
4649        }
4650
4651        self.process_binding_request(now, m, local_index, remote_addr, true)
4652    }
4653
4654    /// Answers a Binding request that failed the short-term credential check with `code` (400
4655    /// or 401, RFC 8489 Section 9.1.3), unless the agent is set to drop such requests.
4656    ///
4657    /// The source of such a request is unverified, so the answer must be of no use to someone
4658    /// who forged it: the response carries the error code and FINGERPRINT only (no reason
4659    /// phrase, and no MESSAGE-INTEGRITY: there is no key the two share), it is sent only when
4660    /// it is no longer than the request, and at most [`MAX_UNAUTHENTICATED_RESPONSE_BURST`]
4661    /// of them go out in a burst, one more per [`UNAUTHENTICATED_RESPONSE_INTERVAL`]. Past
4662    /// that the request is dropped.
4663    fn reject_unauthenticated_request(
4664        &mut self,
4665        now: Instant,
4666        m: &Message,
4667        code: stun::error_code::ErrorCode,
4668        local_index: usize,
4669        remote_addr: SocketAddr,
4670    ) {
4671        if self.unauthenticated_requests == UnauthenticatedRequests::Drop
4672            || !self.remote_policy.allows_candidate(remote_addr)
4673            || !self
4674                .remote_policy
4675                .allows_pair(self.local_candidates[local_index].base_addr(), remote_addr)
4676        {
4677            return;
4678        }
4679        // The token bucket: one token per interval since the last refill, up to the burst.
4680        let elapsed = now.saturating_duration_since(self.unauthenticated_response_refill);
4681        let earned = elapsed.as_nanos() / UNAUTHENTICATED_RESPONSE_INTERVAL.as_nanos();
4682        if earned > 0 {
4683            let earned = u32::try_from(earned).unwrap_or(u32::MAX);
4684            self.unauthenticated_response_tokens = self
4685                .unauthenticated_response_tokens
4686                .saturating_add(earned)
4687                .min(MAX_UNAUTHENTICATED_RESPONSE_BURST);
4688            self.unauthenticated_response_refill = if self.unauthenticated_response_tokens
4689                == MAX_UNAUTHENTICATED_RESPONSE_BURST
4690            {
4691                now
4692            } else {
4693                self.unauthenticated_response_refill + UNAUTHENTICATED_RESPONSE_INTERVAL * earned
4694            };
4695        }
4696        if self.unauthenticated_response_tokens == 0 {
4697            return;
4698        }
4699
4700        let mut out = Message::new();
4701        let built = out.build(&[
4702            Box::new(MessageType::new(METHOD_BINDING, CLASS_ERROR_RESPONSE)),
4703            Box::new(m.transaction_id),
4704            Box::new(stun::error_code::ErrorCodeAttribute {
4705                code,
4706                reason: vec![],
4707            }),
4708            Box::new(FINGERPRINT),
4709        ]);
4710        if let Err(err) = built {
4711            warn!(
4712                "[{}]: cannot build the {} response for {}: {}",
4713                self.get_name(),
4714                code.0,
4715                remote_addr,
4716                err
4717            );
4718            return;
4719        }
4720        if out.raw.len() > m.raw.len() {
4721            // Never more bytes out than came in.
4722            return;
4723        }
4724        self.unauthenticated_response_tokens -= 1;
4725        self.send_stun_to(now, &out, local_index, remote_addr);
4726    }
4727
4728    fn remember_early_request(&mut self, m: &Message, local_index: usize, remote_addr: SocketAddr) {
4729        use crate::attributes::nomination::nomination_of;
4730
4731        let local = &self.local_candidates[local_index];
4732        let request = EarlyRequest {
4733            message: m.clone(),
4734            // What the datagram arrived on is the candidate's base.
4735            local_addr: local.base_addr(),
4736            transport_protocol: local.network_type().to_protocol(),
4737            remote_addr,
4738        };
4739        if let Some(known) = self.early_requests.iter_mut().find(|r| {
4740            r.local_addr == request.local_addr
4741                && r.transport_protocol == request.transport_protocol
4742                && r.remote_addr == remote_addr
4743        }) {
4744            // One entry per path; a nomination is not forgotten for a later plain check.
4745            if nomination_of(&request.message) >= nomination_of(&known.message) {
4746                *known = request;
4747            }
4748        } else if self.early_requests.len() < MAX_EARLY_REQUESTS {
4749            self.early_requests.push(request);
4750        }
4751    }
4752
4753    /// Runs RFC 8445 Sections 7.3.1.3 to 7.3.1.5 for the requests that were answered before the
4754    /// peer's credentials arrived.
4755    pub(crate) fn process_early_requests(&mut self, now: Instant) {
4756        if self.ufrag_pwd.remote_credentials.is_none() {
4757            return;
4758        }
4759        for request in std::mem::take(&mut self.early_requests) {
4760            let Some(local_index) =
4761                self.find_local_candidate(request.local_addr, request.transport_protocol)
4762            else {
4763                continue;
4764            };
4765            let _ = self.process_binding_request(
4766                now,
4767                &request.message,
4768                local_index,
4769                request.remote_addr,
4770                false,
4771            );
4772        }
4773    }
4774
4775    /// Processes an authenticated Binding request: role conflict (Section 7.3.1.1), the
4776    /// response (7.3.1.2), a peer-reflexive remote candidate (7.3.1.3), the triggered check
4777    /// (7.3.1.4) and the nominated flag (7.3.1.5). `respond` is false for a request that was
4778    /// answered when it arrived, before the peer's credentials were known.
4779    fn process_binding_request(
4780        &mut self,
4781        now: Instant,
4782        m: &Message,
4783        local_index: usize,
4784        remote_addr: SocketAddr,
4785        respond: bool,
4786    ) -> Result<()> {
4787        // Role conflicts are acted on only for a request that passed the username and
4788        // MESSAGE-INTEGRITY checks: an unauthenticated datagram must not be able to flip our
4789        // ICE role, re-prioritise every pair and clear the nomination. A request that gets the
4790        // 487 gets nothing else: no success response, no candidate, no triggered check.
4791        if respond && self.detect_role_conflict(now, m)? {
4792            self.send_role_conflict_error(now, m, local_index, remote_addr);
4793            // A peer that claimed the controlling role holds no nomination of ours: it was
4794            // not the controlled agent. If this agent, which keeps the controlling role, has
4795            // concluded, its nomination is lost on the peer (a peer that lost its state
4796            // without an ICE restart), and nothing else would bring it back: the pair is
4797            // nominated again, the same one (RFC 8445 Section 8.1.1: "the agent MUST NOT
4798            // nominate another pair").
4799            if self.is_controlling {
4800                self.repeat_nomination();
4801            }
4802            return Ok(());
4803        }
4804
4805        let mut remote_candidate_index = self.find_remote_candidate(remote_addr);
4806        if remote_candidate_index.is_none() {
4807            remote_candidate_index =
4808                self.add_peer_reflexive_remote_candidate(m, local_index, remote_addr)?;
4809            if remote_candidate_index.is_some() {
4810                debug!(
4811                    "[{}]: adding a new peer-reflexive candidate: {} ",
4812                    self.get_name(),
4813                    remote_addr
4814                );
4815            }
4816        }
4817
4818        trace!(
4819            "[{}]: inbound STUN (Request) from {} to {}",
4820            self.get_name(),
4821            remote_addr,
4822            self.local_candidates[local_index]
4823        );
4824
4825        let Some(remote_index) = remote_candidate_index else {
4826            return Ok(());
4827        };
4828
4829        // RFC 8445 Section 7.3.1.4: the pair is (the local candidate the request arrived on,
4830        // its source); a pair that is not on the checklist is added to it.
4831        if self.find_pair(local_index, remote_index).is_none() {
4832            self.add_pair(local_index, remote_index);
4833        }
4834        if self.find_pair(local_index, remote_index).is_none() {
4835            // The checklist is full of better pairs, but this one the peer is checking: it
4836            // takes the place of the worst pair that has not been checked.
4837            self.add_triggered_pair(local_index, remote_index);
4838        }
4839        if let Some(pair_index) = self.find_pair(local_index, remote_index) {
4840            self.candidate_pairs[pair_index].on_request_received();
4841            // An authenticated request is answered whatever the pair's state (unless the
4842            // destination policy refused the pair, or consent was lost on it: RFC 7675
4843            // Section 5.1, the credentials are not used on that 5-tuple again).
4844            if respond && !self.candidate_pairs[pair_index].consent_lost {
4845                self.send_binding_success(now, m, local_index, remote_addr);
4846            }
4847            self.handle_binding_request(now, m, local_index, remote_index);
4848        }
4849
4850        if let Some(remote) = self.remote_candidates.get_mut(remote_index) {
4851            remote.seen(now, false);
4852            remote.last_authenticated = Some(now);
4853        }
4854
4855        Ok(())
4856    }
4857
4858    /// RFC 8445 Section 7.3.1.3: the source of an authenticated request that is no known remote
4859    /// candidate becomes a peer-reflexive one. Its priority is the request's PRIORITY
4860    /// attribute, its component that of the local candidate the request arrived on, and it is
4861    /// paired with that local candidate only (the caller does that).
4862    fn add_peer_reflexive_remote_candidate(
4863        &mut self,
4864        m: &Message,
4865        local_index: usize,
4866        remote_addr: SocketAddr,
4867    ) -> Result<Option<usize>> {
4868        use crate::attributes::priority::PriorityAttr;
4869
4870        if self.remote_candidates.len() >= MAX_REMOTE_CANDIDATES {
4871            warn!(
4872                "[{}]: ignoring peer-reflexive candidate {}: already holding {} (the cap)",
4873                self.get_name(),
4874                remote_addr,
4875                MAX_REMOTE_CANDIDATES
4876            );
4877            return Ok(None);
4878        }
4879        if !self
4880            .remote_policy
4881            .allows_remote(remote_addr, AddressPurpose::PeerReflexiveSource)
4882        {
4883            warn!(
4884                "[{}]: ignoring peer-reflexive candidate {}: not an allowed destination",
4885                self.get_name(),
4886                remote_addr
4887            );
4888            return Ok(None);
4889        }
4890
4891        // Use the local candidate's network type for the peer-reflexive candidate
4892        let network_type = self.local_candidates[local_index].network_type();
4893        if !self.network_types.is_empty() && !self.network_types.contains(&network_type) {
4894            return Ok(None);
4895        }
4896
4897        // A request without PRIORITY (or with one outside 1..2^31-1) is not refused: the
4898        // candidate then gets the priority this agent would compute for it.
4899        let mut priority = PriorityAttr::default();
4900        let priority = match priority.get_from(m) {
4901            Ok(()) if (1..=MAX_CANDIDATE_PRIORITY).contains(&priority.0) => priority.0,
4902            _ => 0,
4903        };
4904
4905        let prflx_candidate_config = CandidatePeerReflexiveConfig {
4906            base_config: CandidateConfig {
4907                network: network_type.to_string(),
4908                address: remote_addr.ip().to_string(),
4909                port: remote_addr.port(),
4910                component: self.local_candidates[local_index].component(),
4911                priority,
4912                ..CandidateConfig::default()
4913            },
4914            rel_addr: "".to_owned(),
4915            rel_port: 0,
4916        };
4917
4918        let mut prflx_candidate = match prflx_candidate_config.new_candidate_peer_reflexive() {
4919            Ok(c) => c,
4920            Err(err) => {
4921                error!(
4922                    "[{}]: Failed to create new remote prflx candidate ({})",
4923                    self.get_name(),
4924                    err
4925                );
4926                return Err(err);
4927            }
4928        };
4929        // RFC 6544 §7: a peer-reflexive candidate learned over TCP takes the TCP type that
4930        // pairs with the local candidate the check arrived on (a check on our passive
4931        // candidate comes from an active one), or it could never form a pair and the
4932        // controlling agent would never nominate the connection.
4933        prflx_candidate.tcp_type = self.local_candidates[local_index].tcp_type().complement();
4934
4935        self.remote_candidates.push(prflx_candidate);
4936        Ok(Some(self.remote_candidates.len() - 1))
4937    }
4938
4939    // Processes non STUN traffic from a remote candidate, and returns true if it is an actual
4940    // remote candidate.
4941    pub(crate) fn validate_non_stun_traffic(
4942        &mut self,
4943        now: Instant,
4944        remote_addr: SocketAddr,
4945    ) -> bool {
4946        self.find_remote_candidate(remote_addr)
4947            .is_some_and(|remote_index| {
4948                self.remote_candidates[remote_index].seen(now, false);
4949                true
4950            })
4951    }
4952
4953    pub(crate) fn send_stun(
4954        &mut self,
4955        now: Instant,
4956        msg: &Message,
4957        local_index: usize,
4958        remote_index: usize,
4959    ) {
4960        let peer_addr = self.remote_candidates[remote_index].addr();
4961        self.send_stun_to(now, msg, local_index, peer_addr);
4962    }
4963
4964    /// Queues `msg` from the local candidate's base to `peer_addr`.
4965    pub(crate) fn send_stun_to(
4966        &mut self,
4967        now: Instant,
4968        msg: &Message,
4969        local_index: usize,
4970        peer_addr: SocketAddr,
4971    ) {
4972        self.send_raw_stun(now, BytesMut::from(&msg.raw[..]), local_index, peer_addr);
4973    }
4974
4975    /// Queues an encoded STUN message from the local candidate's base to `peer_addr`.
4976    pub(crate) fn send_raw_stun(
4977        &mut self,
4978        now: Instant,
4979        message: BytesMut,
4980        local_index: usize,
4981        peer_addr: SocketAddr,
4982    ) {
4983        // RFC 8445 §6.1.2: checks for a (server/peer-)reflexive candidate must
4984        // be sent from its base, the bound local socket the candidate was
4985        // derived from; the mapped address is not a local socket.
4986        let local_addr = self.local_candidates[local_index].base_addr();
4987        let transport_protocol = if self.local_candidates[local_index].network_type().is_tcp() {
4988            TransportProtocol::TCP
4989        } else {
4990            TransportProtocol::UDP
4991        };
4992        // RFC 8489 Section 6.1: "the STUN usage MUST follow the MTU constraint" outside MTU
4993        // probing. Nothing over UDP leaves larger than the path MTU allows.
4994        if transport_protocol == TransportProtocol::UDP
4995            && message.len() > self.max_udp_stun_size(peer_addr)
4996        {
4997            warn!(
4998                "[{}]: not sending a STUN message of {} bytes to {}: larger than the path MTU allows",
4999                self.get_name(),
5000                message.len(),
5001                peer_addr
5002            );
5003            return;
5004        }
5005
5006        self.write_outs.push_back(TaggedBytesMut {
5007            now,
5008            transport: TransportContext {
5009                local_addr,
5010                peer_addr,
5011                ecn: None,
5012                transport_protocol,
5013            },
5014            message,
5015        });
5016
5017        self.local_candidates[local_index].seen(now, true);
5018    }
5019
5020    /// The largest STUN message sent over UDP to `peer`: the path MTU
5021    /// ([`AgentConfig::path_mtu`]), else the RFC 8489 Section 6.1 assumption (576 bytes for
5022    /// IPv4, 1280 for IPv6), less the IP and UDP headers.
5023    pub(crate) fn max_udp_stun_size(&self, peer: SocketAddr) -> usize {
5024        let (assumed, overhead) = if peer.is_ipv4() {
5025            (576, 20 + 8)
5026        } else {
5027            (1280, 40 + 8)
5028        };
5029        self.path_mtu.unwrap_or(assumed).saturating_sub(overhead)
5030    }
5031
5032    fn handle_inbound_candidate_msg(
5033        &mut self,
5034        local_index: usize,
5035        msg: TaggedBytesMut,
5036    ) -> Result<()> {
5037        if is_stun_message(&msg.message) {
5038            let mut m = Message {
5039                raw: msg.message.to_vec(),
5040                ..Message::default()
5041            };
5042
5043            if let Err(err) = m.decode() {
5044                warn!(
5045                    "[{}]: Failed to handle decode ICE from {} to {}: {}",
5046                    self.get_name(),
5047                    msg.transport.local_addr,
5048                    msg.transport.peer_addr,
5049                    err
5050                );
5051                Err(err)
5052            } else {
5053                self.handle_inbound(msg.now, &mut m, local_index, msg.transport.peer_addr)
5054            }
5055        } else {
5056            if !self.validate_non_stun_traffic(msg.now, msg.transport.peer_addr) {
5057                warn!(
5058                    "[{}]: Discarded message, not a valid remote candidate from {}",
5059                    self.get_name(),
5060                    msg.transport.peer_addr,
5061                );
5062            } else {
5063                warn!(
5064                    "[{}]: non-STUN traffic message from a valid remote candidate from {}",
5065                    self.get_name(),
5066                    msg.transport.peer_addr
5067                );
5068            }
5069            Err(Error::ErrNonStunmessage)
5070        }
5071    }
5072
5073    pub(crate) fn get_name(&self) -> &str {
5074        if self.is_controlling {
5075            "controlling"
5076        } else {
5077            "controlled"
5078        }
5079    }
5080
5081    pub(crate) fn get_selected_pair(&self) -> Option<usize> {
5082        self.selected_pair
5083    }
5084
5085    pub(crate) fn get_best_available_pair(&self) -> Option<usize> {
5086        let mut best_pair_index: Option<usize> = None;
5087
5088        for (index, p) in self.candidate_pairs.iter().enumerate() {
5089            if p.state == CandidatePairState::Failed {
5090                continue;
5091            }
5092
5093            if let Some(pair_index) = &mut best_pair_index {
5094                let b = &self.candidate_pairs[*pair_index];
5095                if b.priority() < p.priority() {
5096                    *pair_index = index;
5097                }
5098            } else {
5099                best_pair_index = Some(index);
5100            }
5101        }
5102
5103        best_pair_index
5104    }
5105
5106    pub(crate) fn get_best_valid_candidate_pair(&self) -> Option<usize> {
5107        let mut best_pair_index: Option<usize> = None;
5108
5109        for (index, p) in self.candidate_pairs.iter().enumerate() {
5110            if p.state != CandidatePairState::Succeeded || !p.valid {
5111                continue;
5112            }
5113
5114            if let Some(pair_index) = &mut best_pair_index {
5115                let b = &self.candidate_pairs[*pair_index];
5116                if b.priority() < p.priority() {
5117                    *pair_index = index;
5118                }
5119            } else {
5120                best_pair_index = Some(index);
5121            }
5122        }
5123
5124        best_pair_index
5125    }
5126}
5127
5128/// The precedence of RFC 6724 Section 2.1's default policy table for `ip` (an IPv4 address
5129/// as its IPv4-mapped form, `::ffff:0:0/96`).
5130pub(crate) fn rfc6724_precedence(ip: IpAddr) -> u8 {
5131    let v6 = match ip {
5132        IpAddr::V4(_) => return 35,
5133        IpAddr::V6(v6) => v6,
5134    };
5135    if let Some(v4) = v6.to_ipv4_mapped() {
5136        return rfc6724_precedence(IpAddr::V4(v4));
5137    }
5138    let s = v6.segments();
5139    if v6.is_loopback() {
5140        50
5141    } else if s[0] == 0x2002 {
5142        30
5143    } else if s[0] == 0x2001 && s[1] == 0 {
5144        5
5145    } else if s[0] & 0xfe00 == 0xfc00 {
5146        3
5147    } else if s[..6] == [0; 6] || s[0] & 0xffc0 == 0xfec0 || s[0] == 0x3ffe {
5148        1
5149    } else {
5150        40
5151    }
5152}