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