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                warn!(
1730                    "remote mDNS candidate added, but mDNS is disabled: ({})",
1731                    c.address()
1732                );
1733                // Ignored (draft Section 3.2.1, step 5), but the peer's checks from behind
1734                // the name still teach a peer-reflexive candidate (Section 5.3). (Not with
1735                // the relay-only policy: see below.)
1736                if self.candidate_types != [CandidateType::Relay] {
1737                    self.note_unpaired_remote(&c);
1738                }
1739                return Ok(false);
1740            }
1741
1742            // draft-ietf-mmusic-mdns-ice-candidates Section 3.2.1, step 2: "If the ICE
1743            // candidate policy is 'relay', as defined in [RFC8829], ignore the candidate":
1744            // it could only be paired with a relayed candidate, which Section 3.3.2 forbids,
1745            // and resolving it would tell the local network who is being called.
1746            if self.candidate_types == [CandidateType::Relay] {
1747                debug!(
1748                    "[{}]: ignoring mDNS candidate {}: relay-only policy",
1749                    self.get_name(),
1750                    c.address()
1751                );
1752                return Ok(false);
1753            }
1754
1755            if c.candidate_type() != CandidateType::Host {
1756                return Err(Error::ErrAddressParseFailed);
1757            }
1758
1759            if !is_ice_mdns_name(c.address()) {
1760                warn!(
1761                    "[{}]: ignoring mDNS candidate {}: not a <uuid>.local name",
1762                    self.get_name(),
1763                    c.address()
1764                );
1765                // Not resolved (Section 3.2.2), but its checks may come (Section 5.3).
1766                self.note_unpaired_remote(&c);
1767                return Ok(false);
1768            }
1769
1770            if self.mdns_queries.len() >= MAX_PENDING_MDNS_QUERIES {
1771                warn!(
1772                    "[{}]: ignoring mDNS candidate {}: {} queries already pending (the cap)",
1773                    self.get_name(),
1774                    c.address(),
1775                    MAX_PENDING_MDNS_QUERIES
1776                );
1777                self.note_unpaired_remote(&c);
1778                return Ok(false);
1779            }
1780
1781            if let Some(mdns_conn) = &mut self.mdns {
1782                let query_id = mdns_conn.schedule_query(c.address());
1783                self.mdns_queries.insert(query_id, c);
1784            } else {
1785                // No mDNS connection: the name is never resolved.
1786                self.note_unpaired_remote(&c);
1787            }
1788
1789            return Ok(false);
1790        }
1791
1792        Ok(self.trigger_request_connectivity_check(vec![c]) > 0)
1793    }
1794
1795    /// Takes remote candidates into the list and pairs them; returns how many are now held.
1796    fn trigger_request_connectivity_check(&mut self, remote_candidates: Vec<Candidate>) -> usize {
1797        let mut held = 0;
1798        for c in remote_candidates {
1799            // Every path that adds a remote candidate comes through here, mDNS-resolved ones
1800            // included (their query was capped, not the candidate list).
1801            if self.remote_candidates.len() >= MAX_REMOTE_CANDIDATES {
1802                warn!(
1803                    "[{}]: ignoring remote candidate {}: already holding {} (the cap)",
1804                    self.get_name(),
1805                    c.address(),
1806                    MAX_REMOTE_CANDIDATES
1807                );
1808                continue;
1809            }
1810            // RFC 8445 §5.1.1.1: a candidate is a unicast transport address. One that can't be
1811            // a destination, or that the application's filter or address policy refuses, is
1812            // never held or paired.
1813            if !self
1814                .remote_policy
1815                .allows_remote(c.addr(), AddressPurpose::RemoteCandidate)
1816            {
1817                warn!(
1818                    "[{}]: ignoring remote candidate {}: its address {} is not an allowed destination",
1819                    self.get_name(),
1820                    c.address(),
1821                    c.addr()
1822                );
1823                continue;
1824            }
1825            // One remote candidate per transport address: a second one could never be told
1826            // apart from the first by the source of what it sends.
1827            if let Some(known) = self
1828                .remote_candidates
1829                .iter()
1830                .position(|cand| cand.addr() == c.addr() && cand.network_type() == c.network_type())
1831            {
1832                if self.remote_candidates[known].candidate_type() == CandidateType::PeerReflexive
1833                    && c.candidate_type() != CandidateType::PeerReflexive
1834                {
1835                    self.replace_peer_reflexive_remote_candidate(known, c);
1836                    held += 1;
1837                }
1838                continue;
1839            }
1840            if !self.remote_candidates.iter().any(|cand| cand.equal(&c)) {
1841                held += 1;
1842                self.remote_candidates.push(c);
1843                let remote_index = self.remote_candidates.len() - 1;
1844
1845                for local_index in 0..self.local_candidates.len() {
1846                    if !self.local_candidates[local_index].held_from_pairing()
1847                        && self.local_candidates[local_index]
1848                            .can_pair_with(&self.remote_candidates[remote_index])
1849                    {
1850                        self.add_pair(local_index, remote_index);
1851                    }
1852                }
1853
1854                self.request_connectivity_check();
1855            }
1856        }
1857        held
1858    }
1859
1860    /// RFC 8838 Section 11: a signalled candidate with the address of a peer-reflexive one the
1861    /// agent learned from a check takes its place. The pairs that candidate is in are kept,
1862    /// with the signalled priority (and so their place in the checklist), and the candidate
1863    /// is now paired with the other local candidates too.
1864    fn replace_peer_reflexive_remote_candidate(&mut self, remote_index: usize, mut c: Candidate) {
1865        let learned = &self.remote_candidates[remote_index];
1866        c.last_sent = learned.last_sent;
1867        c.last_received = learned.last_received;
1868        c.last_authenticated = learned.last_authenticated;
1869        c.last_consent = learned.last_consent;
1870        // The candidate keeps the identity its pairs are known by: the statistics of a pair
1871        // (and its packet counters) are keyed by the two candidates' ids, and a pair that is
1872        // carrying data must not become another pair because its remote candidate was
1873        // signalled after all.
1874        c.id = learned.id.clone();
1875        if c.tcp_type() == TcpType::Unspecified {
1876            c.tcp_type = learned.tcp_type();
1877        }
1878        let priority = c.priority();
1879        self.remote_candidates[remote_index] = c;
1880        for index in 0..self.candidate_pairs.len() {
1881            if self.candidate_pairs[index].remote_index == remote_index {
1882                let local_index = self.candidate_pairs[index].local_index;
1883                let foundation = self.pair_foundation(local_index, remote_index);
1884                let p = &mut self.candidate_pairs[index];
1885                p.remote_priority = priority;
1886                p.foundation = foundation;
1887            }
1888        }
1889        for local_index in 0..self.local_candidates.len() {
1890            if !self.local_candidates[local_index].held_from_pairing()
1891                && self.local_candidates[local_index]
1892                    .can_pair_with(&self.remote_candidates[remote_index])
1893            {
1894                self.add_pair(local_index, remote_index);
1895            }
1896        }
1897        self.request_connectivity_check();
1898    }
1899
1900    /// Takes what the mDNS connection has to report: the remote candidates whose names
1901    /// resolved (returned), the queries that ended without an address, and the local names
1902    /// lost to another host, which are replaced.
1903    pub(crate) fn drain_mdns_events(&mut self, now: Instant) -> Vec<Candidate> {
1904        use mdns::MdnsEvent;
1905
1906        let mut resolved = vec![];
1907        let mut lost = vec![];
1908        if let Some(mdns_conn) = &mut self.mdns {
1909            while let Some(event) = mdns_conn.poll_event() {
1910                match event {
1911                    MdnsEvent::QueryAnswered(id, addr) => {
1912                        if let Some(mut c) = self.mdns_queries.remove(&id)
1913                            && c.set_ip(&addr).is_ok()
1914                        {
1915                            debug!(
1916                                "mDNS query id {} answered Candidate {} with resolved_addr {} is added into remote candidates",
1917                                id,
1918                                c,
1919                                c.addr()
1920                            );
1921                            resolved.push(c);
1922                        }
1923                    }
1924                    MdnsEvent::QueryTimeout(id) => {
1925                        if let Some(c) = self.mdns_queries.remove(&id) {
1926                            error!("mDNS Query {} timed out for {}", id, c.address());
1927                            // Unresolved, and ignored (draft Section 3.2.1, step 5); the
1928                            // peer's checks may still come (Section 5.3).
1929                            UnpairedRemote::note(&mut self.unpaired_remotes, &c);
1930                        }
1931                    }
1932                    MdnsEvent::LocalNameConflict(name) => lost.push(name),
1933                    _ => {}
1934                }
1935            }
1936        }
1937        for name in lost {
1938            self.replace_local_mdns_name(now, &name);
1939        }
1940        resolved
1941    }
1942
1943    /// RFC 6762 Section 9: a host that loses a name to another "MUST [...] choose a new
1944    /// name". The local candidates published under `lost` get a new `<uuid>.local` name,
1945    /// registered with the responder, and are reported with
1946    /// [`Event::LocalCandidateRenamed`] so that they are conveyed to the peer again: the
1947    /// name it holds resolves to the other host, or to nothing.
1948    fn replace_local_mdns_name(&mut self, now: Instant, lost: &str) {
1949        let ip = if self.mdns_local_name == lost {
1950            self.mdns_local_ip
1951        } else {
1952            self.mdns_local_names
1953                .iter()
1954                .find(|(_, name)| name == lost)
1955                .map(|(ip, _)| *ip)
1956        };
1957        let (Some(ip), Some(mdns_conn)) = (ip, &mut self.mdns) else {
1958            return;
1959        };
1960        let name = generate_multicast_dns_name();
1961        if !mdns_conn.add_local_name(&name, ip) {
1962            warn!(
1963                "[{}]: the mDNS name {} was lost to another host and no new one could be registered",
1964                self.get_name(),
1965                lost
1966            );
1967            return;
1968        }
1969        warn!(
1970            "[{}]: the mDNS name {} was lost to another host: its candidates are now {}",
1971            self.get_name(),
1972            lost,
1973            name
1974        );
1975        if self.mdns_local_name == lost {
1976            self.mdns_local_name = name.clone();
1977        }
1978        for (_, published) in &mut self.mdns_local_names {
1979            if published == lost {
1980                *published = name.clone();
1981            }
1982        }
1983        for c in &mut self.local_candidates {
1984            if c.address == lost {
1985                c.address = name.clone();
1986                self.event_outs.push_back(TaggedEvent {
1987                    now,
1988                    event: Event::LocalCandidateRenamed(Box::new(c.clone())),
1989                });
1990            }
1991        }
1992    }
1993
1994    /// The remote mDNS candidates whose names have not resolved yet. They are held by no
1995    /// pair, but they were submitted: statistics list them (mDNS draft Section 3.3.1).
1996    pub fn pending_mdns_candidates(&self) -> impl Iterator<Item = &Candidate> {
1997        self.mdns_queries.values()
1998    }
1999
2000    /// Notes a candidate the peer signalled that is not paired but whose checks may still
2001    /// arrive (see [`UnpairedRemote`]).
2002    fn note_unpaired_remote(&mut self, c: &Candidate) {
2003        UnpairedRemote::note(&mut self.unpaired_remotes, c);
2004    }
2005
2006    /// Whether a pair can still be formed by a check from the peer (RFC 8445 Section 7.3.1.3)
2007    /// although every signalled candidate is in: the peer signalled a candidate that is not
2008    /// paired but can reach one of the local candidates it knows, a `tcptype active` one that
2009    /// dials a local passive candidate, or a `.local` name the agent did not resolve. RFC 8838
2010    /// Section 8: "a Trickle ICE agent MUST keep each checklist in the Running state as long as
2011    /// it expects candidate pairs to be incrementally added to the checklist."
2012    pub(crate) fn pair_may_come_from_a_peer_check(&self) -> bool {
2013        self.unpaired_remotes.iter().any(|remote| {
2014            self.local_candidates
2015                .iter()
2016                .any(|local| !local.held_from_pairing() && remote.can_reach(local))
2017        })
2018    }
2019
2020    /// The peer has no more candidates for this generation (an end-of-candidates indication,
2021    /// RFC 8838 Section 14). Remote candidates signalled after it are ignored, and a checking
2022    /// agent whose pairs have all failed (or that has none) fails without waiting for its
2023    /// timeout, once local gathering is complete too, unless a check from the peer may still
2024    /// form a pair (a `tcptype active` candidate of the peer that dials ours, a `.local` name
2025    /// not resolved): then its timeout ends it. An ICE restart starts a new generation.
2026    pub fn set_remote_end_of_candidates(&mut self) {
2027        self.remote_end_of_candidates = true;
2028        self.request_connectivity_check();
2029    }
2030
2031    /// Local gathering is complete for this generation (RFC 8838 Section 13): no local
2032    /// candidate is accepted after it. An ICE restart starts a new generation.
2033    pub fn set_local_gathering_complete(&mut self) {
2034        self.local_gathering_complete = true;
2035        self.request_connectivity_check();
2036    }
2037
2038    /// Whether this IP address is one the peer's signalling led to: the address of a candidate
2039    /// it signalled, or the address a `.local` name it signalled has been resolved to. A
2040    /// peer-reflexive remote candidate's address may be shown in statistics only then
2041    /// (draft-ietf-mmusic-mdns-ice-candidates Section 3.3.1: "a peer-reflexive remote
2042    /// candidate could be constructed from a remote host IP address as a result of an ICE
2043    /// connectivity check"; before the peer's name resolves, such a candidate would reveal
2044    /// what the name hides). Once the agent has resolved the name itself, the address is no
2045    /// news; the mDNS candidate's own entry still shows the name, never the address.
2046    pub fn is_signalled_remote_ip(&self, ip: IpAddr) -> bool {
2047        self.remote_candidates
2048            .iter()
2049            .any(|c| c.candidate_type() != CandidateType::PeerReflexive && c.addr().ip() == ip)
2050    }
2051
2052    /// The local candidates to signal to the peer: the ones the application added (with their
2053    /// 1:1 NAT companions), not the peer-reflexive ones the agent learned from the mapped
2054    /// address of a response (RFC 8445 Section 7.2.5.3.1), which need no signalling.
2055    pub fn get_local_candidates_to_signal(&self) -> Vec<Candidate> {
2056        self.local_candidates
2057            .iter()
2058            .filter(|c| c.candidate_type() != CandidateType::PeerReflexive)
2059            .cloned()
2060            .collect()
2061    }
2062
2063    /// Sets the credentials of the remote agent.
2064    pub fn set_remote_credentials(
2065        &mut self,
2066        remote_ufrag: String,
2067        remote_pwd: String,
2068    ) -> Result<()> {
2069        if remote_ufrag.is_empty() {
2070            return Err(Error::ErrRemoteUfragEmpty);
2071        } else if remote_pwd.is_empty() {
2072            return Err(Error::ErrRemotePwdEmpty);
2073        }
2074
2075        self.ufrag_pwd.remote_credentials = Some(Credentials {
2076            ufrag: remote_ufrag,
2077            pwd: remote_pwd,
2078        });
2079
2080        // Checks can start: the pairs formed so far get their initial states (RFC 8445
2081        // Section 6.1.2.6).
2082        self.compute_initial_pair_states();
2083
2084        // Requests answered before these credentials were known are processed on the next
2085        // `handle_timeout` (RFC 8445 Section 7.3), which is asked for at once.
2086        self.request_connectivity_check();
2087
2088        Ok(())
2089    }
2090
2091    /// Returns the remote credentials.
2092    pub fn get_remote_credentials(&self) -> Option<&Credentials> {
2093        self.ufrag_pwd.remote_credentials.as_ref()
2094    }
2095
2096    /// Returns the local credentials.
2097    /// The credentials to advertise, which is what SDP generation wants.
2098    ///
2099    /// Returns credentials staged by [`Agent::generate_restart_credentials`] when an ICE restart
2100    /// is pending, so an offer carries the new ufrag/pwd. Inbound STUN validation deliberately
2101    /// does *not* go through here — it reads `local_credentials` directly, so the live session
2102    /// keeps working until [`Agent::apply_restart`] installs the new pair.
2103    pub fn get_local_credentials(&self) -> &Credentials {
2104        self.ufrag_pwd
2105            .pending_local_credentials
2106            .as_ref()
2107            .unwrap_or(&self.ufrag_pwd.local_credentials)
2108    }
2109
2110    /// Queues `CandidatePairRemoved` for every listed pair, before the list is cleared.
2111    pub(crate) fn announce_all_pairs_removed(&mut self) {
2112        for index in 0..self.candidate_pairs.len() {
2113            self.announce_pair(index, false);
2114        }
2115    }
2116
2117    /// The candidate pairs on the agent's list (webrtc-extensions 7 `[[CandidatePairs]]`):
2118    /// (local, remote), in the order they were formed. A pair the application removed is not
2119    /// listed.
2120    pub fn get_candidate_pairs(&self) -> Vec<(Candidate, Candidate)> {
2121        self.candidate_pairs
2122            .iter()
2123            .filter(|p| !p.removed)
2124            .filter_map(|p| {
2125                Some((
2126                    self.local_candidates.get(p.local_index)?.clone(),
2127                    self.remote_candidates.get(p.remote_index)?.clone(),
2128                ))
2129            })
2130            .collect()
2131    }
2132
2133    fn listed_pair(&self, local: &Candidate, remote: &Candidate) -> Option<usize> {
2134        self.candidate_pairs.iter().position(|p| {
2135            !p.removed
2136                && self
2137                    .local_candidates
2138                    .get(p.local_index)
2139                    .is_some_and(|c| c.equal(local))
2140                && self
2141                    .remote_candidates
2142                    .get(p.remote_index)
2143                    .is_some_and(|c| c.equal(remote))
2144        })
2145    }
2146
2147    /// The InvalidStateError checks of `selectCandidatePair` / `removeCandidatePair`: the
2148    /// agent is closed, or its state is new or failed.
2149    fn check_pair_call_state(&self) -> Result<()> {
2150        if matches!(
2151            self.connection_state,
2152            ConnectionState::New | ConnectionState::Failed | ConnectionState::Closed
2153        ) {
2154            return Err(Error::InvalidStateError);
2155        }
2156        Ok(())
2157    }
2158
2159    /// Whether a nomination proposal waits for [`Self::resolve_nomination_proposal`]
2160    /// (webrtc-extensions 7 `[[ProposalPending]]`).
2161    pub fn proposal_pending(&self) -> bool {
2162        self.nomination_proposal.is_some()
2163    }
2164
2165    /// Answers the pending nomination proposal: `accept` nominates the pair (a check with
2166    /// USE-CANDIDATE); otherwise the pair is not nominated and the agent keeps checking
2167    /// (webrtc-extensions 7, a cancelled `icecandidatepairnominate`). Nothing when no
2168    /// proposal is pending.
2169    pub fn resolve_nomination_proposal(&mut self, now: Instant, accept: bool) {
2170        let Some(pair_index) = self.nomination_proposal.take() else {
2171            return;
2172        };
2173        if accept && self.selected_pair.is_none() && self.nominated_pair.is_none() {
2174            self.candidate_pairs[pair_index].nominate = true;
2175            self.nominated_pair = Some(pair_index);
2176            self.enqueue_triggered(pair_index);
2177        } else if !accept {
2178            self.declined_nominations.push(pair_index);
2179        }
2180        let _ = now;
2181    }
2182
2183    /// webrtc-extensions 7 `selectCandidatePair(pair)`: the agent sends data on the pair of
2184    /// `local` and `remote` from now on; the selected pair changes, with its
2185    /// `SelectedCandidatePairChange` event, and the state with its event when it was not
2186    /// connected. Connectivity checks on other pairs stop, as they do once a pair is
2187    /// selected; consent keeps being checked on this one.
2188    ///
2189    /// # Errors
2190    ///
2191    /// `InvalidStateError` when the agent is closed, or new or failed; `NotFoundError` when
2192    /// the pair is not on the list ([`Self::get_candidate_pairs`]).
2193    pub fn select_candidate_pair(
2194        &mut self,
2195        now: Instant,
2196        local: &Candidate,
2197        remote: &Candidate,
2198    ) -> Result<()> {
2199        self.check_pair_call_state()?;
2200        let index = self
2201            .listed_pair(local, remote)
2202            .ok_or(Error::NotFoundError)?;
2203        self.clock = self.clock.max(now);
2204        if self.selected_pair != Some(index) {
2205            self.nominated_pair = Some(index);
2206            self.set_selected_pair(Some(now), Some(index));
2207        }
2208        Ok(())
2209    }
2210
2211    /// webrtc-extensions 7 `removeCandidatePair(pair)`: the agent stops the checks on the
2212    /// pair of `local` and `remote` (an In-Progress transaction is cancelled, no check is
2213    /// sent or answered on it any more, data from it is not accepted through it), then
2214    /// queues `CandidatePairRemoved`. When it was the selected pair the best other valid pair
2215    /// takes its place, or none: the state then follows consent as for a lost path.
2216    ///
2217    /// # Errors
2218    ///
2219    /// As [`Self::select_candidate_pair`].
2220    pub fn remove_candidate_pair(
2221        &mut self,
2222        now: Instant,
2223        local: &Candidate,
2224        remote: &Candidate,
2225    ) -> Result<()> {
2226        self.check_pair_call_state()?;
2227        let index = self
2228            .listed_pair(local, remote)
2229            .ok_or(Error::NotFoundError)?;
2230        self.clock = self.clock.max(now);
2231        let pair = self.candidate_pairs[index];
2232        self.cancel_pair_checks(pair.local_index, pair.remote_index);
2233        {
2234            let p = &mut self.candidate_pairs[index];
2235            p.state = CandidatePairState::Failed;
2236            p.valid = false;
2237            p.nominate = false;
2238            p.triggered = false;
2239            p.nomination_pending = false;
2240        }
2241        self.announce_pair(index, false);
2242        self.candidate_pairs[index].removed = true;
2243        if self.nominated_pair == Some(index) {
2244            self.nominated_pair = None;
2245        }
2246        if self.selected_pair == Some(index) {
2247            let next = self
2248                .candidate_pairs
2249                .iter()
2250                .enumerate()
2251                .filter(|(_, p)| p.valid && !p.removed && p.state == CandidatePairState::Succeeded)
2252                .max_by_key(|(_, p)| p.priority())
2253                .map(|(i, _)| i);
2254            match next {
2255                Some(next) => {
2256                    self.nominated_pair = Some(next);
2257                    self.set_selected_pair(Some(now), Some(next));
2258                }
2259                None => {
2260                    self.selected_pair = None;
2261                    self.request_connectivity_check();
2262                }
2263            }
2264        }
2265        Ok(())
2266    }
2267
2268    /// Whether this agent is the controlling one, which decides nomination.
2269    pub fn role(&self) -> bool {
2270        self.is_controlling
2271    }
2272
2273    /// Sets the role, when the roles are determined (RFC 8445 Section 6.1.1): the agent that
2274    /// started the ICE processing is controlling, unless exactly one of the two is lite (the
2275    /// full one is controlling then).
2276    ///
2277    /// "Once the roles are determined for a session, they persist throughout the lifetime of
2278    /// the session": an ICE restart keeps them (the agent does, by itself), and they are
2279    /// determined again at a restart only when an agent changed between full and lite. A role
2280    /// conflict is repaired by the agent (Section 7.3.1.1).
2281    ///
2282    /// The pairs the agent holds get the priority of the new role (Section 6.1.2.3), and a
2283    /// nomination that was being made is dropped: only the controlling agent nominates.
2284    pub fn set_role(&mut self, is_controlling: bool) {
2285        if self.is_controlling == is_controlling {
2286            return;
2287        }
2288        self.is_controlling = is_controlling;
2289        for pair in &mut self.candidate_pairs {
2290            pair.ice_role_controlling = is_controlling;
2291            pair.nominate = false;
2292        }
2293        self.nominated_pair = None;
2294        self.nomination_proposal = None;
2295        self.declined_nominations.clear();
2296    }
2297
2298    /// The tiebreaker the agent's checks carry (RFC 8445 Section 5.2).
2299    pub fn tie_breaker(&self) -> u64 {
2300        self.tie_breaker
2301    }
2302
2303    /// Whether this agent is a lite implementation.
2304    pub fn is_lite(&self) -> bool {
2305        self.lite
2306    }
2307
2308    /// Tells the agent whether the peer is a lite implementation (in SDP, `a=ice-lite`).
2309    ///
2310    /// It matters to a lite agent: with a full peer it answers checks and waits for the
2311    /// nomination; with a lite peer "no connectivity checks are ever sent. Rather, once the
2312    /// candidates are exchanged, each agent performs the processing described in Section 8
2313    /// without connectivity checks" (RFC 8445 Section 6.1.1). See
2314    /// [`Event::LiteCandidateUpdate`] and [`Agent::replace_remote_candidates`].
2315    pub fn set_remote_lite(&mut self, lite: bool) {
2316        self.remote_lite = lite;
2317        self.request_connectivity_check();
2318    }
2319
2320    /// Ta, the pacing of connectivity checks in use (RFC 8445 Section 14.2).
2321    pub fn pacing(&self) -> Duration {
2322        self.ta
2323    }
2324
2325    /// The Ta this agent proposes to its peer, when it is not the default of 50 ms: "If an
2326    /// agent wants to use a Ta value other than the default value, the agent MUST indicate the
2327    /// proposed value to its peer during the establishment of the ICE session" (RFC 8445
2328    /// Section 14.2; in SDP, `a=ice-pacing`, RFC 8839 Section 5.5, in milliseconds).
2329    pub fn proposed_pacing(&self) -> Option<Duration> {
2330        self.configured_ta
2331            .map(|ta| ta.max(MIN_TA))
2332            .filter(|ta| *ta != DEFAULT_TA)
2333    }
2334
2335    /// The peer's proposal for Ta (`None`: it proposed nothing, which is the default, 50 ms).
2336    /// "Both agents MUST use the higher out of the two proposed values" (RFC 8445 Section
2337    /// 14.2): from now on Ta is the larger of this agent's own and the peer's.
2338    ///
2339    /// Until this is called the agent paces by its own configuration alone: it cannot know
2340    /// that the peer was told. An application that configures a Ta under 50 ms and never
2341    /// calls this is pacing faster than the peer agreed to.
2342    pub fn set_remote_pacing(&mut self, proposed: Option<Duration>) {
2343        let own = self.configured_ta.unwrap_or(DEFAULT_TA);
2344        self.ta = own.max(proposed.unwrap_or(DEFAULT_TA)).max(MIN_TA);
2345    }
2346
2347    /// Two lite agents: replaces the remote candidates with those of an updated candidate
2348    /// exchange (RFC 8445 Section 8.2: "the controlling agent MUST send an updated candidate
2349    /// list to reconcile different agents selecting different candidate pairs. ICE processing
2350    /// is complete after and only after the updated candidate exchange is complete"), and
2351    /// selects again. Returns `false`, and changes nothing, unless both agents are lite.
2352    pub fn replace_remote_candidates(&mut self, now: Instant, candidates: Vec<Candidate>) -> bool {
2353        self.replace_remote_candidates_pinning(now, candidates, None)
2354    }
2355
2356    /// [`Agent::replace_remote_candidates`], with the local side of the pair given: RFC 8839
2357    /// Section 4.4.2.2, a lite answerer offered `a=remote-candidates` forms the pair from the
2358    /// offer's default destination and, as its local candidate, the transport address the
2359    /// attribute names (the controlling agent's remote candidate is this agent's local one).
2360    /// A pair with a local candidate at `local` is chosen over any other; `None` (or an
2361    /// address no local candidate has) leaves the choice to the RFC 6724 preference.
2362    pub fn replace_remote_candidates_pinning(
2363        &mut self,
2364        now: Instant,
2365        candidates: Vec<Candidate>,
2366        local: Option<SocketAddr>,
2367    ) -> bool {
2368        if !(self.lite && self.remote_lite) {
2369            return false;
2370        }
2371        self.pinned_local_addr = local;
2372        self.set_selected_pair(Some(now), None);
2373        self.announce_all_pairs_removed();
2374        self.candidate_pairs = Vec::new();
2375        self.nominated_pair = None;
2376        self.nomination_proposal = None;
2377        self.declined_nominations.clear();
2378        self.triggered_queue.clear();
2379        self.remote_candidates.clear();
2380        self.unpaired_remotes.clear();
2381        self.remote_end_of_candidates = false;
2382        self.trigger_request_connectivity_check(candidates);
2383        self.request_connectivity_check();
2384        true
2385    }
2386
2387    /// Replaces the candidate types the agent accepts as local candidates from now on
2388    /// (`AgentConfig::candidate_types`; empty means the default set).
2389    ///
2390    /// Candidates already added stay: a new ICE transport policy takes effect at the next
2391    /// gathering (RFC 9429, Section 4.1.18). A lite agent keeps host candidates only.
2392    pub fn set_candidate_types(&mut self, candidate_types: Vec<CandidateType>) {
2393        if self.lite {
2394            return;
2395        }
2396        self.candidate_types = if candidate_types.is_empty() {
2397            default_candidate_types()
2398        } else {
2399            candidate_types
2400        };
2401    }
2402
2403    /// The agent's current connection state.
2404    pub fn state(&self) -> ConnectionState {
2405        self.connection_state
2406    }
2407
2408    /// Whether a non-STUN datagram on `transport` should be accepted as media.
2409    ///
2410    /// Guards against accepting media from an address that has not passed a connectivity check.
2411    pub fn is_valid_non_stun_traffic(&mut self, now: Instant, transport: TransportContext) -> bool {
2412        self.remote_policy.allows_source(transport.peer_addr)
2413            && self
2414                .find_local_candidate(transport.local_addr, transport.transport_protocol)
2415                .is_some()
2416            && self.validate_non_stun_traffic(now, transport.peer_addr)
2417    }
2418
2419    fn get_timeout_interval(&self) -> Duration {
2420        let (check_interval, keepalive_interval, disconnected_timeout, failed_timeout) = (
2421            self.check_interval,
2422            self.keepalive_interval,
2423            self.disconnected_timeout,
2424            self.failed_timeout,
2425        );
2426        let mut interval = DEFAULT_CHECK_INTERVAL;
2427
2428        let mut update_interval = |x: Duration| {
2429            if x != ZERO_DURATION && (interval == ZERO_DURATION || interval > x) {
2430                interval = x;
2431            }
2432        };
2433
2434        match self.last_connection_state {
2435            ConnectionState::New | ConnectionState::Checking => {
2436                // While connecting, check candidates more frequently
2437                update_interval(check_interval);
2438            }
2439            ConnectionState::Connected | ConnectionState::Disconnected => {
2440                update_interval(keepalive_interval);
2441            }
2442            _ => {}
2443        };
2444        // Ensure we run our task loop as quickly as the minimum of our various configured timeouts
2445        update_interval(disconnected_timeout);
2446        update_interval(failed_timeout);
2447        interval
2448    }
2449
2450    /// The path data (DTLS, SRTP) is sent on and accepted from: the selected pair's, and
2451    /// during an ICE restart, until the restart selects a pair, the one the session had when
2452    /// the restart was applied.
2453    ///
2454    /// RFC 8445 Section 9: "the ICE agent continues to use the previously selected candidate
2455    /// pair until a new pair is selected by the restart". Without it every packet between
2456    /// `apply_restart` and the first nomination of the new generation was dropped, on both
2457    /// sides, for as long as the offer/answer exchange took.
2458    ///
2459    /// While the controlling agent's nomination is in flight, it is the nominated pair's. That
2460    /// pair is valid, so Section 12.1 allows it ("An ICE agent MAY send data on any valid pair
2461    /// before selected pairs have been produced for the data stream"), and it is the pair
2462    /// the controlled agent selected when the nomination's first request reached it: the peer
2463    /// sends on it from then on (its DTLS handshake starts), and Section 12.2 asks for that
2464    /// data to be received ("ICE implementations SHOULD by default be prepared to receive data
2465    /// on any of the candidates"). Without it, while the responses to the nomination were
2466    /// lost, the controlling agent dropped everything the peer sent and could answer nothing:
2467    /// the peer's DTLS retransmissions went unanswered and its timer backed off for nothing,
2468    /// so that after a few more losses at 10 % the data channel had not opened in 30 seconds.
2469    ///
2470    /// With [`AgentConfig::send_data_before_nomination`], and before the first pair is
2471    /// selected, it is the best valid pair's (Section 12.1).
2472    pub fn media_path(&self) -> Option<MediaPath> {
2473        self.selected_media_path()
2474            .or(self.previous_media_path)
2475            .or_else(|| self.nominating_media_path())
2476            .or_else(|| self.valid_media_path())
2477    }
2478
2479    /// The path an ICE restart replaced, while data on it is still taken after the restart's
2480    /// pair was selected (`RETIRED_MEDIA_PATH_GRACE`); nothing is sent on it.
2481    pub fn retired_media_path(&self) -> Option<MediaPath> {
2482        self.retired_media_path
2483            .filter(|(_, until)| self.clock < *until)
2484            .map(|(path, _)| path)
2485    }
2486
2487    /// The path of the valid pair the controlling agent is nominating, before any pair is
2488    /// selected, while consent on it is fresh: a Binding success response came from its
2489    /// remote candidate less than the consent expiry ago, as of the newest instant the agent
2490    /// was given (RFC 7675 Section 5.1: no data once consent has expired). A nomination's
2491    /// transaction lasts longer than that (39.5 seconds, RFC 8445 Section 14.3).
2492    fn nominating_media_path(&self) -> Option<MediaPath> {
2493        if !self.is_controlling || self.selected_pair.is_some() {
2494            return None;
2495        }
2496        let pair = self.candidate_pairs.get(self.nominated_pair?)?;
2497        let consent = self
2498            .remote_candidates
2499            .get(pair.remote_index)?
2500            .last_consent()?;
2501        (pair.valid
2502            && !pair.removed
2503            && pair.state != CandidatePairState::Failed
2504            && self.clock.saturating_duration_since(consent) < self.consent_expiry())
2505        .then(|| self.path_of(pair.local_index, pair.remote_index))
2506    }
2507
2508    /// The best valid pair's path, when data may be sent before a pair is selected. A lite
2509    /// agent has no valid pair before a nomination (Section 12.1.1).
2510    fn valid_media_path(&self) -> Option<MediaPath> {
2511        if !self.send_data_before_nomination {
2512            return None;
2513        }
2514        let pair = &self.candidate_pairs[self.get_best_valid_candidate_pair()?];
2515        Some(self.path_of(pair.local_index, pair.remote_index))
2516    }
2517
2518    fn path_of(&self, local_index: usize, remote_index: usize) -> MediaPath {
2519        let local = &self.local_candidates[local_index];
2520        MediaPath {
2521            local_addr: local.base_addr(),
2522            peer_addr: self.remote_candidates[remote_index].addr(),
2523            transport_protocol: local.network_type().to_protocol(),
2524        }
2525    }
2526
2527    /// Whether data (anything that is not STUN: DTLS, SRTP) that arrived on `transport` is
2528    /// accepted.
2529    ///
2530    /// RFC 8445 Section 12.2: "ICE implementations SHOULD by default be prepared to receive
2531    /// data on any of the candidates provided in the most recent candidate exchange with the
2532    /// peer", and "an agent will be able to determine that a data stream is from the same peer
2533    /// as a consequence of the STUN exchange that proceeds media data transmission". So, once
2534    /// there is a path to send on ([`Agent::media_path`]), data is accepted on any local
2535    /// candidate, from that path's remote address and from the remote candidate of any valid
2536    /// pair: an address one of the agent's own checks was answered from, by someone who holds
2537    /// the peer's password. A source that only sent requests, or that no check reached, is
2538    /// not accepted.
2539    ///
2540    /// With [`AgentConfig::data_from_selected_pair_only`] only the remote address of the path
2541    /// data is sent on is accepted.
2542    pub fn accepts_data(&self, transport: TransportContext) -> bool {
2543        self.data_path(transport).is_some()
2544    }
2545
2546    /// As [`Agent::accepts_data`], saying which pair the data arrived on: the one in use, or
2547    /// another valid pair (its local and remote candidates).
2548    pub fn data_path(&self, transport: TransportContext) -> Option<DataPath<'_>> {
2549        // Nothing from a source the embedder's address policy refuses.
2550        if !self.remote_policy.allows_source(transport.peer_addr) {
2551            return None;
2552        }
2553        let path = self.media_path()?;
2554        if self.data_from_selected_pair_only {
2555            // (The hardening compares the source only, as it always did.)
2556            return (transport.peer_addr == path.peer_addr).then_some(DataPath::InUse);
2557        }
2558        if transport.peer_addr == path.peer_addr
2559            && transport.local_addr == path.local_addr
2560            && transport.transport_protocol == path.transport_protocol
2561        {
2562            return Some(DataPath::InUse);
2563        }
2564        // The path an ICE restart replaced, for a while after the new pair was selected: the
2565        // peer's packets sent before its own selection switched.
2566        if self.retired_media_path.is_some_and(|(retired, until)| {
2567            self.clock < until
2568                && transport.peer_addr == retired.peer_addr
2569                && transport.local_addr == retired.local_addr
2570                && transport.transport_protocol == retired.transport_protocol
2571        }) {
2572            return Some(DataPath::InUse);
2573        }
2574        // "On any of the candidates provided": the datagram arrived on one of them.
2575        self.find_local_candidate(transport.local_addr, transport.transport_protocol)?;
2576        let valid = |p: &&CandidatePair| {
2577            p.valid
2578                && p.state == CandidatePairState::Succeeded
2579                && self.remote_candidates[p.remote_index].addr() == transport.peer_addr
2580                && self.local_candidates[p.local_index]
2581                    .network_type()
2582                    .to_protocol()
2583                    == transport.transport_protocol
2584        };
2585        // The valid pair it arrived on, when there is one for this local candidate too.
2586        let exact = self
2587            .candidate_pairs
2588            .iter()
2589            .filter(valid)
2590            .find(|p| self.local_candidates[p.local_index].base_addr() == transport.local_addr);
2591        if let Some(p) = exact.or_else(|| self.candidate_pairs.iter().find(valid)) {
2592            return Some(DataPath::Valid(
2593                &self.local_candidates[p.local_index],
2594                &self.remote_candidates[p.remote_index],
2595            ));
2596        }
2597        // From the remote address of the path in use, on another local candidate.
2598        (transport.peer_addr == path.peer_addr
2599            && transport.transport_protocol == path.transport_protocol)
2600            .then_some(DataPath::InUse)
2601    }
2602
2603    fn selected_media_path(&self) -> Option<MediaPath> {
2604        self.get_selected_candidate_pair()
2605            .map(|(local, remote)| MediaPath {
2606                // The local candidate's base: for a (server/peer-)reflexive candidate the
2607                // candidate address is the NAT mapping, not a bound local socket
2608                // (RFC 8445 Section 5.1.1).
2609                local_addr: local.base_addr(),
2610                peer_addr: remote.addr(),
2611                transport_protocol: local.network_type().to_protocol(),
2612            })
2613    }
2614
2615    /// Returns the selected pair (local_candidate, remote_candidate) or none
2616    pub fn get_selected_candidate_pair(&self) -> Option<(&Candidate, &Candidate)> {
2617        if let Some(pair_index) = self.get_selected_pair() {
2618            let candidate_pair = &self.candidate_pairs[pair_index];
2619            Some((
2620                &self.local_candidates[candidate_pair.local_index],
2621                &self.remote_candidates[candidate_pair.remote_index],
2622            ))
2623        } else {
2624            None
2625        }
2626    }
2627
2628    /// The highest-priority pair that is still usable, whether or not it has been nominated.
2629    pub fn get_best_available_candidate_pair(&self) -> Option<(&Candidate, &Candidate)> {
2630        if let Some(pair_index) = self.get_best_available_pair() {
2631            let candidate_pair = &self.candidate_pairs[pair_index];
2632            Some((
2633                &self.local_candidates[candidate_pair.local_index],
2634                &self.remote_candidates[candidate_pair.remote_index],
2635            ))
2636        } else {
2637            None
2638        }
2639    }
2640
2641    /// start connectivity checks
2642    pub fn start_connectivity_checks(
2643        &mut self,
2644        now: Instant,
2645        is_controlling: bool,
2646        remote_ufrag: String,
2647        remote_pwd: String,
2648    ) -> Result<()> {
2649        debug!(
2650            "Started agent: isControlling? {}, remoteUfrag: {}, remotePwd: {}",
2651            is_controlling, remote_ufrag, remote_pwd
2652        );
2653        self.set_remote_credentials(remote_ufrag, remote_pwd)?;
2654        self.is_controlling = is_controlling;
2655        self.start(now);
2656
2657        self.update_connection_state(Some(now), ConnectionState::Checking);
2658        self.request_connectivity_check();
2659
2660        Ok(())
2661    }
2662
2663    /// Restarts the ICE Agent with the provided ufrag/pwd
2664    /// If no ufrag/pwd is provided the Agent will generate one itself.
2665    /// Stages new local credentials for an ICE restart, without disturbing the live session.
2666    ///
2667    /// This is the half of an ICE restart that an offerer needs *before* generating SDP: the offer
2668    /// must carry the new ufrag/pwd. It deliberately does not touch `local_credentials`,
2669    /// candidate pairs, or connection state, because JSEP requires `createOffer` to be free of
2670    /// side effects — and because inbound STUN is still being validated against the current
2671    /// credentials until the local description is applied.
2672    ///
2673    /// Empty `ufrag` / `pwd` are filled from the crypto provider's RNG. Call
2674    /// [`Agent::apply_restart`] to install them.
2675    pub fn generate_restart_credentials(
2676        &mut self,
2677        mut ufrag: String,
2678        mut pwd: String,
2679    ) -> Result<()> {
2680        if ufrag.is_empty() {
2681            ufrag = generate_ufrag_with_random(self.crypto_provider.random())?;
2682        }
2683        if pwd.is_empty() {
2684            pwd = generate_pwd_with_random(self.crypto_provider.random())?;
2685        }
2686
2687        // RFC 8445 Section 9: an ICE restart changes both the fragment and the password. An
2688        // application that pins its credentials would otherwise offer the ones in use: the
2689        // peer sees no restart while this side has flushed its pairs. The pinned pair then
2690        // names the first generation only.
2691        let current = &self.ufrag_pwd.local_credentials;
2692        if !current.ufrag.is_empty() && (ufrag == current.ufrag || pwd == current.pwd) {
2693            warn!(
2694                "[{}]: an ICE restart was given the credentials in use; generating new ones",
2695                self.get_name()
2696            );
2697            ufrag = generate_ufrag_with_random(self.crypto_provider.random())?;
2698            pwd = generate_pwd_with_random(self.crypto_provider.random())?;
2699        }
2700
2701        check_local_credentials(&ufrag, &pwd)?;
2702
2703        self.ufrag_pwd.pending_local_credentials = Some(Credentials { ufrag, pwd });
2704
2705        Ok(())
2706    }
2707
2708    /// Whether [`Agent::generate_restart_credentials`] has staged a restart that is not yet applied.
2709    pub fn has_pending_restart(&self) -> bool {
2710        self.ufrag_pwd.pending_local_credentials.is_some()
2711    }
2712
2713    /// Forgets the credentials [`Agent::generate_restart_credentials`] staged, so that no
2714    /// restart is pending: the description they were staged for was abandoned (a rolled-back
2715    /// remote offer, RFC 9429 section 5.7). The live session is untouched.
2716    pub fn discard_restart_credentials(&mut self) {
2717        self.ufrag_pwd.pending_local_credentials = None;
2718        // What was gathered for it belongs to no generation now; a candidate that could not
2719        // join the current session (it had nominated) still does not.
2720        for c in &mut self.local_candidates {
2721            c.restart_generation = false;
2722        }
2723    }
2724
2725    /// The local candidates gathered for the staged ICE restart (see
2726    /// [`Agent::generate_restart_credentials`]): added, or added again, since it was staged.
2727    /// The restart keeps them whether or not it keeps the others.
2728    pub fn get_restart_generation_local_candidates(&self) -> Vec<Candidate> {
2729        self.local_candidates
2730            .iter()
2731            .filter(|c| c.restart_generation)
2732            .cloned()
2733            .collect()
2734    }
2735
2736    /// Applies a staged ICE restart, tearing down the old session and starting a new one at `now`.
2737    ///
2738    /// Installs the credentials staged by [`Agent::generate_restart_credentials`], if any, then
2739    /// discards the remote credentials, pending binding requests, candidate pairs and selected
2740    /// pair, and restarts the agent's timers. With nothing staged, the current credentials are
2741    /// kept and only the session is restarted.
2742    pub fn apply_restart(&mut self, now: Instant, keep_local_candidates: bool) -> Result<()> {
2743        // A closed agent has shut its mDNS connection and dropped its candidates for good; a
2744        // restart must not bring it back to `Checking`.
2745        if self.connection_state == ConnectionState::Closed {
2746            return Err(Error::ErrClosed);
2747        }
2748        // A restart that is not revertible commits an earlier one.
2749        self.restart_undo = None;
2750        // RFC 8445 Section 16.1: "The agent MAY change the number when an ICE restart
2751        // occurs", when the application asked for it.
2752        if self.new_tie_breaker_on_restart {
2753            self.tie_breaker = generate_tie_breaker(self.crypto_provider.random())?;
2754        }
2755        // A new generation: what the gathering just before showed public is what it unwraps
2756        // (draft-ietf-mmusic-mdns-ice-candidates Section 3.1.2.2).
2757        self.ice_generation += 1;
2758        self.mdns_known_public.restarted(self.ice_generation);
2759        // Data keeps the path it has until the new generation selects a pair (RFC 8445
2760        // Section 9), whether or not the local candidates are kept: discarding them forgets
2761        // what was signalled, not the socket the path's packets leave from. An application
2762        // that closed that socket (a rebind) drops what is written to it, as before.
2763        let previous_media_path = self.media_path();
2764        // Consent goes on being checked on that path (RFC 7675 Section 5.1), with the
2765        // credentials of the generation that validated it. A second restart before the first
2766        // one selected a pair keeps what the first one kept.
2767        let previous_generation = match (self.selected_pair, &self.ufrag_pwd.remote_credentials) {
2768            (Some(pair_index), Some(remote_credentials)) => {
2769                let pair = self.candidate_pairs[pair_index];
2770                let remote = &self.remote_candidates[pair.remote_index];
2771                let last_consent = if self.lite {
2772                    remote.last_authenticated()
2773                } else {
2774                    remote.last_consent()
2775                };
2776                Some(PreviousGeneration {
2777                    local_credentials: self.ufrag_pwd.local_credentials.clone(),
2778                    remote_credentials: remote_credentials.clone(),
2779                    priority: self.local_candidates[pair.local_index].peer_reflexive_priority(),
2780                    last_consent: last_consent.unwrap_or(now),
2781                    next_consent_at: self
2782                        .next_consent_at
2783                        .unwrap_or_else(|| now + self.next_consent_interval()),
2784                    // The consent requests still open on the pair stay open on the path: the
2785                    // peer answers them as it would have without the restart (RFC 7675
2786                    // Section 5.1: "a response might be for a previous request").
2787                    pending: self
2788                        .pending_binding_requests
2789                        .iter()
2790                        .filter(|r| {
2791                            r.consent
2792                                && r.local_index == pair.local_index
2793                                && r.remote_index == pair.remote_index
2794                                && r.next_event > now
2795                        })
2796                        .map(|r| PreviousConsentRequest {
2797                            transaction_id: r.transaction_id,
2798                            sent: r.timestamp,
2799                            until: r.next_event,
2800                        })
2801                        .collect(),
2802                    rto: pair.rto,
2803                })
2804            }
2805            _ => self.previous_generation.take(),
2806        };
2807
2808        if let Some(credentials) = self.ufrag_pwd.pending_local_credentials.take() {
2809            self.ufrag_pwd.local_credentials = credentials;
2810        }
2811        self.ufrag_pwd.remote_credentials = None;
2812
2813        self.pending_binding_requests = vec![];
2814        self.early_requests = vec![];
2815        self.triggered_queue.clear();
2816        // A new generation: its candidates and its end-of-candidates are still to come.
2817        self.lite_update_raised = false;
2818        self.pinned_local_addr = None;
2819        self.remote_end_of_candidates = false;
2820        self.local_gathering_complete = false;
2821
2822        self.announce_all_pairs_removed();
2823        self.candidate_pairs = Vec::new();
2824
2825        self.set_selected_pair(Some(now), None);
2826        // The local candidates gathered while the restart was staged are the new
2827        // generation's: they stay when the previous generation's are discarded.
2828        if !keep_local_candidates {
2829            self.local_candidates.retain(|c| c.restart_generation);
2830        }
2831        self.delete_all_candidates(true);
2832        for c in &mut self.local_candidates {
2833            c.restart_generation = false;
2834            c.awaiting_restart = false;
2835        }
2836        self.reevaluate_kept_host_candidates();
2837        self.previous_media_path = previous_media_path;
2838        self.previous_generation = previous_media_path.and(previous_generation);
2839        self.start(now);
2840
2841        // Restart is used by NewAgent. Accept/Connect should be used to move to checking
2842        // for new Agents. W3C webrtc-pc 5.6.4: "An ICE restart [...] causing a transition to
2843        // connected if begun in the completed state. If begun in the transient disconnected
2844        // state, it causes a transition to checking": a connected or completed agent that keeps
2845        // its path (RFC 8445 Section 9) is connected; a disconnected or failed one, or one
2846        // without a path, checks.
2847        let was_connected = matches!(
2848            self.connection_state,
2849            ConnectionState::Connected | ConnectionState::Completed
2850        );
2851        if was_connected && self.previous_media_path.is_some() {
2852            self.update_connection_state(Some(now), ConnectionState::Connected);
2853        } else if self.connection_state != ConnectionState::New {
2854            self.update_connection_state(Some(now), ConnectionState::Checking);
2855        }
2856
2857        Ok(())
2858    }
2859
2860    /// Generates and immediately applies an ICE restart.
2861    ///
2862    /// Equivalent to [`Agent::generate_restart_credentials`] followed by
2863    /// [`Agent::apply_restart`]. A JSEP-conformant offerer wants the two halves separately —
2864    /// credentials at `createOffer`, application at `setLocalDescription` — but this remains the
2865    /// right call for anything that restarts in one step.
2866    pub fn restart(
2867        &mut self,
2868        now: Instant,
2869        ufrag: String,
2870        pwd: String,
2871        keep_local_candidates: bool,
2872    ) -> Result<()> {
2873        self.generate_restart_credentials(ufrag, pwd)?;
2874        self.apply_restart(now, keep_local_candidates)
2875    }
2876
2877    /// Returns the local candidates.
2878    pub fn get_local_candidates(&self) -> &[Candidate] {
2879        &self.local_candidates
2880    }
2881
2882    /// The remote candidates this agent has been given, in the order they were added.
2883    pub fn get_remote_candidates(&self) -> &[Candidate] {
2884        &self.remote_candidates
2885    }
2886
2887    /// One pass over everything the agent does on its own: retransmissions and timeouts, the
2888    /// selected pair's consent, nomination, the next check Ta allows, and the checklist's
2889    /// state.
2890    fn contact(&mut self, now: Instant) {
2891        // Consume any pending deferred-check request now that we are running one.
2892        // Reset before the early returns below so a failed/settled agent does not
2893        // keep asking `poll_timeout` for an immediate wake-up.
2894        self.force_candidate_contact = false;
2895
2896        if matches!(
2897            self.connection_state,
2898            ConnectionState::Failed | ConnectionState::Closed
2899        ) {
2900            // The connection is currently failed so don't send any checks
2901            // In the future it may be restarted though
2902            self.last_connection_state = self.connection_state;
2903            return;
2904        }
2905        if self.connection_state == ConnectionState::Checking {
2906            // We have just entered checking for the first time so update our checking timer
2907            if self.last_connection_state != self.connection_state {
2908                self.checking_duration = now;
2909            }
2910
2911            // A nomination the peer has not been heard from for the consent expiry ends: its
2912            // pair fails, and the next valid pair is nominated.
2913            self.expire_unanswered_nomination(now);
2914
2915            // Past `disconnected_timeout + failed_timeout` in checking, the agent fails, but
2916            // only once nothing is left that may still produce a selected pair (RFC 8445
2917            // Sections 6.1.4.2 and 8.1.2: the checklist fails when every pair has failed). A
2918            // pair that is still being checked fails by its own transaction (Section 14.3), a
2919            // nomination by `expire_unanswered_nomination`.
2920            if self.failed_timeout != ZERO_DURATION
2921                && now
2922                    .checked_duration_since(self.checking_duration)
2923                    .unwrap_or_else(|| Duration::from_secs(0))
2924                    > self.disconnected_timeout + self.failed_timeout
2925                && !self.checks_in_progress(now)
2926            {
2927                self.update_connection_state(Some(now), ConnectionState::Failed);
2928                self.last_connection_state = self.connection_state;
2929                return;
2930            }
2931        }
2932
2933        self.run_transactions(now);
2934
2935        // Two lite agents: no checks, the pair comes from the candidate exchange (Section 8.2).
2936        if self.lite && self.remote_lite {
2937            self.conclude_lite_to_lite(now);
2938        }
2939
2940        if self.selected_pair.is_some() && self.validate_selected_pair(now) {
2941            if self.lite && (!self.is_controlling || self.remote_lite) {
2942                self.lite_keepalive(now);
2943            } else {
2944                self.check_keepalive(now);
2945            }
2946        }
2947
2948        if !matches!(
2949            self.connection_state,
2950            ConnectionState::Failed | ConnectionState::Closed
2951        ) {
2952            self.maybe_nominate(now);
2953            self.run_ta(now);
2954            self.update_checklist_failure(now);
2955        }
2956
2957        self.last_connection_state = self.connection_state;
2958        self.last_checking_time = now;
2959    }
2960
2961    /// When `contact` next has something to do. `None` when the agent has no peer credentials
2962    /// or is failed or closed.
2963    pub(crate) fn ice_deadline(&self) -> Option<Instant> {
2964        if self.ufrag_pwd.remote_credentials.is_none()
2965            || matches!(
2966                self.connection_state,
2967                ConnectionState::Failed | ConnectionState::Closed
2968            )
2969        {
2970            return None;
2971        }
2972        if self.force_candidate_contact {
2973            // A check or a look at the state was requested: as soon as possible.
2974            // `last_checking_time` is in the past, so the resulting deadline is immediate.
2975            return Some(self.last_checking_time);
2976        }
2977        let mut deadline: Option<Instant> = None;
2978        let mut by = |at: Instant| deadline = Some(deadline.map_or(at, |d| d.min(at)));
2979        // A retransmission, or a transaction that ends.
2980        for request in &self.pending_binding_requests {
2981            by(request.next_event);
2982        }
2983        // Connected: the next consent request, or the moment its silence counts.
2984        if let Some(at) = self.selected_pair_deadline() {
2985            by(at);
2986        }
2987        // Connecting (and a lite agent always): a periodic look at the state.
2988        if self.selected_pair.is_none() || self.lite {
2989            by(self.last_checking_time + self.get_timeout_interval());
2990        }
2991        // The next check, when Ta allows it.
2992        if self.has_check_to_start() {
2993            by(self.next_check_at);
2994        }
2995        deadline
2996    }
2997
2998    pub(crate) fn update_connection_state(
2999        &mut self,
3000        now: Option<Instant>,
3001        new_state: ConnectionState,
3002    ) {
3003        if self.connection_state != new_state {
3004            // Connection has gone to failed, release all gathered candidates
3005            if new_state == ConnectionState::Failed {
3006                self.set_selected_pair(now, None);
3007                self.delete_all_candidates(false);
3008            }
3009            // A failed or closed agent has no path, a restart's previous one included, and no
3010            // open transactions (RFC 7675 Section 5.1: "All outstanding STUN consent
3011            // transactions for a candidate pair MUST be discarded when consent expires").
3012            if matches!(new_state, ConnectionState::Failed | ConnectionState::Closed) {
3013                self.previous_media_path = None;
3014                self.retired_media_path = None;
3015                self.previous_generation = None;
3016                self.pending_binding_requests.clear();
3017                self.triggered_queue.clear();
3018                self.next_consent_at = None;
3019                self.consent_unanswered_since = None;
3020            }
3021
3022            info!(
3023                "[{}]: Setting new connection state: {}",
3024                self.get_name(),
3025                new_state
3026            );
3027            self.connection_state = new_state;
3028            if let Some(now) = now {
3029                self.event_outs.push_back(TaggedEvent {
3030                    now,
3031                    event: Event::ConnectionStateChange(new_state),
3032                });
3033            }
3034        }
3035    }
3036
3037    pub(crate) fn set_selected_pair(&mut self, now: Option<Instant>, selected_pair: Option<usize>) {
3038        if let Some(pair_index) = selected_pair {
3039            trace!(
3040                "[{}]: Set selected candidate pair: {:?}",
3041                self.get_name(),
3042                self.candidate_pairs[pair_index]
3043            );
3044
3045            self.candidate_pairs[pair_index].nominated = true;
3046            if self.selected_pair != Some(pair_index) {
3047                // Consent on the new pair was given by the response that validated it; the
3048                // first consent check follows one interval later. A pair the peer selects
3049                // long after that response (its nomination's responses were lost, so the
3050                // controlled agent waited) has less than 30 seconds of consent left (RFC 7675
3051                // section 5.1), and the check that validated it was sent at least as long
3052                // ago: the first consent check goes now, which keeps the period between
3053                // checks above the minimum.
3054                let interval = self.next_consent_interval();
3055                let remote = self.candidate_pairs[pair_index].remote_index;
3056                let last_consent = self.remote_candidates[remote].last_consent();
3057                self.next_consent_at = now.map(|now| match last_consent {
3058                    Some(at) if now.saturating_duration_since(at) >= interval => now,
3059                    _ => now + interval,
3060                });
3061                self.consent_unanswered_since = None;
3062            }
3063            self.selected_pair = Some(pair_index);
3064            // The restart (if any) has its pair: the previous generation's path is retired. The
3065            // peer may still send on it until its own selection switches: data on it is taken
3066            // a little longer (`RETIRED_MEDIA_PATH_GRACE`).
3067            if let Some(previous) = self.previous_media_path.take() {
3068                let now = now.unwrap_or(self.clock);
3069                self.retired_media_path = Some((previous, now + RETIRED_MEDIA_PATH_GRACE));
3070            }
3071            self.previous_generation = None;
3072
3073            if !matches!(
3074                self.connection_state,
3075                ConnectionState::Connected | ConnectionState::Completed
3076            ) {
3077                self.update_connection_state(now, ConnectionState::Connected);
3078            }
3079
3080            // Notify when the selected pair changes
3081            let candidate_pair = &self.candidate_pairs[pair_index];
3082            if let Some(now) = now {
3083                self.event_outs.push_back(TaggedEvent {
3084                    now,
3085                    event: Event::SelectedCandidatePairChange(
3086                        Box::new(self.local_candidates[candidate_pair.local_index].clone()),
3087                        Box::new(self.remote_candidates[candidate_pair.remote_index].clone()),
3088                    ),
3089                });
3090            }
3091        } else {
3092            self.selected_pair = None;
3093            self.next_consent_at = None;
3094            self.consent_unanswered_since = None;
3095        }
3096    }
3097
3098    /// The state of a connected agent whose consent is fresh: `Completed` once both sides
3099    /// have said they have no more candidates (W3C `RTCIceTransportState`: "finished
3100    /// gathering, received an indication that there are no more remote candidates, finished
3101    /// checking all candidate pairs and found a connection"), `Connected` until then.
3102    fn healthy_state(&self) -> ConnectionState {
3103        if self.remote_end_of_candidates && self.local_gathering_complete {
3104            ConnectionState::Completed
3105        } else {
3106            ConnectionState::Connected
3107        }
3108    }
3109
3110    /// One interval between two consent checks: 0.8 to 1.2 times the basic period, drawn from
3111    /// the crypto provider's RNG, and never under 4 seconds (RFC 7675 Section 5.1: "To prevent
3112    /// synchronization of consent checks, each interval MUST be randomized from between 0.8
3113    /// and 1.2 times the basic period. [...] Implementations MUST NOT set the period between
3114    /// checks to less than 4 seconds").
3115    pub(crate) fn next_consent_interval(&self) -> Duration {
3116        let mut bytes = [0_u8; 4];
3117        // Without randomness the period itself is the interval.
3118        let r = match self.crypto_provider.random().fill(&mut bytes) {
3119            Ok(()) => u64::from(u32::from_be_bytes(bytes)),
3120            Err(_) => u64::from(u32::MAX / 2),
3121        };
3122        // 0.8 + 0.4 * r / (2^32 - 1), in millionths.
3123        let factor = 800_000 + (r * 400_000) / u64::from(u32::MAX);
3124        let nanos = self.keepalive_interval.as_nanos() * u128::from(factor) / 1_000_000;
3125        Duration::from_nanos(u64::try_from(nanos).unwrap_or(u64::MAX)).max(MIN_CONSENT_INTERVAL)
3126    }
3127
3128    /// How long after the last consent response the agent stops sending: the configured
3129    /// `disconnected_timeout + failed_timeout`, and 30 seconds at most (RFC 7675 Section 5.1:
3130    /// "Consent expires after 30 seconds. That is, if a valid STUN binding response has not
3131    /// been received from the remote peer's transport address in 30 seconds, the endpoint MUST
3132    /// cease transmission on that 5-tuple"). A `failed_timeout` of zero, which keeps a
3133    /// checking agent from failing, does not keep consent alive.
3134    pub(crate) fn consent_expiry(&self) -> Duration {
3135        if self.failed_timeout == ZERO_DURATION {
3136            CONSENT_EXPIRY
3137        } else {
3138            (self.disconnected_timeout + self.failed_timeout).min(CONSENT_EXPIRY)
3139        }
3140    }
3141
3142    /// Checks if the selected pair is (still) valid.
3143    /// Re-evaluates the selected pair's liveness as of `now`.
3144    ///
3145    /// `now` comes from the caller so that this decision and the keepalive decision below are
3146    /// made against the same instant as the `contact(now)` that reached them.
3147    pub(crate) fn validate_selected_pair(&mut self, now: Instant) -> bool {
3148        let Some(pair_index) = self.selected_pair else {
3149            return false;
3150        };
3151        let remote_index = self.candidate_pairs[pair_index].remote_index;
3152        let remote = &self.remote_candidates[remote_index];
3153
3154        if self.lite && self.remote_lite {
3155            // Two lite agents exchange no Binding requests at all (Section 6.1.1: "no
3156            // connectivity checks are ever sent"): ICE has no sign of life to judge by.
3157            self.update_connection_state(Some(now), self.healthy_state());
3158            return true;
3159        }
3160
3161        if self.lite {
3162            // A lite agent sends no checks (RFC 8445 §2.5), so for it an authenticated request
3163            // from the peer is the only sign of life, judged by the configured timeouts.
3164            let last_received = remote.last_authenticated().unwrap_or(self.start_time);
3165            let disconnected_time = now.saturating_duration_since(last_received);
3166
3167            // Only allow transitions to fail if a.failedTimeout is non-zero
3168            let mut total_time_to_failure = self.failed_timeout;
3169            if total_time_to_failure != ZERO_DURATION {
3170                total_time_to_failure += self.disconnected_timeout;
3171            }
3172
3173            if total_time_to_failure != ZERO_DURATION && disconnected_time > total_time_to_failure {
3174                self.update_connection_state(Some(now), ConnectionState::Failed);
3175            } else if self.disconnected_timeout != ZERO_DURATION
3176                && disconnected_time > self.disconnected_timeout
3177            {
3178                self.update_connection_state(Some(now), ConnectionState::Disconnected);
3179            } else {
3180                self.update_connection_state(Some(now), self.healthy_state());
3181            }
3182            return true;
3183        }
3184
3185        // Consent (RFC 7675 §5.1) is refreshed only by an authenticated success response to
3186        // one of our own checks: not by non-STUN datagrams, not by unauthenticated
3187        // indications, and not by the peer's own requests, which say the peer is there but not
3188        // that it still wants our traffic.
3189        let last_consent = remote.last_consent().unwrap_or(self.start_time);
3190        let since_consent = now.saturating_duration_since(last_consent);
3191
3192        // Disconnected: a consent request has gone unanswered for `disconnected_timeout`.
3193        // (Consent requests are at least 4 seconds apart, so "no response for 5 seconds" alone
3194        // would be true between two answered requests.) With keepalives off nothing is ever
3195        // asked, and the time since the last response decides.
3196        let unanswered = if self.keepalive_interval == ZERO_DURATION {
3197            since_consent
3198        } else {
3199            self.consent_unanswered_since
3200                .map(|since| now.saturating_duration_since(since))
3201                .unwrap_or(ZERO_DURATION)
3202        };
3203
3204        if since_consent >= self.consent_expiry() {
3205            self.update_connection_state(Some(now), ConnectionState::Failed);
3206        } else if self.disconnected_timeout != ZERO_DURATION
3207            && unanswered >= self.disconnected_timeout
3208        {
3209            let was = self.connection_state;
3210            self.update_connection_state(Some(now), ConnectionState::Disconnected);
3211            if was != ConnectionState::Disconnected {
3212                self.fall_back_to_another_nominated_pair(now);
3213            }
3214        } else {
3215            self.update_connection_state(Some(now), self.healthy_state());
3216        }
3217
3218        true
3219    }
3220
3221    /// Sends a STUN Binding request on the selected pair when the consent interval has run
3222    /// out (RFC 7675). Each one is a new transaction, sent once.
3223    pub(crate) fn check_keepalive(&mut self, now: Instant) {
3224        if self.keepalive_interval == ZERO_DURATION {
3225            return;
3226        }
3227        let Some(pair_index) = self.selected_pair else {
3228            return;
3229        };
3230        match self.next_consent_at {
3231            None => self.next_consent_at = Some(now + self.next_consent_interval()),
3232            Some(at) if now >= at => {
3233                self.next_consent_at = Some(now + self.next_consent_interval());
3234                self.consent_unanswered_since.get_or_insert(now);
3235                self.candidate_pairs[pair_index].on_consent_request_sent();
3236                // A consent check is a plain Binding request (RFC 7675 Section 5.1); RFC 8445
3237                // Section 7.1.2 asks for USE-CANDIDATE "in order to nominate a candidate
3238                // pair", which was done. libwebrtc's controlling agent repeats it on every
3239                // check of its selected pair: `nominate_on_consent_checks`.
3240                let use_candidate = self.is_controlling && self.nominate_on_consent_checks;
3241                self.send_check(now, pair_index, use_candidate, true);
3242            }
3243            Some(_) => {}
3244        }
3245    }
3246
3247    /// When the agent next has something to do for its selected pair: send a consent request,
3248    /// notice that one went unanswered, or let consent expire. `None` without a selected pair
3249    /// and for a lite agent, whose timer is the periodic one.
3250    pub(crate) fn selected_pair_deadline(&self) -> Option<Instant> {
3251        let pair_index = self.selected_pair?;
3252        if self.lite {
3253            return None;
3254        }
3255        let remote = &self.remote_candidates[self.candidate_pairs[pair_index].remote_index];
3256        let last_consent = remote.last_consent().unwrap_or(self.start_time);
3257
3258        let mut deadline = last_consent + self.consent_expiry();
3259        if self.keepalive_interval != ZERO_DURATION {
3260            // Before the first `handle_timeout` after selection there is no schedule yet.
3261            deadline = deadline.min(self.next_consent_at.unwrap_or(self.last_checking_time));
3262        }
3263        if self.disconnected_timeout != ZERO_DURATION
3264            && self.connection_state != ConnectionState::Disconnected
3265        {
3266            let unanswered_since = if self.keepalive_interval == ZERO_DURATION {
3267                Some(last_consent)
3268            } else {
3269                self.consent_unanswered_since
3270            };
3271            if let Some(since) = unanswered_since {
3272                deadline = deadline.min(since + self.disconnected_timeout);
3273            }
3274        }
3275        Some(deadline)
3276    }
3277
3278    /// Consent on the path an ICE restart left in use (RFC 7675 Section 5.1): sends the consent
3279    /// requests of the replaced generation, and retires the path when its consent expires.
3280    pub(crate) fn maintain_previous_generation(&mut self, now: Instant) {
3281        let Some(path) = self.previous_media_path else {
3282            self.previous_generation = None;
3283            return;
3284        };
3285        let expiry = self.consent_expiry();
3286        let interval = self.next_consent_interval();
3287        let (lite, keepalive, controlling, tie_breaker, response_wait) = (
3288            self.lite,
3289            self.keepalive_interval != ZERO_DURATION,
3290            self.is_controlling,
3291            self.tie_breaker,
3292            self.consent_response_wait,
3293        );
3294        let Some(previous) = &mut self.previous_generation else {
3295            return;
3296        };
3297        // The transactions that ended without a response.
3298        previous.pending.retain(|r| r.until > now);
3299
3300        if now.saturating_duration_since(previous.last_consent) >= expiry {
3301            warn!(
3302                "consent expired on the path kept across the ICE restart ({} -> {}): no longer sending on it",
3303                path.local_addr, path.peer_addr
3304            );
3305            self.previous_media_path = None;
3306            self.previous_generation = None;
3307            // The kept path was what made the agent connected through the restart; without it
3308            // and with no pair of the new generation selected, the agent is checking.
3309            if self.selected_pair.is_none() && self.connection_state == ConnectionState::Connected {
3310                self.update_connection_state(Some(now), ConnectionState::Checking);
3311            }
3312            return;
3313        }
3314
3315        if lite || !keepalive || now < previous.next_consent_at {
3316            return;
3317        }
3318        previous.next_consent_at = now + interval;
3319
3320        let username = previous.remote_credentials.ufrag.clone()
3321            + ":"
3322            + previous.local_credentials.ufrag.as_str();
3323        let role: Box<dyn Setter> = if controlling {
3324            Box::new(crate::attributes::control::AttrControlling(tie_breaker))
3325        } else {
3326            Box::new(crate::attributes::control::AttrControlled(tie_breaker))
3327        };
3328        let mut msg = Message::new();
3329        if let Err(err) = msg.build(&[
3330            Box::new(BINDING_REQUEST),
3331            Box::new(TransactionId::new()),
3332            Box::new(Username::new(ATTR_USERNAME, username)),
3333            role,
3334            Box::new(crate::attributes::priority::PriorityAttr(previous.priority)),
3335            Box::new(MessageIntegrity::new_short_term_integrity_with_provider(
3336                previous.remote_credentials.pwd.clone(),
3337                self.crypto_provider.crypto(),
3338            )),
3339            Box::new(FINGERPRINT),
3340        ]) {
3341            error!("{}", err);
3342            return;
3343        }
3344        if previous.pending.len() >= MAX_PREVIOUS_GENERATION_TRANSACTIONS {
3345            previous.pending.remove(0);
3346        }
3347        let wait = consent_response_wait(response_wait, previous.rto.start(now), expiry);
3348        previous.pending.push(PreviousConsentRequest {
3349            transaction_id: msg.transaction_id,
3350            sent: now,
3351            until: now + wait,
3352        });
3353        self.write_outs.push_back(TaggedBytesMut {
3354            now,
3355            transport: TransportContext {
3356                local_addr: path.local_addr,
3357                peer_addr: path.peer_addr,
3358                ecn: None,
3359                transport_protocol: path.transport_protocol,
3360            },
3361            message: BytesMut::from(&msg.raw[..]),
3362        });
3363    }
3364
3365    /// When `maintain_previous_generation` next has something to do.
3366    pub(crate) fn previous_generation_deadline(&self) -> Option<Instant> {
3367        let previous = self.previous_generation.as_ref()?;
3368        self.previous_media_path?;
3369        let expires = previous.last_consent + self.consent_expiry();
3370        if self.lite || self.keepalive_interval == ZERO_DURATION {
3371            Some(expires)
3372        } else {
3373            Some(expires.min(previous.next_consent_at))
3374        }
3375    }
3376
3377    /// STUN on the path an ICE restart left in use that belongs to the replaced generation:
3378    /// the peer's consent requests, which name the old local fragment and are answered with
3379    /// the old password, and the responses to ours. Returns whether `msg` was one of them.
3380    pub(crate) fn handle_previous_generation(&mut self, msg: &TaggedBytesMut) -> bool {
3381        let (Some(path), Some(previous)) = (self.previous_media_path, &self.previous_generation)
3382        else {
3383            return false;
3384        };
3385        if msg.transport.local_addr != path.local_addr
3386            || msg.transport.peer_addr != path.peer_addr
3387            || msg.transport.transport_protocol != path.transport_protocol
3388            || !is_stun_message(&msg.message)
3389        {
3390            return false;
3391        }
3392        let mut m = Message {
3393            raw: msg.message.to_vec(),
3394            ..Message::default()
3395        };
3396        if m.decode().is_err() || m.typ.method != METHOD_BINDING {
3397            return false;
3398        }
3399
3400        if m.typ.class == CLASS_REQUEST {
3401            if assert_inbound_username(&m, &previous.local_credentials.ufrag).is_err()
3402                || assert_inbound_message_integrity(
3403                    &mut m,
3404                    previous.local_credentials.pwd.as_bytes(),
3405                    self.crypto_provider.crypto(),
3406                )
3407                .is_err()
3408            {
3409                return false;
3410            }
3411            let mut out = Message::new();
3412            if let Err(err) = out.build(&[
3413                Box::new(m.clone()),
3414                Box::new(BINDING_SUCCESS),
3415                Box::new(XorMappedAddress {
3416                    ip: path.peer_addr.ip(),
3417                    port: path.peer_addr.port(),
3418                }),
3419                Box::new(MessageIntegrity::new_short_term_integrity_with_provider(
3420                    previous.local_credentials.pwd.clone(),
3421                    self.crypto_provider.crypto(),
3422                )),
3423                Box::new(FINGERPRINT),
3424            ]) {
3425                error!("{}", err);
3426                return true;
3427            }
3428            self.write_outs.push_back(TaggedBytesMut {
3429                now: msg.now,
3430                transport: TransportContext {
3431                    local_addr: path.local_addr,
3432                    peer_addr: path.peer_addr,
3433                    ecn: None,
3434                    transport_protocol: path.transport_protocol,
3435                },
3436                message: BytesMut::from(&out.raw[..]),
3437            });
3438            if self.lite
3439                && let Some(previous) = &mut self.previous_generation
3440            {
3441                previous.last_consent = msg.now;
3442            }
3443            return true;
3444        }
3445
3446        if m.typ.class == CLASS_SUCCESS_RESPONSE || m.typ.class == CLASS_ERROR_RESPONSE {
3447            // Matched by transaction id, to a transaction that is still in progress (RFC
3448            // 8489 Section 6.3).
3449            let Some(position) = previous
3450                .pending
3451                .iter()
3452                .position(|r| r.transaction_id == m.transaction_id && r.until > msg.now)
3453            else {
3454                return false;
3455            };
3456            if assert_inbound_message_integrity(
3457                &mut m,
3458                previous.remote_credentials.pwd.as_bytes(),
3459                self.crypto_provider.crypto(),
3460            )
3461            .is_err()
3462            {
3463                // Claims to answer our transaction but is not signed by the peer: dropped.
3464                return true;
3465            }
3466            let is_success = m.typ.class == CLASS_SUCCESS_RESPONSE;
3467            if is_success && !m.contains(stun::attributes::ATTR_XORMAPPED_ADDRESS) {
3468                // RFC 8489 Section 6.3.3: a Binding success response without
3469                // XOR-MAPPED-ADDRESS fails the client's checks; discarded, no consent.
3470                return true;
3471            }
3472            if let Some(previous) = &mut self.previous_generation {
3473                let request = previous.pending.remove(position);
3474                if is_success {
3475                    previous.last_consent = msg.now;
3476                    // Each consent request is sent once: its response gives the round trip.
3477                    previous
3478                        .rto
3479                        .sample(msg.now.saturating_duration_since(request.sent), msg.now);
3480                }
3481            }
3482            return true;
3483        }
3484
3485        false
3486    }
3487
3488    pub(crate) fn request_connectivity_check(&mut self) {
3489        // Defer the connectivity check to `handle_timeout` instead of running it
3490        // inline. Running `contact()` here is re-entrant: it can advance the state
3491        // to `Failed`, which calls `delete_all_candidates()` and wipes the candidate
3492        // and pair vectors while a caller still holds indices into them (for example
3493        // `handle_inbound` while adding a peer-reflexive candidate). See issue #88.
3494        self.force_candidate_contact = true;
3495    }
3496
3497    /// Remove all candidates.
3498    /// This closes any listening sockets and removes both the local and remote candidate lists.
3499    ///
3500    /// This is used for restarts, failures and on close.
3501    pub(crate) fn delete_all_candidates(&mut self, keep_local_candidates: bool) {
3502        if !keep_local_candidates {
3503            self.local_candidates.clear();
3504        } else {
3505            // What the agent learned from the mapped addresses of the old generation's
3506            // responses goes with that generation.
3507            self.local_candidates
3508                .retain(|c| c.candidate_type() != CandidateType::PeerReflexive);
3509        }
3510        self.remote_candidates.clear();
3511        self.unpaired_remotes.clear();
3512        self.triggered_queue.clear();
3513
3514        // Candidate pairs reference candidates by index, so once the candidates are
3515        // removed every pair - and the `selected_pair`/`nominated_pair` indices into
3516        // the pair list - is dangling and must be dropped to avoid out-of-bounds
3517        // access. `remote_candidates` is always cleared here, so no pair can remain
3518        // valid even when the local candidates are kept. See issue #88.
3519        self.announce_all_pairs_removed();
3520        self.candidate_pairs = Vec::new();
3521        self.selected_pair = None;
3522        self.nominated_pair = None;
3523        self.nomination_proposal = None;
3524        self.declined_nominations.clear();
3525    }
3526
3527    pub(crate) fn find_remote_candidate(&self, addr: SocketAddr) -> Option<usize> {
3528        for (index, c) in self.remote_candidates.iter().enumerate() {
3529            if c.addr() == addr {
3530                return Some(index);
3531            }
3532        }
3533        None
3534    }
3535
3536    /// The local candidate a datagram that arrived on `addr` belongs to.
3537    ///
3538    /// RFC 8445 Section 7.3.1.4: "The local candidate will be either a host candidate [...] or
3539    /// a relayed candidate [...]. The local candidate can never be a server-reflexive
3540    /// candidate." A reflexive candidate is returned only when the application never added
3541    /// the host candidate that is its base.
3542    pub(crate) fn find_local_candidate(
3543        &self,
3544        addr: SocketAddr,
3545        transport_protocol: TransportProtocol,
3546    ) -> Option<usize> {
3547        // An exact address match wins over the TCP active candidates' IP-only match: a
3548        // connection accepted on a passive candidate arrives on that candidate's own address,
3549        // and must not be credited to an active candidate on the same IP that happens to be
3550        // listed first.
3551        let mut active_on_ip = None;
3552        let mut reflexive_on_base = None;
3553        for (index, c) in self.local_candidates.iter().enumerate() {
3554            if c.network_type().to_protocol() != transport_protocol {
3555                continue;
3556            }
3557            let reflexive = matches!(
3558                c.candidate_type(),
3559                CandidateType::ServerReflexive | CandidateType::PeerReflexive
3560            );
3561
3562            // TCP active candidates use port 9 as a placeholder in signalling, but each
3563            // connection they open has its own ephemeral port: they match by IP alone.
3564            if c.tcp_type() == TcpType::Active && transport_protocol == TransportProtocol::TCP {
3565                if active_on_ip.is_none() && !reflexive && c.addr().ip() == addr.ip() {
3566                    active_on_ip = Some(index);
3567                }
3568            } else if reflexive {
3569                if reflexive_on_base.is_none()
3570                    && c.candidate_type() == CandidateType::ServerReflexive
3571                    && c.related_address().is_some_and(|related| {
3572                        related.address == addr.ip().to_string() && related.port == addr.port()
3573                    })
3574                {
3575                    reflexive_on_base = Some(index);
3576                }
3577            } else if c.addr() == addr {
3578                return Some(index);
3579            }
3580        }
3581        active_on_ip.or(reflexive_on_base)
3582    }
3583
3584    /// Answers the Binding request `m`, which arrived on `local_index` from `remote_addr`, with
3585    /// a success response: XOR-MAPPED-ADDRESS is the request's source (RFC 8445 Section
3586    /// 7.3.1.2), MESSAGE-INTEGRITY uses the local password, FINGERPRINT closes it.
3587    pub(crate) fn send_binding_success(
3588        &mut self,
3589        now: Instant,
3590        m: &Message,
3591        local_index: usize,
3592        remote_addr: SocketAddr,
3593    ) {
3594        let (ip, port) = (remote_addr.ip(), remote_addr.port());
3595
3596        let (out, result) = {
3597            let mut out = Message::new();
3598            let result = self.answer_integrity_setter().and_then(|integrity| {
3599                let mut setters: Vec<Box<dyn Setter + '_>> = vec![
3600                    Box::new(m.clone()),
3601                    Box::new(BINDING_SUCCESS),
3602                    Box::new(XorMappedAddress { ip, port }),
3603                ];
3604                // RFC 8489 Section 6.3.1.1: a success response SHOULD carry SOFTWARE.
3605                if let Some(software) = &self.software {
3606                    setters.push(Box::new(Software::new(ATTR_SOFTWARE, software.clone())));
3607                }
3608                setters.push(integrity);
3609                setters.push(Box::new(FINGERPRINT));
3610                out.build(&setters)
3611            });
3612            (out, result)
3613        };
3614
3615        if let Err(err) = result {
3616            warn!(
3617                "[{}]: Failed to handle inbound ICE from: {} to: {} error: {}",
3618                self.get_name(),
3619                self.local_candidates[local_index],
3620                remote_addr,
3621                err
3622            );
3623        } else {
3624            // Track response sent on the candidate pair
3625            if let Some(remote_index) = self.find_remote_candidate(remote_addr)
3626                && let Some(pair_index) = self.find_pair(local_index, remote_index)
3627            {
3628                self.candidate_pairs[pair_index].on_response_sent();
3629            }
3630            self.send_stun_to(now, &out, local_index, remote_addr);
3631        }
3632    }
3633
3634    /// The integrity attribute of a response to the request being answered, with the local
3635    /// password: MESSAGE-INTEGRITY-SHA256 when the request was authenticated by one, else
3636    /// MESSAGE-INTEGRITY (RFC 8489 Section 9.1.3: "A response to a request that contains
3637    /// a MESSAGE-INTEGRITY-SHA256 attribute MUST include the MESSAGE-INTEGRITY-SHA256
3638    /// attribute [...] only one of these attributes can appear in a response").
3639    fn answer_integrity_setter(&self) -> Result<Box<dyn Setter + '_>> {
3640        let local_pwd = self.ufrag_pwd.local_credentials.pwd.clone();
3641        let crypto = self.crypto_provider.crypto();
3642        Ok(match self.answer_integrity {
3643            IntegrityAlgorithm::Sha1 => Box::new(
3644                MessageIntegrity::new_short_term_integrity_with_provider(local_pwd, crypto),
3645            ),
3646            IntegrityAlgorithm::Sha256 => {
3647                Box::new(MessageIntegritySha256::short_term(&local_pwd, crypto)?)
3648            }
3649        })
3650    }
3651
3652    /// Sends a 487 (Role Conflict) error response.
3653    /// RFC 8445 Section 7.3.1.1
3654    pub(crate) fn send_role_conflict_error(
3655        &mut self,
3656        now: Instant,
3657        m: &Message,
3658        local_index: usize,
3659        remote_addr: SocketAddr,
3660    ) {
3661        use stun::error_code::*;
3662
3663        let (out, result) = {
3664            let mut out = Message::new();
3665            let result = self.answer_integrity_setter().and_then(|integrity| {
3666                out.build(&[
3667                    Box::new(m.clone()),
3668                    Box::new(stun::message::BINDING_ERROR),
3669                    Box::new(CODE_ROLE_CONFLICT),
3670                    integrity,
3671                    Box::new(FINGERPRINT),
3672                ])
3673            });
3674            (out, result)
3675        };
3676
3677        if let Err(err) = result {
3678            warn!(
3679                "[{}]: Failed to send role conflict error from: {} to: {} error: {}",
3680                self.get_name(),
3681                self.local_candidates[local_index],
3682                remote_addr,
3683                err
3684            );
3685        } else {
3686            debug!(
3687                "[{}]: Sent 487 Role Conflict error from {} to {}",
3688                self.get_name(),
3689                self.local_candidates[local_index],
3690                remote_addr
3691            );
3692            self.send_stun_to(now, &out, local_index, remote_addr);
3693        }
3694    }
3695
3696    /// Answers a request that carries unknown comprehension-required attributes with a 420
3697    /// (Unknown Attribute) error response listing them (RFC 8489 Section 6.3.1), signed like
3698    /// every response.
3699    fn send_unknown_attributes_error(
3700        &mut self,
3701        now: Instant,
3702        m: &Message,
3703        unknown: &[AttrType],
3704        local_index: usize,
3705        remote_addr: SocketAddr,
3706    ) {
3707        let response = self.answer_integrity_setter().and_then(|integrity| {
3708            stun::validated::unknown_attributes_response(
3709                m,
3710                unknown,
3711                &[integrity, Box::new(FINGERPRINT)],
3712            )
3713        });
3714        match response {
3715            Ok(out) => self.send_stun_to(now, &out, local_index, remote_addr),
3716            Err(err) => warn!(
3717                "[{}]: cannot build the 420 response for {}: {}",
3718                self.get_name(),
3719                remote_addr,
3720                err
3721            ),
3722        }
3723    }
3724
3725    /// Switches the ICE agent role and recomputes all candidate pair priorities.
3726    /// RFC 8445 Section 7.3.1.1
3727    pub(crate) fn switch_role(&mut self, now: Instant) {
3728        self.is_controlling = !self.is_controlling;
3729
3730        // Recompute priorities for all candidate pairs
3731        // The priority calculation depends on ice_role_controlling
3732        for pair in &mut self.candidate_pairs {
3733            pair.ice_role_controlling = self.is_controlling;
3734        }
3735
3736        // Clear nominated pair when switching roles: only the controlling agent nominates.
3737        self.nominated_pair = None;
3738        self.nomination_proposal = None;
3739        self.declined_nominations.clear();
3740        for pair in &mut self.candidate_pairs {
3741            pair.nominate = false;
3742        }
3743
3744        info!(
3745            "[{}]: Role switched, recomputed {} candidate pair priorities",
3746            self.get_name(),
3747            self.candidate_pairs.len()
3748        );
3749
3750        self.event_outs.push_back(TaggedEvent {
3751            now,
3752            event: Event::RoleChange(self.is_controlling),
3753        });
3754    }
3755
3756    /// RFC 8445 Section 7.3.1.1, Detecting and Repairing Role Conflicts, for an authenticated
3757    /// Binding request. Returns `true` when the request must be answered with a 487 (Role
3758    /// Conflict) error response and nothing else; otherwise the agent has kept or switched its
3759    /// role and the request is processed as usual.
3760    fn detect_role_conflict(&mut self, now: Instant, m: &Message) -> Result<bool> {
3761        if self.is_controlling {
3762            if m.contains(ATTR_ICE_CONTROLLING) {
3763                let mut remote = crate::attributes::control::AttrControlling::default();
3764                remote.get_from(m)?;
3765                debug!(
3766                    "[{}]: Role conflict detected (both controlling), local tiebreaker: {}, remote tiebreaker: {}",
3767                    self.get_name(),
3768                    self.tie_breaker,
3769                    remote.0
3770                );
3771                // "If the agent's tiebreaker value is larger than or equal to the contents of
3772                // the ICE-CONTROLLING attribute, the agent generates a Binding error response
3773                // and includes an ERROR-CODE attribute with a value of 487 (Role Conflict) but
3774                // retains its role."
3775                if self.tie_breaker >= remote.0 {
3776                    return Ok(true);
3777                }
3778                // "If the agent's tiebreaker value is less than the contents of the
3779                // ICE-CONTROLLING attribute, the agent switches to the controlled role."
3780                self.switch_role(now);
3781            } else if m.contains(ATTR_USE_CANDIDATE) {
3782                // USE-CANDIDATE only has meaning on the controlled side (RFC 8445 7.3.1.5), and
3783                // role conflicts are decided by ICE-CONTROLLING/ICE-CONTROLLED alone. Like
3784                // libwebrtc, ignore it and answer the check.
3785                debug!(
3786                    "[{}]: USE-CANDIDATE without ICE-CONTROLLING while controlling; ignoring USE-CANDIDATE and answering the check",
3787                    self.get_name(),
3788                );
3789            }
3790        } else if m.contains(ATTR_ICE_CONTROLLED) {
3791            let mut remote = crate::attributes::control::AttrControlled::default();
3792            remote.get_from(m)?;
3793            debug!(
3794                "[{}]: Role conflict detected (both controlled), local tiebreaker: {}, remote tiebreaker: {}",
3795                self.get_name(),
3796                self.tie_breaker,
3797                remote.0
3798            );
3799            // "If the agent's tiebreaker value is larger than or equal to the contents of the
3800            // ICE-CONTROLLED attribute, the agent switches to the controlling role."
3801            if self.tie_breaker >= remote.0 {
3802                self.switch_role(now);
3803            } else {
3804                // "... less than ...: the agent generates a Binding error response and
3805                // includes an ERROR-CODE attribute with a value of 487 (Role Conflict) but
3806                // retains its role."
3807                return Ok(true);
3808            }
3809        }
3810
3811        Ok(false)
3812    }
3813
3814    pub(crate) fn handle_inbound(
3815        &mut self,
3816        now: Instant,
3817        m: &mut Message,
3818        local_index: usize,
3819        remote_addr: SocketAddr,
3820    ) -> Result<()> {
3821        if m.typ.method != METHOD_BINDING
3822            || !(m.typ.class == CLASS_SUCCESS_RESPONSE
3823                || m.typ.class == CLASS_ERROR_RESPONSE
3824                || m.typ.class == CLASS_REQUEST
3825                || m.typ.class == CLASS_INDICATION)
3826        {
3827            trace!(
3828                "[{}]: unhandled STUN from {} to {} class({}) method({})",
3829                self.get_name(),
3830                remote_addr,
3831                self.local_candidates[local_index],
3832                m.typ.class,
3833                m.typ.method
3834            );
3835            return Err(Error::ErrUnhandledStunpacket);
3836        }
3837
3838        if m.typ.class == CLASS_REQUEST {
3839            return self.handle_inbound_request(now, m, local_index, remote_addr);
3840        }
3841
3842        let Some(remote_credentials) = &self.ufrag_pwd.remote_credentials else {
3843            debug!(
3844                "[{}]: ufrag_pwd.remote_credentials.is_none",
3845                self.get_name(),
3846            );
3847            return Err(Error::ErrPasswordEmpty);
3848        };
3849
3850        let remote_candidate_index = self.find_remote_candidate(remote_addr);
3851        if m.typ.class == CLASS_SUCCESS_RESPONSE || m.typ.class == CLASS_ERROR_RESPONSE {
3852            // A response: FINGERPRINT when present, MESSAGE-INTEGRITY with the peer's
3853            // password, no unknown comprehension-required attribute, or it is discarded (RFC
3854            // 8489 Sections 6.3.3 and 9.1.4). Only what the integrity covers is read.
3855            //
3856            // The agent's requests carry MESSAGE-INTEGRITY only, so a response is checked by
3857            // that attribute only (RFC 8489 Section 9.1.4: "the algorithm in the response has
3858            // to match; otherwise, the response MUST be discarded"), and so is every later
3859            // transaction with the peer (Section 9.1.5).
3860            let known = ice_known_attributes();
3861            match stun::validated::Validator::new()
3862                .known_attributes(&known)
3863                .authenticate_with(
3864                    m,
3865                    IntegrityAlgorithm::Sha1,
3866                    remote_credentials.pwd.as_bytes(),
3867                    self.crypto_provider.crypto(),
3868                ) {
3869                Ok(valid) => *m = valid.into_message(),
3870                Err(rejection) => {
3871                    warn!(
3872                        "[{}]: discard message from ({}), {}",
3873                        self.get_name(),
3874                        remote_addr,
3875                        rejection
3876                    );
3877                    if !matches!(rejection, stun::validated::Rejection::UnknownAttributes(_)) {
3878                        self.note_unauthentic_response(m.transaction_id);
3879                    }
3880                    // RFC 8489 Section 6.3.4: an (authenticated) error response with unknown
3881                    // comprehension-required attributes means the transaction failed. (A
3882                    // success response with them is discarded, Section 6.3.3, and the
3883                    // transaction goes on.)
3884                    if m.typ.class == CLASS_ERROR_RESPONSE
3885                        && matches!(rejection, stun::validated::Rejection::UnknownAttributes(_))
3886                    {
3887                        self.handle_failed_transaction(now, m.transaction_id, remote_addr);
3888                    }
3889                    return Err(rejection_error(&rejection));
3890                }
3891            }
3892
3893            // A response is matched to its request by transaction id (RFC 8445 Section
3894            // 7.2.5); where it came from is then checked against where the request went.
3895            if m.typ.class == CLASS_SUCCESS_RESPONSE {
3896                self.handle_success_response(now, m, local_index, remote_addr);
3897            } else {
3898                self.handle_error_response(now, m, remote_addr);
3899            }
3900
3901            if remote_candidate_index.is_none() {
3902                warn!(
3903                    "[{}]: discard response from ({}), no such remote",
3904                    self.get_name(),
3905                    remote_addr
3906                );
3907                return Err(Error::ErrUnhandledStunpacket);
3908            }
3909        }
3910
3911        // RFC 8489 Section 6.3.2: an indication (a lite peer's keepalive) with unknown
3912        // comprehension-required attributes, or a wrong FINGERPRINT, is discarded.
3913        if m.typ.class == CLASS_INDICATION
3914            && let Err(rejection) = stun::validated::Validator::new()
3915                .known_attributes(&ice_known_attributes())
3916                .unauthenticated(m)
3917        {
3918            debug!(
3919                "[{}]: discard indication from ({}), {}",
3920                self.get_name(),
3921                remote_addr,
3922                rejection
3923            );
3924            return Err(rejection_error(&rejection));
3925        }
3926
3927        if let Some(remote) = remote_candidate_index.and_then(|i| self.remote_candidates.get_mut(i))
3928        {
3929            remote.seen(now, false);
3930            // Responses reaching here passed MESSAGE-INTEGRITY; indications did not and carry
3931            // none.
3932            if m.typ.class != CLASS_INDICATION {
3933                remote.last_authenticated = Some(now);
3934            }
3935        }
3936
3937        Ok(())
3938    }
3939
3940    /// A Binding request (RFC 8445 Section 7.3): authenticated with the short-term credential,
3941    /// then answered and processed, or, before the peer's credentials are known, answered and
3942    /// remembered.
3943    fn handle_inbound_request(
3944        &mut self,
3945        now: Instant,
3946        m: &mut Message,
3947        local_index: usize,
3948        remote_addr: SocketAddr,
3949    ) -> Result<()> {
3950        // RFC 8489 Sections 6.3 and 9.1.3, through `rtci-stun`'s validator: FINGERPRINT is
3951        // verified when present, MESSAGE-INTEGRITY with the local password, and from here on
3952        // only what the integrity covers is read: USERNAME, the role attributes, PRIORITY,
3953        // USE-CANDIDATE. An attribute appended after it does not exist for the agent.
3954        // The validator verifies MESSAGE-INTEGRITY-SHA256 when the request has it, and the
3955        // answers carry the attribute that was verified (Section 9.1.3).
3956        self.answer_integrity = if m.contains(ATTR_MESSAGE_INTEGRITY_SHA256) {
3957            IntegrityAlgorithm::Sha256
3958        } else {
3959            IntegrityAlgorithm::Sha1
3960        };
3961        let known = ice_known_attributes();
3962        let validated = stun::validated::Validator::new()
3963            .known_attributes(&known)
3964            .authenticate(
3965                m,
3966                self.ufrag_pwd.local_credentials.pwd.as_bytes(),
3967                self.crypto_provider.crypto(),
3968            );
3969        match validated {
3970            Ok(valid) => *m = valid.into_message(),
3971            Err(stun::validated::Rejection::UnknownAttributes(unknown)) => {
3972                // RFC 8489 Section 6.3.1: an authenticated request with a comprehension-
3973                // required attribute the agent does not know is answered 420 with the list.
3974                self.send_unknown_attributes_error(now, m, &unknown, local_index, remote_addr);
3975                return Err(Error::ErrUnhandledStunpacket);
3976            }
3977            Err(rejection) => {
3978                warn!(
3979                    "[{}]: discard message from ({}), {}",
3980                    self.get_name(),
3981                    remote_addr,
3982                    rejection
3983                );
3984                // RFC 8489 Section 9.1.3, in its order: no MESSAGE-INTEGRITY or no USERNAME
3985                // is 400; a username that is not valid here is 401; a MESSAGE-INTEGRITY that
3986                // does not match is 401. (A FINGERPRINT that does not match is not answered:
3987                // the datagram is not STUN for this agent, Section 7.3.)
3988                use stun::error_code::{CODE_BAD_REQUEST, CODE_UNAUTHENTICATED};
3989                use stun::validated::Rejection;
3990                let code = match rejection {
3991                    Rejection::IntegrityMissing => Some(CODE_BAD_REQUEST),
3992                    Rejection::IntegrityMismatch if !m.contains(ATTR_USERNAME) => {
3993                        Some(CODE_BAD_REQUEST)
3994                    }
3995                    Rejection::IntegrityMismatch => Some(CODE_UNAUTHENTICATED),
3996                    _ => None,
3997                };
3998                if let Some(code) = code {
3999                    self.reject_unauthenticated_request(now, m, code, local_index, remote_addr);
4000                }
4001                return Err(rejection_error(&rejection));
4002            }
4003        }
4004        if let Err(err) = assert_inbound_username(m, &self.ufrag_pwd.local_credentials.ufrag) {
4005            warn!(
4006                "[{}]: discard message from ({}), {}",
4007                self.get_name(),
4008                remote_addr,
4009                err
4010            );
4011            // The integrity matched, so the sender holds the password: the username is
4012            // absent (400) or not this agent's (401).
4013            let code = if m.contains(ATTR_USERNAME) {
4014                stun::error_code::CODE_UNAUTHENTICATED
4015            } else {
4016                stun::error_code::CODE_BAD_REQUEST
4017            };
4018            self.reject_unauthenticated_request(now, m, code, local_index, remote_addr);
4019            return Err(err);
4020        }
4021
4022        if self.ufrag_pwd.remote_credentials.is_none() {
4023            // RFC 8445 Section 7.3: "it is possible (and in fact very likely) that the
4024            // initiating agent will receive a Binding request prior to receiving the candidates
4025            // from its peer. If this happens, the agent MUST immediately generate a response
4026            // [...] Once the answer is received, it MUST proceed with the remaining steps."
4027            // A source the destination policy refuses is not answered, now or later. Nor is
4028            // one the embedder's address policy would refuse as a peer-reflexive candidate
4029            // (what the source of a request from no known candidate becomes, Section 7.3.1.3,
4030            // once the credentials are here): answered now, it would have its answer, and its
4031            // reflexive address in it, before the policy was ever asked about it.
4032            if !self.remote_policy.allows_candidate(remote_addr)
4033                || (self.find_remote_candidate(remote_addr).is_none()
4034                    && !self
4035                        .remote_policy
4036                        .address
4037                        .allows(remote_addr, AddressPurpose::PeerReflexiveSource))
4038            {
4039                return Err(Error::ErrUnhandledStunpacket);
4040            }
4041            self.send_binding_success(now, m, local_index, remote_addr);
4042            self.remember_early_request(m, local_index, remote_addr);
4043            return Ok(());
4044        }
4045
4046        self.process_binding_request(now, m, local_index, remote_addr, true)
4047    }
4048
4049    /// Answers a Binding request that failed the short-term credential check with `code` (400
4050    /// or 401, RFC 8489 Section 9.1.3), unless the agent is set to drop such requests.
4051    ///
4052    /// The source of such a request is unverified, so the answer must be of no use to someone
4053    /// who forged it: the response carries the error code and FINGERPRINT only (no reason
4054    /// phrase, and no MESSAGE-INTEGRITY: there is no key the two share), it is sent only when
4055    /// it is no longer than the request, and at most [`MAX_UNAUTHENTICATED_RESPONSE_BURST`]
4056    /// of them go out in a burst, one more per [`UNAUTHENTICATED_RESPONSE_INTERVAL`]. Past
4057    /// that the request is dropped.
4058    fn reject_unauthenticated_request(
4059        &mut self,
4060        now: Instant,
4061        m: &Message,
4062        code: stun::error_code::ErrorCode,
4063        local_index: usize,
4064        remote_addr: SocketAddr,
4065    ) {
4066        if self.unauthenticated_requests == UnauthenticatedRequests::Drop
4067            || !self.remote_policy.allows_candidate(remote_addr)
4068            || !self
4069                .remote_policy
4070                .allows_pair(self.local_candidates[local_index].base_addr(), remote_addr)
4071        {
4072            return;
4073        }
4074        // The token bucket: one token per interval since the last refill, up to the burst.
4075        let elapsed = now.saturating_duration_since(self.unauthenticated_response_refill);
4076        let earned = elapsed.as_nanos() / UNAUTHENTICATED_RESPONSE_INTERVAL.as_nanos();
4077        if earned > 0 {
4078            let earned = u32::try_from(earned).unwrap_or(u32::MAX);
4079            self.unauthenticated_response_tokens = self
4080                .unauthenticated_response_tokens
4081                .saturating_add(earned)
4082                .min(MAX_UNAUTHENTICATED_RESPONSE_BURST);
4083            self.unauthenticated_response_refill = if self.unauthenticated_response_tokens
4084                == MAX_UNAUTHENTICATED_RESPONSE_BURST
4085            {
4086                now
4087            } else {
4088                self.unauthenticated_response_refill + UNAUTHENTICATED_RESPONSE_INTERVAL * earned
4089            };
4090        }
4091        if self.unauthenticated_response_tokens == 0 {
4092            return;
4093        }
4094
4095        let mut out = Message::new();
4096        let built = out.build(&[
4097            Box::new(MessageType::new(METHOD_BINDING, CLASS_ERROR_RESPONSE)),
4098            Box::new(m.transaction_id),
4099            Box::new(stun::error_code::ErrorCodeAttribute {
4100                code,
4101                reason: vec![],
4102            }),
4103            Box::new(FINGERPRINT),
4104        ]);
4105        if let Err(err) = built {
4106            warn!(
4107                "[{}]: cannot build the {} response for {}: {}",
4108                self.get_name(),
4109                code.0,
4110                remote_addr,
4111                err
4112            );
4113            return;
4114        }
4115        if out.raw.len() > m.raw.len() {
4116            // Never more bytes out than came in.
4117            return;
4118        }
4119        self.unauthenticated_response_tokens -= 1;
4120        self.send_stun_to(now, &out, local_index, remote_addr);
4121    }
4122
4123    fn remember_early_request(&mut self, m: &Message, local_index: usize, remote_addr: SocketAddr) {
4124        use crate::attributes::nomination::nomination_of;
4125
4126        let local = &self.local_candidates[local_index];
4127        let request = EarlyRequest {
4128            message: m.clone(),
4129            // What the datagram arrived on is the candidate's base.
4130            local_addr: local.base_addr(),
4131            transport_protocol: local.network_type().to_protocol(),
4132            remote_addr,
4133        };
4134        if let Some(known) = self.early_requests.iter_mut().find(|r| {
4135            r.local_addr == request.local_addr
4136                && r.transport_protocol == request.transport_protocol
4137                && r.remote_addr == remote_addr
4138        }) {
4139            // One entry per path; a nomination is not forgotten for a later plain check.
4140            if nomination_of(&request.message) >= nomination_of(&known.message) {
4141                *known = request;
4142            }
4143        } else if self.early_requests.len() < MAX_EARLY_REQUESTS {
4144            self.early_requests.push(request);
4145        }
4146    }
4147
4148    /// Runs RFC 8445 Sections 7.3.1.3 to 7.3.1.5 for the requests that were answered before the
4149    /// peer's credentials arrived.
4150    pub(crate) fn process_early_requests(&mut self, now: Instant) {
4151        if self.ufrag_pwd.remote_credentials.is_none() {
4152            return;
4153        }
4154        for request in std::mem::take(&mut self.early_requests) {
4155            let Some(local_index) =
4156                self.find_local_candidate(request.local_addr, request.transport_protocol)
4157            else {
4158                continue;
4159            };
4160            let _ = self.process_binding_request(
4161                now,
4162                &request.message,
4163                local_index,
4164                request.remote_addr,
4165                false,
4166            );
4167        }
4168    }
4169
4170    /// Processes an authenticated Binding request: role conflict (Section 7.3.1.1), the
4171    /// response (7.3.1.2), a peer-reflexive remote candidate (7.3.1.3), the triggered check
4172    /// (7.3.1.4) and the nominated flag (7.3.1.5). `respond` is false for a request that was
4173    /// answered when it arrived, before the peer's credentials were known.
4174    fn process_binding_request(
4175        &mut self,
4176        now: Instant,
4177        m: &Message,
4178        local_index: usize,
4179        remote_addr: SocketAddr,
4180        respond: bool,
4181    ) -> Result<()> {
4182        // Role conflicts are acted on only for a request that passed the username and
4183        // MESSAGE-INTEGRITY checks: an unauthenticated datagram must not be able to flip our
4184        // ICE role, re-prioritise every pair and clear the nomination. A request that gets the
4185        // 487 gets nothing else: no success response, no candidate, no triggered check.
4186        if respond && self.detect_role_conflict(now, m)? {
4187            self.send_role_conflict_error(now, m, local_index, remote_addr);
4188            // A peer that claimed the controlling role holds no nomination of ours: it was
4189            // not the controlled agent. If this agent, which keeps the controlling role, has
4190            // concluded, its nomination is lost on the peer (a peer that lost its state
4191            // without an ICE restart), and nothing else would bring it back: the pair is
4192            // nominated again, the same one (RFC 8445 Section 8.1.1: "the agent MUST NOT
4193            // nominate another pair").
4194            if self.is_controlling {
4195                self.repeat_nomination();
4196            }
4197            return Ok(());
4198        }
4199
4200        let mut remote_candidate_index = self.find_remote_candidate(remote_addr);
4201        if remote_candidate_index.is_none() {
4202            remote_candidate_index =
4203                self.add_peer_reflexive_remote_candidate(m, local_index, remote_addr)?;
4204            if remote_candidate_index.is_some() {
4205                debug!(
4206                    "[{}]: adding a new peer-reflexive candidate: {} ",
4207                    self.get_name(),
4208                    remote_addr
4209                );
4210            }
4211        }
4212
4213        trace!(
4214            "[{}]: inbound STUN (Request) from {} to {}",
4215            self.get_name(),
4216            remote_addr,
4217            self.local_candidates[local_index]
4218        );
4219
4220        let Some(remote_index) = remote_candidate_index else {
4221            return Ok(());
4222        };
4223
4224        // RFC 8445 Section 7.3.1.4: the pair is (the local candidate the request arrived on,
4225        // its source); a pair that is not on the checklist is added to it.
4226        if self.find_pair(local_index, remote_index).is_none() {
4227            self.add_pair(local_index, remote_index);
4228        }
4229        if self.find_pair(local_index, remote_index).is_none() {
4230            // The checklist is full of better pairs, but this one the peer is checking: it
4231            // takes the place of the worst pair that has not been checked.
4232            self.add_triggered_pair(local_index, remote_index);
4233        }
4234        if let Some(pair_index) = self.find_pair(local_index, remote_index) {
4235            self.candidate_pairs[pair_index].on_request_received();
4236            // An authenticated request is answered whatever the pair's state (unless the
4237            // destination policy refused the pair).
4238            if respond {
4239                self.send_binding_success(now, m, local_index, remote_addr);
4240            }
4241            self.handle_binding_request(now, m, local_index, remote_index);
4242        }
4243
4244        if let Some(remote) = self.remote_candidates.get_mut(remote_index) {
4245            remote.seen(now, false);
4246            remote.last_authenticated = Some(now);
4247        }
4248
4249        Ok(())
4250    }
4251
4252    /// RFC 8445 Section 7.3.1.3: the source of an authenticated request that is no known remote
4253    /// candidate becomes a peer-reflexive one. Its priority is the request's PRIORITY
4254    /// attribute, its component that of the local candidate the request arrived on, and it is
4255    /// paired with that local candidate only (the caller does that).
4256    fn add_peer_reflexive_remote_candidate(
4257        &mut self,
4258        m: &Message,
4259        local_index: usize,
4260        remote_addr: SocketAddr,
4261    ) -> Result<Option<usize>> {
4262        use crate::attributes::priority::PriorityAttr;
4263
4264        if self.remote_candidates.len() >= MAX_REMOTE_CANDIDATES {
4265            warn!(
4266                "[{}]: ignoring peer-reflexive candidate {}: already holding {} (the cap)",
4267                self.get_name(),
4268                remote_addr,
4269                MAX_REMOTE_CANDIDATES
4270            );
4271            return Ok(None);
4272        }
4273        if !self
4274            .remote_policy
4275            .allows_remote(remote_addr, AddressPurpose::PeerReflexiveSource)
4276        {
4277            warn!(
4278                "[{}]: ignoring peer-reflexive candidate {}: not an allowed destination",
4279                self.get_name(),
4280                remote_addr
4281            );
4282            return Ok(None);
4283        }
4284
4285        // Use the local candidate's network type for the peer-reflexive candidate
4286        let network_type = self.local_candidates[local_index].network_type();
4287        if !self.network_types.is_empty() && !self.network_types.contains(&network_type) {
4288            return Ok(None);
4289        }
4290
4291        // A request without PRIORITY (or with one outside 1..2^31-1) is not refused: the
4292        // candidate then gets the priority this agent would compute for it.
4293        let mut priority = PriorityAttr::default();
4294        let priority = match priority.get_from(m) {
4295            Ok(()) if (1..=MAX_CANDIDATE_PRIORITY).contains(&priority.0) => priority.0,
4296            _ => 0,
4297        };
4298
4299        let prflx_candidate_config = CandidatePeerReflexiveConfig {
4300            base_config: CandidateConfig {
4301                network: network_type.to_string(),
4302                address: remote_addr.ip().to_string(),
4303                port: remote_addr.port(),
4304                component: self.local_candidates[local_index].component(),
4305                priority,
4306                ..CandidateConfig::default()
4307            },
4308            rel_addr: "".to_owned(),
4309            rel_port: 0,
4310        };
4311
4312        let mut prflx_candidate = match prflx_candidate_config.new_candidate_peer_reflexive() {
4313            Ok(c) => c,
4314            Err(err) => {
4315                error!(
4316                    "[{}]: Failed to create new remote prflx candidate ({})",
4317                    self.get_name(),
4318                    err
4319                );
4320                return Err(err);
4321            }
4322        };
4323        // RFC 6544 §7: a peer-reflexive candidate learned over TCP takes the TCP type that
4324        // pairs with the local candidate the check arrived on (a check on our passive
4325        // candidate comes from an active one), or it could never form a pair and the
4326        // controlling agent would never nominate the connection.
4327        prflx_candidate.tcp_type = self.local_candidates[local_index].tcp_type().complement();
4328
4329        self.remote_candidates.push(prflx_candidate);
4330        Ok(Some(self.remote_candidates.len() - 1))
4331    }
4332
4333    // Processes non STUN traffic from a remote candidate, and returns true if it is an actual
4334    // remote candidate.
4335    pub(crate) fn validate_non_stun_traffic(
4336        &mut self,
4337        now: Instant,
4338        remote_addr: SocketAddr,
4339    ) -> bool {
4340        self.find_remote_candidate(remote_addr)
4341            .is_some_and(|remote_index| {
4342                self.remote_candidates[remote_index].seen(now, false);
4343                true
4344            })
4345    }
4346
4347    pub(crate) fn send_stun(
4348        &mut self,
4349        now: Instant,
4350        msg: &Message,
4351        local_index: usize,
4352        remote_index: usize,
4353    ) {
4354        let peer_addr = self.remote_candidates[remote_index].addr();
4355        self.send_stun_to(now, msg, local_index, peer_addr);
4356    }
4357
4358    /// Queues `msg` from the local candidate's base to `peer_addr`.
4359    pub(crate) fn send_stun_to(
4360        &mut self,
4361        now: Instant,
4362        msg: &Message,
4363        local_index: usize,
4364        peer_addr: SocketAddr,
4365    ) {
4366        self.send_raw_stun(now, BytesMut::from(&msg.raw[..]), local_index, peer_addr);
4367    }
4368
4369    /// Queues an encoded STUN message from the local candidate's base to `peer_addr`.
4370    pub(crate) fn send_raw_stun(
4371        &mut self,
4372        now: Instant,
4373        message: BytesMut,
4374        local_index: usize,
4375        peer_addr: SocketAddr,
4376    ) {
4377        // RFC 8445 §6.1.2: checks for a (server/peer-)reflexive candidate must
4378        // be sent from its base, the bound local socket the candidate was
4379        // derived from; the mapped address is not a local socket.
4380        let local_addr = self.local_candidates[local_index].base_addr();
4381        let transport_protocol = if self.local_candidates[local_index].network_type().is_tcp() {
4382            TransportProtocol::TCP
4383        } else {
4384            TransportProtocol::UDP
4385        };
4386        // RFC 8489 Section 6.1: "the STUN usage MUST follow the MTU constraint" outside MTU
4387        // probing. Nothing over UDP leaves larger than the path MTU allows.
4388        if transport_protocol == TransportProtocol::UDP
4389            && message.len() > self.max_udp_stun_size(peer_addr)
4390        {
4391            warn!(
4392                "[{}]: not sending a STUN message of {} bytes to {}: larger than the path MTU allows",
4393                self.get_name(),
4394                message.len(),
4395                peer_addr
4396            );
4397            return;
4398        }
4399
4400        self.write_outs.push_back(TaggedBytesMut {
4401            now,
4402            transport: TransportContext {
4403                local_addr,
4404                peer_addr,
4405                ecn: None,
4406                transport_protocol,
4407            },
4408            message,
4409        });
4410
4411        self.local_candidates[local_index].seen(now, true);
4412    }
4413
4414    /// The largest STUN message sent over UDP to `peer`: the path MTU
4415    /// ([`AgentConfig::path_mtu`]), else the RFC 8489 Section 6.1 assumption (576 bytes for
4416    /// IPv4, 1280 for IPv6), less the IP and UDP headers.
4417    pub(crate) fn max_udp_stun_size(&self, peer: SocketAddr) -> usize {
4418        let (assumed, overhead) = if peer.is_ipv4() {
4419            (576, 20 + 8)
4420        } else {
4421            (1280, 40 + 8)
4422        };
4423        self.path_mtu.unwrap_or(assumed).saturating_sub(overhead)
4424    }
4425
4426    fn handle_inbound_candidate_msg(
4427        &mut self,
4428        local_index: usize,
4429        msg: TaggedBytesMut,
4430    ) -> Result<()> {
4431        if is_stun_message(&msg.message) {
4432            let mut m = Message {
4433                raw: msg.message.to_vec(),
4434                ..Message::default()
4435            };
4436
4437            if let Err(err) = m.decode() {
4438                warn!(
4439                    "[{}]: Failed to handle decode ICE from {} to {}: {}",
4440                    self.get_name(),
4441                    msg.transport.local_addr,
4442                    msg.transport.peer_addr,
4443                    err
4444                );
4445                Err(err)
4446            } else {
4447                self.handle_inbound(msg.now, &mut m, local_index, msg.transport.peer_addr)
4448            }
4449        } else {
4450            if !self.validate_non_stun_traffic(msg.now, msg.transport.peer_addr) {
4451                warn!(
4452                    "[{}]: Discarded message, not a valid remote candidate from {}",
4453                    self.get_name(),
4454                    msg.transport.peer_addr,
4455                );
4456            } else {
4457                warn!(
4458                    "[{}]: non-STUN traffic message from a valid remote candidate from {}",
4459                    self.get_name(),
4460                    msg.transport.peer_addr
4461                );
4462            }
4463            Err(Error::ErrNonStunmessage)
4464        }
4465    }
4466
4467    pub(crate) fn get_name(&self) -> &str {
4468        if self.is_controlling {
4469            "controlling"
4470        } else {
4471            "controlled"
4472        }
4473    }
4474
4475    pub(crate) fn get_selected_pair(&self) -> Option<usize> {
4476        self.selected_pair
4477    }
4478
4479    pub(crate) fn get_best_available_pair(&self) -> Option<usize> {
4480        let mut best_pair_index: Option<usize> = None;
4481
4482        for (index, p) in self.candidate_pairs.iter().enumerate() {
4483            if p.state == CandidatePairState::Failed {
4484                continue;
4485            }
4486
4487            if let Some(pair_index) = &mut best_pair_index {
4488                let b = &self.candidate_pairs[*pair_index];
4489                if b.priority() < p.priority() {
4490                    *pair_index = index;
4491                }
4492            } else {
4493                best_pair_index = Some(index);
4494            }
4495        }
4496
4497        best_pair_index
4498    }
4499
4500    pub(crate) fn get_best_valid_candidate_pair(&self) -> Option<usize> {
4501        let mut best_pair_index: Option<usize> = None;
4502
4503        for (index, p) in self.candidate_pairs.iter().enumerate() {
4504            if p.state != CandidatePairState::Succeeded || !p.valid {
4505                continue;
4506            }
4507
4508            if let Some(pair_index) = &mut best_pair_index {
4509                let b = &self.candidate_pairs[*pair_index];
4510                if b.priority() < p.priority() {
4511                    *pair_index = index;
4512                }
4513            } else {
4514                best_pair_index = Some(index);
4515            }
4516        }
4517
4518        best_pair_index
4519    }
4520}
4521
4522/// The precedence of RFC 6724 Section 2.1's default policy table for `ip` (an IPv4 address
4523/// as its IPv4-mapped form, `::ffff:0:0/96`).
4524pub(crate) fn rfc6724_precedence(ip: IpAddr) -> u8 {
4525    let v6 = match ip {
4526        IpAddr::V4(_) => return 35,
4527        IpAddr::V6(v6) => v6,
4528    };
4529    if let Some(v4) = v6.to_ipv4_mapped() {
4530        return rfc6724_precedence(IpAddr::V4(v4));
4531    }
4532    let s = v6.segments();
4533    if v6.is_loopback() {
4534        50
4535    } else if s[0] == 0x2002 {
4536        30
4537    } else if s[0] == 0x2001 && s[1] == 0 {
4538        5
4539    } else if s[0] & 0xfe00 == 0xfc00 {
4540        3
4541    } else if s[..6] == [0; 6] || s[0] & 0xffc0 == 0xfec0 || s[0] == 0x3ffe {
4542        1
4543    } else {
4544        40
4545    }
4546}