Skip to main content

rtci_ice/agent/
agent_selector.rs

1//! The checklist of RFC 8445: candidate pairs and their states, the ordinary and the triggered
2//! checks paced by Ta, the STUN transaction behind each check, the valid list, nomination and
3//! the conclusion of ICE.
4//!
5//! The engine has one data stream with one component (BUNDLE and rtcp-mux), so there is one
6//! checklist. `Agent::candidate_pairs` holds it together with the valid pairs a check produces
7//! that are not on it (Section 7.2.5.3.2); the order of the checklist is the pairs' priority,
8//! read when a pair is picked (Section 6.1.2.3).
9//!
10//! Section 8.1.1 uses the nominated pair with the highest priority, and so does the controlled
11//! agent here. libwebrtc moves a session to another pair after it connects, whatever that
12//! pair's priority: following the controlling agent's *latest* nomination (or the highest
13//! libwebrtc `NOMINATION` value) is `AgentConfig::nomination_acceptance`.
14//!
15//! One of the RFC's rules is not followed, on purpose: Sections 7.2.5.3.4 and 7.3.1.5 fail the
16//! checklist when a nomination fails. Here the pair fails, and the checklist only when no
17//! other pair can still be nominated.
18
19use crate::agent::agent_config::*;
20use crate::agent::{Agent, BindingRequest, Event, TaggedEvent};
21use bytes::BytesMut;
22use crc::{CRC_32_ISCSI, Crc};
23use log::{debug, error, trace, warn};
24use std::net::{IpAddr, SocketAddr};
25use std::time::{Duration, Instant};
26use stun::attributes::*;
27use stun::fingerprint::*;
28use stun::integrity::*;
29use stun::message::*;
30use stun::textattrs::*;
31use stun::xoraddr::XorMappedAddress;
32
33use crate::attributes::{control::*, nomination::nomination_of, priority::*, use_candidate::*};
34use crate::candidate::candidate_peer_reflexive::CandidatePeerReflexiveConfig;
35use crate::candidate::{candidate_pair::*, *};
36use crate::state::ConnectionState;
37
38/// What a transport reports about the path of a connectivity check. See
39/// [`Agent::handle_transport_error`].
40#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum TransportError {
43    /// A hard ICMP error (destination, port or protocol unreachable) for a datagram sent on
44    /// the path.
45    IcmpHardError,
46    /// The TCP connection of the path could not be established.
47    ConnectionFailed,
48    /// What arrived on the path's TCP connection, in answer to the first check, is not STUN.
49    NotStun,
50}
51
52/// RFC 6544 Section 12: "an ICE agent SHOULD NOT have more than 5 outstanding TCP connection
53/// attempts with the same peer to the same IP address."
54pub(crate) const MAX_TCP_CONNECTION_ATTEMPTS_PER_ADDRESS: usize = 5;
55
56/// The state of the checklist (RFC 8445 Section 6.1.2.1). With one checklist it is also the
57/// state of the ICE session (Section 6.1.3).
58#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum ChecklistState {
61    /// Checks are, or may still be, performed.
62    Running,
63    /// A pair has been nominated: no further ordinary checks.
64    Completed,
65    /// No valid pair could be produced, or consent was lost.
66    Failed,
67}
68
69impl Agent {
70    /// Whether `index` has been waiting long enough to be nominated, as of `now`.
71    ///
72    /// `now` is supplied by the caller rather than sampled here so that one nomination decision
73    /// makes one time observation: both halves of a pair are tested against the same instant.
74    fn is_nominatable(&self, now: Instant, index: usize, is_local: bool) -> bool {
75        let c = if is_local {
76            &self.local_candidates[index]
77        } else {
78            &self.remote_candidates[index]
79        };
80        let min_wait = match c.candidate_type() {
81            CandidateType::Host => self.host_acceptance_min_wait,
82            CandidateType::ServerReflexive => self.srflx_acceptance_min_wait,
83            CandidateType::PeerReflexive => self.prflx_acceptance_min_wait,
84            CandidateType::Relay => self.relay_acceptance_min_wait,
85            CandidateType::Unspecified => {
86                error!(
87                    "is_nominatable invalid candidate type {}",
88                    c.candidate_type()
89                );
90                return false;
91            }
92        };
93        // RFC 8838 Section 14: the wait is for higher-priority candidates; once both sides
94        // have said they have no more (end-of-candidates, and local gathering complete), there
95        // is nothing left to wait for.
96        if self.remote_end_of_candidates && self.local_gathering_complete {
97            return true;
98        }
99        now.saturating_duration_since(self.start_time) > min_wait
100    }
101
102    /// The state of the checklist, in RFC 8445's terms: Running until a pair is nominated,
103    /// Completed from then on, Failed when the agent is.
104    ///
105    /// [`Agent::state`] is the W3C transport state, which is `Connected` once a pair is
106    /// nominated and `Completed` only when, in addition, both sides have said they have no
107    /// more candidates.
108    pub fn checklist_state(&self) -> ChecklistState {
109        if self.connection_state == ConnectionState::Failed {
110            ChecklistState::Failed
111        } else if self.selected_pair.is_some() {
112            ChecklistState::Completed
113        } else {
114            ChecklistState::Running
115        }
116    }
117
118    // ---------------------------------------------------------------------------------------
119    // Pairs: forming, pruning, limiting, initial state (Sections 6.1.2.2 to 6.1.2.6)
120    // ---------------------------------------------------------------------------------------
121
122    /// Whether two local candidates send from the same socket: same base, same transport.
123    pub(crate) fn same_base(&self, a: usize, b: usize) -> bool {
124        let (a, b) = (&self.local_candidates[a], &self.local_candidates[b]);
125        a.base_addr() == b.base_addr()
126            && a.network_type() == b.network_type()
127            && a.tcp_type() == b.tcp_type()
128    }
129
130    pub(crate) fn pair_foundation(&self, local_index: usize, remote_index: usize) -> u32 {
131        let mut buf = self.local_candidates[local_index].foundation().into_bytes();
132        buf.push(b':');
133        buf.extend_from_slice(self.remote_candidates[remote_index].foundation().as_bytes());
134        Crc::<u32>::new(&CRC_32_ISCSI).checksum(&buf)
135    }
136
137    /// Forms the pair (Section 6.1.2.2) and puts it on the checklist, unless it is redundant
138    /// (6.1.2.4) or the checklist is full of better pairs (6.1.2.5).
139    pub(crate) fn add_pair(&mut self, local_index: usize, remote_index: usize) {
140        let local = &self.local_candidates[local_index];
141        let remote = &self.remote_candidates[remote_index];
142        // Every check goes out on a pair, so this is where the destination policy holds: a
143        // loopback or link-local remote address is reached only from a local candidate in the
144        // same scope (unless the configuration allows it). See `remote_policy`.
145        let local_base = local.base_addr();
146        let remote_addr = remote.addr();
147        if !self.remote_policy.allows_pair(local_base, remote_addr) {
148            debug!(
149                "[{}]: not pairing local {} with remote {}: destination not allowed from this local candidate",
150                self.get_name(),
151                local_base,
152                remote_addr
153            );
154            return;
155        }
156        // Section 6.1.2.2: "A local candidate is paired with a remote candidate if and only if
157        // the two candidates have the same component ID and have the same IP address version."
158        if local.component() != remote.component() {
159            debug!(
160                "[{}]: not pairing local {} with remote {}: components {} and {}",
161                self.get_name(),
162                local,
163                remote,
164                local.component(),
165                remote.component()
166            );
167            return;
168        }
169
170        // draft-ietf-mmusic-mdns-ice-candidates Section 3.3.2: "an ICE agent MUST NOT form
171        // candidate pairs between its own relay candidates and remote mDNS candidates": the
172        // TURN server would learn the address the name hides.
173        if local.candidate_type() == CandidateType::Relay && remote.address().ends_with(".local") {
174            debug!(
175                "[{}]: not pairing relay candidate {} with mDNS candidate {}",
176                self.get_name(),
177                local,
178                remote.address()
179            );
180            return;
181        }
182
183        let mut pair = CandidatePair::new(
184            local_index,
185            remote_index,
186            local.priority(),
187            remote.priority(),
188            self.is_controlling,
189        );
190        pair.foundation = self.pair_foundation(local_index, remote_index);
191
192        // Section 6.1.2.4: a reflexive local candidate stands for its base, and of two pairs
193        // with the same base and the same remote candidate the one with the higher priority
194        // stays. RFC 8838 Section 11: only a pair that is still Waiting or Frozen gives way.
195        let redundant = self.candidate_pairs.iter().position(|p| {
196            p.remote_index == remote_index && self.same_base(p.local_index, local_index)
197        });
198        if let Some(existing) = redundant {
199            let e = self.candidate_pairs[existing];
200            let unchecked = matches!(
201                e.state,
202                CandidatePairState::Waiting | CandidatePairState::Frozen
203            ) && !e.triggered
204                && !e.nomination_pending;
205            if unchecked && pair.priority() > e.priority() {
206                pair.state = self.initial_pair_state(&pair, Some(existing));
207                self.announce_pair(existing, false);
208                self.candidate_pairs[existing] = pair;
209                self.announce_pair(existing, true);
210            }
211            return;
212        }
213
214        // Section 6.1.2.5: the checklist holds a limited number of pairs.
215        let slot = if self.checklist_len() < self.max_candidate_pairs {
216            None
217        } else {
218            match self.pair_to_discard(pair.priority()) {
219                Some(slot) => Some(slot),
220                None => {
221                    debug!(
222                        "[{}]: checklist full ({} pairs): dropping pair {}",
223                        self.get_name(),
224                        self.max_candidate_pairs,
225                        pair
226                    );
227                    return;
228                }
229            }
230        };
231        pair.state = self.initial_pair_state(&pair, slot);
232        let index = match slot {
233            Some(slot) => {
234                self.announce_pair(slot, false);
235                self.candidate_pairs[slot] = pair;
236                slot
237            }
238            None => {
239                self.candidate_pairs.push(pair);
240                self.candidate_pairs.len() - 1
241            }
242        };
243        self.announce_pair(index, true);
244    }
245
246    /// Queues `CandidatePairAdded` (`added`) or `CandidatePairRemoved` for the pair at
247    /// `index`. A pair the application removed was announced removed already.
248    pub(crate) fn announce_pair(&mut self, index: usize, added: bool) {
249        let p = self.candidate_pairs[index];
250        if p.removed {
251            return;
252        }
253        let (Some(local), Some(remote)) = (
254            self.local_candidates.get(p.local_index),
255            self.remote_candidates.get(p.remote_index),
256        ) else {
257            return;
258        };
259        let (local, remote) = (Box::new(local.clone()), Box::new(remote.clone()));
260        self.event_outs.push_back(TaggedEvent {
261            now: self.clock,
262            event: if added {
263                Event::CandidatePairAdded(local, remote)
264            } else {
265                Event::CandidatePairRemoved(local, remote)
266            },
267        });
268    }
269
270    /// Section 7.3.1.4: the pair of a request the peer sent is put on the checklist even when
271    /// the checklist is full: it replaces the lowest-priority pair that has not been checked
272    /// (or a Failed one), whatever the priorities. When every pair is in flight or done it is
273    /// not added.
274    pub(crate) fn add_triggered_pair(&mut self, local_index: usize, remote_index: usize) {
275        let local = &self.local_candidates[local_index];
276        let remote = &self.remote_candidates[remote_index];
277        if !self
278            .remote_policy
279            .allows_pair(local.base_addr(), remote.addr())
280            || local.component() != remote.component()
281            || self.checklist_len() < self.max_candidate_pairs
282        {
283            return;
284        }
285        let Some(slot) = self.pair_to_discard(u64::MAX) else {
286            return;
287        };
288        let mut pair = CandidatePair::new(
289            local_index,
290            remote_index,
291            local.priority(),
292            remote.priority(),
293            self.is_controlling,
294        );
295        pair.foundation = self.pair_foundation(local_index, remote_index);
296        self.announce_pair(slot, false);
297        self.candidate_pairs[slot] = pair;
298        self.announce_pair(slot, true);
299    }
300
301    /// The pairs that count against the limit: the checklist, not the valid pairs a response
302    /// added beside it.
303    fn checklist_len(&self) -> usize {
304        self.candidate_pairs
305            .iter()
306            .filter(|p| !(p.valid && self.is_learned_local(p.local_index)))
307            .count()
308    }
309
310    /// Whether the local candidate was learned from a response's mapped address.
311    fn is_learned_local(&self, local_index: usize) -> bool {
312        self.local_candidates[local_index].candidate_type() == CandidateType::PeerReflexive
313    }
314
315    /// RFC 8838 Section 11, step 5: when the checklist is full, "the agent SHOULD discard any
316    /// pairs in the Failed state to make room for the new pair. If there are no such pairs,
317    /// the agent SHOULD discard a pair with a lower priority than the new pair". A pair whose
318    /// check is in flight or done is never discarded.
319    fn pair_to_discard(&self, new_priority: u64) -> Option<usize> {
320        let lowest = |wanted: &dyn Fn(&CandidatePair) -> bool| {
321            self.candidate_pairs
322                .iter()
323                .enumerate()
324                .filter(|(i, p)| {
325                    wanted(p)
326                        && !p.triggered
327                        && !p.nomination_pending
328                        && Some(*i) != self.selected_pair
329                        && Some(*i) != self.nominated_pair
330                })
331                .min_by_key(|(_, p)| p.priority())
332                .map(|(i, p)| (i, p.priority()))
333        };
334        if let Some((failed, _)) = lowest(&|p| p.state == CandidatePairState::Failed) {
335            return Some(failed);
336        }
337        match lowest(&|p| {
338            matches!(
339                p.state,
340                CandidatePairState::Waiting | CandidatePairState::Frozen
341            )
342        }) {
343            Some((index, priority)) if priority < new_priority => Some(index),
344            _ => None,
345        }
346    }
347
348    /// The state a new pair starts in (RFC 8838 Section 12, which for a checklist that is
349    /// complete from the start gives RFC 8445 Section 6.1.2.6): Waiting when it is the
350    /// highest-priority pair of its foundation or a pair of that foundation has succeeded,
351    /// Frozen otherwise. `replacing` is the slot it takes over, if any.
352    fn initial_pair_state(
353        &self,
354        pair: &CandidatePair,
355        replacing: Option<usize>,
356    ) -> CandidatePairState {
357        let mut topmost = true;
358        for (index, p) in self.candidate_pairs.iter().enumerate() {
359            if Some(index) == replacing || p.foundation != pair.foundation {
360                continue;
361            }
362            if p.state == CandidatePairState::Succeeded {
363                return CandidatePairState::Waiting;
364            }
365            if p.priority() >= pair.priority() {
366                topmost = false;
367            }
368        }
369        if topmost {
370            CandidatePairState::Waiting
371        } else {
372            CandidatePairState::Frozen
373        }
374    }
375
376    /// RFC 8445 Section 6.1.2.6, when checks start: "For each foundation, the agent sets the
377    /// state of exactly one candidate pair to the Waiting state", the one with the highest
378    /// priority; the others are Frozen. Pairs added one by one before that each started
379    /// Waiting when they were, at the time, the best of their foundation.
380    pub(crate) fn compute_initial_pair_states(&mut self) {
381        let untouched = self.candidate_pairs.iter().all(|p| {
382            matches!(
383                p.state,
384                CandidatePairState::Waiting | CandidatePairState::Frozen
385            ) && !p.triggered
386        });
387        if !untouched {
388            return;
389        }
390        for index in 0..self.candidate_pairs.len() {
391            let pair = self.candidate_pairs[index];
392            let best = !self.candidate_pairs.iter().enumerate().any(|(other, p)| {
393                p.foundation == pair.foundation
394                    && (p.priority() > pair.priority()
395                        || (p.priority() == pair.priority() && other < index))
396            });
397            self.candidate_pairs[index].state = if best {
398                CandidatePairState::Waiting
399            } else {
400                CandidatePairState::Frozen
401            };
402        }
403    }
404
405    pub(crate) fn find_pair_exact(&self, local_index: usize, remote_index: usize) -> Option<usize> {
406        self.candidate_pairs
407            .iter()
408            .position(|p| p.local_index == local_index && p.remote_index == remote_index)
409    }
410
411    /// The pair of these two candidates, or, when pruning kept another pair for the same
412    /// socket and remote candidate (Section 6.1.2.4), that one.
413    pub(crate) fn find_pair(&self, local_index: usize, remote_index: usize) -> Option<usize> {
414        self.find_pair_exact(local_index, remote_index).or_else(|| {
415            self.candidate_pairs.iter().position(|p| {
416                p.remote_index == remote_index
417                    && !(p.valid && self.is_learned_local(p.local_index))
418                    && self.same_base(p.local_index, local_index)
419            })
420        })
421    }
422
423    // ---------------------------------------------------------------------------------------
424    // Scheduling: the triggered-check queue and Ta (Sections 6.1.4.1 and 6.1.4.2)
425    // ---------------------------------------------------------------------------------------
426
427    /// Puts the pair on the triggered-check queue (FIFO, once).
428    pub(crate) fn enqueue_triggered(&mut self, pair_index: usize) {
429        let p = &mut self.candidate_pairs[pair_index];
430        if p.removed {
431            return;
432        }
433        if !p.triggered {
434            p.triggered = true;
435            self.triggered_queue
436                .push_back((p.local_index, p.remote_index));
437        }
438        self.request_connectivity_check();
439    }
440
441    fn pop_triggered(&mut self) -> Option<usize> {
442        while let Some((local_index, remote_index)) = self.triggered_queue.pop_front() {
443            if let Some(pair_index) = self.find_pair_exact(local_index, remote_index)
444                && self.candidate_pairs[pair_index].triggered
445            {
446                return Some(pair_index);
447            }
448        }
449        None
450    }
451
452    /// Section 7.3.1.4, what a Binding request does to its pair unless the pair has succeeded:
453    /// an In-Progress transaction is cancelled, the pair is Waiting and on the triggered-check
454    /// queue.
455    pub(crate) fn trigger_check(&mut self, pair_index: usize) {
456        let p = self.candidate_pairs[pair_index];
457        if p.removed {
458            return;
459        }
460        if p.state == CandidatePairState::InProgress {
461            self.cancel_transactions(p.local_index, p.remote_index);
462        }
463        self.candidate_pairs[pair_index].state = CandidatePairState::Waiting;
464        self.enqueue_triggered(pair_index);
465    }
466
467    /// Whether ordinary checks are performed: the checklist is Running, and the agent is not a
468    /// lite one answering a full agent (Section 6.2: no checks).
469    fn ordinary_checks_allowed(&self) -> bool {
470        self.selected_pair.is_none()
471            // (Nor a lite one with a lite peer, Section 6.1.1: "no connectivity checks are
472            // ever sent".)
473            && !(self.lite && (!self.is_controlling || self.remote_lite))
474            && !matches!(
475                self.connection_state,
476                ConnectionState::Failed | ConnectionState::Closed
477            )
478    }
479
480    /// The Waiting pair with the highest priority (Section 6.1.4.2, step 3).
481    fn next_waiting(&self) -> Option<usize> {
482        let mut best: Option<usize> = None;
483        for (index, p) in self.candidate_pairs.iter().enumerate() {
484            if p.state != CandidatePairState::Waiting || p.triggered {
485                continue;
486            }
487            if self.tcp_attempts_exhausted(p) {
488                continue;
489            }
490            if best.is_none_or(|b| self.candidate_pairs[b].priority() < p.priority()) {
491                best = Some(index);
492            }
493        }
494        best
495    }
496
497    /// Whether the pair is one this agent opens a TCP connection for (an active local
498    /// candidate, RFC 6544 Section 7.1).
499    fn opens_tcp_connection(&self, p: &CandidatePair) -> bool {
500        let local = &self.local_candidates[p.local_index];
501        local.network_type().is_tcp() && local.tcp_type() == crate::tcp_type::TcpType::Active
502    }
503
504    /// RFC 6544 Section 12: whether as many connection attempts as allowed are outstanding to
505    /// the IP address of this pair's remote candidate, so that its check has to wait. An
506    /// attempt is outstanding while its check is In-Progress: it ends with the response, or
507    /// with the transaction (Ti, 39.5 s, or a failure the transport reports).
508    fn tcp_attempts_exhausted(&self, p: &CandidatePair) -> bool {
509        if !self.opens_tcp_connection(p) {
510            return false;
511        }
512        let ip = self.remote_candidates[p.remote_index].addr().ip();
513        self.candidate_pairs
514            .iter()
515            .filter(|q| {
516                q.state == CandidatePairState::InProgress
517                    && self.opens_tcp_connection(q)
518                    && self.remote_candidates[q.remote_index].addr().ip() == ip
519            })
520            .count()
521            >= MAX_TCP_CONNECTION_ATTEMPTS_PER_ADDRESS
522    }
523
524    /// The Frozen pairs step 2 of Section 6.1.4.2 would unfreeze: with no pair Waiting, for
525    /// each foundation without a Waiting or In-Progress pair, its highest-priority Frozen pair.
526    fn pairs_to_unfreeze(&self) -> Vec<usize> {
527        let mut out: Vec<usize> = vec![];
528        for (index, p) in self.candidate_pairs.iter().enumerate() {
529            if p.state != CandidatePairState::Frozen {
530                continue;
531            }
532            let busy = self.candidate_pairs.iter().any(|q| {
533                q.foundation == p.foundation
534                    && matches!(
535                        q.state,
536                        CandidatePairState::Waiting | CandidatePairState::InProgress
537                    )
538            });
539            if busy {
540                continue;
541            }
542            match out
543                .iter()
544                .position(|&o| self.candidate_pairs[o].foundation == p.foundation)
545            {
546                Some(slot) if self.candidate_pairs[out[slot]].priority() < p.priority() => {
547                    out[slot] = index
548                }
549                Some(_) => {}
550                None => out.push(index),
551            }
552        }
553        out
554    }
555
556    /// Whether `run_ta` would start a check now if Ta allowed it.
557    pub(crate) fn has_check_to_start(&self) -> bool {
558        if !self.triggered_queue.is_empty() {
559            return true;
560        }
561        self.ordinary_checks_allowed()
562            && (self.next_waiting().is_some() || !self.pairs_to_unfreeze().is_empty())
563    }
564
565    /// Timer Ta (Section 6.1.4.2): at most one check is started per Ta, a triggered one first,
566    /// else the highest-priority Waiting pair, unfreezing pairs when none is Waiting.
567    pub(crate) fn run_ta(&mut self, now: Instant) {
568        if now < self.next_check_at || self.ufrag_pwd.remote_credentials.is_none() {
569            return;
570        }
571        let pair_index = match self.pop_triggered() {
572            Some(pair_index) => Some(pair_index),
573            None if self.ordinary_checks_allowed() => {
574                if self.next_waiting().is_none() {
575                    for index in self.pairs_to_unfreeze() {
576                        self.candidate_pairs[index].state = CandidatePairState::Waiting;
577                    }
578                }
579                self.next_waiting()
580            }
581            None => None,
582        };
583        if let Some(pair_index) = pair_index {
584            // Section 14.2: with other agents, one transaction per 5 ms for all of them.
585            if let Some(group) = &self.pacing_group
586                && let Err(at) = group.take(now)
587            {
588                // (A triggered check taken off the queue goes back at its head.)
589                let p = self.candidate_pairs[pair_index];
590                if p.triggered {
591                    self.triggered_queue
592                        .push_front((p.local_index, p.remote_index));
593                }
594                self.next_check_at = at;
595                return;
596            }
597            self.start_check(now, pair_index);
598            self.next_check_at = now + self.ta;
599        }
600    }
601
602    fn start_check(&mut self, now: Instant, pair_index: usize) {
603        let p = &mut self.candidate_pairs[pair_index];
604        p.triggered = false;
605        // Section 8.1.1: the controlling agent nominates with USE-CANDIDATE; the controlled
606        // agent never sends it.
607        let use_candidate = self.is_controlling && p.nominate;
608        // A nomination is a check on a pair that is valid already; it stays Succeeded.
609        if p.state != CandidatePairState::Succeeded {
610            p.state = CandidatePairState::InProgress;
611        }
612        trace!(
613            "[{}]: check on {} (nominating: {})",
614            self.get_name(),
615            self.candidate_pairs[pair_index],
616            use_candidate
617        );
618        self.send_check(now, pair_index, use_candidate, false);
619    }
620
621    // ---------------------------------------------------------------------------------------
622    // Transactions (Sections 7.2.2 to 7.2.5, 14.3; RFC 8489 Section 6.2)
623    // ---------------------------------------------------------------------------------------
624
625    /// Section 14.3: "RTO = MAX (500ms, Ta * N * (Num-Waiting + Num-In-Progress))", N being
626    /// the number of checklists, one here.
627    pub(crate) fn check_rto(&self) -> Duration {
628        let active = self
629            .candidate_pairs
630            .iter()
631            .filter(|p| {
632                matches!(
633                    p.state,
634                    CandidatePairState::Waiting | CandidatePairState::InProgress
635                )
636            })
637            .count();
638        (self.ta * u32::try_from(active).unwrap_or(u32::MAX)).max(MIN_RTO)
639    }
640
641    /// How long a consent request waits for its response: four times the pair's last
642    /// round-trip time, between 500 ms and 4 s (RFC 7675 Section 5.1).
643    fn consent_wait(&self, pair: &CandidatePair) -> Duration {
644        (pair.current_round_trip_time * 4).clamp(MIN_RTO, MAX_BINDING_REQUEST_TIMEOUT)
645    }
646
647    /// Builds and sends a Binding request on the pair and opens its transaction: a
648    /// connectivity check (retransmitted over UDP, Section 14.3), with USE-CANDIDATE a
649    /// nomination, or with `consent` a consent request, which is sent once (RFC 7675).
650    pub(crate) fn send_check(
651        &mut self,
652        now: Instant,
653        pair_index: usize,
654        use_candidate: bool,
655        consent: bool,
656    ) {
657        let Some(remote_credentials) = &self.ufrag_pwd.remote_credentials else {
658            error!("ufrag_pwd.remote_credentials is none");
659            return;
660        };
661        let pair = self.candidate_pairs[pair_index];
662        let local = &self.local_candidates[pair.local_index];
663        // Section 7.1.1: the priority the local candidate would have as a peer-reflexive one,
664        // which is what the peer makes of an unknown source.
665        let priority = local.peer_reflexive_priority();
666        let is_tcp = local.network_type().is_tcp();
667
668        // Section 7.2.2: USERNAME is the peer's fragment, a colon, ours; the key is the peer's
669        // password.
670        let username = remote_credentials.ufrag.clone()
671            + ":"
672            + self.ufrag_pwd.local_credentials.ufrag.as_str();
673        let mut msg = Message::new();
674        let built = {
675            let mut setters: Vec<Box<dyn Setter + '_>> = vec![
676                Box::new(BINDING_REQUEST),
677                Box::new(TransactionId::new()),
678                Box::new(Username::new(ATTR_USERNAME, username)),
679            ];
680            if use_candidate {
681                setters.push(Box::<UseCandidateAttr>::default());
682            }
683            // Section 7.1.3.
684            if self.is_controlling {
685                setters.push(Box::new(AttrControlling(self.tie_breaker)));
686            } else {
687                setters.push(Box::new(AttrControlled(self.tie_breaker)));
688            }
689            setters.push(Box::new(PriorityAttr(priority)));
690            // RFC 8489 Section 6.1: a request SHOULD carry SOFTWARE.
691            if let Some(software) = &self.software {
692                setters.push(Box::new(Software::new(ATTR_SOFTWARE, software.clone())));
693            }
694            setters.push(Box::new(
695                MessageIntegrity::new_short_term_integrity_with_provider(
696                    remote_credentials.pwd.clone(),
697                    self.crypto_provider.crypto(),
698                ),
699            ));
700            // Section 7.2.4.
701            setters.push(Box::new(FINGERPRINT));
702            msg.build(&setters)
703        };
704        if let Err(err) = built {
705            // (A USERNAME of 509 bytes or more, say: the check can never be sent.)
706            error!("{}", err);
707            self.fail_pair(pair_index);
708            return;
709        }
710        // RFC 8489 Section 6.1: over UDP a STUN message fits the path MTU (assumed 576 / 1280
711        // bytes when not known): long ufrags can make a check that does not. It is not sent,
712        // and the pair fails at once.
713        if !is_tcp {
714            let destination = self.remote_candidates[pair.remote_index].addr();
715            if msg.raw.len() > self.max_udp_stun_size(destination) {
716                warn!(
717                    "[{}]: a check of {} bytes on {} exceeds the path MTU: the pair failed",
718                    self.get_name(),
719                    msg.raw.len(),
720                    pair
721                );
722                self.fail_pair(pair_index);
723                return;
724            }
725        }
726
727        let rto = self.check_rto();
728        let (retransmit, next_event) = if consent {
729            (false, now + self.consent_wait(&pair))
730        } else if is_tcp {
731            // RFC 6544 Section 7.1: no retransmissions over TCP.
732            (false, now + STUN_TI)
733        } else if self.max_binding_requests <= 1 {
734            (false, now + rto * STUN_RM)
735        } else {
736            (true, now + rto)
737        };
738        trace!(
739            "[{}]: ping STUN from {} to {}",
740            self.get_name(),
741            self.local_candidates[pair.local_index],
742            self.remote_candidates[pair.remote_index],
743        );
744        self.track_transaction(BindingRequest {
745            timestamp: now,
746            transaction_id: msg.transaction_id,
747            destination: self.remote_candidates[pair.remote_index].addr(),
748            is_use_candidate: use_candidate,
749            local_index: pair.local_index,
750            remote_index: pair.remote_index,
751            sent_as_controlling: self.is_controlling,
752            raw: BytesMut::from(&msg.raw[..]),
753            rto,
754            interval: rto,
755            transmissions: 1,
756            next_event,
757            retransmit,
758            cancelled: false,
759            consent,
760            priority,
761            unauthentic_response: false,
762        });
763
764        // Track request sent on the candidate pair
765        self.candidate_pairs[pair_index].on_request_sent();
766        self.send_stun(now, &msg, pair.local_index, pair.remote_index);
767    }
768
769    /// Remembers an open transaction. Checks are bounded by the checklist (one per pair);
770    /// consent requests and cancelled transactions by `MAX_PENDING_BINDING_REQUESTS`, the
771    /// oldest of them being forgotten first.
772    pub(crate) fn track_transaction(&mut self, transaction: BindingRequest) {
773        self.pending_binding_requests.push(transaction);
774        self.trim_passive_transactions();
775    }
776
777    fn trim_passive_transactions(&mut self) {
778        let passive = |r: &BindingRequest| r.consent || r.cancelled;
779        let mut excess = self
780            .pending_binding_requests
781            .iter()
782            .filter(|r| passive(r))
783            .count()
784            .saturating_sub(MAX_PENDING_BINDING_REQUESTS);
785        if excess > 0 {
786            self.pending_binding_requests.retain(|r| {
787                if excess > 0 && passive(r) {
788                    excess -= 1;
789                    false
790                } else {
791                    true
792                }
793            });
794        }
795    }
796
797    /// Cancels the pair's open check transactions (Section 7.3.1.4): "the agent will not
798    /// retransmit the Binding requests associated with the connectivity-check transaction,
799    /// will not treat the lack of response to be a failure, but will wait the duration of the
800    /// transaction timeout for a response."
801    /// Cancels the transactions on a pair the application removed.
802    pub(crate) fn cancel_pair_checks(&mut self, local_index: usize, remote_index: usize) {
803        self.cancel_transactions(local_index, remote_index);
804    }
805
806    fn cancel_transactions(&mut self, local_index: usize, remote_index: usize) {
807        // How long a transaction lasts without a response (RFC 8489 Section 6.2.1): the `Rc`
808        // requests are RTO, 2 RTO, 4 RTO, ... apart and the last one is given `Rm` times the
809        // RTO: 39.5 s with the defaults.
810        let rc = u32::from(self.max_binding_requests.clamp(1, 16));
811        let duration = |rto: Duration| rto * ((1u32 << (rc - 1)) - 1 + STUN_RM);
812        for r in &mut self.pending_binding_requests {
813            if r.local_index == local_index
814                && r.remote_index == remote_index
815                && !r.consent
816                && !r.is_use_candidate
817            {
818                r.cancelled = true;
819                r.next_event = r.next_event.max(r.timestamp + duration(r.rto));
820            }
821        }
822        self.trim_passive_transactions();
823    }
824
825    /// Retransmits the requests whose RTO ran out and ends the transactions that got no
826    /// response (RFC 8489 Section 6.2.1: requests RTO, 2 RTO, 4 RTO, ... apart, `Rc` of them,
827    /// then `Rm * RTO` of patience). A check that times out fails its pair (Section
828    /// 7.2.5.2.3).
829    pub(crate) fn run_transactions(&mut self, now: Instant) {
830        let rc = self.max_binding_requests.max(1);
831        let mut resend: Vec<(BytesMut, usize, SocketAddr)> = vec![];
832        let mut timed_out: Vec<BindingRequest> = vec![];
833        let mut index = 0;
834        while index < self.pending_binding_requests.len() {
835            let r = &mut self.pending_binding_requests[index];
836            if r.next_event > now {
837                index += 1;
838                continue;
839            }
840            if r.retransmit && !r.cancelled && r.transmissions < rc {
841                r.transmissions += 1;
842                r.interval *= 2;
843                r.next_event = now
844                    + if r.transmissions >= rc {
845                        r.rto * STUN_RM
846                    } else {
847                        r.interval
848                    };
849                resend.push((r.raw.clone(), r.local_index, r.destination));
850                index += 1;
851            } else {
852                timed_out.push(self.pending_binding_requests.remove(index));
853            }
854        }
855
856        for (raw, local_index, destination) in resend {
857            if local_index < self.local_candidates.len() {
858                self.send_raw_stun(now, raw, local_index, destination);
859            }
860        }
861
862        let mut failed = false;
863        for r in timed_out {
864            if r.unauthentic_response && !r.cancelled {
865                self.signal_integrity_violation(&r);
866            }
867            if r.cancelled || r.consent {
868                continue;
869            }
870            let Some(pair_index) = self.find_pair_exact(r.local_index, r.remote_index) else {
871                continue;
872            };
873            let pair = self.candidate_pairs[pair_index];
874            // A nomination is a check on a valid pair: the pair has received a success
875            // response and stays Succeeded (Section 7.2.5.3.3). When it times out, the pair
876            // and the checklist fail (Section 7.2.5.3.4), or with `FailedNomination::Retry`
877            // it is sent again for as long as the peer is heard from (see
878            // `nomination_is_alive`).
879            let nomination = self.is_open_nomination(&r, pair_index);
880            if self.failed_nomination == FailedNomination::FailChecklist
881                && (nomination || self.is_followed_nomination(&r, pair_index))
882            {
883                self.fail_nomination(now, pair_index, "no response");
884                return;
885            }
886            if nomination && self.nomination_is_alive(now, pair_index) {
887                debug!(
888                    "[{}]: no response to the nomination of {} after {} requests: nominating it again",
889                    self.get_name(),
890                    pair,
891                    r.transmissions
892                );
893                self.candidate_pairs[pair_index].nominate = true;
894                self.enqueue_triggered(pair_index);
895                continue;
896            }
897            // A check that timed out on a pair another transaction has validated since is
898            // moot; a nomination that timed out is not.
899            if pair.state == CandidatePairState::InProgress || r.is_use_candidate {
900                warn!(
901                    "[{}]: no response to {} requests on {}{}: the pair failed",
902                    self.get_name(),
903                    r.transmissions,
904                    self.candidate_pairs[pair_index],
905                    if r.is_use_candidate {
906                        " (nomination)"
907                    } else {
908                        ""
909                    }
910                );
911                self.fail_pair(pair_index);
912                failed = true;
913            }
914        }
915        if failed {
916            self.maybe_nominate(now);
917        }
918    }
919
920    /// A response with the transaction id `id` failed its integrity check and was discarded.
921    ///
922    /// Over UDP the transaction stays open: a genuine response may still come. Over a
923    /// reliable transport (ICE-TCP, where a check is sent once) none will: RFC 8489 Section
924    /// 9.1.4, "the transaction MUST be ended immediately and the layer MUST signal an
925    /// integrity protection violation". The transaction is ended at the next timer pass, which
926    /// is due at once: the pair fails and `Event::IntegrityViolation` is raised.
927    pub(crate) fn note_unauthentic_response(&mut self, id: TransactionId) {
928        let clock = self.clock;
929        let tcp = |local_index: usize, candidates: &[Candidate]| {
930            candidates
931                .get(local_index)
932                .is_some_and(|c| c.network_type().is_tcp())
933        };
934        if let Some(r) = self
935            .pending_binding_requests
936            .iter_mut()
937            .find(|r| r.transaction_id == id)
938        {
939            r.unauthentic_response = true;
940            if tcp(r.local_index, &self.local_candidates) {
941                r.retransmit = false;
942                r.next_event = r.next_event.min(clock);
943            }
944        }
945    }
946
947    /// RFC 8489 Section 9.1.4: "If all responses received are discarded, then instead of
948    /// signaling a timeout after ending the transaction, the layer MUST signal an integrity
949    /// protection violation."
950    fn signal_integrity_violation(&mut self, r: &BindingRequest) {
951        let (Some(local), Some(remote)) = (
952            self.local_candidates.get(r.local_index),
953            self.remote_candidates.get(r.remote_index),
954        ) else {
955            return;
956        };
957        warn!(
958            "[{}]: every response to the request on {} -> {} failed its integrity check: integrity violation",
959            self.get_name(),
960            local,
961            remote
962        );
963        let event = Event::IntegrityViolation(Box::new(local.clone()), Box::new(remote.clone()));
964        self.event_outs.push_back(TaggedEvent {
965            now: self.clock,
966            event,
967        });
968    }
969
970    /// The pair is Failed: out of the valid list, not nominated, not awaited. The selected
971    /// pair is not failed this way; it ends when its consent expires.
972    pub(crate) fn fail_pair(&mut self, pair_index: usize) {
973        if self.selected_pair == Some(pair_index) {
974            return;
975        }
976        let failed = |p: &mut CandidatePair| {
977            p.state = CandidatePairState::Failed;
978            p.valid = false;
979            p.valid_pair = None;
980            p.nominated = false;
981            p.nomination_pending = false;
982            p.nominate = false;
983            p.triggered = false;
984        };
985        failed(&mut self.candidate_pairs[pair_index]);
986        if self.nominated_pair == Some(pair_index) {
987            self.nominated_pair = None;
988        }
989        // The pairs whose check produced this valid pair go with it.
990        for index in 0..self.candidate_pairs.len() {
991            if self.candidate_pairs[index].valid_pair == Some(pair_index)
992                && self.selected_pair != Some(index)
993            {
994                failed(&mut self.candidate_pairs[index]);
995            }
996        }
997    }
998
999    /// Whether `request` is the controlling agent's nomination of `pair_index`, a valid pair,
1000    /// with no pair selected yet: the check Section 7.2.5.3.4 says the checklist fails with.
1001    fn is_open_nomination(&self, request: &BindingRequest, pair_index: usize) -> bool {
1002        let pair = &self.candidate_pairs[pair_index];
1003        request.is_use_candidate
1004            && request.sent_as_controlling
1005            && self.is_controlling
1006            && self.selected_pair.is_none()
1007            && pair.valid
1008            && pair.state == CandidatePairState::Succeeded
1009    }
1010
1011    /// Whether `request` is the controlled agent's check of `pair_index` that a received
1012    /// USE-CANDIDATE triggered (Section 7.3.1.5: the nomination waits for it), with no pair
1013    /// selected yet: Section 7.2.5.3.4, "If the triggered request fails, the agent MUST remove
1014    /// the candidate pair from the valid list, set the candidate pair state to Failed, and set
1015    /// the checklist state to Failed." (Once a pair is selected the checklist is Completed and
1016    /// a later nomination's check failing only fails its pair.)
1017    fn is_followed_nomination(&self, request: &BindingRequest, pair_index: usize) -> bool {
1018        !request.sent_as_controlling
1019            && !self.is_controlling
1020            && !request.consent
1021            && self.selected_pair.is_none()
1022            && self.candidate_pairs[pair_index].nomination_pending
1023    }
1024
1025    /// Section 7.2.5.3.4: "If the request fails (Section 7.2.5.2), the agent MUST remove the
1026    /// candidate pair from the valid list, set the candidate pair state to Failed, and set the
1027    /// checklist state to Failed." (`FailedNomination::FailChecklist`.)
1028    fn fail_nomination(&mut self, now: Instant, pair_index: usize, why: &str) {
1029        warn!(
1030            "[{}]: {} to the nomination of {}: the pair and the checklist failed",
1031            self.get_name(),
1032            why,
1033            self.candidate_pairs[pair_index]
1034        );
1035        self.fail_pair(pair_index);
1036        self.nomination_started = None;
1037        self.update_connection_state(Some(now), ConnectionState::Failed);
1038    }
1039
1040    /// Takes the open transaction `id`, if there is one.
1041    pub(crate) fn handle_inbound_binding_success(
1042        &mut self,
1043        _now: Instant,
1044        id: TransactionId,
1045    ) -> Option<BindingRequest> {
1046        let index = self
1047            .pending_binding_requests
1048            .iter()
1049            .position(|r| r.transaction_id == id)?;
1050        Some(self.pending_binding_requests.remove(index))
1051    }
1052
1053    // ---------------------------------------------------------------------------------------
1054    // Responses (Section 7.2.5)
1055    // ---------------------------------------------------------------------------------------
1056
1057    /// An authenticated success response. `local_index` is the local candidate it arrived on,
1058    /// `remote_addr` its source.
1059    pub(crate) fn handle_success_response(
1060        &mut self,
1061        now: Instant,
1062        m: &Message,
1063        local_index: usize,
1064        remote_addr: SocketAddr,
1065    ) {
1066        // RFC 8489 Section 6.3.3: "For the Binding method, the client checks that the
1067        // XOR-MAPPED-ADDRESS attribute is present in the response", and processes the success
1068        // response only "if all the checks succeed". Without it the response is discarded: the
1069        // transaction goes on (retransmissions, its timeout) as if it had not arrived, and it
1070        // refreshes no consent. (One whose address family cannot be decoded is processed; the
1071        // value is ignored, Section 6.3.3's SHOULD, and the pair is valid on the sent local
1072        // candidate.)
1073        if !m.contains(ATTR_XORMAPPED_ADDRESS) {
1074            debug!(
1075                "[{}]: discard Binding success response from {} without XOR-MAPPED-ADDRESS",
1076                self.get_name(),
1077                remote_addr
1078            );
1079            return;
1080        }
1081
1082        // Section 7.2.5: the response belongs to the transaction with its id, and so to that
1083        // transaction's pair.
1084        let Some(request) = self.handle_inbound_binding_success(now, m.transaction_id) else {
1085            warn!(
1086                "[{}]: discard message from ({}), unknown TransactionID 0x{:?}",
1087                self.get_name(),
1088                remote_addr,
1089                m.transaction_id
1090            );
1091            return;
1092        };
1093        let checked = self.find_pair_exact(request.local_index, request.remote_index);
1094
1095        // Section 7.2.5.2.1: "The ICE agent MUST check that the source and destination
1096        // transport addresses in the Binding request and response are symmetric. [...] If the
1097        // addresses are not symmetric, the agent MUST set the candidate pair state to Failed."
1098        let symmetric = request.destination == remote_addr
1099            && request.local_index < self.local_candidates.len()
1100            && self.same_base(request.local_index, local_index);
1101        if !symmetric {
1102            debug!(
1103                "[{}]: response from {} to a request sent to {}: not symmetric",
1104                self.get_name(),
1105                remote_addr,
1106                request.destination
1107            );
1108            if let Some(pair_index) = checked
1109                && !request.consent
1110            {
1111                if self.failed_nomination == FailedNomination::FailChecklist
1112                    && (self.is_open_nomination(&request, pair_index)
1113                        || self.is_followed_nomination(&request, pair_index))
1114                {
1115                    self.fail_nomination(now, pair_index, "a response from another address");
1116                    return;
1117                }
1118                self.fail_pair(pair_index);
1119                self.maybe_nominate(now);
1120            }
1121            return;
1122        }
1123        let Some(checked) = checked else {
1124            return;
1125        };
1126        // The application removed the pair: its checks stopped (webrtc-extensions 7).
1127        if self.candidate_pairs[checked].removed {
1128            return;
1129        }
1130
1131        // Consent (RFC 7675 Section 5.1): a matching, authenticated success response from the
1132        // address the request went to.
1133        if let Some(remote) = self.remote_candidates.get_mut(request.remote_index) {
1134            remote.last_consent = Some(now);
1135        }
1136        if self.selected_pair.is_some_and(|selected| {
1137            self.candidate_pairs[selected].remote_index == request.remote_index
1138        }) {
1139            self.consent_unanswered_since = None;
1140            // Consent is back: the state is looked at now, not at the next consent check.
1141            if self.connection_state == ConnectionState::Disconnected {
1142                self.request_connectivity_check();
1143            }
1144        }
1145
1146        // Round-trip time, from a request that was sent once (a retransmitted one does not say
1147        // which transmission was answered).
1148        let rtt = now.saturating_duration_since(request.timestamp);
1149        if request.transmissions == 1 {
1150            self.candidate_pairs[checked].on_response_received(rtt);
1151        } else {
1152            self.candidate_pairs[checked].responses_received += 1;
1153        }
1154        if request.consent {
1155            return;
1156        }
1157
1158        trace!(
1159            "[{}]: inbound STUN (SuccessResponse) from {} to {}",
1160            self.get_name(),
1161            self.remote_candidates[request.remote_index],
1162            self.local_candidates[local_index]
1163        );
1164
1165        // Sections 7.2.5.3.1 and 7.2.5.3.2: the valid pair is (mapped address, the request's
1166        // destination).
1167        let valid_local = self.local_candidate_for_mapped_address(m, &request);
1168        let valid = if valid_local == request.local_index {
1169            checked
1170        } else {
1171            self.valid_pair_for(valid_local, request.remote_index)
1172        };
1173
1174        // Section 7.2.5.3.3: the pair that generated the check and the valid pair are
1175        // Succeeded, and the Frozen pairs with the same foundation are unfrozen.
1176        let remote_nomination = self.candidate_pairs[checked].remote_nomination;
1177        {
1178            let c = &mut self.candidate_pairs[checked];
1179            c.state = CandidatePairState::Succeeded;
1180            c.valid_pair = Some(valid);
1181            // A triggered check still queued for the pair is not needed any more, but a
1182            // nomination queued for it is (Section 8.1.1): an answer to an earlier check
1183            // must not take it off the queue.
1184            c.triggered = c.triggered && c.nominate;
1185        }
1186        {
1187            let v = &mut self.candidate_pairs[valid];
1188            v.state = CandidatePairState::Succeeded;
1189            v.valid = true;
1190            v.valid_pair = Some(valid);
1191            v.remote_nomination = v.remote_nomination.max(remote_nomination);
1192        }
1193        let foundation = self.candidate_pairs[checked].foundation;
1194        for p in &mut self.candidate_pairs {
1195            if p.state == CandidatePairState::Frozen && p.foundation == foundation {
1196                p.state = CandidatePairState::Waiting;
1197            }
1198        }
1199        // The pair's other open checks have nothing left to decide.
1200        self.cancel_transactions(request.local_index, request.remote_index);
1201
1202        trace!(
1203            "[{}]: valid pair {} from check on {}, use-candidate: {}, rtt: {:.3}ms",
1204            self.get_name(),
1205            self.candidate_pairs[valid],
1206            self.candidate_pairs[checked],
1207            request.is_use_candidate,
1208            rtt.as_millis()
1209        );
1210
1211        // Section 7.2.5.3.4.
1212        if request.is_use_candidate && self.is_controlling {
1213            // "If the controlling agent sends a Binding request with the USE-CANDIDATE
1214            // attribute set, and if the ICE agent receives a successful response to the
1215            // request, the agent sets the nominated flag of the pair to true."
1216            self.candidate_pairs[valid].nominate = false;
1217            self.candidate_pairs[checked].nominate = false;
1218            if self.selected_pair.is_none() {
1219                self.set_selected_pair(Some(now), Some(valid));
1220                self.conclude();
1221            }
1222        } else if self.adopt_tcp_reconnection(now, valid) {
1223            // The selected pair's connection was opened again: see `adopt_tcp_reconnection`.
1224        } else if std::mem::take(&mut self.candidate_pairs[checked].nomination_pending) {
1225            // "If the controlled agent receives a successful response to a Binding request
1226            // sent by the agent, and that Binding request was triggered by a received Binding
1227            // request with the USE-CANDIDATE attribute set, the agent sets the nominated flag
1228            // of the pair to true."
1229            self.accept_nomination(now, valid);
1230        } else {
1231            self.maybe_nominate(now);
1232        }
1233    }
1234
1235    /// RFC 6544 Section 11.1: when the selected pair's TCP connection is lost, the active side
1236    /// opens it again and the passive side waits for it. The new connection has another source
1237    /// port, so on the passive side it is a new peer-reflexive candidate and a new pair. Once
1238    /// that pair is valid it *is* the selected pair's connection, re-established: the session
1239    /// moves to it without a nomination (the active side still sees the pair it nominated).
1240    /// Returns whether `valid` was adopted.
1241    fn adopt_tcp_reconnection(&mut self, now: Instant, valid: usize) -> bool {
1242        let Some(selected) = self.selected_pair else {
1243            return false;
1244        };
1245        if selected == valid {
1246            return false;
1247        }
1248        let (old, new) = (self.candidate_pairs[selected], self.candidate_pairs[valid]);
1249        let local = &self.local_candidates[new.local_index];
1250        let (old_remote, new_remote) = (
1251            &self.remote_candidates[old.remote_index],
1252            &self.remote_candidates[new.remote_index],
1253        );
1254        let reconnection = local.network_type().is_tcp()
1255            && local.tcp_type() == crate::tcp_type::TcpType::Passive
1256            && self.same_base(old.local_index, new.local_index)
1257            && new_remote.candidate_type() == CandidateType::PeerReflexive
1258            && new_remote.tcp_type() == crate::tcp_type::TcpType::Active
1259            && old_remote.tcp_type() == crate::tcp_type::TcpType::Active
1260            && old_remote.addr().ip() == new_remote.addr().ip();
1261        if !reconnection {
1262            return false;
1263        }
1264        debug!(
1265            "[{}]: the selected TCP pair was reconnected: {} replaces {}",
1266            self.get_name(),
1267            new,
1268            old
1269        );
1270        self.candidate_pairs[valid].remote_nomination = old.remote_nomination;
1271        self.candidate_pairs[valid].nomination_pending = false;
1272        self.candidate_pairs[selected].nominated = false;
1273        self.set_selected_pair(Some(now), Some(valid));
1274        self.conclude();
1275        true
1276    }
1277
1278    /// Section 7.2.5.3.1: "The ICE agent MUST check the mapped address from the STUN response.
1279    /// If the transport address does not match any of the local candidates that the agent
1280    /// knows about, the mapped address represents a new candidate: a peer-reflexive
1281    /// candidate", whose base is the local candidate the request was sent from and whose
1282    /// priority is the PRIORITY the request carried. Returns the local candidate of the valid
1283    /// pair.
1284    fn local_candidate_for_mapped_address(
1285        &mut self,
1286        m: &Message,
1287        request: &BindingRequest,
1288    ) -> usize {
1289        let sent_index = request.local_index;
1290        let mut mapped = XorMappedAddress::default();
1291        if mapped.get_from(m).is_err() {
1292            return sent_index;
1293        }
1294        let mapped = SocketAddr::new(mapped.ip, mapped.port);
1295        let has_address = |c: &Candidate| {
1296            c.addr() == mapped
1297                || (c.port() == mapped.port() && c.address().parse::<IpAddr>() == Ok(mapped.ip()))
1298        };
1299        let sent = &self.local_candidates[sent_index];
1300        if has_address(sent) {
1301            return sent_index;
1302        }
1303        // Over TCP the mapped port is the connection's (an active candidate is signalled on
1304        // port 9, RFC 6544 Section 4.5): the same IP address is the same candidate.
1305        if sent.network_type().is_tcp() && sent.base_addr().ip() == mapped.ip() {
1306            return sent_index;
1307        }
1308        let (base, network_type) = (sent.base_addr(), sent.network_type());
1309        if let Some(known) = self.local_candidates.iter().position(|c| {
1310            has_address(c) && c.network_type() == network_type && c.base_addr() == base
1311        }) {
1312            return known;
1313        }
1314
1315        // Bounded: a peer can answer each check with another mapped address.
1316        let learned = self
1317            .local_candidates
1318            .iter()
1319            .filter(|c| c.candidate_type() == CandidateType::PeerReflexive)
1320            .count();
1321        if learned >= MAX_LOCAL_PEER_REFLEXIVE_CANDIDATES {
1322            return sent_index;
1323        }
1324        let (component, tcp_type) = (sent.component(), sent.tcp_type());
1325        match (CandidatePeerReflexiveConfig {
1326            base_config: CandidateConfig {
1327                network: network_type.to_string(),
1328                address: mapped.ip().to_string(),
1329                port: mapped.port(),
1330                component,
1331                priority: request.priority.min(MAX_CANDIDATE_PRIORITY),
1332                ..CandidateConfig::default()
1333            },
1334            rel_addr: base.ip().to_string(),
1335            rel_port: base.port(),
1336        })
1337        .new_candidate_peer_reflexive()
1338        {
1339            Ok(mut prflx) => {
1340                prflx.tcp_type = tcp_type;
1341                debug!(
1342                    "[{}]: new local peer-reflexive candidate {} (base {})",
1343                    self.get_name(),
1344                    mapped,
1345                    base
1346                );
1347                self.local_candidates.push(prflx);
1348                self.local_candidates.len() - 1
1349            }
1350            Err(err) => {
1351                warn!(
1352                    "[{}]: cannot make a local peer-reflexive candidate for {}: {}",
1353                    self.get_name(),
1354                    mapped,
1355                    err
1356                );
1357                sent_index
1358            }
1359        }
1360    }
1361
1362    /// The valid pair with this local candidate, created beside the checklist when it is
1363    /// not there (Section 7.2.5.3.2, case 3).
1364    fn valid_pair_for(&mut self, local_index: usize, remote_index: usize) -> usize {
1365        if let Some(index) = self.find_pair_exact(local_index, remote_index) {
1366            return index;
1367        }
1368        let mut pair = CandidatePair::new(
1369            local_index,
1370            remote_index,
1371            self.local_candidates[local_index].priority(),
1372            self.remote_candidates[remote_index].priority(),
1373            self.is_controlling,
1374        );
1375        pair.foundation = self.pair_foundation(local_index, remote_index);
1376        pair.state = CandidatePairState::Succeeded;
1377        self.candidate_pairs.push(pair);
1378        let index = self.candidate_pairs.len() - 1;
1379        self.announce_pair(index, true);
1380        index
1381    }
1382
1383    /// An error response to one of our Binding requests, already authenticated.
1384    ///
1385    /// RFC 8445 Section 7.2.5.1: a 487 (Role Conflict) switches the role away from the one the
1386    /// request claimed, changes the tiebreaker, and the pair goes back on the triggered-check
1387    /// queue. Section 7.2.5.2.4: any other error response is unrecoverable and fails the pair.
1388    pub(crate) fn handle_error_response(
1389        &mut self,
1390        now: Instant,
1391        m: &Message,
1392        remote_addr: SocketAddr,
1393    ) {
1394        use crate::rand::generate_tie_breaker;
1395        use stun::error_code::{CODE_ROLE_CONFLICT, ErrorCodeAttribute};
1396
1397        let Some(pending) = self.handle_inbound_binding_success(now, m.transaction_id) else {
1398            warn!(
1399                "[{}]: discard error response from ({}), unknown TransactionID 0x{:?}",
1400                self.get_name(),
1401                remote_addr,
1402                m.transaction_id
1403            );
1404            return;
1405        };
1406        if pending.destination != remote_addr {
1407            return;
1408        }
1409
1410        let mut error = ErrorCodeAttribute::default();
1411        let role_conflict = error.get_from(m).is_ok() && error.code == CODE_ROLE_CONFLICT;
1412        let pair_index = self.find_pair_exact(pending.local_index, pending.remote_index);
1413        let is_selected = pair_index.is_some() && pair_index == self.selected_pair;
1414
1415        if role_conflict {
1416            if pending.sent_as_controlling == self.is_controlling {
1417                log::info!(
1418                    "[{}]: 487 (Role Conflict) from {}: switching role",
1419                    self.get_name(),
1420                    remote_addr
1421                );
1422                self.switch_role(now);
1423            }
1424            match generate_tie_breaker(self.crypto_provider.random()) {
1425                Ok(tie_breaker) => self.tie_breaker = tie_breaker,
1426                Err(err) => warn!(
1427                    "[{}]: cannot generate a new tiebreaker: {}",
1428                    self.get_name(),
1429                    err
1430                ),
1431            }
1432            // "the agent MUST add the candidate pair whose check generated the 487 error
1433            // response to the triggered-check queue [...] and set the candidate pair state to
1434            // Waiting." The selected pair keeps its state: its next consent check carries the
1435            // new role.
1436            if let Some(pair_index) = pair_index
1437                && !is_selected
1438                && !pending.cancelled
1439                && self.candidate_pairs[pair_index].state != CandidatePairState::Succeeded
1440            {
1441                self.candidate_pairs[pair_index].state = CandidatePairState::Waiting;
1442                self.enqueue_triggered(pair_index);
1443            }
1444            self.request_connectivity_check();
1445        } else if let Some(pair_index) = pair_index
1446            && !is_selected
1447            && !pending.cancelled
1448            && !pending.consent
1449        {
1450            // (An error answer to a consent check on the selected pair grants no consent, RFC
1451            // 7675 Section 5.1, and takes nothing away either.)
1452            if self.failed_nomination == FailedNomination::FailChecklist
1453                && (self.is_open_nomination(&pending, pair_index)
1454                    || self.is_followed_nomination(&pending, pair_index))
1455            {
1456                self.fail_nomination(now, pair_index, "an error response");
1457                return;
1458            }
1459            debug!(
1460                "[{}]: error response {} from {}: pair {} failed",
1461                self.get_name(),
1462                error,
1463                remote_addr,
1464                self.candidate_pairs[pair_index]
1465            );
1466            self.fail_pair(pair_index);
1467            self.maybe_nominate(now);
1468        }
1469    }
1470
1471    /// The transaction `id` failed on an authenticated response the agent cannot use (RFC 8489
1472    /// Section 6.3.4: an error response with unknown comprehension-required attributes): its
1473    /// pair fails as on an error response (Section 7.2.5.2.4), its nomination with the
1474    /// checklist by default (Section 7.2.5.3.4).
1475    pub(crate) fn handle_failed_transaction(
1476        &mut self,
1477        now: Instant,
1478        id: TransactionId,
1479        remote_addr: SocketAddr,
1480    ) {
1481        let Some(pending) = self.handle_inbound_binding_success(now, id) else {
1482            return;
1483        };
1484        if pending.destination != remote_addr || pending.cancelled || pending.consent {
1485            return;
1486        }
1487        let Some(pair_index) = self.find_pair_exact(pending.local_index, pending.remote_index)
1488        else {
1489            return;
1490        };
1491        if self.selected_pair == Some(pair_index) {
1492            return;
1493        }
1494        if self.failed_nomination == FailedNomination::FailChecklist
1495            && (self.is_open_nomination(&pending, pair_index)
1496                || self.is_followed_nomination(&pending, pair_index))
1497        {
1498            self.fail_nomination(now, pair_index, "an unusable error response");
1499            return;
1500        }
1501        self.fail_pair(pair_index);
1502        self.maybe_nominate(now);
1503    }
1504
1505    // ---------------------------------------------------------------------------------------
1506    // Requests (Sections 7.3.1.4, 7.3.1.5, 7.3.2)
1507    // ---------------------------------------------------------------------------------------
1508
1509    /// What an authenticated Binding request does beyond being answered. The caller answered
1510    /// it and made sure the pair is on the checklist.
1511    pub(crate) fn handle_binding_request(
1512        &mut self,
1513        now: Instant,
1514        m: &Message,
1515        local_index: usize,
1516        remote_index: usize,
1517    ) {
1518        let Some(pair_index) = self.find_pair(local_index, remote_index) else {
1519            return;
1520        };
1521
1522        // A nomination is `USE-CANDIDATE` (value 1) or libwebrtc's `NOMINATION` value, read
1523        // only from the part of the request MESSAGE-INTEGRITY covers. It has a meaning for
1524        // the controlled agent only (Section 7.3.1.5); like libwebrtc, a controlling agent
1525        // ignores it and answers the check.
1526        let nomination = if self.is_controlling {
1527            0
1528        } else {
1529            nomination_of(m)
1530        };
1531        if nomination > 0 {
1532            let p = &mut self.candidate_pairs[pair_index];
1533            p.remote_nomination = p.remote_nomination.max(nomination);
1534            let value = p.remote_nomination;
1535            if let Some(valid) = p.valid_pair {
1536                let v = &mut self.candidate_pairs[valid];
1537                v.remote_nomination = v.remote_nomination.max(value);
1538            }
1539        }
1540
1541        if self.lite && !self.is_controlling {
1542            // Section 7.3.2: a lite agent sends no checks. A request with USE-CANDIDATE is all
1543            // it gets: "the agent constructs a candidate pair [...] This candidate pair is
1544            // then added to the valid list" and its nominated flag is set. Without
1545            // USE-CANDIDATE there is nothing more to do than answer.
1546            if nomination > 0 {
1547                let p = &mut self.candidate_pairs[pair_index];
1548                p.state = CandidatePairState::Succeeded;
1549                p.valid = true;
1550                p.valid_pair = Some(pair_index);
1551                self.accept_nomination(now, pair_index);
1552            }
1553            return;
1554        }
1555
1556        let p = self.candidate_pairs[pair_index];
1557        if p.state == CandidatePairState::Succeeded {
1558            // Section 7.3.1.4: "If the state of that pair is Succeeded, nothing further is
1559            // done." Section 7.3.1.5: with USE-CANDIDATE, "the agent sets the nominated flag
1560            // value of the valid pair to true". Which nominated pair is then used is
1561            // `accept_nomination`'s business.
1562            if nomination > 0 {
1563                self.accept_nomination(now, p.valid_pair.unwrap_or(pair_index));
1564            } else {
1565                self.maybe_nominate(now);
1566            }
1567            return;
1568        }
1569
1570        if nomination > 0 {
1571            // Section 7.3.1.5: the nomination takes effect once our triggered check on this
1572            // pair succeeds (see `handle_success_response`). If the check fails, the pair is
1573            // not used.
1574            self.candidate_pairs[pair_index].nomination_pending = true;
1575        }
1576        // Section 7.3.1.4: In-Progress, Waiting, Frozen or Failed: a triggered check.
1577        self.trigger_check(pair_index);
1578    }
1579
1580    // ---------------------------------------------------------------------------------------
1581    // Nomination and conclusion (Section 8)
1582    // ---------------------------------------------------------------------------------------
1583
1584    /// Controlled agent: `pair_index`, a valid pair, was nominated by the controlling agent.
1585    /// It becomes the selected pair when there is none. When there is one:
1586    ///
1587    /// - [`NominationAcceptance::HighestPriority`] (RFC 8445 Section 8.1.1: "the agents MUST
1588    ///   produce the selected pairs and use the pairs with the highest priority"): it takes
1589    ///   over when its priority is higher. A nominated pair of lower priority takes over only
1590    ///   when the selected pair has lost the peer's consent (the agent is `Disconnected`): that
1591    ///   pair is on its way out of the valid list, and the highest-priority nominated pair is
1592    ///   then this one.
1593    /// - [`NominationAcceptance::Latest`] (libwebrtc): it takes over unless the selected pair
1594    ///   carries a higher nomination (libwebrtc's renomination: the highest `NOMINATION` value
1595    ///   wins, so a delayed earlier one does not move the session back). Between regular
1596    ///   nominations, all value 1, the latest one wins.
1597    ///
1598    /// Switching emits `SelectedCandidatePairChange`, and `media_path` follows at once: DTLS,
1599    /// SRTP and SCTP go out on the new pair from the next datagram.
1600    pub(crate) fn accept_nomination(&mut self, now: Instant, pair_index: usize) {
1601        self.candidate_pairs[pair_index].nominated = true;
1602        match self.get_selected_pair() {
1603            Some(selected) if selected == pair_index => {}
1604            Some(selected) => {
1605                let (current, offered) = (
1606                    self.candidate_pairs[selected],
1607                    self.candidate_pairs[pair_index],
1608                );
1609                let takes_over = match self.nomination_acceptance {
1610                    NominationAcceptance::HighestPriority => {
1611                        offered.priority() > current.priority()
1612                            || self.connection_state == ConnectionState::Disconnected
1613                    }
1614                    NominationAcceptance::Latest => {
1615                        offered.remote_nomination >= current.remote_nomination
1616                    }
1617                };
1618                if takes_over {
1619                    debug!(
1620                        "[{}]: peer nominated another pair: switching selected pair from {} to {} (nomination {} -> {})",
1621                        self.get_name(),
1622                        current,
1623                        offered,
1624                        current.remote_nomination,
1625                        offered.remote_nomination
1626                    );
1627                    if self.nomination_acceptance == NominationAcceptance::Latest {
1628                        self.candidate_pairs[selected].nominated = false;
1629                    }
1630                    self.set_selected_pair(Some(now), Some(pair_index));
1631                    self.conclude();
1632                } else {
1633                    debug!(
1634                        "[{}]: nomination of {} accepted, selected pair {} kept (nomination {} / {})",
1635                        self.get_name(),
1636                        offered,
1637                        current,
1638                        offered.remote_nomination,
1639                        current.remote_nomination
1640                    );
1641                }
1642            }
1643            None => {
1644                self.set_selected_pair(Some(now), Some(pair_index));
1645                self.conclude();
1646            }
1647        }
1648    }
1649
1650    /// Controlled agent, [`NominationAcceptance::HighestPriority`], when consent is lost on
1651    /// the selected pair: the session moves to the nominated valid pair with the highest
1652    /// priority the peer has been heard on since it last consented on the selected one, if
1653    /// there is one. (RFC 8445 Section 8.1.1 uses the nominated pairs "with the highest
1654    /// priority"; a pair without consent may not be sent on, RFC 7675 Section 5.1.)
1655    pub(crate) fn fall_back_to_another_nominated_pair(&mut self, now: Instant) {
1656        if self.is_controlling
1657            || self.nomination_acceptance != NominationAcceptance::HighestPriority
1658        {
1659            return;
1660        }
1661        let Some(selected) = self.selected_pair else {
1662            return;
1663        };
1664        let last_consent = self.remote_candidates[self.candidate_pairs[selected].remote_index]
1665            .last_consent()
1666            .unwrap_or(self.start_time);
1667        let best = self
1668            .candidate_pairs
1669            .iter()
1670            .enumerate()
1671            .filter(|(index, p)| {
1672                *index != selected
1673                    && p.nominated
1674                    && p.valid
1675                    && p.state == CandidatePairState::Succeeded
1676                    && p.remote_index != self.candidate_pairs[selected].remote_index
1677                    && self.remote_candidates[p.remote_index]
1678                        .last_authenticated()
1679                        .is_some_and(|heard| heard > last_consent)
1680            })
1681            .max_by_key(|(_, p)| p.priority())
1682            .map(|(index, _)| index);
1683        if let Some(pair_index) = best {
1684            debug!(
1685                "[{}]: consent lost on {}: moving to the nominated pair {}",
1686                self.get_name(),
1687                self.candidate_pairs[selected],
1688                self.candidate_pairs[pair_index]
1689            );
1690            self.set_selected_pair(Some(now), Some(pair_index));
1691            self.conclude();
1692        }
1693    }
1694
1695    /// What the transport learned about the path `transport` (its local address the base of
1696    /// a local candidate, its peer address a remote candidate):
1697    ///
1698    /// - [`TransportError::IcmpHardError`], RFC 8445 Section 7.2.5.2.2: "if a Binding request
1699    ///   generates a hard ICMP error, the agent SHOULD set the state of the candidate pair to
1700    ///   Failed". Only a pair whose check is in flight fails, and never a valid one: an ICMP
1701    ///   error is not authenticated ("ICMP errors can be used as a method for
1702    ///   Denial-of-Service attacks"), so it cannot take away a pair a check has validated.
1703    ///   Consent decides for those.
1704    /// - [`TransportError::ConnectionFailed`], RFC 6544 Section 7.1: "If the TCP connection
1705    ///   cannot be established, the check is considered to have failed, and a full-mode agent
1706    ///   MUST update the pair state to Failed". The pair fails whether or not its check has
1707    ///   started; a valid pair is left to consent, as above.
1708    /// - [`TransportError::NotStun`], RFC 6544 Section 7.1: "If the response to the first
1709    ///   connectivity check on the established TCP connection is something other than a STUN
1710    ///   message, the remote candidate address apparently was not one of the peer's addresses,
1711    ///   and the agent SHOULD close the connection and consider all pairs with that remote
1712    ///   candidate as failed." Every pair with that remote candidate that is not valid fails;
1713    ///   closing the connection is the caller's.
1714    ///
1715    /// Returns whether a pair failed.
1716    pub fn handle_transport_error(
1717        &mut self,
1718        now: Instant,
1719        transport: shared::TransportContext,
1720        error: TransportError,
1721    ) -> bool {
1722        let Some(local_index) =
1723            self.find_local_candidate(transport.local_addr, transport.transport_protocol)
1724        else {
1725            return false;
1726        };
1727        let Some(remote_index) = self.remote_candidates.iter().position(|c| {
1728            c.addr() == transport.peer_addr
1729                && c.network_type().to_protocol() == transport.transport_protocol
1730        }) else {
1731            return false;
1732        };
1733        let is_tcp = transport.transport_protocol == shared::TransportProtocol::TCP;
1734        let mut failed = vec![];
1735        for (index, p) in self.candidate_pairs.iter().enumerate() {
1736            if p.remote_index != remote_index
1737                || p.valid
1738                || p.state == CandidatePairState::Succeeded
1739                || p.state == CandidatePairState::Failed
1740                || Some(index) == self.selected_pair
1741            {
1742                continue;
1743            }
1744            let on_path = self.same_base(p.local_index, local_index);
1745            let fails = match error {
1746                TransportError::IcmpHardError => {
1747                    on_path && p.state == CandidatePairState::InProgress
1748                }
1749                TransportError::ConnectionFailed => is_tcp && on_path,
1750                TransportError::NotStun => is_tcp,
1751            };
1752            if fails {
1753                failed.push(index);
1754            }
1755        }
1756        if error == TransportError::NotStun
1757            && !failed.iter().any(|&index| {
1758                self.candidate_pairs[index].state == CandidatePairState::InProgress
1759                    && self.same_base(self.candidate_pairs[index].local_index, local_index)
1760            })
1761        {
1762            // Not the answer to a first check: nothing is concluded from it.
1763            return false;
1764        }
1765        for &index in &failed {
1766            let p = self.candidate_pairs[index];
1767            debug!(
1768                "[{}]: {:?} on {}: the pair failed",
1769                self.get_name(),
1770                error,
1771                p
1772            );
1773            self.pending_binding_requests
1774                .retain(|r| !(r.local_index == p.local_index && r.remote_index == p.remote_index));
1775            self.fail_pair(index);
1776        }
1777        if !failed.is_empty() {
1778            self.maybe_nominate(now);
1779            self.request_connectivity_check();
1780        }
1781        !failed.is_empty()
1782    }
1783
1784    /// Something other than STUN arrived over TCP on `transport`, on no valid pair: what a
1785    /// driver that demultiplexes the connection itself (the peer connection does) calls
1786    /// instead of deciding on [`TransportError::NotStun`] on its own.
1787    ///
1788    /// RFC 6544 Section 7.1 concludes from "the response to the first connectivity check on
1789    /// the established TCP connection". Only on a connection this agent opened (its local
1790    /// candidate is active) are the peer's first bytes that response: the agent sends its
1791    /// check as soon as the connection is up, and the peer has nothing to send before it. On
1792    /// a connection the peer opened (a passive local candidate) the peer may send DTLS before
1793    /// it answers this agent's triggered check, so nothing is concluded there. Returns
1794    /// whether a pair failed; closing the connection is the caller's.
1795    pub fn handle_non_stun_before_validation(
1796        &mut self,
1797        now: Instant,
1798        transport: shared::TransportContext,
1799    ) -> bool {
1800        if transport.transport_protocol != shared::TransportProtocol::TCP {
1801            return false;
1802        }
1803        let opened_here = self
1804            .find_local_candidate(transport.local_addr, transport.transport_protocol)
1805            .is_some_and(|local| {
1806                self.local_candidates[local].tcp_type() == crate::tcp_type::TcpType::Active
1807            });
1808        opened_here && self.handle_transport_error(now, transport, TransportError::NotStun)
1809    }
1810
1811    /// Two lite agents (RFC 8445 Sections 6.2 and 8.2): "the agent pairs local candidates
1812    /// with remote candidates that are of the same data stream and have the same component,
1813    /// transport protocol, and IP address family. [...] if there is only one candidate pair,
1814    /// that pair is added to the valid list. If there is more than one pair, it is
1815    /// RECOMMENDED that an agent follow the procedures of RFC 6724 to select a pair and add it
1816    /// to the valid list." The pair chosen is the selected pair: there is no nomination
1817    /// between two agents that send no checks.
1818    ///
1819    /// With more than one pair "the controlling agent MUST send an updated candidate list":
1820    /// it raises [`Event::LiteCandidateUpdate`], once, with the pair it chose; the peer takes
1821    /// the update with [`Agent::replace_remote_candidates`].
1822    pub(crate) fn conclude_lite_to_lite(&mut self, now: Instant) {
1823        if self.selected_pair.is_some()
1824            || self.ufrag_pwd.remote_credentials.is_none()
1825            || matches!(
1826                self.connection_state,
1827                ConnectionState::Failed | ConnectionState::Closed
1828            )
1829        {
1830            return;
1831        }
1832        let Some(chosen) =
1833            (0..self.candidate_pairs.len()).max_by_key(|&index| self.lite_pair_preference(index))
1834        else {
1835            return;
1836        };
1837        let several = self.candidate_pairs.len() > 1;
1838        {
1839            let p = &mut self.candidate_pairs[chosen];
1840            p.state = CandidatePairState::Succeeded;
1841            p.valid = true;
1842            p.valid_pair = Some(chosen);
1843        }
1844        self.set_selected_pair(Some(now), Some(chosen));
1845        if several && self.is_controlling && !self.lite_update_raised {
1846            self.lite_update_raised = true;
1847            let p = self.candidate_pairs[chosen];
1848            self.event_outs.push_back(crate::agent::TaggedEvent {
1849                now,
1850                event: crate::agent::Event::LiteCandidateUpdate(
1851                    Box::new(self.local_candidates[p.local_index].clone()),
1852                    Box::new(self.remote_candidates[p.remote_index].clone()),
1853                ),
1854            });
1855        }
1856    }
1857
1858    /// How a pair ranks among the pairs of two lite agents, larger first: a pair whose local
1859    /// candidate an updated candidate exchange named (`pinned_local_addr`), then the destination
1860    /// address selection of RFC 6724 Section 6, as far as it applies to two transport
1861    /// addresses that are given: Rule 2, prefer matching scope (link-local with link-local,
1862    /// loopback with loopback, global with global); Rule 6, prefer higher precedence (the
1863    /// default policy table puts IPv6 above IPv4); Rule 9, the longest matching prefix
1864    /// between source and destination. What is left is decided by the pair priority, which
1865    /// both agents compute alike.
1866    fn lite_pair_preference(&self, index: usize) -> (bool, bool, bool, u32, u64) {
1867        use crate::agent::remote_policy::ip_scope;
1868
1869        let p = &self.candidate_pairs[index];
1870        // RFC 8839 Section 4.4.2.2: the local candidate an updated exchange named wins.
1871        let pinned = self.pinned_local_addr.is_some_and(|pinned| {
1872            let candidate = &self.local_candidates[p.local_index];
1873            candidate.addr() == pinned || candidate.base_addr() == pinned
1874        });
1875        let local = self.local_candidates[p.local_index].base_addr().ip();
1876        let remote = self.remote_candidates[p.remote_index].addr().ip();
1877        let matching_scope = ip_scope(local) == ip_scope(remote);
1878        let is_v6 = matches!(remote.to_canonical(), IpAddr::V6(_));
1879        let common_prefix = match (local.to_canonical(), remote.to_canonical()) {
1880            (IpAddr::V4(a), IpAddr::V4(b)) => (u32::from(a) ^ u32::from(b)).leading_zeros(),
1881            (IpAddr::V6(a), IpAddr::V6(b)) => (u128::from(a) ^ u128::from(b)).leading_zeros(),
1882            _ => 0,
1883        };
1884        (pinned, matching_scope, is_v6, common_prefix, p.priority())
1885    }
1886
1887    /// Controlling agent that has concluded: sends the nomination of its selected pair again
1888    /// (a check with USE-CANDIDATE, retransmitted like any check). Used when the peer has
1889    /// shown that it does not hold the nomination; no other pair is ever nominated.
1890    pub(crate) fn repeat_nomination(&mut self) {
1891        let Some(selected) = self.selected_pair else {
1892            return;
1893        };
1894        if !self.is_controlling || (self.lite && self.is_controlling) {
1895            return;
1896        }
1897        self.candidate_pairs[selected].nominate = true;
1898        self.enqueue_triggered(selected);
1899    }
1900
1901    /// Controlling agent, regular nomination (Section 8.1.1): once its best valid pair has
1902    /// waited long enough for its type, that pair is put on the triggered-check queue for a
1903    /// check with USE-CANDIDATE. One nomination is in flight at a time; when it fails the
1904    /// next valid pair is nominated.
1905    pub(crate) fn maybe_nominate(&mut self, now: Instant) {
1906        if !self.is_controlling || self.selected_pair.is_some() || self.nominated_pair.is_some() {
1907            return;
1908        }
1909        let Some(pair_index) = self.get_best_valid_candidate_pair() else {
1910            return;
1911        };
1912        let p = self.candidate_pairs[pair_index];
1913        // The wait is that of the candidates the agent chose to check: when the valid pair's
1914        // local candidate is the mapped address of the response, the candidate its check was
1915        // sent from.
1916        let checked_local = self
1917            .candidate_pairs
1918            .iter()
1919            .enumerate()
1920            .find(|(index, c)| *index != pair_index && c.valid_pair == Some(pair_index))
1921            .map_or(p.local_index, |(_, c)| c.local_index);
1922        if !self.is_nominatable(now, checked_local, true)
1923            || !self.is_nominatable(now, p.remote_index, false)
1924        {
1925            return;
1926        }
1927        if self.candidate_pair_proposals {
1928            // webrtc-extensions 7: propose the pair, once; the application decides.
1929            if self.nomination_proposal.is_some() || self.declined_nominations.contains(&pair_index)
1930            {
1931                return;
1932            }
1933            self.nomination_proposal = Some(pair_index);
1934            self.event_outs.push_back(crate::agent::TaggedEvent {
1935                now,
1936                event: crate::agent::Event::CandidatePairNominationProposed(
1937                    Box::new(self.local_candidates[p.local_index].clone()),
1938                    Box::new(self.remote_candidates[p.remote_index].clone()),
1939                ),
1940            });
1941            return;
1942        }
1943        trace!(
1944            "Nominatable pair found, nominating ({}, {})",
1945            self.local_candidates[p.local_index], self.remote_candidates[p.remote_index],
1946        );
1947        self.candidate_pairs[pair_index].nominate = true;
1948        self.nominated_pair = Some(pair_index);
1949        self.nomination_started = Some(now);
1950        self.enqueue_triggered(pair_index);
1951    }
1952
1953    /// Whether the controlling agent's nomination of `pair_index` may still be answered: the
1954    /// peer has been heard from on the pair's remote candidate (an authenticated request or
1955    /// response) or the nomination started, less than the consent expiry ago (30 seconds,
1956    /// the time RFC 7675 Section 5.1 gives a peer to answer before the path is given up).
1957    pub(crate) fn nomination_is_alive(&self, now: Instant, pair_index: usize) -> bool {
1958        let p = &self.candidate_pairs[pair_index];
1959        let heard = self
1960            .remote_candidates
1961            .get(p.remote_index)
1962            .and_then(|r| r.last_authenticated);
1963        let started = self
1964            .nomination_started
1965            .filter(|_| self.nominated_pair == Some(pair_index));
1966        heard
1967            .into_iter()
1968            .chain(started)
1969            .max()
1970            .is_some_and(|at| now.saturating_duration_since(at) < self.consent_expiry())
1971    }
1972
1973    /// Controlling agent, checking, with `FailedNomination::Retry`: a nomination the peer has
1974    /// not been heard from on for the consent expiry is given up. The pair fails (its
1975    /// transactions with it), and the next valid pair, if there is one, is nominated.
1976    ///
1977    /// With `FailedNomination::FailChecklist` (RFC 8445 Section 7.2.5.3.4) a nomination fails
1978    /// only as a request does (Section 7.2.5.2): at the end of its transaction (Section 14.3),
1979    /// by an error response or by a response from another address; not by this.
1980    pub(crate) fn expire_unanswered_nomination(&mut self, now: Instant) {
1981        let Some(nominated) = self.nominated_pair else {
1982            return;
1983        };
1984        if self.failed_nomination != FailedNomination::Retry
1985            || !self.is_controlling
1986            || self.selected_pair.is_some()
1987            || self.nomination_is_alive(now, nominated)
1988        {
1989            return;
1990        }
1991        warn!(
1992            "[{}]: nomination of {} is unanswered and the peer is not heard from: the pair failed",
1993            self.get_name(),
1994            self.candidate_pairs[nominated]
1995        );
1996        let p = self.candidate_pairs[nominated];
1997        self.pending_binding_requests
1998            .retain(|r| !(r.local_index == p.local_index && r.remote_index == p.remote_index));
1999        self.fail_pair(nominated);
2000        self.nomination_started = None;
2001        self.maybe_nominate(now);
2002    }
2003
2004    /// Whether something may still produce a selected pair: a pair Frozen, Waiting or In
2005    /// Progress, a triggered check queued, a valid pair the controlling agent nominates (or
2006    /// will), or a pair the peer has been heard from on within the consent expiry (the peer
2007    /// is checking it, and the controlled agent waits for its nomination). While this holds,
2008    /// the checklist has not failed (RFC 8445 Section 8.1.2) and the agent does not fail by
2009    /// its timer.
2010    pub(crate) fn checks_in_progress(&self, now: Instant) -> bool {
2011        if !self.triggered_queue.is_empty() {
2012            return true;
2013        }
2014        let expiry = self.consent_expiry();
2015        self.candidate_pairs.iter().any(|p| match p.state {
2016            CandidatePairState::Frozen
2017            | CandidatePairState::Waiting
2018            | CandidatePairState::InProgress => true,
2019            CandidatePairState::Failed | CandidatePairState::Unspecified => false,
2020            CandidatePairState::Succeeded => {
2021                (self.is_controlling && p.valid)
2022                    || self
2023                        .remote_candidates
2024                        .get(p.remote_index)
2025                        .and_then(|r| r.last_authenticated)
2026                        .is_some_and(|at| now.saturating_duration_since(at) < expiry)
2027            }
2028        })
2029    }
2030
2031    /// Section 8.1.2, once a pair is nominated: the other pairs leave the triggered-check
2032    /// queue and their In-Progress transactions are cancelled; no ordinary check is started
2033    /// from now on (the checklist is Completed). The pairs stay in the list, for statistics
2034    /// and because the peer may still nominate another one: a request on one of them is
2035    /// answered and triggers a check as before.
2036    pub(crate) fn conclude(&mut self) {
2037        let Some(selected) = self.selected_pair else {
2038            return;
2039        };
2040        let mut cancel: Vec<(usize, usize)> = vec![];
2041        for (index, p) in self.candidate_pairs.iter_mut().enumerate() {
2042            // (A pair the peer nominated keeps its place in the queue too.)
2043            p.triggered = p.triggered && p.nomination_pending;
2044            p.nominate = false;
2045            // A pair the peer nominated before its check finished keeps its transaction: its
2046            // answer decides whether the peer's (later) nomination is followed.
2047            if index != selected
2048                && p.state == CandidatePairState::InProgress
2049                && !p.nomination_pending
2050            {
2051                p.state = CandidatePairState::Waiting;
2052                cancel.push((p.local_index, p.remote_index));
2053            }
2054        }
2055        for (local_index, remote_index) in cancel {
2056            self.cancel_transactions(local_index, remote_index);
2057        }
2058        let pairs = &self.candidate_pairs;
2059        self.triggered_queue.retain(|(local_index, remote_index)| {
2060            pairs.iter().any(|p| {
2061                p.triggered && p.local_index == *local_index && p.remote_index == *remote_index
2062            })
2063        });
2064        // The state is looked at again at once: `Completed` when both sides are done
2065        // gathering.
2066        self.request_connectivity_check();
2067    }
2068
2069    /// Sections 7.2.5.4 and 8.1.2 with RFC 8838 Section 8: the checklist is Failed when every
2070    /// pair has failed and none is valid, but only once no pair can be added any more: local
2071    /// gathering is complete and the peer has signalled end-of-candidates. Until then a
2072    /// checking agent fails by its timeout only.
2073    pub(crate) fn update_checklist_failure(&mut self, now: Instant) {
2074        if self.connection_state != ConnectionState::Checking
2075            || self.selected_pair.is_some()
2076            || !self.remote_end_of_candidates
2077            || !self.local_gathering_complete
2078            || !self.mdns_queries.is_empty()
2079            || !self.early_requests.is_empty()
2080            || !self.triggered_queue.is_empty()
2081        {
2082            return;
2083        }
2084        if self
2085            .candidate_pairs
2086            .iter()
2087            .all(|p| p.state == CandidatePairState::Failed)
2088        {
2089            debug!(
2090                "[{}]: every pair failed and no candidate is to come: the checklist failed",
2091                self.get_name()
2092            );
2093            self.update_connection_state(Some(now), ConnectionState::Failed);
2094        }
2095    }
2096
2097    /// A lite agent's keepalive (RFC 8445 Section 11): it sends no Binding requests, so when
2098    /// it has sent nothing on the selected pair for Tr (15 seconds) it sends a Binding
2099    /// indication: no authentication, FINGERPRINT only.
2100    pub(crate) fn lite_keepalive(&mut self, now: Instant) {
2101        let Some(pair_index) = self.selected_pair else {
2102            return;
2103        };
2104        if self.keepalive_interval == Duration::ZERO {
2105            return;
2106        }
2107        let p = self.candidate_pairs[pair_index];
2108        let last_sent = self.local_candidates[p.local_index]
2109            .last_sent()
2110            .unwrap_or(self.start_time);
2111        if now.saturating_duration_since(last_sent) < KEEPALIVE_TR {
2112            return;
2113        }
2114        let mut msg = Message::new();
2115        if let Err(err) = msg.build(&[
2116            Box::new(MessageType::new(METHOD_BINDING, CLASS_INDICATION)),
2117            Box::new(TransactionId::new()),
2118            Box::new(FINGERPRINT),
2119        ]) {
2120            error!("{}", err);
2121            return;
2122        }
2123        self.send_stun(now, &msg, p.local_index, p.remote_index);
2124    }
2125
2126    /// Called when the session (re)starts.
2127    pub(crate) fn start(&mut self, now: Instant) {
2128        self.nominated_pair = None;
2129        self.start_time = now;
2130        self.next_check_at = now;
2131    }
2132}