Skip to main content

is/
agent.rs

1// Changed by Alakazam Labs for sew-str0m-is; the fork's patches are listed in its README.
2use std::collections::{HashSet, VecDeque};
3use std::fmt;
4use std::net::SocketAddr;
5use std::ops::RangeInclusive;
6use std::panic::{RefUnwindSafe, UnwindSafe};
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10use serde::{Deserialize, Serialize};
11
12use crate::Sha1HmacProvider;
13use crate::preference::default_local_preference;
14use crate::stun::{Class as StunClass, Method as StunMethod, StunTiming};
15use crate::stun::{StunMessage, StunPacket, TransId};
16use str0m_proto::{DATAGRAM_MTU_TARGET, DATAGRAM_MTU_WARN, Id, Transmit};
17use str0m_proto::{NonCryptographicRng, Pii, Protocol};
18
19use crate::candidate::{Candidate, CandidateKind};
20use crate::pair::{CandidatePair, CheckState, PairId};
21
22/// How long a USE-CANDIDATE request keeps a pair "still nominated" for a
23/// controlled ice-lite agent (`evaluate_nomination`). libwebrtc checks a lite
24/// peer's selected pair about every 2.5 s once stable.
25const LITE_NOMINATION_FRESH: Duration = Duration::from_secs(3);
26
27/// Handles the ICE protocol for a given peer.
28///
29/// Each connection between two peers corresponds to one [`IceAgent`] on either end.
30/// To form connections to multiple peers, a peer needs to create a dedicated [`IceAgent`] for
31/// each one.
32#[derive(Debug)]
33pub struct IceAgent {
34    /// Last time handle_timeout run (paced by timing_advance).
35    ///
36    /// This drives the state forward.
37    last_now: Option<Instant>,
38
39    /// Timing advance (Ta) value.
40    ///
41    /// ICE agents SHOULD use a default Ta value, 50 ms, but MAY use another
42    /// value based on the characteristics of the associated data.
43    timing_advance: Duration,
44
45    /// Whether this agent is operating as ice-lite.
46    /// ice-lite is a minimal version of the ICE specification, intended for servers
47    /// running on a public IP address. ice-lite requires the media server to only answer
48    /// incoming STUN binding requests and acting as a controlled entity in the ICE
49    /// process itself.
50    ice_lite: bool,
51
52    // The default limit of candidate pairs for the checklist set is 100,
53    // but the value MUST be configurable.
54    max_candidate_pairs: Option<usize>,
55
56    /// Whether we have previously exceeded the `max_candidate_pairs` limit.
57    has_exceeded_max_candidate_pairs: bool,
58
59    /// Credentials for this side. Set on init and ice-restart.
60    local_credentials: IceCreds,
61
62    /// Credentials for the remote side. Set when we learn about it.
63    remote_credentials: Option<IceCreds>,
64
65    /// If this side is controlling or controlled.
66    controlling: bool,
67
68    /// Number used in STUN attribute ICE-CONTROLLING and ICE-CONTROLLED.
69    /// An ICE agent MUST use the same number for all Binding requests,
70    /// for all streams, within an ICE session
71    control_tie_breaker: u64,
72
73    /// Current state of the agent.
74    state: IceConnectionState,
75
76    /// All local candidates, in the order they are "discovered" (either by
77    /// adding explicitly using add_candidate, or via binding/allocation
78    /// requests.
79    local_candidates: Vec<Candidate>,
80
81    /// All remote candidates, in the order we get to know them.
82    remote_candidates: Vec<Candidate>,
83
84    /// The candidate pairs.
85    candidate_pairs: Vec<CandidatePair>,
86
87    /// Transmit packet ready to be polled by poll_transmit.
88    transmit: VecDeque<Transmit>,
89
90    /// Events ready to be polled by poll_event.
91    events: VecDeque<IceAgentEvent>,
92
93    /// Queue of incoming STUN requests we might have to queue up before we receive
94    /// the remote_credentials.
95    stun_server_queue: VecDeque<StunRequest>,
96
97    /// Remote addresses we have seen traffic appear from. This is used
98    /// to dedupe [`IceAgentEvent::DiscoveredRecv`].
99    discovered_recv: HashSet<(Protocol, SocketAddr)>,
100
101    /// Currently nominated pair for sending. This is used to evaluate
102    /// if we get a better candidate for [`IceAgentEvent::NominatedSend`].
103    nominated_send: Option<PairId>,
104
105    /// Statistics counter for the agent.
106    stats: IceAgentStats,
107
108    /// SHA1-HMAC provider for STUN message integrity.
109    sha1_hmac_provider: &'static dyn Sha1HmacProvider,
110
111    /// The timing configuration for STUN bindings.
112    timing_config: StunTiming,
113
114    /// Pluggable calculation of local preference.
115    local_preference: LocalPreferenceHolder,
116
117    /// Target MTU (start) and warn threshold (end). Buffer sizing uses the
118    /// target; oversized outgoing datagrams above the warn threshold log a warning.
119    mtu: RangeInclusive<usize>,
120}
121
122/// IceAgent contains only static references to thread-safe traits,
123/// so it's safe to use across panic boundaries.
124impl UnwindSafe for IceAgent {}
125impl RefUnwindSafe for IceAgent {}
126
127// Stupid holder to implement fmt::Debug
128struct LocalPreferenceHolder(Arc<dyn LocalPreference>);
129
130/// Trait for pluggable LocalPreference calculation
131pub trait LocalPreference: RefUnwindSafe + Send + Sync + 'static {
132    /// Calculate the local preference for a candidate.
133    ///
134    /// The `same_kind` parameter is the number of candidates of the same IP version that
135    /// have already been added to the agent.
136    ///
137    /// The `c` parameter is the candidate to calculate the preference for.
138    fn calculate(&self, c: &Candidate, same_kind: usize) -> u32;
139}
140
141/// Blanket impl for functions that look like preference calculations.
142impl<F> LocalPreference for F
143where
144    F: Fn(&Candidate, usize) -> u32 + RefUnwindSafe + Send + Sync + 'static,
145{
146    fn calculate(&self, c: &Candidate, same_kind: usize) -> u32 {
147        (self)(c, same_kind)
148    }
149}
150
151#[derive(Debug)]
152struct StunRequest {
153    now: Instant,
154    proto: Protocol,
155    source: SocketAddr,
156    destination: SocketAddr,
157    trans_id: TransId,
158    prio: u32,
159    use_candidate: bool,
160    remote_ufrag: String,
161    ice_controlling: Option<u64>,
162    ice_controlled: Option<u64>,
163}
164
165impl StunRequest {
166    fn role_conflict_tiebreaker(&self, controlling: bool) -> Option<u64> {
167        if controlling {
168            self.ice_controlling
169        } else {
170            self.ice_controlled
171        }
172    }
173}
174
175fn role_name(controlling: bool) -> &'static str {
176    if controlling {
177        "controlling"
178    } else {
179        "controlled"
180    }
181}
182
183/// Whether `addr` can reach a peer. Port 0 can't be sent to, and an unspecified
184/// IP (`0.0.0.0`, `::` or `::ffff:0.0.0.0`) is delivered to the local host.
185fn is_valid_peer_addr(addr: SocketAddr) -> bool {
186    addr.port() != 0 && !addr.ip().to_canonical().is_unspecified()
187}
188
189const REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION: &str = "tmp_prflx";
190
191/// States the ICE connection can be in.
192///
193/// More details on connection states can be found in the [ICE RFC][1].
194///
195/// [1]: https://www.rfc-editor.org/rfc/rfc8445
196#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub enum IceConnectionState {
198    /// The ICE agent is gathering addresses.
199    New,
200
201    /// The ICE agent is checking pairs of local and remote candidates against one
202    /// another to try to find a compatible match, but has not yet found a pair
203    /// which will allow the peer connection to be made. It is possible that
204    /// gathering of candidates is also still underway.
205    Checking,
206
207    /// A usable pairing of local and remote candidates has been found, and the
208    /// connection has been established. The agent is not in `Completed` because
209    /// it is still gathering candidates or is still checking candidates against
210    /// one another looking for a better connection to use.
211    Connected,
212
213    /// The ICE agent has finished gathering candidates, has checked all pairs
214    /// against one another, and has found a working connection.
215    Completed,
216
217    /// Connection failed. This is a less stringent test than `failed` and may trigger
218    /// intermittently and resolve just as spontaneously on less reliable networks,
219    /// or during temporary disconnections. When the problem resolves, the connection
220    /// may return to the connected state.
221    Disconnected,
222    //
223    // NB: The failed and closed state doesn't really have a mapping in this implementation.
224    //     We never end trickle ice and it's always possible to "come back" if more remote
225    //     candidates are added.
226    //
227    // The ICE candidate has checked all candidates pairs against one another and has
228    // failed to find compatible matches.
229    // Failed,
230    // The ICE agent has shut down and is no longer handling requests.
231    // Closed,
232}
233
234impl IceConnectionState {
235    /// Tells if this state is a connected state.
236    pub fn is_connected(&self) -> bool {
237        use IceConnectionState::*;
238        matches!(self, Connected | Completed)
239    }
240
241    /// Tells if this state is a disconnected state.
242    pub fn is_disconnected(&self) -> bool {
243        *self == IceConnectionState::Disconnected
244    }
245}
246
247/// Credentials for STUN packages.
248///
249/// By matching IceCreds in STUN to SDP, we know which STUN belongs to which Peer.
250#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
251pub struct IceCreds {
252    /// From a=ice-ufrag
253    pub ufrag: String,
254    /// From a=ice-pwd
255    pub pass: String,
256}
257
258#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
259pub struct IceAgentStats {
260    pub bind_request_sent: u64,
261    pub bind_success_recv: u64,
262    pub bind_request_recv: u64,
263    pub discovered_recv_count: u64,
264    pub nomination_send_count: u64,
265}
266
267/// Events from an [`IceAgent`].
268#[derive(Debug, PartialEq, Eq)]
269pub enum IceAgentEvent {
270    /// The agent restarted (or started).
271    IceRestart(IceCreds),
272
273    /// Connection state changed.
274    ///
275    /// This is mostly for show since the actual addresses to use will be
276    /// communicated in `PossibleRemote` and `NominatedLocal`.
277    IceConnectionStateChange(IceConnectionState),
278
279    /// A possible remote socket for the peer.
280    ///
281    /// The application should associate this with the peer. There will
282    /// be more than one of these, and traffic might eventually come in
283    /// on any of them.
284    ///
285    /// For each ICE restart, the app will only receive unique addresses once.
286    DiscoveredRecv {
287        /// The protocol to use for the socket.
288        proto: Protocol,
289        /// The remote socket to look out for.
290        source: SocketAddr,
291    },
292
293    /// A nominated local and remote socket for sending data.
294    ///
295    /// As opposed to the ICE spec, we can send this multiple times without
296    /// requiring an ICE restart. The application should always use the values
297    /// of the last emitted event to send data.
298    NominatedSend {
299        /// The protocol to use for the socket.
300        proto: Protocol,
301        /// The local socket address to send datagrams from.
302        ///
303        /// This will correspond to some local address added to
304        /// [`IceAgent::add_local_candidate`].
305        source: SocketAddr,
306        /// The remote address to send datagrams to.
307        destination: SocketAddr,
308    },
309}
310
311impl IceCreds {
312    /// Creates a new instance of `IceCreds` with random values for the username fragment and password.
313    pub fn new() -> Self {
314        // Username Fragment and Password:  Values used to perform connectivity
315        // checks.  The values MUST be unguessable, with at least 128 bits of
316        // random number generator output used to generate the password, and
317        // at least 24 bits of output to generate the username fragment.
318        let ufrag = Id::<16>::random().to_string();
319        let pass = Id::<22>::random().to_string();
320        IceCreds { ufrag, pass }
321    }
322}
323
324impl IceAgent {
325    /// Create a new [`IceAgent`] using the default SHA1-HMAC provider.
326    ///
327    /// Available when the `sha1` feature is enabled (on by default).
328    #[cfg(feature = "sha1")]
329    pub fn new(local_credentials: IceCreds) -> Self {
330        Self::with_hmac(local_credentials, &crate::DefaultSha1HmacProvider)
331    }
332
333    /// Create a new [`IceAgent`] with a specific SHA1-HMAC provider.
334    pub fn with_hmac(
335        local_credentials: IceCreds,
336        sha1_hmac_provider: &'static dyn Sha1HmacProvider,
337    ) -> Self {
338        IceAgent {
339            last_now: None,
340            ice_lite: false,
341            max_candidate_pairs: None,
342            has_exceeded_max_candidate_pairs: false,
343            local_credentials,
344            remote_credentials: None,
345            controlling: false,
346            control_tie_breaker: NonCryptographicRng::u64(),
347            state: IceConnectionState::New,
348            local_candidates: vec![],
349            remote_candidates: vec![],
350            candidate_pairs: vec![],
351            transmit: VecDeque::new(),
352            events: VecDeque::new(),
353            stun_server_queue: VecDeque::new(),
354            discovered_recv: HashSet::new(),
355            nominated_send: None,
356            stats: IceAgentStats::default(),
357            timing_advance: Duration::from_millis(50),
358            timing_config: StunTiming::default(),
359            local_preference: LocalPreferenceHolder(Arc::new(default_local_preference)),
360            sha1_hmac_provider,
361            mtu: DATAGRAM_MTU_TARGET..=DATAGRAM_MTU_WARN,
362        }
363    }
364
365    /// Set the UDP datagram MTU range used for sizing internal buffers (target..=warn).
366    pub fn set_mtu(&mut self, mtu: RangeInclusive<usize>) {
367        self.mtu = mtu;
368    }
369
370    /// Target MTU used for sizing outgoing STUN buffers.
371    pub fn mtu(&self) -> usize {
372        *self.mtu.start()
373    }
374
375    /// Threshold above which an outgoing datagram triggers an MTU warning.
376    pub fn mtu_warn(&self) -> usize {
377        *self.mtu.end()
378    }
379
380    /// Sets the control tie breaker of this agent.
381    ///
382    /// By default, this is randomly generated and per the ICE spec,
383    /// this MUST be the same for the duration of an ICE session.
384    pub fn set_control_tie_breaker(&mut self, tie_breaker: u64) {
385        self.control_tie_breaker = tie_breaker;
386    }
387
388    /// The maximum number of candidate pairs to test.
389    ///
390    /// Any pairs above this limit will be dropped (worst priority first).
391    pub fn set_max_candidate_pairs(&mut self, max: usize) {
392        self.max_candidate_pairs = Some(max);
393        self.has_exceeded_max_candidate_pairs = false; // Reset the flag.
394    }
395
396    /// Whether ice_lite is enabled.
397    ///
398    /// Default is disabled.
399    pub fn ice_lite(&self) -> bool {
400        self.ice_lite
401    }
402
403    /// Enable or disable ice_lite.
404    ///
405    /// Default is disabled.
406    pub fn set_ice_lite(&mut self, enabled: bool) {
407        self.ice_lite = enabled;
408    }
409
410    /// Set a new timing advance (Ta) value.
411    ///
412    /// Ta specifies the minimum increment of time that has to pass between calls to
413    /// [`IceAgent::handle_timeout`]s (guided via [`IceAgent::poll_timeout`]).
414    ///
415    /// Defaults to 50ms.
416    pub fn set_timing_advance(&mut self, duration: Duration) {
417        self.timing_advance = duration
418    }
419
420    /// Local ice credentials.
421    pub fn local_credentials(&self) -> &IceCreds {
422        &self.local_credentials
423    }
424
425    /// Sets the local ice credentials.
426    pub fn set_local_credentials(&mut self, r: IceCreds) {
427        if self.local_credentials != r {
428            debug!("Set local credentials: {:?}", Pii(&r));
429            self.local_credentials = r;
430        }
431    }
432
433    /// Sets the initial STUN **R**etransmission **T**ime**O**ut.
434    ///
435    /// It defines the initial period of time between transmission of a request
436    /// and the first retransmit of that request. The actual RTO doubles with
437    /// each retransmit up until the configured maximum RTO.
438    ///
439    /// Defaults to 250ms.
440    pub fn set_initial_stun_rto(&mut self, timeout: Duration) {
441        if self.timing_config.initial_rto == timeout {
442            return;
443        }
444
445        self.timing_config.initial_rto = timeout;
446
447        debug!("initial_rto = {timeout:?}");
448
449        self.bust_candidate_pair_timeout_caches();
450    }
451
452    /// Sets the maximum STUN **R**etransmission **T**ime**O**ut.
453    ///
454    /// It defines the maximum period of time between transmission of a request
455    /// and the first retransmit of that request. Once a candidate pair is
456    /// successful, this is how often we check that a STUN binding is alive.
457    /// As the STUN bindings of a successful candidate pair start to time out,
458    /// we probe the binding more often by halfing this value, up until the
459    /// maximum number of retransmits before we declare them failed.
460    ///
461    /// Defaults to 3000ms.
462    pub fn set_max_stun_rto(&mut self, timeout: Duration) {
463        if self.timing_config.max_rto == timeout {
464            return;
465        }
466
467        self.timing_config.max_rto = timeout;
468
469        debug!("max_rto = {timeout:?}");
470
471        self.bust_candidate_pair_timeout_caches();
472    }
473
474    /// Sets the maximum number of retransmits for STUN messages.
475    ///
476    /// Defaults to 9.
477    pub fn set_max_stun_retransmits(&mut self, num: usize) {
478        if self.timing_config.max_retransmits == num {
479            return;
480        }
481
482        self.timing_config.max_retransmits = num;
483
484        debug!("max_retransmits = {num}");
485    }
486
487    /// Sets the local preference calculation.
488    ///
489    /// This must be used before adding any local candidates.
490    pub fn set_local_preference(&mut self, p: impl LocalPreference) {
491        self.local_preference = LocalPreferenceHolder(Arc::new(p));
492    }
493
494    fn bust_candidate_pair_timeout_caches(&mut self) {
495        for pair in self.candidate_pairs.iter_mut() {
496            pair.reset_cached_next_attempt_time();
497        }
498    }
499
500    /// How long we at most tolerate missing replies for a successful candidate pair
501    /// before considering it failed.
502    pub fn ice_timeout(&self) -> Duration {
503        self.timing_config.timeout()
504    }
505
506    /// Local ice candidates.
507    ///
508    /// The candidates have their ufrag filled out to the local credentials.
509    pub fn local_candidates(&self) -> impl Iterator<Item = Candidate> + Clone + '_ {
510        self.local_candidates
511            .iter()
512            .filter(|c| !c.discarded())
513            .cloned()
514    }
515
516    /// Remote ice candidates.
517    pub fn remote_candidates(&self) -> impl Iterator<Item = Candidate> + Clone + '_ {
518        self.remote_candidates
519            .iter()
520            .filter(|c| !c.discarded())
521            .cloned()
522    }
523
524    /// Determines whether any remote candidates match the specified address and
525    /// have been verified with a STUN request/response.
526    pub fn has_viable_remote_candidate(&self, addr: SocketAddr) -> bool {
527        self.candidate_pairs
528            .iter()
529            .filter(|cand| cand.state() == CheckState::Succeeded)
530            .any(|pair| self.remote_candidates[pair.remote_idx()].addr() == addr)
531    }
532
533    /// Remote ice credentials.
534    pub fn remote_credentials(&self) -> Option<&IceCreds> {
535        self.remote_credentials.as_ref()
536    }
537
538    /// Sets the remote ice credentials.
539    pub fn set_remote_credentials(&mut self, r: IceCreds) {
540        if self.remote_credentials.as_ref() != Some(&r) {
541            debug!("Set remote credentials: {:?}", Pii(&r));
542            self.remote_credentials = Some(r);
543        }
544    }
545
546    /// Determine whether an equivalent remote candidate is part of a viable candidate pair.
547    pub fn find_pair_for_equivalent_remote_candidate(
548        &self,
549        c: &Candidate,
550    ) -> Option<&CandidatePair> {
551        self.candidate_pairs.iter().find(|pair| {
552            let o = &self.remote_candidates[pair.remote_idx()];
553            c.addr() == o.addr()
554                && c.base() == o.base()
555                && c.proto() == o.proto()
556                && c.kind() == o.kind()
557                && c.raddr() == o.raddr()
558        })
559    }
560
561    /// Credentials for STUN.
562    ///
563    /// The username for the credential is formed by concatenating the
564    /// username fragment provided by the peer with the username fragment of
565    /// the ICE agent sending the request, separated by a colon (":").
566    ///
567    /// The password is equal to the password provided by the peer.
568    ///
569    /// The responses utilize the same usernames and passwords as the requests
570    /// (note that the USERNAME attribute is not present in the response).
571    ///
572    /// ### Panics
573    ///
574    /// Panics if there are no remote credentials set.
575    fn stun_credentials(&self, reply: bool) -> (String, String) {
576        let local = &self.local_credentials;
577
578        let (left, right, peer_pass) = if reply {
579            ("not_used", "not_used", "not_used")
580        } else {
581            let peer = self
582                .remote_credentials
583                .as_ref()
584                .expect("Remote ICE credentials");
585            (&peer.ufrag[..], &local.ufrag[..], &peer.pass[..])
586        };
587
588        let username = format!("{left}:{right}");
589        let password = if reply {
590            local.pass.clone()
591        } else {
592            peer_pass.into()
593        };
594
595        (username, password)
596    }
597
598    /// Whether this side is controlling or controlled.
599    #[allow(unused)]
600    pub fn controlling(&self) -> bool {
601        self.controlling
602    }
603
604    /// Set whether we are the controlling side.
605    ///
606    /// You should not call this function after ICE candidate pair formation
607    /// has started, as the controlling state influences candidate prio!
608    pub fn set_controlling(&mut self, v: bool) {
609        self.controlling = v;
610    }
611
612    /// Current ice agent state.
613    pub fn state(&self) -> IceConnectionState {
614        self.state
615    }
616
617    /// Stats for the agent.
618    ///
619    /// Resets on ICE restart.
620    #[allow(unused)]
621    pub fn stats(&self) -> IceAgentStats {
622        self.stats
623    }
624
625    /// Adds a local candidate.
626    ///
627    /// Returns `Some` if the candidate was added and `None` in all other cases.
628    /// If the candidate was added, it should be signalled to the remote party.
629    ///
630    /// Adding loopback addresses or multicast/broadcast addresses causes
631    /// an error.
632    pub fn add_local_candidate(&mut self, mut c: Candidate) -> Option<&Candidate> {
633        let ip = c.addr().ip();
634
635        if self.ice_lite {
636            // Reject all non-host candidates.
637            if c.kind() != CandidateKind::Host {
638                debug!("Reject non-host candidate due to ice-lite mode: {:?}", c);
639                return None;
640            }
641        }
642
643        // Count the number of existing candidates of the same kind.
644        let same_kind = self
645            .local_candidates
646            .iter()
647            .filter(|v| v.kind() == c.kind())
648            .filter(|v| v.addr().is_ipv6() == ip.is_ipv6())
649            .count();
650
651        // Delegate local preference calculation to pluggable algo.
652        let pref = self.local_preference.0.calculate(&c, same_kind);
653        trace!("Calculated local preference: {}", pref);
654        c.set_local_preference(pref);
655
656        // "Adopt" any incoming candidate by setting our current ufrag.
657        c.set_ufrag(&self.local_credentials.ufrag);
658
659        // A candidate is redundant if and only if its transport address and base equal those
660        // of another candidate.  The agent SHOULD eliminate the redundant
661        // candidate with the lower priority.
662        //
663        // NB this must be done _after_ set_local_preference(), since the prio() used in the
664        // elimination is calculated from that preference.
665        let maybe_redundant =
666            self.local_candidates.iter_mut().enumerate().find(|(_, v)| {
667                v.addr() == c.addr() && v.base() == c.base() && v.proto() == c.proto()
668            });
669
670        let local_idx = if let Some((idx, other)) = maybe_redundant {
671            if other.discarded() && c.kind() == other.kind() && c.raddr() == other.raddr() {
672                debug!("Re-enable previously discarded local: {:?}", other);
673                other.set_discarded(false);
674                idx
675            } else {
676                if c.prio() < other.prio() {
677                    // The new candidate is not better than what we already got.
678                    debug!(
679                        "Reject redundant candidate, current: {:?} rejected: {:?}",
680                        Pii(&other),
681                        Pii(&c)
682                    );
683                    return None;
684                }
685
686                // Stop using the current candidate in favor of the new one.
687                debug!(
688                    "Replace redundant candidate, current: {:?} replaced with: {:?}",
689                    Pii(&other),
690                    Pii(&c)
691                );
692                other.set_discarded(true);
693                self.discard_candidate_pairs_by_local(idx);
694
695                let new_idx = self.local_candidates.len();
696
697                debug!("Add local candidate ({new_idx}): {:?}", Pii(&c));
698                self.local_candidates.push(c);
699
700                new_idx
701            }
702        } else {
703            let new_idx = self.local_candidates.len();
704
705            debug!("Add local candidate ({new_idx}): {:?}", Pii(&c));
706            self.local_candidates.push(c);
707
708            new_idx
709        };
710
711        // These are the indexes of the remote candidates this candidate should be paired with.
712        let remote_idxs: Vec<_> = self
713            .remote_candidates
714            .iter()
715            .enumerate()
716            .filter(|(_, v)| !v.discarded() && v.addr().is_ipv4() == ip.is_ipv4())
717            .map(|(i, _)| i)
718            .collect();
719
720        // We always run in trickle ice mode.
721        //
722        // https://www.rfc-editor.org/rfc/rfc8838.html#section-10
723        // A Trickle ICE agent MUST NOT pair a local candidate until it has been trickled
724        // to the remote party.
725        //
726        // TODO: The trickle ice spec is strange. What does it mean "has been trickled to the
727        // remote party"? Since we don't get a confirmation that the candidate has been received
728        // by the remote party, whether we form local pairs directly or later seems irrelevant.
729        self.form_pairs(&[local_idx], &remote_idxs);
730
731        // We specifically use indexing here instead of `.get`.
732        // If the index is wrong, this is a bug!
733        Some(&self.local_candidates[local_idx])
734    }
735
736    /// Adds a remote candidate.
737    ///
738    /// Candidates with port 0 or an unspecified IP address (`0.0.0.0` or `::`)
739    /// are ignored, since neither can reach the remote peer.
740    pub fn add_remote_candidate(&mut self, mut c: Candidate) {
741        // This is a a:rtcp-mux-only implementation. The only component
742        // we accept is 1 for RTP.
743        if c.component_id() != 1 {
744            debug!("Reject candidate for component other than 1: {:?}", Pii(&c));
745            return;
746        }
747
748        if !is_valid_peer_addr(c.addr()) {
749            debug!("Reject candidate that can't reach the peer: {:?}", Pii(&c));
750            return;
751        }
752
753        if let Some(creds) = &self.remote_credentials {
754            if let Some(ufrag) = c.ufrag() {
755                if ufrag != creds.ufrag {
756                    debug!(
757                        "Reject candidate with ufrag mismatch: {} != {}",
758                        Pii(&ufrag),
759                        Pii(&creds.ufrag)
760                    );
761                    return;
762                }
763            }
764        }
765
766        // After we accepted the ufrag, don't keep this around since it will look
767        // confusing inspecting the state.
768        c.clear_ufrag();
769
770        let existing_pair = self.find_pair_for_equivalent_remote_candidate(&c);
771        let existing_candidate =
772            existing_pair.map(|p| (p.remote_idx(), &self.remote_candidates[p.remote_idx()]));
773
774        let existing_idx = match existing_candidate {
775            Some((_, o)) if !o.discarded() => {
776                // Existing non-discarded candidate in viable pair, ignore
777                // Discarded candidates and candidates not in a viable pair are handled below
778                trace!(
779                    "Ignoring candidate({c:?}) that exactly matches existing non-discarded candidate"
780                );
781                return;
782            }
783            Some((i, o)) if o.discarded() => Some(i),
784            _ => None,
785        };
786
787        let existing_prflx = self
788            .remote_candidates
789            .iter_mut()
790            .enumerate()
791            .find(|(_, v)| {
792                v.foundation() == REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION
793                    && v.kind() == CandidateKind::PeerReflexive
794                    && v.addr() == c.addr()
795            });
796
797        let ipv4 = c.addr().is_ipv4();
798
799        let remote_idx = if let Some((idx, existing)) = existing_prflx {
800            // If any subsequent candidate exchanges contain this peer-reflexive
801            // candidate, it will signal the actual foundation for the candidate.
802            debug!(
803                "Replace peer reflexive candidate, current: {:?} replaced with: {:?}",
804                Pii(&existing),
805                Pii(&c)
806            );
807            *existing = c;
808            idx
809        } else {
810            let existing_discarded = existing_idx.and_then(|idx| {
811                let o = &mut self.remote_candidates[idx];
812
813                o.discarded().then_some((idx, o))
814            });
815
816            if let Some((idx, other)) = existing_discarded {
817                debug!("Re-enable previously discarded remote: {:?}", Pii(&other));
818                other.set_discarded(false);
819                idx
820            } else {
821                let new_idx = self.remote_candidates.len();
822
823                debug!("Add remote candidate ({new_idx}): {:?}", Pii(&c));
824                self.remote_candidates.push(c);
825
826                new_idx
827            }
828        };
829
830        // These are the indexes of the local candidates this candidate should be paired with.
831        let local_idxs: Vec<_> = self
832            .local_candidates
833            .iter()
834            .enumerate()
835            .filter(|(_, v)| !v.discarded() && v.addr().is_ipv4() == ipv4)
836            .map(|(i, _)| i)
837            .collect();
838
839        let remote_idxs = [remote_idx];
840        self.form_pairs(&local_idxs, &remote_idxs);
841    }
842
843    /// Form pairs given two slices of indexes into the local_candidates and remote_candidates.
844    fn form_pairs(&mut self, local_idxs: &[usize], remote_idxs: &[usize]) {
845        // Ensure to first update the kinds so any log statements are up-to-date.
846        for pair in &mut self.candidate_pairs {
847            pair.update_kinds(&self.local_candidates, &self.remote_candidates);
848        }
849
850        for local_idx in local_idxs {
851            'outer: for remote_idx in remote_idxs {
852                let local = &self.local_candidates[*local_idx];
853                let remote = &self.remote_candidates[*remote_idx];
854
855                // Candidates in a pair must share the same protocol
856                if local.proto() != remote.proto() {
857                    continue 'outer;
858                }
859
860                let prio =
861                    CandidatePair::calculate_prio(self.controlling, remote.prio(), local.prio());
862                let mut pair =
863                    CandidatePair::new(*local_idx, local.kind(), *remote_idx, remote.kind(), prio);
864
865                trace!("Form pair local: {:?} remote: {:?}", local, remote);
866
867                // The agent prunes each checklist.  This is done by removing a
868                // candidate pair if it is redundant with a higher-priority candidate
869                // pair in the same checklist.  Two candidate pairs are redundant if
870                // their local candidates have the same base and their remote candidates
871                // are identical.
872
873                for (check_idx, check) in self.candidate_pairs.iter().enumerate() {
874                    let check_local = check.local_candidate(&self.local_candidates);
875                    let check_remote = check.remote_candidate(&self.remote_candidates);
876
877                    let redundant = local.base() == check_local.base()
878                        && remote.addr() == check_remote.addr()
879                        && local.proto() == check_local.proto()
880                        && remote.proto() == check_remote.proto();
881
882                    if redundant {
883                        if check.prio() >= pair.prio() {
884                            // skip this new pair since there is a redundant pair already in the
885                            // list with higher/equal priority.
886                            debug!(
887                                "Reject redundant pair, current: {:?} rejected: {:?}",
888                                Pii(&check),
889                                Pii(&pair)
890                            );
891                        } else {
892                            // replace the existing candidate pair, since the new one got a higher prio.
893                            pair.copy_nominated_and_success_state(&self.candidate_pairs[check_idx]);
894
895                            debug!(
896                                "Replace redundant pair, current: {:?} replaced with: {:?}",
897                                Pii(&check),
898                                Pii(&pair)
899                            );
900
901                            if self.ice_lite {
902                                debug!("Retain incoming binding requests for pair");
903                                pair.copy_remote_binding_requests(&self.candidate_pairs[check_idx]);
904                            }
905
906                            self.candidate_pairs[check_idx] = pair;
907                        }
908
909                        // There can only be one candidate pair per local base / remote addr.
910                        // Since we found that redundant entry, there's no point in checking further
911                        // candidate pairs.
912                        continue 'outer;
913                    }
914                }
915
916                debug!("Add new pair {:?}", Pii(&pair));
917
918                // This is not a redundant pair, add it.
919                self.candidate_pairs.push(pair);
920            }
921        }
922
923        // NB it would be nicer to have BTreeSet, but that makes it impossible to
924        // get mut references to the elements in the list.
925        self.candidate_pairs.sort();
926
927        // an ICE agent MUST limit the total number of connectivity checks
928        // the agent performs across all checklists in the checklist set.
929        // This is done by limiting the total number of candidate pairs in the
930        // checklist set. The default limit of candidate pairs for the checklist
931        // set is 100, but the value MUST be configurable.
932        //
933        // TODO: How does this work with trickle ice?
934        let max = self.max_candidate_pairs.unwrap_or(100);
935
936        let num_pairs = self.candidate_pairs.len();
937        if num_pairs > max && !self.has_exceeded_max_candidate_pairs {
938            warn!(%max, %num_pairs, "Exceeded max number of candidate pairs");
939            self.has_exceeded_max_candidate_pairs = true;
940        }
941
942        while self.candidate_pairs.len() > max {
943            let pair = self.candidate_pairs.pop();
944            debug!("Remove overflow pair {:?}", Pii(&pair));
945        }
946    }
947
948    /// Invalidate a candidate and remove it from the connection.
949    ///
950    /// This is done for host candidates disappearing due to changes in the network
951    /// interfaces like a WiFi disconnecting or changing IPs.
952    ///
953    /// It can also be used to invalidate _remote_ candidates, i.e. if the remote
954    /// has signalled us that they have invalidated one of their candidates.
955    ///
956    /// Returns `true` if the candidate was found and invalidated.
957    pub fn invalidate_candidate(&mut self, c: &Candidate) -> bool {
958        if let Some((idx, other)) = self.local_candidates.iter_mut().enumerate().find(|(_, v)| {
959            v.addr() == c.addr()
960                && v.base() == c.base()
961                && v.raddr() == c.raddr()
962                && v.kind() == c.kind()
963                && v.proto() == c.proto()
964        }) {
965            if !other.discarded() {
966                debug!("Local candidate to discard {:?}", Pii(&other));
967                other.set_discarded(true);
968                self.discard_candidate_pairs_by_local(idx);
969                return true;
970            }
971        }
972
973        if let Some((idx, other)) = self
974            .remote_candidates
975            .iter_mut()
976            .enumerate()
977            .find(|(_, v)| {
978                v.addr() == c.addr()
979                    && v.base() == c.base()
980                    && v.raddr() == c.raddr()
981                    && v.kind() == c.kind()
982                    && v.proto() == c.proto()
983            })
984        {
985            if !other.discarded() {
986                debug!("Remote candidate to discard {:?}", Pii(&other));
987                other.set_discarded(true);
988                self.discard_candidate_pairs_by_remote(idx);
989                return true;
990            }
991        }
992
993        debug!("No local or remote candidate found: {:?}", Pii(&c));
994        false
995    }
996
997    /// Restart ICE.
998    ///
999    /// This is useful when detecting a change in network interfaces, such as
1000    /// current session running off a 4G, and we connect to a WiFi. The session
1001    /// should continue sending data over the 4G until we redone the ICE gathering
1002    /// process.
1003    #[allow(unused)]
1004    pub fn ice_restart(&mut self, local_credentials: IceCreds, keep_local_candidates: bool) {
1005        // An ICE agent MAY restart ICE for existing data streams.  An ICE
1006        // restart causes all previous states of the data streams, excluding the
1007        // roles of the agents, to be flushed.  The only difference between an
1008        // ICE restart and a brand new data session is that during the restart,
1009        // data can continue to be sent using existing data sessions, and a new
1010        // data session always requires the roles to be determined.
1011
1012        self.remote_credentials = None;
1013        self.remote_candidates.clear();
1014        self.candidate_pairs.clear();
1015        self.has_exceeded_max_candidate_pairs = false;
1016        self.transmit.clear();
1017        self.events.clear();
1018        self.discovered_recv.clear();
1019
1020        if keep_local_candidates {
1021            // If we're keeping the candidates, we must update the ufrag to the new credentials.
1022            // This is so anyone inspecting `.local_candidates()` will get the correct ufrag.
1023            for c in &mut self.local_candidates {
1024                c.set_ufrag(&local_credentials.ufrag)
1025            }
1026        } else {
1027            self.local_candidates.clear();
1028        }
1029
1030        self.local_credentials = local_credentials;
1031
1032        self.emit_event(IceAgentEvent::IceRestart(self.local_credentials.clone()));
1033        self.set_connection_state(IceConnectionState::Checking, "ice restart");
1034    }
1035
1036    /// Re-create all candidate pairs from the current candidates.
1037    ///
1038    /// This is similar to an ICE restart but also retains all remote candidates.
1039    pub fn recreate_candidate_pairs(&mut self) {
1040        self.candidate_pairs.clear();
1041
1042        let local_idxs: Vec<_> = self
1043            .local_candidates
1044            .iter()
1045            .enumerate()
1046            .filter(|(_, v)| !v.discarded())
1047            .map(|(i, _)| i)
1048            .collect();
1049        let remote_idxs: Vec<_> = self
1050            .remote_candidates
1051            .iter()
1052            .enumerate()
1053            .filter(|(_, v)| !v.discarded())
1054            .map(|(i, _)| i)
1055            .collect();
1056
1057        self.form_pairs(&local_idxs, &remote_idxs);
1058        self.set_connection_state(IceConnectionState::Checking, "recreate candidate pairs");
1059    }
1060
1061    /// Discard candidate pairs that contain the candidate identified by a local index.
1062    fn discard_candidate_pairs_by_local(&mut self, local_idx: usize) {
1063        trace!("Discard pairs for local candidate index: {:?}", local_idx);
1064        self.candidate_pairs.retain(|c| c.local_idx() != local_idx);
1065    }
1066
1067    /// Discard candidate pairs that contain the candidate identified by a remote index.
1068    fn discard_candidate_pairs_by_remote(&mut self, remote: usize) {
1069        trace!("Discard pairs for remote candidate index: {:?}", remote);
1070        self.candidate_pairs.retain(|c| c.remote_idx() != remote);
1071    }
1072
1073    /// Tells whether the message is for this agent instance.
1074    ///
1075    /// This is used to multiplex multiple ice agents on a server sharing the same UDP socket.
1076    ///
1077    /// For binding requests, if no remote credentials have been set using
1078    /// `set_remote_credentials`, the remote ufrag is not checked.
1079    pub fn accepts_message(&self, message: &StunMessage<'_>) -> bool {
1080        trace!("Check if accepts message: {:?}", message);
1081
1082        let sha1_hmac =
1083            |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads);
1084
1085        let do_integrity_check = |is_request: bool| -> bool {
1086            let (_, password) = self.stun_credentials(is_request);
1087            let integrity_passed = message.verify(password.as_bytes(), sha1_hmac);
1088
1089            // The integrity is always the last thing we check
1090            if integrity_passed {
1091                trace!("Message accepted");
1092            } else {
1093                trace!("Message rejected, integrity check failed");
1094            }
1095            integrity_passed
1096        };
1097
1098        let method = message.method();
1099        let class = message.class();
1100        match (method, class) {
1101            (StunMethod::Binding, StunClass::Indication) => {
1102                // https://datatracker.ietf.org/doc/html/rfc8489#section-6.3.2
1103                // An Indication can be safely ignored, its purpose is to refresh NATs in the
1104                // network path. Some clients MAY omit USERNAME attribute.
1105                false
1106            }
1107            (StunMethod::Binding, StunClass::Request) => {
1108                // The username for the credential is formed by concatenating the
1109                // username fragment provided by the peer with the username fragment of
1110                // the ICE agent sending the request, separated by a colon (":").
1111                // The existence of this username is checked in the STUN parser.
1112                let (local, remote) = message.split_username().unwrap();
1113
1114                let local_creds = self.local_credentials();
1115                if local != local_creds.ufrag {
1116                    trace!(
1117                        "Message rejected, local user mismatch: {} != {}",
1118                        local, local_creds.ufrag
1119                    );
1120                    return false;
1121                }
1122
1123                if let Some(remote_creds) = &self.remote_credentials {
1124                    if remote != remote_creds.ufrag {
1125                        trace!(
1126                            "Message rejected, remote user mismatch: {} != {}",
1127                            remote, remote_creds.ufrag
1128                        );
1129                        return false;
1130                    }
1131                }
1132
1133                do_integrity_check(true)
1134            }
1135            (StunMethod::Binding, StunClass::Success | StunClass::Failure) => {
1136                let belongs_to_a_candidate_pair = self
1137                    .candidate_pairs
1138                    .iter()
1139                    .any(|pair| pair.binding_attempt(message.trans_id()).is_some());
1140
1141                if !belongs_to_a_candidate_pair {
1142                    trace!(
1143                        "Message rejected, transaction ID does not belong to any of our candidate pairs"
1144                    );
1145                    return false;
1146                }
1147
1148                do_integrity_check(false)
1149            }
1150            (StunMethod::Binding, StunClass::Unknown) => {
1151                // Without a known class, it's impossible to know how to validate the message
1152                trace!("Message rejected, unknown STUN class");
1153                false
1154            }
1155            (StunMethod::Unknown, _) => {
1156                // Without a known method, it's impossible to know how to validate the message
1157                trace!("Message rejected, unknown STUN method");
1158                false
1159            }
1160            (
1161                StunMethod::Allocate
1162                | StunMethod::Refresh
1163                | StunMethod::Send
1164                | StunMethod::Data
1165                | StunMethod::CreatePermission
1166                | StunMethod::ChannelBind,
1167                _,
1168            ) => {
1169                // Unexpected TURN related message
1170                trace!("Message rejected, TURN method({method:?}) unexpected in this context");
1171                false
1172            }
1173        }
1174    }
1175
1176    /// Handles an incoming STUN message.
1177    ///
1178    /// Will not be used if [`IceAgent::accepts_message`] returns false.
1179    pub fn handle_packet(&mut self, now: Instant, packet: StunPacket) -> bool {
1180        trace!("Handle receive: {:?}", &packet.message);
1181
1182        // We can't reply to such an address, nor use it as a peer-reflexive candidate.
1183        if !is_valid_peer_addr(packet.source) {
1184            debug!(
1185                "Drop STUN message from invalid address: {}",
1186                Pii(packet.source)
1187            );
1188            return false;
1189        }
1190
1191        // Regardless of whether we have remote_creds at this point, we can
1192        // at least check the message integrity.
1193        if !self.accepts_message(&packet.message) {
1194            debug!("Message not accepted");
1195            return false;
1196        }
1197
1198        if packet.message.is_binding_request() {
1199            self.stun_server_handle_message(now, &packet);
1200        } else if packet.message.is_successful_binding_response() {
1201            self.stun_client_handle_response(now, packet.message);
1202        } else if packet.message.is_failed_binding_response() {
1203            self.stun_client_handle_error(packet.message);
1204        }
1205
1206        self.emit_event(IceAgentEvent::DiscoveredRecv {
1207            proto: packet.proto,
1208            source: packet.source,
1209        });
1210
1211        // TODO handle unsuccessful responses.
1212
1213        true
1214    }
1215
1216    /// Provide the current time to the [`IceAgent`].
1217    ///
1218    /// Typically, you will want to call [`IceAgent::poll_timeout`] and "wake-up"
1219    /// the agent once that time is reached.
1220    pub fn handle_timeout(&mut self, now: Instant) {
1221        // This happens exactly once because evaluate_state() below will
1222        // switch away from New -> Checking.
1223        if self.state == IceConnectionState::New {
1224            self.emit_event(IceAgentEvent::IceRestart(self.local_credentials.clone()));
1225        }
1226
1227        self.evaluate_state(now);
1228
1229        // First we try to empty the queue of saved STUN requests.
1230        if self.remote_credentials.is_some() {
1231            let queue = &mut self.stun_server_queue;
1232
1233            // No need hanging on to very old requests.
1234            while let Some(peek) = queue.front() {
1235                if now - peek.now >= self.timing_config.timeout() {
1236                    let r = queue.pop_front();
1237                    trace!("Drop too old enqueued STUN request: {:?}", r.unwrap());
1238                } else {
1239                    break;
1240                }
1241            }
1242
1243            if let Some(req) = self.stun_server_queue.pop_front() {
1244                debug!("Handle enqueued STUN request: {:?}", Pii(&req));
1245                self.stun_server_handle_request(req);
1246                return;
1247            }
1248        }
1249
1250        self.last_now = Some(now);
1251
1252        self.evaluate_nomination(now);
1253
1254        // prune failed candidates.
1255        let mut any_pruned = false;
1256        self.candidate_pairs.retain(|p| {
1257            let keep = if self.ice_lite {
1258                p.is_ice_lite_alive(now)
1259            } else {
1260                p.is_still_possible(now, &self.timing_config)
1261            };
1262            if !keep {
1263                debug!("Remove failed pair: {:?}", Pii(&p));
1264                any_pruned = true;
1265            }
1266            keep
1267        });
1268        if any_pruned {
1269            self.evaluate_nomination(now);
1270            self.evaluate_state(now);
1271        }
1272
1273        if self.remote_credentials.is_none() {
1274            trace!("Stop timeout due to missing remote credentials");
1275            return;
1276        }
1277
1278        if self.ice_lite {
1279            // Remote binding request time is the timestamp in the CandidatePair that
1280            // is used to decide whether something is timed out or not. We need all
1281            // pairs to have this time set, so that pairs that don't receive any
1282            // STUN binding requests eventually times out.
1283            for p in &mut self.candidate_pairs {
1284                if p.remote_binding_request_time().is_none() {
1285                    p.increase_remote_binding_requests(now);
1286                }
1287            }
1288
1289            trace!("Stop timeout since ice-lite do no checks");
1290            return;
1291        }
1292
1293        // when do we need to handle the next candidate pair?
1294        let next = self
1295            .candidate_pairs
1296            .iter_mut()
1297            .enumerate()
1298            .map(|(i, c)| (i, c.next_binding_attempt(now, &self.timing_config)))
1299            .min_by_key(|(_, t)| *t);
1300
1301        if let Some((idx, deadline)) = next {
1302            if now >= deadline {
1303                let pair = &self.candidate_pairs[idx];
1304                trace!("Handle next triggered pair: {:?}", pair);
1305                self.stun_client_binding_request(now, idx);
1306            } else {
1307                // trace!("Next triggered pair is in the future: {:?}", deadline - now);
1308            }
1309        }
1310    }
1311
1312    /// Poll for the next datagram to send.
1313    pub fn poll_transmit(&mut self) -> Option<Transmit> {
1314        let x = self.transmit.pop_front();
1315        if let Some(x) = &x {
1316            if x.contents.len() > self.mtu_warn() {
1317                warn!("ICE above MTU {}: {}", self.mtu_warn(), x.contents.len());
1318            }
1319            trace!("Poll transmit: {:?}", x);
1320        }
1321        x
1322    }
1323
1324    /// Poll for the next time to call [`IceAgent::handle_timeout`].
1325    ///
1326    /// For optimal performance, you should call this every time the [`IceAgent`]s state changes.
1327    /// For example, after you call [`IceAgent::add_local_candidate`] or [`IceAgent::add_remote_candidate`].
1328    ///
1329    /// Returns `None` until the first ever `handle_timeout` is called.
1330    pub fn poll_timeout(&mut self) -> Option<Instant> {
1331        // if we never called handle_timeout, there will be no current time.
1332        let last_now = self.last_now?;
1333
1334        let has_request = !self.stun_server_queue.is_empty();
1335        let has_transmit = !self.transmit.is_empty();
1336
1337        // We must empty the queued replies or stuff to send as soon as possible.
1338        if has_request || has_transmit {
1339            return Some(last_now + self.timing_advance);
1340        }
1341
1342        // when do we need to handle the next candidate pair?
1343        let maybe_next = if self.ice_lite {
1344            // ice-lite doesn't do checks.
1345            None
1346        } else {
1347            self.candidate_pairs
1348                .iter_mut()
1349                .map(|c| c.next_binding_attempt(last_now, &self.timing_config))
1350                .min()
1351        };
1352
1353        // Time must advance with at least Ta.
1354        let next = if let Some(next) = maybe_next {
1355            if next < last_now + self.timing_advance {
1356                last_now + self.timing_advance
1357            } else {
1358                next
1359            }
1360        } else {
1361            // IDLE for a while.
1362            last_now + Duration::from_secs(3)
1363        };
1364
1365        Some(next)
1366    }
1367
1368    fn emit_event(&mut self, event: IceAgentEvent) {
1369        if let IceAgentEvent::DiscoveredRecv { proto, source } = event {
1370            if !self.discovered_recv.insert((proto, source)) {
1371                // we already dispatched this discovered
1372                return;
1373            }
1374            self.stats.discovered_recv_count += 1;
1375        } else if matches!(event, IceAgentEvent::NominatedSend { .. }) {
1376            self.stats.nomination_send_count += 1;
1377        }
1378
1379        trace!("Enqueueing event: {:?}", event);
1380        self.events.push_back(event);
1381    }
1382
1383    /// Return a pending [`IceAgentEvent`] from this agent.
1384    pub fn poll_event(&mut self) -> Option<IceAgentEvent> {
1385        let x = self.events.pop_front();
1386        if x.is_some() {
1387            trace!("Poll event: {:?}", x);
1388        }
1389        x
1390    }
1391
1392    fn stun_server_handle_message(&mut self, now: Instant, packet: &StunPacket) {
1393        let message = &packet.message;
1394        let prio = message
1395            .prio()
1396            // this should be guarded in the parsing
1397            .expect("STUN request prio");
1398        let use_candidate = message.use_candidate();
1399
1400        if use_candidate {
1401            trace!("Binding request sent USE-CANDIDATE");
1402        }
1403
1404        let trans_id = message.trans_id();
1405
1406        // The existence of USERNAME is checked by the STUN parser.
1407        let (_, remote_ufrag) = message.split_username().unwrap();
1408
1409        // Because we might have to delay stun requests until we receive the remote
1410        // credentials, we extract all relevant bits of information so it can be owned.
1411        let req = StunRequest {
1412            now,
1413            proto: packet.proto,
1414            source: packet.source,
1415            destination: packet.destination,
1416            trans_id,
1417            prio,
1418            use_candidate,
1419            remote_ufrag: remote_ufrag.into(),
1420            ice_controlling: message.ice_controlling(),
1421            ice_controlled: message.ice_controlled(),
1422        };
1423
1424        if self.remote_credentials.is_some() {
1425            self.stun_server_handle_request(req);
1426        } else {
1427            debug!(
1428                "Enqueue STUN request due to missing remote credentials: {:?}",
1429                Pii(&req)
1430            );
1431
1432            let queue = &mut self.stun_server_queue;
1433
1434            // It is possible (and in fact very likely) that the
1435            // initiating agent will receive a Binding request prior to receiving
1436            // the candidates from its peer.
1437            queue.push_back(req);
1438
1439            // This is some denial-of-service attack protection.
1440            while queue.len() > 100 {
1441                let r = queue.pop_front();
1442                debug!("Remove overflow STUN request {:?}", Pii(&r));
1443            }
1444
1445            // If this happens, the agent MUST
1446            // immediately generate a response.  The agent has sufficient
1447            // information at this point to generate the response; the password from
1448            // the peer is not required.
1449
1450            // TODO: The spec seems to indicate we can generate a reply, but that seems
1451            // to fly in the face of logic. A reply requires a fingerprint message integrity
1452            // and we can't construct that until we get the remote password.
1453        }
1454    }
1455
1456    fn stun_server_handle_request(&mut self, req: StunRequest) {
1457        let remote_creds = self.remote_credentials.as_ref().expect("Remote ICE creds");
1458        if req.remote_ufrag != remote_creds.ufrag {
1459            // this check can be delayed due to receiving STUN bind requests before we
1460            // get the exchange on the signal level.
1461            debug!(
1462                "STUN request rejected, remote user mismatch (enqueued): {} != {}",
1463                Pii(&req.remote_ufrag),
1464                Pii(&remote_creds.ufrag)
1465            );
1466            return;
1467        }
1468
1469        // Drop requests that did not arrive on one of our local candidates
1470        // before doing anything else. We must not mutate state, send replies
1471        // (including 487 Role Conflict) or create peer-reflexive candidates
1472        // for traffic that isn't actually directed at one of our interfaces.
1473        let local_idx = match self.local_candidates.iter().position(|v| {
1474            matches!(v.kind(), CandidateKind::Host | CandidateKind::Relayed)
1475                && v.addr() == req.destination
1476                && v.proto() == req.proto
1477        }) {
1478            Some(i) => i,
1479            None => {
1480                // Receiving traffic for an IP address that neither is a HOST nor RELAY
1481                // is most likely a configuration fault where the user forgot to add a
1482                // candidate for the local interface. We are network-connected application
1483                // so we need to handle this gracefully: Log a message and discard the packet.
1484                debug!(
1485                    "Discarding STUN request on unknown interface: {}",
1486                    Pii(req.destination)
1487                );
1488                return;
1489            }
1490        };
1491
1492        // Role conflict detection: if the peer claims the same role as us,
1493        // the agent with the higher tiebreaker keeps its role and the loser yields.
1494        if let Some(peer_tb) = req.role_conflict_tiebreaker(self.controlling) {
1495            debug!(
1496                "Role conflict on {} role: ours={}, peer={}",
1497                role_name(self.controlling),
1498                self.control_tie_breaker,
1499                peer_tb,
1500            );
1501
1502            if self.control_tie_breaker >= peer_tb {
1503                self.send_role_conflict_reply(&req);
1504                return;
1505            }
1506
1507            self.switch_role(!self.controlling);
1508        }
1509
1510        if req.use_candidate && self.controlling {
1511            // the other side is not controlling, and it sent USE-CANDIDATE. that's wrong.
1512            debug!("STUN request rejected, USE-CANDIDATE when local is controlling");
1513            return;
1514        }
1515
1516        self.stats.bind_request_recv += 1;
1517
1518        // If the source transport address of the request does not match any
1519        // existing remote candidates, it represents a new peer-reflexive remote
1520        // candidate.
1521        let found_in_remote = self
1522            .remote_candidates
1523            .iter()
1524            .enumerate()
1525            .filter(|(_, c)| !c.discarded() && c.proto() == req.proto && c.addr() == req.source)
1526            // We may have multiple candidates with the same address
1527            // (i.e. host and server-reflexive could be the same).
1528            .max_by_key(|(_, c)| c.prio());
1529
1530        let remote_idx = if let Some((idx, _)) = found_in_remote {
1531            trace!("Remote candidate for STUN request found");
1532            idx
1533        } else {
1534            let maybe_discarded = self
1535                .remote_candidates
1536                .iter()
1537                .any(|c| c.discarded() && c.proto() == req.proto && c.addr() == req.source);
1538
1539            if maybe_discarded {
1540                // The remote has been discarded, we do not want to create a
1541                // peer reflexive in this case.
1542                trace!("STUN request ignored because remote candidate is discarded");
1543                return;
1544            }
1545
1546            // o  The priority is the value of the PRIORITY attribute in the Binding
1547            //     request.
1548            //
1549            // o  The foundation is an arbitrary value, different from the
1550            //     foundations of all other remote candidates.  If any subsequent
1551            //     candidate exchanges contain this peer-reflexive candidate, it will
1552            //     signal the actual foundation for the candidate.
1553            let c = Candidate::peer_reflexive(
1554                req.proto,
1555                req.source,
1556                req.source,
1557                req.prio,
1558                // TODO: REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION should probably have
1559                // a counter to really make it "different from the foundations of
1560                // all other remote candidates".
1561                // In practice it might no matter since we don't do the frozen-waiting
1562                // dance for candidate pairs.
1563                Some(REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION.into()),
1564                self.local_credentials.ufrag.clone(),
1565            );
1566
1567            debug!(
1568                "Created peer reflexive remote candidate from STUN request: {:?}",
1569                Pii(&c)
1570            );
1571
1572            // This candidate is added to the list of remote candidates.  However,
1573            // the ICE agent does not pair this candidate with any local candidates.
1574            self.remote_candidates.push(c);
1575
1576            self.remote_candidates.len() - 1
1577        };
1578
1579        let maybe_pair = self
1580            .candidate_pairs
1581            .iter_mut()
1582            .find(|p| p.local_idx() == local_idx && p.remote_idx() == remote_idx);
1583
1584        if let Some(pair) = maybe_pair {
1585            // When the pair is already on the checklist:
1586            trace!("Found existing pair for STUN request: {:?}", pair);
1587
1588            // TODO: The spec has all these ideas about resetting to Waiting state
1589            // for the candidate pair. I think that's to do speeding up the triggered
1590            // checks if a nomination comes through. It doesn't seem to make much
1591            // sense in this implementation, where a nomination jumps the queue.
1592            // https://datatracker.ietf.org/doc/html/rfc8445#section-7.3.1.4
1593        } else {
1594            // If the pair is not already on the checklist:
1595            let local = &self.local_candidates[local_idx];
1596            let remote = &self.remote_candidates[remote_idx];
1597
1598            if local.discarded() {
1599                return; // Ignore STUN requests to discarded candidates
1600            }
1601
1602            let prio = CandidatePair::calculate_prio(self.controlling, remote.prio(), local.prio());
1603
1604            // *  Its state is set to Waiting. (this is the default)
1605            // *  The pair is inserted into the checklist based on its priority.
1606            // *  The pair is enqueued into the triggered-check queue.
1607            let pair = CandidatePair::new(local_idx, local.kind(), remote_idx, remote.kind(), prio);
1608
1609            debug!("Created new pair for STUN request: {:?}", Pii(&pair));
1610
1611            self.candidate_pairs.push(pair);
1612            self.candidate_pairs.sort();
1613        }
1614
1615        let pair = self
1616            .candidate_pairs
1617            .iter_mut()
1618            .find(|p| p.local_idx() == local_idx && p.remote_idx() == remote_idx)
1619            // unwrap is fine since we have inserted a pair if it was missing.
1620            .unwrap();
1621
1622        let local = pair.local_candidate(&self.local_candidates);
1623        let proto = local.proto();
1624        let local_addr = local.base();
1625        let remote = pair.remote_candidate(&self.remote_candidates);
1626        let remote_addr = remote.addr();
1627
1628        pair.increase_remote_binding_requests(req.now);
1629
1630        if self.ice_lite && !self.controlling {
1631            // ice-lite sends no checks of its own, so this pair can never be
1632            // promoted by a binding response and stays `Waiting` for its
1633            // whole life. `has_viable_remote_candidate` therefore never
1634            // reports the remote, and `Rtc::accepts` refuses the peer's
1635            // non-STUN traffic until nomination has given us a send address.
1636            //
1637            // An answered binding request is not return-routability proof
1638            // the way a binding *response* is, and this does not claim to
1639            // be. It is the only validation an ice-lite agent can ever
1640            // have, and for a controlled agent it grants strictly less
1641            // than an attacker already has: a forged USE-CANDIDATE request
1642            // already reaches `pair.nominate()` below and redirects
1643            // egress, while this only lets ingress reach DTLS/SRTP.
1644            //
1645            // A *controlling* ice-lite agent is left alone: there,
1646            // `CheckState::Succeeded` feeds `evaluate_nomination()` just
1647            // below, so promoting a pair here would let one forged request
1648            // with a high PRIORITY choose the send address.
1649            pair.record_remote_binding_request_success();
1650        }
1651
1652        if !self.controlling && !pair.is_nominated() && req.use_candidate {
1653            // We need to answer a nomination request with a binding request
1654            // in the other direction.
1655            //
1656            // If this is ice-lite, we make it successful straight away.
1657            pair.nominate(self.ice_lite);
1658        }
1659
1660        // A controlled ice-lite agent sends on a pair the controlling agent
1661        // still nominates: after a NAT rebinding the controlling agent keeps
1662        // checking its selected pair (with USE-CANDIDATE, as libwebrtc does
1663        // towards a lite peer) from a new source, which forms a new pair with a
1664        // peer-reflexive remote of lower priority than the old one. Choosing
1665        // by priority alone kept egress on the dead address until the old pair
1666        // was pruned (RECENT_BINDING_REQUEST, 15 s). See `evaluate_nomination`.
1667        let renominated = self.ice_lite && !self.controlling && req.use_candidate;
1668        if renominated {
1669            pair.record_use_candidate(req.now);
1670        }
1671
1672        if self.controlling && pair.state() == CheckState::Succeeded {
1673            // See if we can nominate something now.
1674            self.evaluate_nomination(req.now);
1675        } else if renominated {
1676            self.evaluate_nomination(req.now);
1677        }
1678
1679        let (_, password) = self.stun_credentials(true);
1680
1681        let reply = StunMessage::binding_reply(req.trans_id, req.source);
1682
1683        trace!(
1684            "Send STUN reply: {} -> {} {:?}",
1685            local_addr, remote_addr, reply
1686        );
1687
1688        let mut buf = vec![0_u8; self.mtu()];
1689
1690        let sha1_hmac =
1691            |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads);
1692        let n = reply
1693            .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac)
1694            .expect("IO error writing STUN reply");
1695        buf.truncate(n);
1696
1697        let trans = Transmit {
1698            proto,
1699            source: local_addr,
1700            destination: remote_addr,
1701            contents: buf.into(),
1702        };
1703
1704        self.transmit.push_back(trans);
1705    }
1706
1707    fn send_role_conflict_reply(&mut self, req: &StunRequest) {
1708        let (_, password) = self.stun_credentials(true);
1709
1710        let reply = StunMessage::binding_role_conflict_reply(req.trans_id);
1711
1712        debug!(
1713            "Reply 487 Role Conflict (keep {} role): {} -> {}",
1714            role_name(self.controlling),
1715            req.destination,
1716            req.source,
1717        );
1718
1719        let mut buf = vec![0_u8; self.mtu()];
1720
1721        let sha1_hmac =
1722            |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads);
1723        let n = reply
1724            .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac)
1725            .expect("IO error writing STUN error reply");
1726        buf.truncate(n);
1727
1728        let trans = Transmit {
1729            proto: req.proto,
1730            source: req.destination,
1731            destination: req.source,
1732            contents: buf.into(),
1733        };
1734
1735        self.transmit.push_back(trans);
1736    }
1737
1738    /// Switches the controlling/controlled role and recomputes pair priorities
1739    /// per RFC 8445 §7.3.1.1.
1740    fn switch_role(&mut self, controlling: bool) {
1741        if self.controlling == controlling {
1742            return;
1743        }
1744
1745        debug!(
1746            "Switch role: {} -> {}",
1747            role_name(self.controlling),
1748            role_name(controlling),
1749        );
1750
1751        self.controlling = controlling;
1752
1753        for i in 0..self.candidate_pairs.len() {
1754            let local_idx = self.candidate_pairs[i].local_idx();
1755            let remote_idx = self.candidate_pairs[i].remote_idx();
1756            let local_prio = self.local_candidates[local_idx].prio();
1757            let remote_prio = self.remote_candidates[remote_idx].prio();
1758            let new_prio = CandidatePair::calculate_prio(controlling, remote_prio, local_prio);
1759            self.candidate_pairs[i].set_prio(new_prio);
1760        }
1761        self.candidate_pairs.sort();
1762    }
1763
1764    fn stun_client_binding_request(&mut self, now: Instant, pair_idx: usize) {
1765        let (username, password) = self.stun_credentials(false);
1766
1767        let pair = &mut self.candidate_pairs[pair_idx];
1768        let local = pair.local_candidate(&self.local_candidates);
1769        let remote = pair.remote_candidate(&self.remote_candidates);
1770        let prio = local.prio_prflx();
1771        // Only the controlling side sends USE-CANDIDATE.
1772        let use_candidate = self.controlling && pair.is_nominated();
1773
1774        let trans_id = pair.new_attempt(now, &self.timing_config, self.controlling);
1775
1776        self.stats.bind_request_sent += 1;
1777
1778        let binding = StunMessage::binding_request(
1779            &username,
1780            trans_id,
1781            self.controlling,
1782            self.control_tie_breaker,
1783            prio,
1784            use_candidate,
1785        );
1786
1787        trace!(
1788            "Send STUN request: {} -> {} {:?}",
1789            local.base(),
1790            remote.addr(),
1791            binding
1792        );
1793
1794        let mut buf = vec![0_u8; self.mtu()];
1795
1796        let sha1_hmac =
1797            |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads);
1798        let n = binding
1799            .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac)
1800            .expect("IO error writing STUN reply");
1801        buf.truncate(n);
1802
1803        let trans = Transmit {
1804            proto: local.proto(),
1805            source: local.base(),
1806            destination: remote.addr(),
1807            contents: buf.into(),
1808        };
1809
1810        self.transmit.push_back(trans);
1811    }
1812
1813    /// Handle a STUN binding error response.
1814    ///
1815    /// We only act on 487 (Role Conflict) per RFC 8445 §7.3.1.1: switch to
1816    /// the opposite role, but only if the request that triggered the 487 was
1817    /// sent under our current role. Otherwise the response is stale —
1818    /// in-flight from before an earlier swap — and acting on it would flap.
1819    fn stun_client_handle_error(&mut self, message: StunMessage<'_>) {
1820        let Some((code, _)) = message.error_code() else {
1821            return;
1822        };
1823        if code != 487 {
1824            debug!("Ignoring binding error response with code {code}");
1825            return;
1826        }
1827
1828        let trans_id = message.trans_id();
1829        let attempt = self
1830            .candidate_pairs
1831            .iter()
1832            .find_map(|p| p.binding_attempt(trans_id));
1833
1834        let Some(attempt) = attempt else {
1835            debug!("Ignore 487 for unknown transaction id");
1836            return;
1837        };
1838
1839        if attempt.controlling() != self.controlling {
1840            debug!(
1841                "Ignore stale 487 (request was sent as {}, we are now {})",
1842                role_name(attempt.controlling()),
1843                role_name(self.controlling),
1844            );
1845            return;
1846        }
1847
1848        debug!(
1849            "Got 487 Role Conflict, switching from {}",
1850            role_name(self.controlling),
1851        );
1852        self.switch_role(!self.controlling);
1853    }
1854
1855    fn stun_client_handle_response(&mut self, now: Instant, message: StunMessage<'_>) {
1856        // Find the candidate pair that this trans_id was sent for.
1857        let trans_id = message.trans_id();
1858        let maybe_pair = self
1859            .candidate_pairs
1860            .iter_mut()
1861            .find(|p| p.binding_attempt(trans_id).is_some());
1862
1863        self.stats.bind_success_recv += 1;
1864
1865        let pair = match maybe_pair {
1866            Some(v) => v,
1867            // Not finding the candidate pair is fine. That might mean the
1868            // binding response came in "too late", after we discarded the
1869            // pair for some reason.
1870            None => {
1871                debug!("No pair found for STUN response: {:?}", message);
1872                return;
1873            }
1874        };
1875
1876        // The ICE agent MUST check the mapped address from the STUN response.
1877        // If the transport address does not match any of the local candidates
1878        // that the agent knows about, the mapped address represents a new
1879        // candidate: a peer-reflexive candidate.
1880        let mapped_address = message
1881            .mapped_address()
1882            // This should be caught in the parsing.
1883            .expect("Mapped address in STUN response");
1884
1885        let found_in_local = self
1886            .local_candidates
1887            .iter()
1888            .enumerate()
1889            .find(|(_, c)| c.addr() == mapped_address);
1890
1891        let (pair, valid_idx) = if let Some((valid_idx, _)) = found_in_local {
1892            // Note, the valid_idx might not be the same as the local_idx that we
1893            // sent the request from. This might happen for hosts with asymmetric
1894            // routing, traffic leaving on one interface and responses coming back
1895            // on another.
1896            trace!(
1897                "Found local candidate for mapped address: {}",
1898                mapped_address
1899            );
1900            (pair, valid_idx)
1901        } else {
1902            let local_sent_from = pair.local_candidate(&self.local_candidates);
1903
1904            // Like other candidates, a peer-reflexive candidate has a type, base, priority,
1905            // and foundation. They are computed as follows:
1906
1907            // o  The priority is the value of the PRIORITY attribute in the Binding
1908            //     request.
1909            //
1910            // The PRIORITY attribute MUST be included in a Binding request and be
1911            // set to the value computed by the algorithm in Section 5.1.2 for the
1912            // local candidate, but with the candidate type preference of peer-
1913            // reflexive candidates.
1914            let prio = local_sent_from.prio_prflx();
1915
1916            // o  The base is the local candidate of the candidate pair from which
1917            //     the Binding request was sent.
1918            let base = local_sent_from.base();
1919
1920            // o  The type is peer reflexive.
1921            let candidate = Candidate::peer_reflexive(
1922                local_sent_from.proto(),
1923                mapped_address,
1924                base,
1925                prio,
1926                None,
1927                self.local_credentials.ufrag.clone(),
1928            );
1929
1930            debug!(
1931                "Created local peer reflexive candidate for mapped address: {}",
1932                Pii(&mapped_address)
1933            );
1934
1935            // The ICE agent does not need to pair the peer-reflexive candidate with
1936            // remote candidates.
1937            // If an agent wishes to pair the peer-reflexive candidate with remote
1938            // candidates other than the one in the valid pair that will be generated,
1939            // the agent MAY provide updated candidate information to the peer that includes
1940            // the peer-reflexive candidate.  This will cause the peer-reflexive candidate
1941            // to be paired with all other remote candidates.
1942
1943            // For now we do not tell the other side about discovered peer-reflexive candidates.
1944            // We just include it in our list of local candidates and use it for the "valid pair".
1945            self.local_candidates.push(candidate);
1946
1947            let idx = self.local_candidates.len() - 1;
1948
1949            (pair, idx)
1950        };
1951
1952        pair.record_binding_response(now, trans_id, valid_idx);
1953
1954        // For a controlled agent, a successful check can make a nominated pair valid.
1955        self.evaluate_nomination(now);
1956
1957        // State might change when we get a response.
1958        self.evaluate_state(now);
1959    }
1960
1961    fn evaluate_nomination(&mut self, now: Instant) {
1962        let nominated_pair_priority = self.nominated_pair_priority();
1963
1964        let best_prio = if self.controlling {
1965            // For controlling agents, we pick the best candidate pair using
1966            // this strategy.
1967            self.candidate_pairs
1968                .iter_mut()
1969                .filter(|p| p.state() == CheckState::Succeeded)
1970                .max_by_key(|p| p.prio())
1971        } else if self.ice_lite {
1972            // A controlled ice-lite agent picks the highest-priority pair among
1973            // those the controlling agent still nominates (a USE-CANDIDATE
1974            // request within LITE_NOMINATION_FRESH); a pair it stopped
1975            // nominating loses to one it nominates now, whatever their
1976            // priorities (a NAT rebinding: the old tuple goes quiet, the new
1977            // peer-reflexive pair has a lower priority). With no fresh
1978            // nomination, the highest-priority nominated pair as before.
1979            let fresh = |p: &CandidatePair| {
1980                p.last_use_candidate()
1981                    .is_some_and(|t| now.saturating_duration_since(t) < LITE_NOMINATION_FRESH)
1982            };
1983            let any_fresh = self
1984                .candidate_pairs
1985                .iter()
1986                .any(|p| p.is_nominated() && fresh(p));
1987            self.candidate_pairs
1988                .iter_mut()
1989                .filter(|p| p.is_nominated() && (!any_fresh || fresh(p)))
1990                .max_by_key(|p| p.prio())
1991        } else {
1992            // For controlled agents, we pick the best pair from what the controlling
1993            // agent has indicated with USE-CANDIDATE stun attribute. RFC 8445 §7.3.1.5
1994            // lets us act on a nomination only once the pair is valid, i.e. our own
1995            // check on it succeeded, so a pair the peer nominated but we cannot reach
1996            // never becomes the send path.
1997            self.candidate_pairs
1998                .iter_mut()
1999                .filter(|p| p.is_nominated() && p.state() == CheckState::Succeeded)
2000                .max_by_key(|p| p.prio())
2001        };
2002
2003        if let Some(best_prio) = best_prio {
2004            if self.ice_lite && !self.controlling {
2005                if self.nominated_send == Some(best_prio.id()) {
2006                    return;
2007                }
2008            } else if let Some(nominated) = nominated_pair_priority {
2009                if nominated == best_prio.prio() {
2010                    // The best prio is also the current nominated prio. Make
2011                    // no changes since there can be multiple pairs having the
2012                    // same best_prio.
2013                    return;
2014                }
2015            }
2016            trace!("Nominating best candidate");
2017
2018            if !best_prio.is_nominated() && (self.controlling || self.ice_lite) {
2019                // ice lite progresses pair to success straight away.
2020                best_prio.nominate(self.ice_lite);
2021            }
2022
2023            let local = best_prio.local_candidate(&self.local_candidates);
2024            let remote = best_prio.remote_candidate(&self.remote_candidates);
2025
2026            self.nominated_send = Some(best_prio.id());
2027            self.emit_event(IceAgentEvent::NominatedSend {
2028                proto: local.proto(),
2029                source: local.base(),
2030                destination: remote.addr(),
2031            })
2032        }
2033    }
2034
2035    fn nominated_pair_priority(&self) -> Option<u64> {
2036        let id = self.nominated_send?;
2037
2038        self.candidate_pairs
2039            .iter()
2040            .find_map(|p| (p.id() == id).then_some(p.prio()))
2041    }
2042
2043    fn nominated_pair(&self) -> Option<&CandidatePair> {
2044        let id = self.nominated_send?;
2045        self.candidate_pairs.iter().find(|p| p.id() == id)
2046    }
2047
2048    /// The round-trip time of the most recent successful STUN binding
2049    /// transaction on the nominated candidate pair.
2050    ///
2051    /// Returns `None` if there is no nominated pair, or no successful
2052    /// binding response has been recorded on it.
2053    ///
2054    /// This is the ICE-level equivalent of
2055    /// [`RTCIceCandidatePairStats.currentRoundTripTime`][1] and is updated
2056    /// on every STUN keepalive/consent exchange — useful for measuring RTT
2057    /// on receive-only endpoints where RTP-based RTT estimates aren't
2058    /// available.
2059    ///
2060    /// [1]: https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-currentroundtriptime
2061    pub fn nominated_pair_rtt(&self) -> Option<Duration> {
2062        self.nominated_pair().and_then(|p| p.last_successful_rtt())
2063    }
2064
2065    /// Sum of all RTTs measured from successful STUN binding transactions
2066    /// on the nominated candidate pair over its lifetime.
2067    ///
2068    /// Spec equivalent of [`RTCIceCandidatePairStats.totalRoundTripTime`][1].
2069    /// Divide by [`nominated_pair_responses_received`] to get the average.
2070    ///
2071    /// Returns `None` if there is no nominated pair.
2072    ///
2073    /// [`nominated_pair_responses_received`]: Self::nominated_pair_responses_received
2074    /// [1]: https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-totalroundtriptime
2075    pub fn nominated_pair_total_rtt(&self) -> Option<Duration> {
2076        self.nominated_pair().map(|p| p.total_round_trip_time())
2077    }
2078
2079    /// Total number of STUN binding responses received on the nominated
2080    /// candidate pair over its lifetime.
2081    ///
2082    /// Spec equivalent of [`RTCIceCandidatePairStats.responsesReceived`][1].
2083    ///
2084    /// Returns `None` if there is no nominated pair.
2085    ///
2086    /// [1]: https://www.w3.org/TR/webrtc-stats/#dom-rtcicecandidatepairstats-responsesreceived
2087    pub fn nominated_pair_responses_received(&self) -> Option<u64> {
2088        self.nominated_pair().map(|p| p.responses_received())
2089    }
2090
2091    fn set_connection_state(&mut self, state: IceConnectionState, reason: &'static str) {
2092        if self.state != state {
2093            debug!("State change ({}): {:?} -> {:?}", reason, self.state, state);
2094            self.state = state;
2095            self.emit_event(IceAgentEvent::IceConnectionStateChange(state));
2096        }
2097    }
2098
2099    fn evaluate_state(&mut self, now: Instant) {
2100        use IceConnectionState::*;
2101
2102        let mut any_nomination = false;
2103        let mut any_still_possible = false;
2104
2105        for p in &self.candidate_pairs {
2106            // A nominated pair counts once it is valid (RFC 8445 §8.1.1), which is
2107            // also when `evaluate_nomination` can make it the send path. Until then
2108            // it is just another pair being checked.
2109            if p.is_nominated() && p.state() == CheckState::Succeeded {
2110                any_nomination = true;
2111            } else if p.is_still_possible(now, &self.timing_config) {
2112                any_still_possible = true;
2113            }
2114        }
2115
2116        // As a special case, before the ice agent has received any candidates or
2117        // discovered a peer reflexive via a STUN message, the agent is still viable. This is
2118        // also the case for ice_restart.
2119        if self.remote_candidates.is_empty() || self.local_candidates.is_empty() {
2120            any_still_possible = true;
2121        }
2122
2123        match self.state {
2124            New => {
2125                self.set_connection_state(Checking, "new connection");
2126            }
2127            Checking | Disconnected => {
2128                if any_nomination {
2129                    if self.ice_lite {
2130                        self.set_connection_state(Completed, "got nomination in ice lite");
2131                        return;
2132                    }
2133                    if any_still_possible {
2134                        self.set_connection_state(Connected, "got nomination, still trying others");
2135                    } else {
2136                        self.set_connection_state(Completed, "got nomination, no others to try");
2137                    }
2138                } else if !any_still_possible {
2139                    self.set_connection_state(Disconnected, "no possible pairs");
2140                } else {
2141                    self.set_connection_state(Checking, "got new possible");
2142                }
2143            }
2144            Connected => {
2145                if any_nomination {
2146                    if !any_still_possible {
2147                        self.set_connection_state(Completed, "no more possible to try");
2148                    }
2149                } else if any_still_possible {
2150                    self.set_connection_state(Checking, "got new possible");
2151                } else {
2152                    self.set_connection_state(Disconnected, "none nominated");
2153                }
2154            }
2155            Completed => {
2156                if any_nomination {
2157                    if any_still_possible && !self.ice_lite {
2158                        self.set_connection_state(Connected, "got new possible");
2159                    }
2160                } else if any_still_possible {
2161                    self.set_connection_state(Checking, "got new possible");
2162                } else {
2163                    self.set_connection_state(Disconnected, "none nominated");
2164                }
2165            }
2166        }
2167    }
2168}
2169
2170impl fmt::Debug for LocalPreferenceHolder {
2171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2172        f.debug_tuple("LocalPreferenceHolder").finish()
2173    }
2174}
2175
2176#[cfg(test)]
2177mod test {
2178    use super::*;
2179    use crate::DefaultSha1HmacProvider;
2180    use std::{iter, net::SocketAddr};
2181
2182    fn host(s: impl Into<String>, proto: impl TryInto<Protocol>) -> Candidate {
2183        let s: String = s.into();
2184        Candidate::host(s.parse().unwrap(), proto).unwrap()
2185    }
2186
2187    impl IceAgent {
2188        pub(crate) fn num_candidate_pairs(&self) -> usize {
2189            self.candidate_pairs.len()
2190        }
2191
2192        fn pair_indexes(&self) -> Vec<(usize, usize)> {
2193            self.candidate_pairs
2194                .iter()
2195                .map(|c| (c.local_idx(), c.remote_idx()))
2196                .collect()
2197        }
2198    }
2199
2200    fn new_test_agent() -> IceAgent {
2201        IceAgent::new(IceCreds::new())
2202    }
2203
2204    fn ipv4_1() -> SocketAddr {
2205        "1.2.3.4:5000".parse().unwrap()
2206    }
2207    fn ipv4_2() -> SocketAddr {
2208        "2.3.4.5:5000".parse().unwrap()
2209    }
2210    fn ipv4_3() -> SocketAddr {
2211        "3.4.5.6:5000".parse().unwrap()
2212    }
2213    fn ipv4_4() -> SocketAddr {
2214        "4.5.6.7:5000".parse().unwrap()
2215    }
2216    fn ipv6_1() -> SocketAddr {
2217        "[1001::]:5000".parse().unwrap()
2218    }
2219    fn ipv6_2() -> SocketAddr {
2220        "[1002::]:5000".parse().unwrap()
2221    }
2222
2223    #[test]
2224    fn local_preference_host() {
2225        let mut agent = new_test_agent();
2226
2227        agent
2228            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2229            .unwrap();
2230        agent
2231            .add_local_candidate(Candidate::host(ipv6_1(), "udp").unwrap())
2232            .unwrap();
2233        agent
2234            .add_local_candidate(Candidate::host(ipv6_2(), "udp").unwrap())
2235            .unwrap();
2236        agent
2237            .add_local_candidate(Candidate::host(ipv4_2(), "udp").unwrap())
2238            .unwrap();
2239
2240        let v: Vec<_> = agent
2241            .local_candidates
2242            .iter()
2243            .map(|c| c.local_preference())
2244            .collect();
2245
2246        assert_eq!(v, vec![65534, 65535, 65533, 65532]);
2247    }
2248
2249    #[test]
2250    fn discard_adding_redundant() {
2251        let mut agent = new_test_agent();
2252
2253        // Frequently, a server-reflexive candidate and a host candidate will be
2254        // redundant when the agent is not behind a NAT.
2255
2256        let x2 = agent.add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap());
2257        assert!(x2.is_some());
2258
2259        // this is redundant given we have the direct host candidate above.
2260        let x1 = agent.add_local_candidate(Candidate::test_peer_rflx(ipv4_1(), ipv4_1(), "udp"));
2261        assert!(x1.is_none());
2262    }
2263
2264    #[test]
2265    fn does_not_invalidate_local_candidate_with_same_ip_but_different_kind() {
2266        let mut agent = new_test_agent();
2267        let host = Candidate::host(ipv4_1(), "udp").unwrap();
2268        let srflx = Candidate::server_reflexive(ipv4_1(), ipv4_1(), "udp").unwrap();
2269
2270        agent.add_local_candidate(host.clone()).unwrap();
2271        let invalidated = agent.invalidate_candidate(&srflx);
2272        assert!(!invalidated);
2273
2274        let invalidated = agent.invalidate_candidate(&host);
2275        assert!(invalidated);
2276    }
2277
2278    #[test]
2279    fn does_not_invalidate_local_candidate_with_same_ip_but_different_protocol() {
2280        let mut agent = new_test_agent();
2281        let udp = Candidate::host(ipv4_1(), "udp").unwrap();
2282        let tcp = Candidate::host(ipv4_1(), "tcp").unwrap();
2283
2284        agent.add_local_candidate(udp.clone()).unwrap();
2285        agent.add_local_candidate(tcp.clone()).unwrap();
2286
2287        let invalidated = agent.invalidate_candidate(&tcp);
2288        assert!(invalidated);
2289
2290        let udp_discarded = agent
2291            .local_candidates
2292            .iter()
2293            .find(|v| {
2294                v.addr() == udp.addr()
2295                    && v.base() == udp.base()
2296                    && v.raddr() == udp.raddr()
2297                    && v.kind() == udp.kind()
2298                    && v.proto() == udp.proto()
2299            })
2300            .unwrap()
2301            .discarded();
2302        assert!(!udp_discarded);
2303
2304        let tcp_discarded = agent
2305            .local_candidates
2306            .iter()
2307            .find(|v| {
2308                v.addr() == tcp.addr()
2309                    && v.base() == tcp.base()
2310                    && v.raddr() == tcp.raddr()
2311                    && v.kind() == tcp.kind()
2312                    && v.proto() == tcp.proto()
2313            })
2314            .unwrap()
2315            .discarded();
2316        assert!(tcp_discarded);
2317
2318        let invalidated = agent.invalidate_candidate(&udp);
2319        assert!(invalidated);
2320        let udp_discarded = agent
2321            .local_candidates
2322            .iter()
2323            .find(|v| {
2324                v.addr() == udp.addr()
2325                    && v.base() == udp.base()
2326                    && v.raddr() == udp.raddr()
2327                    && v.kind() == udp.kind()
2328                    && v.proto() == udp.proto()
2329            })
2330            .unwrap()
2331            .discarded();
2332        assert!(udp_discarded);
2333    }
2334
2335    #[test]
2336    fn does_not_invalidate_remote_candidate_with_same_ip_but_different_kind() {
2337        let mut agent = new_test_agent();
2338        let host = Candidate::host(ipv4_1(), "udp").unwrap();
2339        let srflx = Candidate::server_reflexive(ipv4_1(), ipv4_1(), "udp").unwrap();
2340
2341        agent.add_remote_candidate(host.clone());
2342        let invalidated = agent.invalidate_candidate(&srflx);
2343
2344        assert!(!invalidated);
2345
2346        let invalidated = agent.invalidate_candidate(&host);
2347        assert!(invalidated);
2348    }
2349
2350    #[test]
2351    fn does_not_invalidate_remote_candidate_with_same_ip_but_different_protocol() {
2352        let mut agent = new_test_agent();
2353        let udp = Candidate::host(ipv4_1(), "udp").unwrap();
2354        let tcp = Candidate::host(ipv4_1(), "tcp").unwrap();
2355
2356        agent.add_remote_candidate(udp.clone());
2357        agent.add_remote_candidate(tcp.clone());
2358
2359        let invalidated = agent.invalidate_candidate(&tcp);
2360        assert!(invalidated);
2361
2362        let udp_discarded = agent
2363            .remote_candidates
2364            .iter()
2365            .find(|v| {
2366                v.addr() == udp.addr()
2367                    && v.base() == udp.base()
2368                    && v.raddr() == udp.raddr()
2369                    && v.kind() == udp.kind()
2370                    && v.proto() == udp.proto()
2371            })
2372            .unwrap()
2373            .discarded();
2374        assert!(!udp_discarded);
2375
2376        let tcp_discarded = agent
2377            .remote_candidates
2378            .iter()
2379            .find(|v| {
2380                v.addr() == tcp.addr()
2381                    && v.base() == tcp.base()
2382                    && v.raddr() == tcp.raddr()
2383                    && v.kind() == tcp.kind()
2384                    && v.proto() == tcp.proto()
2385            })
2386            .unwrap()
2387            .discarded();
2388        assert!(tcp_discarded);
2389
2390        let invalidated = agent.invalidate_candidate(&udp);
2391        assert!(invalidated);
2392        let udp_discarded = agent
2393            .remote_candidates
2394            .iter()
2395            .find(|v| {
2396                v.addr() == udp.addr()
2397                    && v.base() == udp.base()
2398                    && v.raddr() == udp.raddr()
2399                    && v.kind() == udp.kind()
2400                    && v.proto() == udp.proto()
2401            })
2402            .unwrap()
2403            .discarded();
2404        assert!(udp_discarded);
2405    }
2406
2407    #[test]
2408    fn discard_adding_redundant_by_address_and_protocol() {
2409        let mut agent = new_test_agent();
2410
2411        // Candidates with the same SocketAddr but different protocols are considered distinct.
2412        assert!(
2413            agent
2414                .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2415                .is_some()
2416        );
2417        assert!(
2418            agent
2419                .add_local_candidate(Candidate::host(ipv4_1(), "tcp").unwrap())
2420                .is_some()
2421        );
2422        assert!(
2423            agent
2424                .add_local_candidate(Candidate::host(ipv4_1(), "ssltcp").unwrap())
2425                .is_some()
2426        );
2427
2428        // Verify these are rejected, since these tuples of address and protocol have been added.
2429        assert!(
2430            agent
2431                .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2432                .is_none()
2433        );
2434        assert!(
2435            agent
2436                .add_local_candidate(Candidate::host(ipv4_1(), "ssltcp").unwrap())
2437                .is_none()
2438        );
2439
2440        // Verify these are allowed, since these have different addresses.
2441        assert!(
2442            agent
2443                .add_local_candidate(Candidate::host(ipv4_2(), "udp").unwrap())
2444                .is_some()
2445        );
2446        assert!(
2447            agent
2448                .add_local_candidate(Candidate::host(ipv4_2(), "ssltcp").unwrap())
2449                .is_some()
2450        );
2451    }
2452
2453    #[test]
2454    fn discard_already_added_redundant() {
2455        let mut agent = new_test_agent();
2456
2457        // Frequently, a server-reflexive candidate and a host candidate will be
2458        // redundant when the agent is not behind a NAT.
2459
2460        // this is contrived, but it is redundant when we add the host candidate below.
2461        let x1 = agent.add_local_candidate(Candidate::test_peer_rflx(ipv4_1(), ipv4_1(), "udp"));
2462        assert!(x1.is_some());
2463
2464        let x2 = agent.add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap());
2465        assert!(x2.is_some());
2466
2467        let v: Vec<_> = agent
2468            .local_candidates
2469            .iter()
2470            .map(|v| v.discarded())
2471            .collect();
2472
2473        assert_eq!(v, vec![true, false]);
2474    }
2475
2476    #[test]
2477    fn form_pairs() {
2478        let mut agent = new_test_agent();
2479
2480        // local 0
2481        agent
2482            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2483            .unwrap();
2484        // local 1 "udp"
2485        agent
2486            .add_local_candidate(Candidate::test_peer_rflx(ipv4_4(), ipv4_2(), "udp"))
2487            .unwrap();
2488        // local 2 "tcp"
2489        agent
2490            .add_local_candidate(Candidate::host(ipv4_1(), "tcp").unwrap())
2491            .unwrap();
2492
2493        // remote 0
2494        agent.add_remote_candidate(Candidate::test_peer_rflx(ipv4_4(), ipv4_3(), "udp"));
2495        // remote 1 "udp"
2496        agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2497        // remote 2 "tcp"
2498        agent.add_remote_candidate(Candidate::host(ipv4_3(), "tcp").unwrap());
2499
2500        // we expect:
2501        // (host/udp host/udp) - (0, 1)
2502        // (host/udp rflx/udp) - (0, 1)
2503        // (rflx/udp host/udp) - (1, 1)
2504        // (rflx/udp rflx/udp) - (1, 0)
2505        // (host/tcp host/tcp) - (2, 2)
2506
2507        assert_eq!(
2508            agent.pair_indexes(),
2509            [(0, 1), (0, 0), (1, 1), (1, 0), (2, 2)]
2510        );
2511    }
2512
2513    #[test]
2514    fn form_pairs_skip_redundant() {
2515        let mut agent = new_test_agent();
2516
2517        agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2518        agent.add_remote_candidate(Candidate::host(ipv4_3(), "tcp").unwrap());
2519        agent
2520            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2521            .unwrap();
2522
2523        // the UDP candidates should be pair up.
2524        assert_eq!(agent.pair_indexes(), [(0, 0)]);
2525
2526        // this local UDP candidate is redundant an won't form a new pair.
2527        agent
2528            .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp"))
2529            .unwrap();
2530
2531        assert_eq!(agent.pair_indexes(), [(0, 0)]);
2532
2533        // this local TCP candidate will be paired up (This is the 3rd local candidate)
2534        agent
2535            .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "tcp"))
2536            .unwrap();
2537
2538        assert_eq!(agent.pair_indexes(), [(0, 0), (2, 1)]);
2539    }
2540
2541    #[test]
2542    fn form_pairs_replace_redundant() {
2543        let mut agent = new_test_agent();
2544
2545        agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2546        agent
2547            .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp"))
2548            .unwrap();
2549
2550        assert_eq!(agent.pair_indexes(), [(0, 0)]);
2551
2552        // this local candidate is redundant, but has higher priority than then existing pair.
2553        // it replaces the existing pair.
2554        agent
2555            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2556            .unwrap();
2557
2558        assert_eq!(agent.pair_indexes(), [(1, 0)]);
2559    }
2560
2561    #[test]
2562    fn form_pairs_replace_remote_redundant() {
2563        let mut agent = new_test_agent();
2564        agent.set_ice_lite(true);
2565
2566        // This is just prepping the test, this would have been discovered in a STUN packet.
2567        let c = Candidate::peer_reflexive(
2568            "udp",
2569            ipv4_3(),
2570            ipv4_3(),
2571            123,
2572            Some(REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION.into()),
2573            "".to_string(),
2574        );
2575
2576        agent.add_remote_candidate(c);
2577        agent
2578            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2579            .unwrap();
2580
2581        assert_eq!(agent.pair_indexes(), [(0, 0)]);
2582
2583        let now = Instant::now();
2584        agent.candidate_pairs[0].nominate(true);
2585        agent.candidate_pairs[0].increase_remote_binding_requests(now);
2586
2587        // this remote should replace the "discovered" peer reflexive added above.
2588        agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2589
2590        // The index should not have changed, since we replaced the peer reflexive remote candidate.
2591        assert_eq!(agent.pair_indexes(), [(0, 0)]);
2592
2593        let pair = &agent.candidate_pairs[0];
2594        assert!(pair.is_nominated());
2595
2596        let (req, time) = pair.remote_binding_requests();
2597        assert_eq!(req, 1);
2598        assert_eq!(time, Some(now));
2599    }
2600
2601    #[test]
2602    fn form_pairs_skip_invalidated_local() {
2603        let mut agent = new_test_agent();
2604
2605        let local = Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp");
2606
2607        agent.add_local_candidate(local.clone()).unwrap();
2608        agent.invalidate_candidate(&local);
2609
2610        agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2611
2612        // There should be no pairs since we invalidated the local candidate.
2613        assert_eq!(agent.pair_indexes(), []);
2614    }
2615
2616    #[test]
2617    fn form_pairs_skip_invalidated_remote() {
2618        let mut agent = new_test_agent();
2619
2620        let remote = Candidate::host(ipv4_3(), "udp").unwrap();
2621
2622        agent.add_remote_candidate(remote.clone());
2623        agent.invalidate_candidate(&remote);
2624
2625        agent
2626            .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp"))
2627            .unwrap();
2628
2629        // There should be no pairs since we invalidated the local candidate.
2630        assert_eq!(agent.pair_indexes(), []);
2631    }
2632
2633    #[test]
2634    fn poll_time_must_timing_advance() {
2635        let mut agent = new_test_agent();
2636        agent
2637            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2638            .unwrap();
2639        agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2640
2641        let now1 = Instant::now();
2642        agent.handle_timeout(now1);
2643        let now2 = agent.poll_timeout().unwrap();
2644
2645        assert!(now2 - now1 == Duration::from_millis(50));
2646    }
2647
2648    #[test]
2649    fn no_disconnect_before_remote_candidates() {
2650        let mut agent = new_test_agent();
2651
2652        let now = Instant::now();
2653        agent.handle_timeout(now);
2654
2655        while let Some(ev) = agent.poll_event() {
2656            if let IceAgentEvent::IceConnectionStateChange(s) = ev {
2657                assert!(s != IceConnectionState::Disconnected);
2658            }
2659        }
2660
2661        agent.handle_timeout(now + Duration::from_millis(200));
2662        while let Some(ev) = agent.poll_event() {
2663            if let IceAgentEvent::IceConnectionStateChange(s) = ev {
2664                assert!(s != IceConnectionState::Disconnected);
2665            }
2666        }
2667    }
2668
2669    #[test]
2670    fn does_not_accept_response_with_unknown_transaction_id() {
2671        let mut agent = new_test_agent();
2672        let remote_creds = IceCreds::new();
2673        let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
2674        remote_candidate.set_ufrag(&remote_creds.ufrag);
2675
2676        agent.set_remote_credentials(remote_creds.clone());
2677        agent
2678            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2679            .unwrap();
2680        agent.add_remote_candidate(remote_candidate);
2681        agent.handle_timeout(Instant::now());
2682
2683        let payload = Vec::from(agent.poll_transmit().unwrap().contents);
2684        let stun_message = StunMessage::parse(&payload).unwrap();
2685
2686        let valid_reply =
2687            make_authenticated_stun_reply(stun_message.trans_id(), ipv4_4(), &remote_creds.pass);
2688        let fake_reply =
2689            make_authenticated_stun_reply(TransId::new(), ipv4_4(), &remote_creds.pass);
2690
2691        assert!(!agent.accepts_message(&StunMessage::parse(&fake_reply).unwrap()));
2692        assert!(agent.accepts_message(&StunMessage::parse(&valid_reply).unwrap()));
2693    }
2694
2695    #[test]
2696    fn ignore_binding_indication() {
2697        // STUN Binding Indication from OBS WHIP Client using Wireshark
2698        //
2699        // Session Traversal Utilities for NAT
2700        // Message Type: 0x0011 (Binding Indication)
2701        // Message Length: 8
2702        // Message Cookie: 2112a442
2703        // Message Transaction ID: fb9859e67da4bc991c0cab8f
2704        // [STUN Network Version: RFC-5389/8489 (3)]
2705        // Attributes
2706        //     FINGERPRINT
2707        //         Attribute Type: FINGERPRINT
2708        //         Attribute Length: 4
2709        //         CRC-32: 0xed80c297 [correct]
2710        //         [CRC-32 Status: Good]
2711        const BINDING: &[u8] = &[
2712            0x00, 0x11, 0x00, 0x08, 0x21, 0x12, 0xa4, 0x42, 0xfb, 0x98, 0x59, 0xe6, 0x7d, 0xa4,
2713            0xbc, 0x99, 0x1c, 0x0c, 0xab, 0x8f, 0x80, 0x28, 0x00, 0x04, 0xed, 0x80, 0xc2, 0x97,
2714        ];
2715        let stun_msg = StunMessage::parse(BINDING).unwrap();
2716
2717        let agent = new_test_agent();
2718        assert!(!agent.accepts_message(&stun_msg));
2719    }
2720
2721    #[test]
2722    fn queues_stun_binding_before_remote_creds() {
2723        let mut agent = new_test_agent();
2724        agent
2725            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2726            .unwrap();
2727
2728        let remote_creds = IceCreds::new();
2729        let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
2730        remote_candidate.set_ufrag(&remote_creds.ufrag);
2731        let prio = remote_candidate.prio();
2732        agent.add_remote_candidate(remote_candidate);
2733
2734        let serialized_req = make_serialized_binding_request(
2735            &agent.local_credentials,
2736            &remote_creds,
2737            !agent.controlling(),
2738            prio,
2739        );
2740        let binding_req = StunMessage::parse(&serialized_req).unwrap();
2741
2742        // Should not be dropped
2743        assert!(agent.accepts_message(&binding_req));
2744        agent.handle_packet(
2745            Instant::now(),
2746            StunPacket {
2747                message: binding_req,
2748                source: ipv4_3(),
2749                destination: ipv4_1(),
2750                proto: Protocol::Udp,
2751            },
2752        );
2753
2754        // Should not yet get a response
2755        agent.handle_timeout(Instant::now());
2756        assert!(agent.poll_transmit().is_none());
2757
2758        agent.set_remote_credentials(remote_creds.clone());
2759        agent.handle_timeout(Instant::now());
2760
2761        // Now should have a response
2762        let payload = Vec::from(agent.poll_transmit().unwrap().contents);
2763        let stun_message = StunMessage::parse(&payload).unwrap();
2764        assert!(stun_message.is_successful_binding_response());
2765    }
2766
2767    /// On simultaneous controlling/controlling startup, the lower-tiebreaker
2768    /// agent typically receives the peer's request first (server-side swap)
2769    /// while its own in-flight requests — sent under the old role — are
2770    /// still being 487'd by the peer. Each of those stale 487s must be
2771    /// ignored, otherwise the role flaps with every retransmit until the
2772    /// in-flight drain finishes.
2773    #[test]
2774    pub fn ignores_stale_487_after_role_swap() {
2775        let mut agent = new_test_agent();
2776        agent.set_controlling(true);
2777        let remote_creds = IceCreds::new();
2778        agent.set_remote_credentials(remote_creds.clone());
2779        agent
2780            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2781            .unwrap();
2782        let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
2783        remote_candidate.set_ufrag(&remote_creds.ufrag);
2784        agent.add_remote_candidate(remote_candidate);
2785
2786        // Drive one binding request out — recorded as `controlling=true`.
2787        agent.handle_timeout(Instant::now());
2788        let req_payload = Vec::from(agent.poll_transmit().unwrap().contents);
2789        let trans_id = StunMessage::parse(&req_payload).unwrap().trans_id();
2790
2791        // Simulate that an earlier 487 (or a server-side conflict from an
2792        // incoming peer request) already moved us to controlled.
2793        agent.set_controlling(false);
2794
2795        // Now the original request's 487 lands. It is stale: the attempt was
2796        // sent as controlling, but we are no longer controlling.
2797        let reply = make_role_conflict_reply(trans_id, &remote_creds.pass);
2798        agent.handle_packet(
2799            Instant::now(),
2800            StunPacket {
2801                proto: Protocol::Udp,
2802                source: ipv4_3(),
2803                destination: ipv4_1(),
2804                message: StunMessage::parse(&reply).unwrap(),
2805            },
2806        );
2807
2808        assert!(
2809            !agent.controlling(),
2810            "stale 487 must not flip role back to controlling"
2811        );
2812    }
2813
2814    #[test]
2815    pub fn discards_packet_from_unknown_candidate() {
2816        let mut agent = new_test_agent();
2817        let remote_creds = IceCreds::new();
2818        agent.set_remote_credentials(remote_creds.clone());
2819
2820        let request =
2821            make_serialized_binding_request(&agent.local_credentials, &remote_creds, false, 0);
2822
2823        agent.handle_packet(
2824            Instant::now(),
2825            StunPacket {
2826                proto: Protocol::Udp,
2827                source: ipv4_1(),
2828                destination: ipv4_2(),
2829                message: StunMessage::parse(&request).unwrap(),
2830            },
2831        );
2832
2833        assert!(agent.poll_transmit().is_none());
2834    }
2835
2836    #[test]
2837    fn ignores_remote_candidates_that_cant_reach_the_peer() {
2838        for addr in [
2839            "3.4.5.6 0",
2840            "0.0.0.0 5000",
2841            ":: 5000",
2842            "::ffff:0.0.0.0 5000",
2843        ] {
2844            let mut agent = new_test_agent();
2845            agent.set_remote_credentials(IceCreds::new());
2846            for local in [ipv4_1(), ipv6_1()] {
2847                agent
2848                    .add_local_candidate(Candidate::host(local, "udp").unwrap())
2849                    .unwrap();
2850            }
2851
2852            let sdp = format!("candidate:1 1 udp 2130706431 {addr} typ host");
2853            agent.add_remote_candidate(Candidate::from_sdp_string(&sdp).unwrap());
2854
2855            assert_eq!(agent.remote_candidates().count(), 0, "{addr}");
2856            assert_eq!(agent.num_candidate_pairs(), 0, "{addr}");
2857            agent.handle_timeout(Instant::now());
2858            assert!(agent.poll_transmit().is_none(), "{addr}");
2859        }
2860    }
2861
2862    #[test]
2863    fn ignores_binding_requests_from_addresses_that_cant_be_replied_to() {
2864        for (source, destination) in [
2865            ("3.4.5.6:0", ipv4_1()),
2866            ("0.0.0.0:5000", ipv4_1()),
2867            ("[::]:5000", ipv6_1()),
2868            ("[::ffff:0.0.0.0]:5000", ipv6_1()),
2869        ] {
2870            let mut agent = new_test_agent();
2871            for local in [ipv4_1(), ipv6_1()] {
2872                agent
2873                    .add_local_candidate(Candidate::host(local, "udp").unwrap())
2874                    .unwrap();
2875            }
2876            let remote_creds = IceCreds::new();
2877            agent.set_remote_credentials(remote_creds.clone());
2878
2879            let request = make_serialized_binding_request(
2880                &agent.local_credentials,
2881                &remote_creds,
2882                !agent.controlling(),
2883                1,
2884            );
2885
2886            agent.handle_packet(
2887                Instant::now(),
2888                StunPacket {
2889                    proto: Protocol::Udp,
2890                    source: source.parse().unwrap(),
2891                    destination,
2892                    message: StunMessage::parse(&request).unwrap(),
2893                },
2894            );
2895
2896            // Neither a peer-reflexive candidate nor a reply.
2897            assert_eq!(agent.remote_candidates().count(), 0, "{source}");
2898            assert!(agent.poll_transmit().is_none(), "{source}");
2899        }
2900    }
2901
2902    #[test]
2903    pub fn no_disconnect_missing_local_candidates() {
2904        let mut agent = new_test_agent();
2905        agent.set_remote_credentials(IceCreds::new().clone());
2906
2907        agent.add_remote_candidate(host("1.1.1.1:1000", "udp"));
2908        agent.handle_timeout(Instant::now());
2909        agent.handle_timeout(Instant::now() + Duration::from_millis(100));
2910
2911        let events = iter::from_fn(|| agent.poll_event()).collect::<Vec<_>>();
2912        assert!(!events.contains(&IceAgentEvent::IceConnectionStateChange(
2913            IceConnectionState::Disconnected
2914        )));
2915    }
2916
2917    #[test]
2918    fn discarded_local_candidates_are_not_returned() {
2919        let mut agent = new_test_agent();
2920        let host1 = Candidate::host(ipv4_1(), "udp").unwrap();
2921        let host2 = Candidate::host(ipv4_2(), "udp").unwrap();
2922
2923        let host1 = agent.add_local_candidate(host1.clone()).unwrap().clone();
2924        let host2 = agent.add_local_candidate(host2.clone()).unwrap().clone();
2925        agent.invalidate_candidate(&host1);
2926
2927        assert_eq!(agent.local_candidates().collect::<Vec<_>>(), vec![host2]);
2928    }
2929
2930    #[test]
2931    fn discarded_remote_candidates_are_not_returned() {
2932        let mut agent = new_test_agent();
2933        let host1 = Candidate::host(ipv4_1(), "udp").unwrap();
2934        let host2 = Candidate::host(ipv4_2(), "udp").unwrap();
2935
2936        agent.add_remote_candidate(host1.clone());
2937        agent.add_remote_candidate(host2.clone());
2938        agent.invalidate_candidate(&host1);
2939
2940        assert_eq!(agent.remote_candidates().collect::<Vec<_>>(), vec![host2]);
2941    }
2942
2943    #[test]
2944    fn ice_lite_remote_candidate_viable_after_binding_request() {
2945        let mut agent = new_test_agent();
2946        agent.set_ice_lite(true);
2947        agent.set_controlling(false);
2948        agent
2949            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2950            .unwrap();
2951
2952        let remote_creds = IceCreds::new();
2953        agent.set_remote_credentials(remote_creds.clone());
2954
2955        let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
2956        remote_candidate.set_ufrag(&remote_creds.ufrag);
2957        let prio = remote_candidate.prio();
2958        agent.add_remote_candidate(remote_candidate);
2959
2960        // Nothing has been heard from the remote yet.
2961        assert!(!agent.has_viable_remote_candidate(ipv4_3()));
2962
2963        let serialized_req = make_serialized_binding_request(
2964            &agent.local_credentials,
2965            &remote_creds,
2966            true, // the remote is the controlling agent
2967            prio,
2968        );
2969        let binding_req = StunMessage::parse(&serialized_req).unwrap();
2970
2971        let now = Instant::now();
2972        assert!(agent.handle_packet(
2973            now,
2974            StunPacket {
2975                message: binding_req,
2976                source: ipv4_3(),
2977                destination: ipv4_1(),
2978                proto: Protocol::Udp,
2979            },
2980        ));
2981
2982        // We answered a binding request whose integrity checked out against our
2983        // local password. An ice-lite agent sends no checks of its own, so this
2984        // is the only validation the pair will ever get, and it must be enough
2985        // for the remote address to count as viable.
2986        assert!(agent.has_viable_remote_candidate(ipv4_3()));
2987    }
2988
2989    #[test]
2990    fn ice_lite_validation_survives_trickle() {
2991        let mut agent = new_test_agent();
2992        agent.set_ice_lite(true);
2993        agent.set_controlling(false);
2994        agent
2995            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2996            .unwrap();
2997        let remote_creds = IceCreds::new();
2998        agent.set_remote_credentials(remote_creds.clone());
2999        // Receive a check before the remote host candidate is signaled.
3000        let remote = Candidate::host(ipv4_3(), "udp").unwrap();
3001        let serialized = make_serialized_binding_request(
3002            &agent.local_credentials,
3003            &remote_creds,
3004            true,
3005            remote.prio() - 1,
3006        );
3007        assert!(agent.handle_packet(
3008            Instant::now(),
3009            StunPacket {
3010                message: StunMessage::parse(&serialized).unwrap(),
3011                source: ipv4_3(),
3012                destination: ipv4_1(),
3013                proto: Protocol::Udp,
3014            }
3015        ));
3016        assert!(agent.has_viable_remote_candidate(ipv4_3()));
3017        // The higher-priority signaled candidate replaces the peer-reflexive pair.
3018        agent.add_remote_candidate(remote);
3019        assert!(
3020            agent.has_viable_remote_candidate(ipv4_3()),
3021            "trickling the real candidate must retain validated ingress"
3022        );
3023    }
3024
3025    #[test]
3026    fn ice_lite_controlling_does_not_nominate_on_a_binding_request() {
3027        // The controlled case above is the supported one. A *controlling*
3028        // ice-lite agent must not be promoted the same way: there,
3029        // `CheckState::Succeeded` feeds `evaluate_nomination`, so one
3030        // request — whose PRIORITY the sender chooses — would pick the
3031        // send address without any return-routability proof.
3032        let mut agent = new_test_agent();
3033        agent.set_ice_lite(true);
3034        agent.set_controlling(true);
3035        agent
3036            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
3037            .unwrap();
3038
3039        let remote_creds = IceCreds::new();
3040        agent.set_remote_credentials(remote_creds.clone());
3041
3042        let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
3043        remote_candidate.set_ufrag(&remote_creds.ufrag);
3044        let prio = remote_candidate.prio();
3045        agent.add_remote_candidate(remote_candidate);
3046
3047        let serialized_req = make_serialized_binding_request(
3048            &agent.local_credentials,
3049            &remote_creds,
3050            false, // we are the controlling agent
3051            prio,
3052        );
3053        let binding_req = StunMessage::parse(&serialized_req).unwrap();
3054
3055        assert!(agent.handle_packet(
3056            Instant::now(),
3057            StunPacket {
3058                message: binding_req,
3059                source: ipv4_3(),
3060                destination: ipv4_1(),
3061                proto: Protocol::Udp,
3062            },
3063        ));
3064
3065        assert!(!agent.has_viable_remote_candidate(ipv4_3()));
3066        assert!(
3067            !agent
3068                .events
3069                .iter()
3070                .any(|e| matches!(e, IceAgentEvent::NominatedSend { .. })),
3071            "a single binding request must not choose the send address"
3072        );
3073    }
3074
3075    #[test]
3076    fn ice_lite_controlled_follows_a_fresh_nomination() {
3077        // A NAT rebinding: the controlling agent keeps checking its selected
3078        // pair with USE-CANDIDATE, now from a new source port. The new pair has
3079        // a peer-reflexive remote of lower priority than the signaled host
3080        // candidate. While both are nominated recently the higher priority wins
3081        // (aggressive nomination); once the old pair is no longer nominated
3082        // (LITE_NOMINATION_FRESH) the controlled ice-lite agent sends on the new
3083        // one, and a fresh nomination of the old tuple takes egress back.
3084        let mut agent = new_test_agent();
3085        agent.set_ice_lite(true);
3086        agent.set_controlling(false);
3087        agent
3088            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
3089            .unwrap();
3090        let remote_creds = IceCreds::new();
3091        agent.set_remote_credentials(remote_creds.clone());
3092        let mut host = Candidate::host(ipv4_3(), "udp").unwrap();
3093        host.set_ufrag(&remote_creds.ufrag);
3094        let host_prio = host.prio();
3095        agent.add_remote_candidate(host);
3096
3097        let nominate = |agent: &mut IceAgent, now: Instant, source: SocketAddr, prio: u32| {
3098            let username = format!("{}:{}", agent.local_credentials.ufrag, remote_creds.ufrag);
3099            let req = StunMessage::binding_request(&username, TransId::new(), true, 0, prio, true);
3100            let bytes = serialize_stun_msg(req, &agent.local_credentials.pass);
3101            assert!(agent.handle_packet(
3102                now,
3103                StunPacket {
3104                    message: StunMessage::parse(&bytes).unwrap(),
3105                    source,
3106                    destination: ipv4_1(),
3107                    proto: Protocol::Udp,
3108                },
3109            ));
3110        };
3111        let sends_to = |agent: &IceAgent| {
3112            agent.events.iter().rev().find_map(|e| match e {
3113                IceAgentEvent::NominatedSend { destination, .. } => Some(*destination),
3114                _ => None,
3115            })
3116        };
3117
3118        let t0 = Instant::now();
3119        nominate(&mut agent, t0, ipv4_3(), host_prio);
3120        assert_eq!(sends_to(&agent), Some(ipv4_3()));
3121
3122        // The rebound source, with a peer-reflexive (lower) priority: the old
3123        // pair was nominated 1 s ago, so the higher priority still wins.
3124        let rebound = SocketAddr::new(ipv4_3().ip(), ipv4_3().port() + 1);
3125        nominate(
3126            &mut agent,
3127            t0 + Duration::from_secs(1),
3128            rebound,
3129            host_prio - 1000,
3130        );
3131        assert_eq!(sends_to(&agent), Some(ipv4_3()));
3132
3133        // The old tuple stopped nominating: egress moves on the next tick.
3134        agent.handle_timeout(t0 + LITE_NOMINATION_FRESH + Duration::from_millis(100));
3135        assert_eq!(
3136            sends_to(&agent),
3137            Some(rebound),
3138            "egress follows the pair still nominated"
3139        );
3140
3141        // A fresh nomination of the old tuple (higher priority) takes it back
3142        // at once (also what undoes a replayed check from a spoofed source).
3143        nominate(&mut agent, t0 + Duration::from_secs(4), ipv4_3(), host_prio);
3144        assert_eq!(sends_to(&agent), Some(ipv4_3()));
3145    }
3146
3147    #[test]
3148    fn ice_lite_controlled_picks_only_succeeded_pairs() {
3149        // A controlled ice-lite agent sends no checks; a pair succeeds when an
3150        // authenticated binding request arrives on it. The send pair must be
3151        // one of those that the controlling agent also nominated: never a
3152        // signaled candidate that sent nothing (however high its priority),
3153        // nor a pair whose request carried no USE-CANDIDATE.
3154        let mut agent = new_test_agent();
3155        agent.set_ice_lite(true);
3156        agent.set_controlling(false);
3157        agent
3158            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
3159            .unwrap();
3160        let remote_creds = IceCreds::new();
3161        agent.set_remote_credentials(remote_creds.clone());
3162
3163        // Signaled with the highest priority, but it never sends a request.
3164        let mut silent =
3165            Candidate::from_sdp_string("candidate:1 1 udp 2130706431 3.4.5.6 5000 typ host")
3166                .unwrap();
3167        silent.set_ufrag(&remote_creds.ufrag);
3168        let silent_addr = silent.addr();
3169        agent.add_remote_candidate(silent);
3170
3171        let request = |agent: &mut IceAgent, now: Instant, source: SocketAddr, nominate: bool| {
3172            let username = format!("{}:{}", agent.local_credentials.ufrag, remote_creds.ufrag);
3173            let req =
3174                StunMessage::binding_request(&username, TransId::new(), true, 0, 1000, nominate);
3175            let bytes = serialize_stun_msg(req, &agent.local_credentials.pass);
3176            assert!(agent.handle_packet(
3177                now,
3178                StunPacket {
3179                    message: StunMessage::parse(&bytes).unwrap(),
3180                    source,
3181                    destination: ipv4_1(),
3182                    proto: Protocol::Udp,
3183                },
3184            ));
3185        };
3186        let sends_to = |agent: &IceAgent| {
3187            agent.events.iter().rev().find_map(|e| match e {
3188                IceAgentEvent::NominatedSend { destination, .. } => Some(*destination),
3189                _ => None,
3190            })
3191        };
3192        let send_pair_succeeded = |agent: &IceAgent| {
3193            let id = agent.nominated_send.expect("a send pair");
3194            let pair = agent
3195                .candidate_pairs
3196                .iter()
3197                .find(|p| p.id() == id)
3198                .expect("the send pair exists");
3199            pair.state() == CheckState::Succeeded && pair.is_nominated()
3200        };
3201
3202        let t0 = Instant::now();
3203        agent.handle_timeout(t0);
3204        assert_eq!(sends_to(&agent), None, "nothing to send on yet");
3205
3206        // A request without USE-CANDIDATE: the pair succeeds but is not nominated.
3207        request(&mut agent, t0, ipv4_4(), false);
3208        agent.handle_timeout(t0 + Duration::from_millis(100));
3209        assert_eq!(sends_to(&agent), None, "a pair that was not nominated");
3210
3211        // A nominated, low-priority pair: chosen over the silent high-priority one.
3212        request(&mut agent, t0 + Duration::from_millis(200), ipv4_2(), true);
3213        assert_eq!(sends_to(&agent), Some(ipv4_2()));
3214        assert!(send_pair_succeeded(&agent));
3215
3216        for ms in [500, 2_000, 5_000] {
3217            agent.handle_timeout(t0 + Duration::from_millis(ms));
3218            assert_ne!(sends_to(&agent), Some(silent_addr), "at {ms} ms");
3219            assert_ne!(sends_to(&agent), Some(ipv4_4()), "at {ms} ms");
3220            if agent.nominated_send.is_some() {
3221                assert!(send_pair_succeeded(&agent), "at {ms} ms");
3222            }
3223        }
3224    }
3225
3226    #[test]
3227    fn controlled_sends_only_on_a_nominated_pair_whose_check_succeeded() {
3228        // RFC 8445 §7.3.1.5: the controlled agent acts on USE-CANDIDATE only
3229        // for a pair that is, or becomes, valid. Here the peer nominates the
3230        // highest-priority pair first, but our checks on it are never
3231        // answered (one-way connectivity). It then nominates a lower-priority
3232        // pair whose check succeeds. Media must go to the second pair.
3233        let mut agent = new_test_agent();
3234        agent.set_controlling(false);
3235        agent
3236            .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
3237            .unwrap();
3238
3239        let remote_creds = IceCreds::new();
3240        agent.set_remote_credentials(remote_creds.clone());
3241
3242        let mut dead =
3243            Candidate::from_sdp_string("candidate:1 1 udp 2130706431 3.4.5.6 5000 typ host")
3244                .unwrap();
3245        dead.set_ufrag(&remote_creds.ufrag);
3246        let mut alive =
3247            Candidate::from_sdp_string("candidate:2 1 udp 1694498815 4.5.6.7 5000 typ host")
3248                .unwrap();
3249        alive.set_ufrag(&remote_creds.ufrag);
3250        let (dead_prio, alive_prio) = (dead.prio(), alive.prio());
3251        assert!(dead_prio > alive_prio);
3252        agent.add_remote_candidate(dead);
3253        agent.add_remote_candidate(alive);
3254
3255        let nominate = |agent: &mut IceAgent, now: Instant, source: SocketAddr, prio: u32| {
3256            let username = format!("{}:{}", agent.local_credentials.ufrag, remote_creds.ufrag);
3257            let req = StunMessage::binding_request(&username, TransId::new(), true, 0, prio, true);
3258            let req = serialize_stun_msg(req, &agent.local_credentials.pass);
3259            assert!(agent.handle_packet(
3260                now,
3261                StunPacket {
3262                    message: StunMessage::parse(&req).unwrap(),
3263                    source,
3264                    destination: ipv4_1(),
3265                    proto: Protocol::Udp,
3266                },
3267            ));
3268        };
3269
3270        // Answer our checks toward `alive` only; drop everything else.
3271        let answer_alive = |agent: &mut IceAgent, now: Instant| {
3272            let mut replies = vec![];
3273            while let Some(t) = agent.poll_transmit() {
3274                let msg = StunMessage::parse(&t.contents).unwrap();
3275                if t.destination == ipv4_4() && msg.is_binding_request() {
3276                    replies.push(make_authenticated_stun_reply(
3277                        msg.trans_id(),
3278                        ipv4_1(),
3279                        &remote_creds.pass,
3280                    ));
3281                }
3282            }
3283            for reply in replies {
3284                agent.handle_packet(
3285                    now,
3286                    StunPacket {
3287                        message: StunMessage::parse(&reply).unwrap(),
3288                        source: ipv4_4(),
3289                        destination: ipv4_1(),
3290                        proto: Protocol::Udp,
3291                    },
3292                );
3293            }
3294        };
3295
3296        let nominated_sends = |agent: &mut IceAgent| {
3297            let mut v = vec![];
3298            while let Some(e) = agent.poll_event() {
3299                if let IceAgentEvent::NominatedSend { destination, .. } = e {
3300                    v.push(destination);
3301                }
3302            }
3303            v
3304        };
3305
3306        let mut now = Instant::now();
3307        agent.handle_timeout(now);
3308
3309        nominate(&mut agent, now, ipv4_3(), dead_prio);
3310        for _ in 0..20 {
3311            answer_alive(&mut agent, now);
3312            now += Duration::from_millis(50);
3313            agent.handle_timeout(now);
3314        }
3315        assert_eq!(
3316            nominated_sends(&mut agent),
3317            vec![],
3318            "a nominated pair whose check has not succeeded must not be used"
3319        );
3320
3321        nominate(&mut agent, now, ipv4_4(), alive_prio);
3322        for _ in 0..20 {
3323            answer_alive(&mut agent, now);
3324            now += Duration::from_millis(50);
3325            agent.handle_timeout(now);
3326        }
3327        assert_eq!(nominated_sends(&mut agent), vec![ipv4_4()]);
3328    }
3329
3330    fn make_serialized_binding_request(
3331        local_creds: &IceCreds,
3332        remote_creds: &IceCreds,
3333        controlling: bool,
3334        prio: u32,
3335    ) -> Vec<u8> {
3336        let username = format!("{}:{}", local_creds.ufrag, remote_creds.ufrag);
3337        let binding_req =
3338            StunMessage::binding_request(&username, TransId::new(), controlling, 0, prio, false);
3339        serialize_stun_msg(binding_req, &local_creds.pass)
3340    }
3341
3342    fn make_authenticated_stun_reply(tx_id: TransId, addr: SocketAddr, password: &str) -> Vec<u8> {
3343        let reply = StunMessage::binding_reply(tx_id, addr);
3344        serialize_stun_msg(reply, password)
3345    }
3346
3347    fn make_role_conflict_reply(tx_id: TransId, password: &str) -> Vec<u8> {
3348        let reply = StunMessage::binding_role_conflict_reply(tx_id);
3349        serialize_stun_msg(reply, password)
3350    }
3351
3352    /// Serializing will calculate a message integrity for it. You can then re-parse to get a message
3353    /// that contains that correct integrity value.
3354    fn serialize_stun_msg(msg: StunMessage<'_>, password: &str) -> Vec<u8> {
3355        let mut buf = vec![0_u8; DATAGRAM_MTU_TARGET];
3356
3357        let sha1_hmac =
3358            |key: &[u8], payloads: &[&[u8]]| DefaultSha1HmacProvider.sha1_hmac(key, payloads);
3359        let n = msg
3360            .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac)
3361            .expect("IO error writing STUN message");
3362        buf.truncate(n);
3363
3364        buf
3365    }
3366
3367    #[test]
3368    fn set_mtu_updates_mtu() {
3369        let mut agent = IceAgent::new(IceCreds::new());
3370        assert_eq!(agent.mtu(), DATAGRAM_MTU_TARGET);
3371        assert_eq!(agent.mtu_warn(), DATAGRAM_MTU_WARN);
3372
3373        agent.set_mtu(900..=1280);
3374        assert_eq!(agent.mtu(), 900);
3375        assert_eq!(agent.mtu_warn(), 1280);
3376    }
3377}