1use 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#[derive(Debug, Clone, Copy, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum TransportError {
44 IcmpHardError,
47 ConnectionFailed,
49 NotStun,
51}
52
53pub(crate) const MAX_TCP_CONNECTION_ATTEMPTS_PER_ADDRESS: usize = 5;
56
57#[derive(Debug, Clone, Copy, PartialEq, Eq)]
60#[non_exhaustive]
61pub enum ChecklistState {
62 Running,
64 Completed,
66 Failed,
68}
69
70impl Agent {
71 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 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 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 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 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 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 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 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 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 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 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 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 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 fn is_learned_local(&self, local_index: usize) -> bool {
313 self.local_candidates[local_index].candidate_type() == CandidateType::PeerReflexive
314 }
315
316 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 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 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 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 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 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 fn ordinary_checks_allowed(&self) -> bool {
471 self.selected_pair.is_none()
472 && !(self.lite && (!self.is_controlling || self.remote_lite))
475 && !matches!(
476 self.connection_state,
477 ConnectionState::Failed | ConnectionState::Closed
478 )
479 }
480
481 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 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 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 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 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 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 if let Some(group) = &self.pacing_group
587 && let Err(at) = group.take(now)
588 {
589 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 let use_candidate = self.is_controlling && p.nominate;
609 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 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 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 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 let priority = local.peer_reflexive_priority();
669 let is_tcp = local.network_type().is_tcp();
670
671 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 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 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 setters.push(Box::new(FINGERPRINT));
705 msg.build(&setters)
706 };
707 if let Err(err) = built {
708 error!("{}", err);
710 self.fail_pair(pair_index);
711 return;
712 }
713 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 (false, now + self.consent_wait(now, pair_index))
735 } else if is_tcp {
736 (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 self.candidate_pairs[pair_index].on_request_sent();
771 self.send_stun(now, &msg, pair.local_index, pair.remote_index);
772 }
773
774 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 if self.candidate_pairs[checked].removed {
1137 return;
1138 }
1139
1140 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 if self.connection_state == ConnectionState::Disconnected {
1151 self.request_connectivity_check();
1152 }
1153 }
1154
1155 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 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 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 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 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 if request.is_use_candidate && self.is_controlling {
1225 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 } else if std::mem::take(&mut self.candidate_pairs[checked].nomination_pending) {
1237 self.accept_nomination(now, valid);
1242 } else {
1243 self.maybe_nominate(now);
1244 }
1245 }
1246
1247 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 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 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 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 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 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 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 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 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 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 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 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 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 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 self.candidate_pairs[pair_index].nomination_pending = true;
1598 }
1599 self.trigger_check(pair_index);
1601 }
1602
1603 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 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 p.triggered = p.triggered && p.nomination_pending;
2067 p.nominate = false;
2068 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 self.request_connectivity_check();
2090 }
2091
2092 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 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 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}