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