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