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