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