1use crate::agent::agent_config::*;
20use crate::agent::{Agent, BindingRequest, Event, TaggedEvent};
21use bytes::BytesMut;
22use crc::{CRC_32_ISCSI, Crc};
23use log::{debug, error, trace, warn};
24use std::net::{IpAddr, SocketAddr};
25use std::time::{Duration, Instant};
26use stun::attributes::*;
27use stun::fingerprint::*;
28use stun::integrity::*;
29use stun::message::*;
30use stun::textattrs::*;
31use stun::xoraddr::XorMappedAddress;
32
33use crate::attributes::{control::*, nomination::nomination_of, priority::*, use_candidate::*};
34use crate::candidate::candidate_peer_reflexive::CandidatePeerReflexiveConfig;
35use crate::candidate::{candidate_pair::*, *};
36use crate::state::ConnectionState;
37
38#[derive(Debug, Clone, Copy, PartialEq, Eq)]
41#[non_exhaustive]
42pub enum TransportError {
43 IcmpHardError,
46 ConnectionFailed,
48 NotStun,
50}
51
52pub(crate) const MAX_TCP_CONNECTION_ATTEMPTS_PER_ADDRESS: usize = 5;
55
56#[derive(Debug, Clone, Copy, PartialEq, Eq)]
59#[non_exhaustive]
60pub enum ChecklistState {
61 Running,
63 Completed,
65 Failed,
67}
68
69impl Agent {
70 fn is_nominatable(&self, now: Instant, index: usize, is_local: bool) -> bool {
75 let c = if is_local {
76 &self.local_candidates[index]
77 } else {
78 &self.remote_candidates[index]
79 };
80 let min_wait = match c.candidate_type() {
81 CandidateType::Host => self.host_acceptance_min_wait,
82 CandidateType::ServerReflexive => self.srflx_acceptance_min_wait,
83 CandidateType::PeerReflexive => self.prflx_acceptance_min_wait,
84 CandidateType::Relay => self.relay_acceptance_min_wait,
85 CandidateType::Unspecified => {
86 error!(
87 "is_nominatable invalid candidate type {}",
88 c.candidate_type()
89 );
90 return false;
91 }
92 };
93 if self.remote_end_of_candidates && self.local_gathering_complete {
97 return true;
98 }
99 now.saturating_duration_since(self.start_time) > min_wait
100 }
101
102 pub fn checklist_state(&self) -> ChecklistState {
109 if self.connection_state == ConnectionState::Failed {
110 ChecklistState::Failed
111 } else if self.selected_pair.is_some() {
112 ChecklistState::Completed
113 } else {
114 ChecklistState::Running
115 }
116 }
117
118 pub(crate) fn same_base(&self, a: usize, b: usize) -> bool {
124 let (a, b) = (&self.local_candidates[a], &self.local_candidates[b]);
125 a.base_addr() == b.base_addr()
126 && a.network_type() == b.network_type()
127 && a.tcp_type() == b.tcp_type()
128 }
129
130 pub(crate) fn pair_foundation(&self, local_index: usize, remote_index: usize) -> u32 {
131 let mut buf = self.local_candidates[local_index].foundation().into_bytes();
132 buf.push(b':');
133 buf.extend_from_slice(self.remote_candidates[remote_index].foundation().as_bytes());
134 Crc::<u32>::new(&CRC_32_ISCSI).checksum(&buf)
135 }
136
137 pub(crate) fn add_pair(&mut self, local_index: usize, remote_index: usize) {
140 let local = &self.local_candidates[local_index];
141 let remote = &self.remote_candidates[remote_index];
142 let local_base = local.base_addr();
146 let remote_addr = remote.addr();
147 if !self.remote_policy.allows_pair(local_base, remote_addr) {
148 debug!(
149 "[{}]: not pairing local {} with remote {}: destination not allowed from this local candidate",
150 self.get_name(),
151 local_base,
152 remote_addr
153 );
154 return;
155 }
156 if local.component() != remote.component() {
159 debug!(
160 "[{}]: not pairing local {} with remote {}: components {} and {}",
161 self.get_name(),
162 local,
163 remote,
164 local.component(),
165 remote.component()
166 );
167 return;
168 }
169
170 if local.candidate_type() == CandidateType::Relay && remote.address().ends_with(".local") {
174 debug!(
175 "[{}]: not pairing relay candidate {} with mDNS candidate {}",
176 self.get_name(),
177 local,
178 remote.address()
179 );
180 return;
181 }
182
183 let mut pair = CandidatePair::new(
184 local_index,
185 remote_index,
186 local.priority(),
187 remote.priority(),
188 self.is_controlling,
189 );
190 pair.foundation = self.pair_foundation(local_index, remote_index);
191
192 let redundant = self.candidate_pairs.iter().position(|p| {
196 p.remote_index == remote_index && self.same_base(p.local_index, local_index)
197 });
198 if let Some(existing) = redundant {
199 let e = self.candidate_pairs[existing];
200 let unchecked = matches!(
201 e.state,
202 CandidatePairState::Waiting | CandidatePairState::Frozen
203 ) && !e.triggered
204 && !e.nomination_pending;
205 if unchecked && pair.priority() > e.priority() {
206 pair.state = self.initial_pair_state(&pair, Some(existing));
207 self.announce_pair(existing, false);
208 self.candidate_pairs[existing] = pair;
209 self.announce_pair(existing, true);
210 }
211 return;
212 }
213
214 let slot = if self.checklist_len() < self.max_candidate_pairs {
216 None
217 } else {
218 match self.pair_to_discard(pair.priority()) {
219 Some(slot) => Some(slot),
220 None => {
221 debug!(
222 "[{}]: checklist full ({} pairs): dropping pair {}",
223 self.get_name(),
224 self.max_candidate_pairs,
225 pair
226 );
227 return;
228 }
229 }
230 };
231 pair.state = self.initial_pair_state(&pair, slot);
232 let index = match slot {
233 Some(slot) => {
234 self.announce_pair(slot, false);
235 self.candidate_pairs[slot] = pair;
236 slot
237 }
238 None => {
239 self.candidate_pairs.push(pair);
240 self.candidate_pairs.len() - 1
241 }
242 };
243 self.announce_pair(index, true);
244 }
245
246 pub(crate) fn announce_pair(&mut self, index: usize, added: bool) {
249 let p = self.candidate_pairs[index];
250 if p.removed {
251 return;
252 }
253 let (Some(local), Some(remote)) = (
254 self.local_candidates.get(p.local_index),
255 self.remote_candidates.get(p.remote_index),
256 ) else {
257 return;
258 };
259 let (local, remote) = (Box::new(local.clone()), Box::new(remote.clone()));
260 self.event_outs.push_back(TaggedEvent {
261 now: self.clock,
262 event: if added {
263 Event::CandidatePairAdded(local, remote)
264 } else {
265 Event::CandidatePairRemoved(local, remote)
266 },
267 });
268 }
269
270 pub(crate) fn add_triggered_pair(&mut self, local_index: usize, remote_index: usize) {
275 let local = &self.local_candidates[local_index];
276 let remote = &self.remote_candidates[remote_index];
277 if !self
278 .remote_policy
279 .allows_pair(local.base_addr(), remote.addr())
280 || local.component() != remote.component()
281 || self.checklist_len() < self.max_candidate_pairs
282 {
283 return;
284 }
285 let Some(slot) = self.pair_to_discard(u64::MAX) else {
286 return;
287 };
288 let mut pair = CandidatePair::new(
289 local_index,
290 remote_index,
291 local.priority(),
292 remote.priority(),
293 self.is_controlling,
294 );
295 pair.foundation = self.pair_foundation(local_index, remote_index);
296 self.announce_pair(slot, false);
297 self.candidate_pairs[slot] = pair;
298 self.announce_pair(slot, true);
299 }
300
301 fn checklist_len(&self) -> usize {
304 self.candidate_pairs
305 .iter()
306 .filter(|p| !(p.valid && self.is_learned_local(p.local_index)))
307 .count()
308 }
309
310 fn is_learned_local(&self, local_index: usize) -> bool {
312 self.local_candidates[local_index].candidate_type() == CandidateType::PeerReflexive
313 }
314
315 fn pair_to_discard(&self, new_priority: u64) -> Option<usize> {
320 let lowest = |wanted: &dyn Fn(&CandidatePair) -> bool| {
321 self.candidate_pairs
322 .iter()
323 .enumerate()
324 .filter(|(i, p)| {
325 wanted(p)
326 && !p.triggered
327 && !p.nomination_pending
328 && Some(*i) != self.selected_pair
329 && Some(*i) != self.nominated_pair
330 })
331 .min_by_key(|(_, p)| p.priority())
332 .map(|(i, p)| (i, p.priority()))
333 };
334 if let Some((failed, _)) = lowest(&|p| p.state == CandidatePairState::Failed) {
335 return Some(failed);
336 }
337 match lowest(&|p| {
338 matches!(
339 p.state,
340 CandidatePairState::Waiting | CandidatePairState::Frozen
341 )
342 }) {
343 Some((index, priority)) if priority < new_priority => Some(index),
344 _ => None,
345 }
346 }
347
348 fn initial_pair_state(
353 &self,
354 pair: &CandidatePair,
355 replacing: Option<usize>,
356 ) -> CandidatePairState {
357 let mut topmost = true;
358 for (index, p) in self.candidate_pairs.iter().enumerate() {
359 if Some(index) == replacing || p.foundation != pair.foundation {
360 continue;
361 }
362 if p.state == CandidatePairState::Succeeded {
363 return CandidatePairState::Waiting;
364 }
365 if p.priority() >= pair.priority() {
366 topmost = false;
367 }
368 }
369 if topmost {
370 CandidatePairState::Waiting
371 } else {
372 CandidatePairState::Frozen
373 }
374 }
375
376 pub(crate) fn compute_initial_pair_states(&mut self) {
381 let untouched = self.candidate_pairs.iter().all(|p| {
382 matches!(
383 p.state,
384 CandidatePairState::Waiting | CandidatePairState::Frozen
385 ) && !p.triggered
386 });
387 if !untouched {
388 return;
389 }
390 for index in 0..self.candidate_pairs.len() {
391 let pair = self.candidate_pairs[index];
392 let best = !self.candidate_pairs.iter().enumerate().any(|(other, p)| {
393 p.foundation == pair.foundation
394 && (p.priority() > pair.priority()
395 || (p.priority() == pair.priority() && other < index))
396 });
397 self.candidate_pairs[index].state = if best {
398 CandidatePairState::Waiting
399 } else {
400 CandidatePairState::Frozen
401 };
402 }
403 }
404
405 pub(crate) fn find_pair_exact(&self, local_index: usize, remote_index: usize) -> Option<usize> {
406 self.candidate_pairs
407 .iter()
408 .position(|p| p.local_index == local_index && p.remote_index == remote_index)
409 }
410
411 pub(crate) fn find_pair(&self, local_index: usize, remote_index: usize) -> Option<usize> {
414 self.find_pair_exact(local_index, remote_index).or_else(|| {
415 self.candidate_pairs.iter().position(|p| {
416 p.remote_index == remote_index
417 && !(p.valid && self.is_learned_local(p.local_index))
418 && self.same_base(p.local_index, local_index)
419 })
420 })
421 }
422
423 pub(crate) fn enqueue_triggered(&mut self, pair_index: usize) {
429 let p = &mut self.candidate_pairs[pair_index];
430 if p.removed {
431 return;
432 }
433 if !p.triggered {
434 p.triggered = true;
435 self.triggered_queue
436 .push_back((p.local_index, p.remote_index));
437 }
438 self.request_connectivity_check();
439 }
440
441 fn pop_triggered(&mut self) -> Option<usize> {
442 while let Some((local_index, remote_index)) = self.triggered_queue.pop_front() {
443 if let Some(pair_index) = self.find_pair_exact(local_index, remote_index)
444 && self.candidate_pairs[pair_index].triggered
445 {
446 return Some(pair_index);
447 }
448 }
449 None
450 }
451
452 pub(crate) fn trigger_check(&mut self, pair_index: usize) {
456 let p = self.candidate_pairs[pair_index];
457 if p.removed {
458 return;
459 }
460 if p.state == CandidatePairState::InProgress {
461 self.cancel_transactions(p.local_index, p.remote_index);
462 }
463 self.candidate_pairs[pair_index].state = CandidatePairState::Waiting;
464 self.enqueue_triggered(pair_index);
465 }
466
467 fn ordinary_checks_allowed(&self) -> bool {
470 self.selected_pair.is_none()
471 && !(self.lite && (!self.is_controlling || self.remote_lite))
474 && !matches!(
475 self.connection_state,
476 ConnectionState::Failed | ConnectionState::Closed
477 )
478 }
479
480 fn next_waiting(&self) -> Option<usize> {
482 let mut best: Option<usize> = None;
483 for (index, p) in self.candidate_pairs.iter().enumerate() {
484 if p.state != CandidatePairState::Waiting || p.triggered {
485 continue;
486 }
487 if self.tcp_attempts_exhausted(p) {
488 continue;
489 }
490 if best.is_none_or(|b| self.candidate_pairs[b].priority() < p.priority()) {
491 best = Some(index);
492 }
493 }
494 best
495 }
496
497 fn opens_tcp_connection(&self, p: &CandidatePair) -> bool {
500 let local = &self.local_candidates[p.local_index];
501 local.network_type().is_tcp() && local.tcp_type() == crate::tcp_type::TcpType::Active
502 }
503
504 fn tcp_attempts_exhausted(&self, p: &CandidatePair) -> bool {
509 if !self.opens_tcp_connection(p) {
510 return false;
511 }
512 let ip = self.remote_candidates[p.remote_index].addr().ip();
513 self.candidate_pairs
514 .iter()
515 .filter(|q| {
516 q.state == CandidatePairState::InProgress
517 && self.opens_tcp_connection(q)
518 && self.remote_candidates[q.remote_index].addr().ip() == ip
519 })
520 .count()
521 >= MAX_TCP_CONNECTION_ATTEMPTS_PER_ADDRESS
522 }
523
524 fn pairs_to_unfreeze(&self) -> Vec<usize> {
527 let mut out: Vec<usize> = vec![];
528 for (index, p) in self.candidate_pairs.iter().enumerate() {
529 if p.state != CandidatePairState::Frozen {
530 continue;
531 }
532 let busy = self.candidate_pairs.iter().any(|q| {
533 q.foundation == p.foundation
534 && matches!(
535 q.state,
536 CandidatePairState::Waiting | CandidatePairState::InProgress
537 )
538 });
539 if busy {
540 continue;
541 }
542 match out
543 .iter()
544 .position(|&o| self.candidate_pairs[o].foundation == p.foundation)
545 {
546 Some(slot) if self.candidate_pairs[out[slot]].priority() < p.priority() => {
547 out[slot] = index
548 }
549 Some(_) => {}
550 None => out.push(index),
551 }
552 }
553 out
554 }
555
556 pub(crate) fn has_check_to_start(&self) -> bool {
558 if !self.triggered_queue.is_empty() {
559 return true;
560 }
561 self.ordinary_checks_allowed()
562 && (self.next_waiting().is_some() || !self.pairs_to_unfreeze().is_empty())
563 }
564
565 pub(crate) fn run_ta(&mut self, now: Instant) {
568 if now < self.next_check_at || self.ufrag_pwd.remote_credentials.is_none() {
569 return;
570 }
571 let pair_index = match self.pop_triggered() {
572 Some(pair_index) => Some(pair_index),
573 None if self.ordinary_checks_allowed() => {
574 if self.next_waiting().is_none() {
575 for index in self.pairs_to_unfreeze() {
576 self.candidate_pairs[index].state = CandidatePairState::Waiting;
577 }
578 }
579 self.next_waiting()
580 }
581 None => None,
582 };
583 if let Some(pair_index) = pair_index {
584 if let Some(group) = &self.pacing_group
586 && let Err(at) = group.take(now)
587 {
588 let p = self.candidate_pairs[pair_index];
590 if p.triggered {
591 self.triggered_queue
592 .push_front((p.local_index, p.remote_index));
593 }
594 self.next_check_at = at;
595 return;
596 }
597 self.start_check(now, pair_index);
598 self.next_check_at = now + self.ta;
599 }
600 }
601
602 fn start_check(&mut self, now: Instant, pair_index: usize) {
603 let p = &mut self.candidate_pairs[pair_index];
604 p.triggered = false;
605 let use_candidate = self.is_controlling && p.nominate;
608 if p.state != CandidatePairState::Succeeded {
610 p.state = CandidatePairState::InProgress;
611 }
612 trace!(
613 "[{}]: check on {} (nominating: {})",
614 self.get_name(),
615 self.candidate_pairs[pair_index],
616 use_candidate
617 );
618 self.send_check(now, pair_index, use_candidate, false);
619 }
620
621 pub(crate) fn check_rto(&self) -> Duration {
628 let active = self
629 .candidate_pairs
630 .iter()
631 .filter(|p| {
632 matches!(
633 p.state,
634 CandidatePairState::Waiting | CandidatePairState::InProgress
635 )
636 })
637 .count();
638 (self.ta * u32::try_from(active).unwrap_or(u32::MAX)).max(MIN_RTO)
639 }
640
641 fn consent_wait(&self, pair: &CandidatePair) -> Duration {
644 (pair.current_round_trip_time * 4).clamp(MIN_RTO, MAX_BINDING_REQUEST_TIMEOUT)
645 }
646
647 pub(crate) fn send_check(
651 &mut self,
652 now: Instant,
653 pair_index: usize,
654 use_candidate: bool,
655 consent: bool,
656 ) {
657 let Some(remote_credentials) = &self.ufrag_pwd.remote_credentials else {
658 error!("ufrag_pwd.remote_credentials is none");
659 return;
660 };
661 let pair = self.candidate_pairs[pair_index];
662 let local = &self.local_candidates[pair.local_index];
663 let priority = local.peer_reflexive_priority();
666 let is_tcp = local.network_type().is_tcp();
667
668 let username = remote_credentials.ufrag.clone()
671 + ":"
672 + self.ufrag_pwd.local_credentials.ufrag.as_str();
673 let mut msg = Message::new();
674 let built = {
675 let mut setters: Vec<Box<dyn Setter + '_>> = vec![
676 Box::new(BINDING_REQUEST),
677 Box::new(TransactionId::new()),
678 Box::new(Username::new(ATTR_USERNAME, username)),
679 ];
680 if use_candidate {
681 setters.push(Box::<UseCandidateAttr>::default());
682 }
683 if self.is_controlling {
685 setters.push(Box::new(AttrControlling(self.tie_breaker)));
686 } else {
687 setters.push(Box::new(AttrControlled(self.tie_breaker)));
688 }
689 setters.push(Box::new(PriorityAttr(priority)));
690 if let Some(software) = &self.software {
692 setters.push(Box::new(Software::new(ATTR_SOFTWARE, software.clone())));
693 }
694 setters.push(Box::new(
695 MessageIntegrity::new_short_term_integrity_with_provider(
696 remote_credentials.pwd.clone(),
697 self.crypto_provider.crypto(),
698 ),
699 ));
700 setters.push(Box::new(FINGERPRINT));
702 msg.build(&setters)
703 };
704 if let Err(err) = built {
705 error!("{}", err);
707 self.fail_pair(pair_index);
708 return;
709 }
710 if !is_tcp {
714 let destination = self.remote_candidates[pair.remote_index].addr();
715 if msg.raw.len() > self.max_udp_stun_size(destination) {
716 warn!(
717 "[{}]: a check of {} bytes on {} exceeds the path MTU: the pair failed",
718 self.get_name(),
719 msg.raw.len(),
720 pair
721 );
722 self.fail_pair(pair_index);
723 return;
724 }
725 }
726
727 let rto = self.check_rto();
728 let (retransmit, next_event) = if consent {
729 (false, now + self.consent_wait(&pair))
730 } else if is_tcp {
731 (false, now + STUN_TI)
733 } else if self.max_binding_requests <= 1 {
734 (false, now + rto * STUN_RM)
735 } else {
736 (true, now + rto)
737 };
738 trace!(
739 "[{}]: ping STUN from {} to {}",
740 self.get_name(),
741 self.local_candidates[pair.local_index],
742 self.remote_candidates[pair.remote_index],
743 );
744 self.track_transaction(BindingRequest {
745 timestamp: now,
746 transaction_id: msg.transaction_id,
747 destination: self.remote_candidates[pair.remote_index].addr(),
748 is_use_candidate: use_candidate,
749 local_index: pair.local_index,
750 remote_index: pair.remote_index,
751 sent_as_controlling: self.is_controlling,
752 raw: BytesMut::from(&msg.raw[..]),
753 rto,
754 interval: rto,
755 transmissions: 1,
756 next_event,
757 retransmit,
758 cancelled: false,
759 consent,
760 priority,
761 unauthentic_response: false,
762 });
763
764 self.candidate_pairs[pair_index].on_request_sent();
766 self.send_stun(now, &msg, pair.local_index, pair.remote_index);
767 }
768
769 pub(crate) fn track_transaction(&mut self, transaction: BindingRequest) {
773 self.pending_binding_requests.push(transaction);
774 self.trim_passive_transactions();
775 }
776
777 fn trim_passive_transactions(&mut self) {
778 let passive = |r: &BindingRequest| r.consent || r.cancelled;
779 let mut excess = self
780 .pending_binding_requests
781 .iter()
782 .filter(|r| passive(r))
783 .count()
784 .saturating_sub(MAX_PENDING_BINDING_REQUESTS);
785 if excess > 0 {
786 self.pending_binding_requests.retain(|r| {
787 if excess > 0 && passive(r) {
788 excess -= 1;
789 false
790 } else {
791 true
792 }
793 });
794 }
795 }
796
797 pub(crate) fn cancel_pair_checks(&mut self, local_index: usize, remote_index: usize) {
803 self.cancel_transactions(local_index, remote_index);
804 }
805
806 fn cancel_transactions(&mut self, local_index: usize, remote_index: usize) {
807 let rc = u32::from(self.max_binding_requests.clamp(1, 16));
811 let duration = |rto: Duration| rto * ((1u32 << (rc - 1)) - 1 + STUN_RM);
812 for r in &mut self.pending_binding_requests {
813 if r.local_index == local_index
814 && r.remote_index == remote_index
815 && !r.consent
816 && !r.is_use_candidate
817 {
818 r.cancelled = true;
819 r.next_event = r.next_event.max(r.timestamp + duration(r.rto));
820 }
821 }
822 self.trim_passive_transactions();
823 }
824
825 pub(crate) fn run_transactions(&mut self, now: Instant) {
830 let rc = self.max_binding_requests.max(1);
831 let mut resend: Vec<(BytesMut, usize, SocketAddr)> = vec![];
832 let mut timed_out: Vec<BindingRequest> = vec![];
833 let mut index = 0;
834 while index < self.pending_binding_requests.len() {
835 let r = &mut self.pending_binding_requests[index];
836 if r.next_event > now {
837 index += 1;
838 continue;
839 }
840 if r.retransmit && !r.cancelled && r.transmissions < rc {
841 r.transmissions += 1;
842 r.interval *= 2;
843 r.next_event = now
844 + if r.transmissions >= rc {
845 r.rto * STUN_RM
846 } else {
847 r.interval
848 };
849 resend.push((r.raw.clone(), r.local_index, r.destination));
850 index += 1;
851 } else {
852 timed_out.push(self.pending_binding_requests.remove(index));
853 }
854 }
855
856 for (raw, local_index, destination) in resend {
857 if local_index < self.local_candidates.len() {
858 self.send_raw_stun(now, raw, local_index, destination);
859 }
860 }
861
862 let mut failed = false;
863 for r in timed_out {
864 if r.unauthentic_response && !r.cancelled {
865 self.signal_integrity_violation(&r);
866 }
867 if r.cancelled || r.consent {
868 continue;
869 }
870 let Some(pair_index) = self.find_pair_exact(r.local_index, r.remote_index) else {
871 continue;
872 };
873 let pair = self.candidate_pairs[pair_index];
874 let nomination = self.is_open_nomination(&r, pair_index);
880 if self.failed_nomination == FailedNomination::FailChecklist
881 && (nomination || self.is_followed_nomination(&r, pair_index))
882 {
883 self.fail_nomination(now, pair_index, "no response");
884 return;
885 }
886 if nomination && self.nomination_is_alive(now, pair_index) {
887 debug!(
888 "[{}]: no response to the nomination of {} after {} requests: nominating it again",
889 self.get_name(),
890 pair,
891 r.transmissions
892 );
893 self.candidate_pairs[pair_index].nominate = true;
894 self.enqueue_triggered(pair_index);
895 continue;
896 }
897 if pair.state == CandidatePairState::InProgress || r.is_use_candidate {
900 warn!(
901 "[{}]: no response to {} requests on {}{}: the pair failed",
902 self.get_name(),
903 r.transmissions,
904 self.candidate_pairs[pair_index],
905 if r.is_use_candidate {
906 " (nomination)"
907 } else {
908 ""
909 }
910 );
911 self.fail_pair(pair_index);
912 failed = true;
913 }
914 }
915 if failed {
916 self.maybe_nominate(now);
917 }
918 }
919
920 pub(crate) fn note_unauthentic_response(&mut self, id: TransactionId) {
928 let clock = self.clock;
929 let tcp = |local_index: usize, candidates: &[Candidate]| {
930 candidates
931 .get(local_index)
932 .is_some_and(|c| c.network_type().is_tcp())
933 };
934 if let Some(r) = self
935 .pending_binding_requests
936 .iter_mut()
937 .find(|r| r.transaction_id == id)
938 {
939 r.unauthentic_response = true;
940 if tcp(r.local_index, &self.local_candidates) {
941 r.retransmit = false;
942 r.next_event = r.next_event.min(clock);
943 }
944 }
945 }
946
947 fn signal_integrity_violation(&mut self, r: &BindingRequest) {
951 let (Some(local), Some(remote)) = (
952 self.local_candidates.get(r.local_index),
953 self.remote_candidates.get(r.remote_index),
954 ) else {
955 return;
956 };
957 warn!(
958 "[{}]: every response to the request on {} -> {} failed its integrity check: integrity violation",
959 self.get_name(),
960 local,
961 remote
962 );
963 let event = Event::IntegrityViolation(Box::new(local.clone()), Box::new(remote.clone()));
964 self.event_outs.push_back(TaggedEvent {
965 now: self.clock,
966 event,
967 });
968 }
969
970 pub(crate) fn fail_pair(&mut self, pair_index: usize) {
973 if self.selected_pair == Some(pair_index) {
974 return;
975 }
976 let failed = |p: &mut CandidatePair| {
977 p.state = CandidatePairState::Failed;
978 p.valid = false;
979 p.valid_pair = None;
980 p.nominated = false;
981 p.nomination_pending = false;
982 p.nominate = false;
983 p.triggered = false;
984 };
985 failed(&mut self.candidate_pairs[pair_index]);
986 if self.nominated_pair == Some(pair_index) {
987 self.nominated_pair = None;
988 }
989 for index in 0..self.candidate_pairs.len() {
991 if self.candidate_pairs[index].valid_pair == Some(pair_index)
992 && self.selected_pair != Some(index)
993 {
994 failed(&mut self.candidate_pairs[index]);
995 }
996 }
997 }
998
999 fn is_open_nomination(&self, request: &BindingRequest, pair_index: usize) -> bool {
1002 let pair = &self.candidate_pairs[pair_index];
1003 request.is_use_candidate
1004 && request.sent_as_controlling
1005 && self.is_controlling
1006 && self.selected_pair.is_none()
1007 && pair.valid
1008 && pair.state == CandidatePairState::Succeeded
1009 }
1010
1011 fn is_followed_nomination(&self, request: &BindingRequest, pair_index: usize) -> bool {
1018 !request.sent_as_controlling
1019 && !self.is_controlling
1020 && !request.consent
1021 && self.selected_pair.is_none()
1022 && self.candidate_pairs[pair_index].nomination_pending
1023 }
1024
1025 fn fail_nomination(&mut self, now: Instant, pair_index: usize, why: &str) {
1029 warn!(
1030 "[{}]: {} to the nomination of {}: the pair and the checklist failed",
1031 self.get_name(),
1032 why,
1033 self.candidate_pairs[pair_index]
1034 );
1035 self.fail_pair(pair_index);
1036 self.nomination_started = None;
1037 self.update_connection_state(Some(now), ConnectionState::Failed);
1038 }
1039
1040 pub(crate) fn handle_inbound_binding_success(
1042 &mut self,
1043 _now: Instant,
1044 id: TransactionId,
1045 ) -> Option<BindingRequest> {
1046 let index = self
1047 .pending_binding_requests
1048 .iter()
1049 .position(|r| r.transaction_id == id)?;
1050 Some(self.pending_binding_requests.remove(index))
1051 }
1052
1053 pub(crate) fn handle_success_response(
1060 &mut self,
1061 now: Instant,
1062 m: &Message,
1063 local_index: usize,
1064 remote_addr: SocketAddr,
1065 ) {
1066 if !m.contains(ATTR_XORMAPPED_ADDRESS) {
1074 debug!(
1075 "[{}]: discard Binding success response from {} without XOR-MAPPED-ADDRESS",
1076 self.get_name(),
1077 remote_addr
1078 );
1079 return;
1080 }
1081
1082 let Some(request) = self.handle_inbound_binding_success(now, m.transaction_id) else {
1085 warn!(
1086 "[{}]: discard message from ({}), unknown TransactionID 0x{:?}",
1087 self.get_name(),
1088 remote_addr,
1089 m.transaction_id
1090 );
1091 return;
1092 };
1093 let checked = self.find_pair_exact(request.local_index, request.remote_index);
1094
1095 let symmetric = request.destination == remote_addr
1099 && request.local_index < self.local_candidates.len()
1100 && self.same_base(request.local_index, local_index);
1101 if !symmetric {
1102 debug!(
1103 "[{}]: response from {} to a request sent to {}: not symmetric",
1104 self.get_name(),
1105 remote_addr,
1106 request.destination
1107 );
1108 if let Some(pair_index) = checked
1109 && !request.consent
1110 {
1111 if self.failed_nomination == FailedNomination::FailChecklist
1112 && (self.is_open_nomination(&request, pair_index)
1113 || self.is_followed_nomination(&request, pair_index))
1114 {
1115 self.fail_nomination(now, pair_index, "a response from another address");
1116 return;
1117 }
1118 self.fail_pair(pair_index);
1119 self.maybe_nominate(now);
1120 }
1121 return;
1122 }
1123 let Some(checked) = checked else {
1124 return;
1125 };
1126 if self.candidate_pairs[checked].removed {
1128 return;
1129 }
1130
1131 if let Some(remote) = self.remote_candidates.get_mut(request.remote_index) {
1134 remote.last_consent = Some(now);
1135 }
1136 if self.selected_pair.is_some_and(|selected| {
1137 self.candidate_pairs[selected].remote_index == request.remote_index
1138 }) {
1139 self.consent_unanswered_since = None;
1140 if self.connection_state == ConnectionState::Disconnected {
1142 self.request_connectivity_check();
1143 }
1144 }
1145
1146 let rtt = now.saturating_duration_since(request.timestamp);
1149 if request.transmissions == 1 {
1150 self.candidate_pairs[checked].on_response_received(rtt);
1151 } else {
1152 self.candidate_pairs[checked].responses_received += 1;
1153 }
1154 if request.consent {
1155 return;
1156 }
1157
1158 trace!(
1159 "[{}]: inbound STUN (SuccessResponse) from {} to {}",
1160 self.get_name(),
1161 self.remote_candidates[request.remote_index],
1162 self.local_candidates[local_index]
1163 );
1164
1165 let valid_local = self.local_candidate_for_mapped_address(m, &request);
1168 let valid = if valid_local == request.local_index {
1169 checked
1170 } else {
1171 self.valid_pair_for(valid_local, request.remote_index)
1172 };
1173
1174 let remote_nomination = self.candidate_pairs[checked].remote_nomination;
1177 {
1178 let c = &mut self.candidate_pairs[checked];
1179 c.state = CandidatePairState::Succeeded;
1180 c.valid_pair = Some(valid);
1181 c.triggered = c.triggered && c.nominate;
1185 }
1186 {
1187 let v = &mut self.candidate_pairs[valid];
1188 v.state = CandidatePairState::Succeeded;
1189 v.valid = true;
1190 v.valid_pair = Some(valid);
1191 v.remote_nomination = v.remote_nomination.max(remote_nomination);
1192 }
1193 let foundation = self.candidate_pairs[checked].foundation;
1194 for p in &mut self.candidate_pairs {
1195 if p.state == CandidatePairState::Frozen && p.foundation == foundation {
1196 p.state = CandidatePairState::Waiting;
1197 }
1198 }
1199 self.cancel_transactions(request.local_index, request.remote_index);
1201
1202 trace!(
1203 "[{}]: valid pair {} from check on {}, use-candidate: {}, rtt: {:.3}ms",
1204 self.get_name(),
1205 self.candidate_pairs[valid],
1206 self.candidate_pairs[checked],
1207 request.is_use_candidate,
1208 rtt.as_millis()
1209 );
1210
1211 if request.is_use_candidate && self.is_controlling {
1213 self.candidate_pairs[valid].nominate = false;
1217 self.candidate_pairs[checked].nominate = false;
1218 if self.selected_pair.is_none() {
1219 self.set_selected_pair(Some(now), Some(valid));
1220 self.conclude();
1221 }
1222 } else if self.adopt_tcp_reconnection(now, valid) {
1223 } else if std::mem::take(&mut self.candidate_pairs[checked].nomination_pending) {
1225 self.accept_nomination(now, valid);
1230 } else {
1231 self.maybe_nominate(now);
1232 }
1233 }
1234
1235 fn adopt_tcp_reconnection(&mut self, now: Instant, valid: usize) -> bool {
1242 let Some(selected) = self.selected_pair else {
1243 return false;
1244 };
1245 if selected == valid {
1246 return false;
1247 }
1248 let (old, new) = (self.candidate_pairs[selected], self.candidate_pairs[valid]);
1249 let local = &self.local_candidates[new.local_index];
1250 let (old_remote, new_remote) = (
1251 &self.remote_candidates[old.remote_index],
1252 &self.remote_candidates[new.remote_index],
1253 );
1254 let reconnection = local.network_type().is_tcp()
1255 && local.tcp_type() == crate::tcp_type::TcpType::Passive
1256 && self.same_base(old.local_index, new.local_index)
1257 && new_remote.candidate_type() == CandidateType::PeerReflexive
1258 && new_remote.tcp_type() == crate::tcp_type::TcpType::Active
1259 && old_remote.tcp_type() == crate::tcp_type::TcpType::Active
1260 && old_remote.addr().ip() == new_remote.addr().ip();
1261 if !reconnection {
1262 return false;
1263 }
1264 debug!(
1265 "[{}]: the selected TCP pair was reconnected: {} replaces {}",
1266 self.get_name(),
1267 new,
1268 old
1269 );
1270 self.candidate_pairs[valid].remote_nomination = old.remote_nomination;
1271 self.candidate_pairs[valid].nomination_pending = false;
1272 self.candidate_pairs[selected].nominated = false;
1273 self.set_selected_pair(Some(now), Some(valid));
1274 self.conclude();
1275 true
1276 }
1277
1278 fn local_candidate_for_mapped_address(
1285 &mut self,
1286 m: &Message,
1287 request: &BindingRequest,
1288 ) -> usize {
1289 let sent_index = request.local_index;
1290 let mut mapped = XorMappedAddress::default();
1291 if mapped.get_from(m).is_err() {
1292 return sent_index;
1293 }
1294 let mapped = SocketAddr::new(mapped.ip, mapped.port);
1295 let has_address = |c: &Candidate| {
1296 c.addr() == mapped
1297 || (c.port() == mapped.port() && c.address().parse::<IpAddr>() == Ok(mapped.ip()))
1298 };
1299 let sent = &self.local_candidates[sent_index];
1300 if has_address(sent) {
1301 return sent_index;
1302 }
1303 if sent.network_type().is_tcp() && sent.base_addr().ip() == mapped.ip() {
1306 return sent_index;
1307 }
1308 let (base, network_type) = (sent.base_addr(), sent.network_type());
1309 if let Some(known) = self.local_candidates.iter().position(|c| {
1310 has_address(c) && c.network_type() == network_type && c.base_addr() == base
1311 }) {
1312 return known;
1313 }
1314
1315 let learned = self
1317 .local_candidates
1318 .iter()
1319 .filter(|c| c.candidate_type() == CandidateType::PeerReflexive)
1320 .count();
1321 if learned >= MAX_LOCAL_PEER_REFLEXIVE_CANDIDATES {
1322 return sent_index;
1323 }
1324 let (component, tcp_type) = (sent.component(), sent.tcp_type());
1325 match (CandidatePeerReflexiveConfig {
1326 base_config: CandidateConfig {
1327 network: network_type.to_string(),
1328 address: mapped.ip().to_string(),
1329 port: mapped.port(),
1330 component,
1331 priority: request.priority.min(MAX_CANDIDATE_PRIORITY),
1332 ..CandidateConfig::default()
1333 },
1334 rel_addr: base.ip().to_string(),
1335 rel_port: base.port(),
1336 })
1337 .new_candidate_peer_reflexive()
1338 {
1339 Ok(mut prflx) => {
1340 prflx.tcp_type = tcp_type;
1341 debug!(
1342 "[{}]: new local peer-reflexive candidate {} (base {})",
1343 self.get_name(),
1344 mapped,
1345 base
1346 );
1347 self.local_candidates.push(prflx);
1348 self.local_candidates.len() - 1
1349 }
1350 Err(err) => {
1351 warn!(
1352 "[{}]: cannot make a local peer-reflexive candidate for {}: {}",
1353 self.get_name(),
1354 mapped,
1355 err
1356 );
1357 sent_index
1358 }
1359 }
1360 }
1361
1362 fn valid_pair_for(&mut self, local_index: usize, remote_index: usize) -> usize {
1365 if let Some(index) = self.find_pair_exact(local_index, remote_index) {
1366 return index;
1367 }
1368 let mut pair = CandidatePair::new(
1369 local_index,
1370 remote_index,
1371 self.local_candidates[local_index].priority(),
1372 self.remote_candidates[remote_index].priority(),
1373 self.is_controlling,
1374 );
1375 pair.foundation = self.pair_foundation(local_index, remote_index);
1376 pair.state = CandidatePairState::Succeeded;
1377 self.candidate_pairs.push(pair);
1378 let index = self.candidate_pairs.len() - 1;
1379 self.announce_pair(index, true);
1380 index
1381 }
1382
1383 pub(crate) fn handle_error_response(
1389 &mut self,
1390 now: Instant,
1391 m: &Message,
1392 remote_addr: SocketAddr,
1393 ) {
1394 use crate::rand::generate_tie_breaker;
1395 use stun::error_code::{CODE_ROLE_CONFLICT, ErrorCodeAttribute};
1396
1397 let Some(pending) = self.handle_inbound_binding_success(now, m.transaction_id) else {
1398 warn!(
1399 "[{}]: discard error response from ({}), unknown TransactionID 0x{:?}",
1400 self.get_name(),
1401 remote_addr,
1402 m.transaction_id
1403 );
1404 return;
1405 };
1406 if pending.destination != remote_addr {
1407 return;
1408 }
1409
1410 let mut error = ErrorCodeAttribute::default();
1411 let role_conflict = error.get_from(m).is_ok() && error.code == CODE_ROLE_CONFLICT;
1412 let pair_index = self.find_pair_exact(pending.local_index, pending.remote_index);
1413 let is_selected = pair_index.is_some() && pair_index == self.selected_pair;
1414
1415 if role_conflict {
1416 if pending.sent_as_controlling == self.is_controlling {
1417 log::info!(
1418 "[{}]: 487 (Role Conflict) from {}: switching role",
1419 self.get_name(),
1420 remote_addr
1421 );
1422 self.switch_role(now);
1423 }
1424 match generate_tie_breaker(self.crypto_provider.random()) {
1425 Ok(tie_breaker) => self.tie_breaker = tie_breaker,
1426 Err(err) => warn!(
1427 "[{}]: cannot generate a new tiebreaker: {}",
1428 self.get_name(),
1429 err
1430 ),
1431 }
1432 if let Some(pair_index) = pair_index
1437 && !is_selected
1438 && !pending.cancelled
1439 && self.candidate_pairs[pair_index].state != CandidatePairState::Succeeded
1440 {
1441 self.candidate_pairs[pair_index].state = CandidatePairState::Waiting;
1442 self.enqueue_triggered(pair_index);
1443 }
1444 self.request_connectivity_check();
1445 } else if let Some(pair_index) = pair_index
1446 && !is_selected
1447 && !pending.cancelled
1448 && !pending.consent
1449 {
1450 if self.failed_nomination == FailedNomination::FailChecklist
1453 && (self.is_open_nomination(&pending, pair_index)
1454 || self.is_followed_nomination(&pending, pair_index))
1455 {
1456 self.fail_nomination(now, pair_index, "an error response");
1457 return;
1458 }
1459 debug!(
1460 "[{}]: error response {} from {}: pair {} failed",
1461 self.get_name(),
1462 error,
1463 remote_addr,
1464 self.candidate_pairs[pair_index]
1465 );
1466 self.fail_pair(pair_index);
1467 self.maybe_nominate(now);
1468 }
1469 }
1470
1471 pub(crate) fn handle_failed_transaction(
1476 &mut self,
1477 now: Instant,
1478 id: TransactionId,
1479 remote_addr: SocketAddr,
1480 ) {
1481 let Some(pending) = self.handle_inbound_binding_success(now, id) else {
1482 return;
1483 };
1484 if pending.destination != remote_addr || pending.cancelled || pending.consent {
1485 return;
1486 }
1487 let Some(pair_index) = self.find_pair_exact(pending.local_index, pending.remote_index)
1488 else {
1489 return;
1490 };
1491 if self.selected_pair == Some(pair_index) {
1492 return;
1493 }
1494 if self.failed_nomination == FailedNomination::FailChecklist
1495 && (self.is_open_nomination(&pending, pair_index)
1496 || self.is_followed_nomination(&pending, pair_index))
1497 {
1498 self.fail_nomination(now, pair_index, "an unusable error response");
1499 return;
1500 }
1501 self.fail_pair(pair_index);
1502 self.maybe_nominate(now);
1503 }
1504
1505 pub(crate) fn handle_binding_request(
1512 &mut self,
1513 now: Instant,
1514 m: &Message,
1515 local_index: usize,
1516 remote_index: usize,
1517 ) {
1518 let Some(pair_index) = self.find_pair(local_index, remote_index) else {
1519 return;
1520 };
1521
1522 let nomination = if self.is_controlling {
1527 0
1528 } else {
1529 nomination_of(m)
1530 };
1531 if nomination > 0 {
1532 let p = &mut self.candidate_pairs[pair_index];
1533 p.remote_nomination = p.remote_nomination.max(nomination);
1534 let value = p.remote_nomination;
1535 if let Some(valid) = p.valid_pair {
1536 let v = &mut self.candidate_pairs[valid];
1537 v.remote_nomination = v.remote_nomination.max(value);
1538 }
1539 }
1540
1541 if self.lite && !self.is_controlling {
1542 if nomination > 0 {
1547 let p = &mut self.candidate_pairs[pair_index];
1548 p.state = CandidatePairState::Succeeded;
1549 p.valid = true;
1550 p.valid_pair = Some(pair_index);
1551 self.accept_nomination(now, pair_index);
1552 }
1553 return;
1554 }
1555
1556 let p = self.candidate_pairs[pair_index];
1557 if p.state == CandidatePairState::Succeeded {
1558 if nomination > 0 {
1563 self.accept_nomination(now, p.valid_pair.unwrap_or(pair_index));
1564 } else {
1565 self.maybe_nominate(now);
1566 }
1567 return;
1568 }
1569
1570 if nomination > 0 {
1571 self.candidate_pairs[pair_index].nomination_pending = true;
1575 }
1576 self.trigger_check(pair_index);
1578 }
1579
1580 pub(crate) fn accept_nomination(&mut self, now: Instant, pair_index: usize) {
1601 self.candidate_pairs[pair_index].nominated = true;
1602 match self.get_selected_pair() {
1603 Some(selected) if selected == pair_index => {}
1604 Some(selected) => {
1605 let (current, offered) = (
1606 self.candidate_pairs[selected],
1607 self.candidate_pairs[pair_index],
1608 );
1609 let takes_over = match self.nomination_acceptance {
1610 NominationAcceptance::HighestPriority => {
1611 offered.priority() > current.priority()
1612 || self.connection_state == ConnectionState::Disconnected
1613 }
1614 NominationAcceptance::Latest => {
1615 offered.remote_nomination >= current.remote_nomination
1616 }
1617 };
1618 if takes_over {
1619 debug!(
1620 "[{}]: peer nominated another pair: switching selected pair from {} to {} (nomination {} -> {})",
1621 self.get_name(),
1622 current,
1623 offered,
1624 current.remote_nomination,
1625 offered.remote_nomination
1626 );
1627 if self.nomination_acceptance == NominationAcceptance::Latest {
1628 self.candidate_pairs[selected].nominated = false;
1629 }
1630 self.set_selected_pair(Some(now), Some(pair_index));
1631 self.conclude();
1632 } else {
1633 debug!(
1634 "[{}]: nomination of {} accepted, selected pair {} kept (nomination {} / {})",
1635 self.get_name(),
1636 offered,
1637 current,
1638 offered.remote_nomination,
1639 current.remote_nomination
1640 );
1641 }
1642 }
1643 None => {
1644 self.set_selected_pair(Some(now), Some(pair_index));
1645 self.conclude();
1646 }
1647 }
1648 }
1649
1650 pub(crate) fn fall_back_to_another_nominated_pair(&mut self, now: Instant) {
1656 if self.is_controlling
1657 || self.nomination_acceptance != NominationAcceptance::HighestPriority
1658 {
1659 return;
1660 }
1661 let Some(selected) = self.selected_pair else {
1662 return;
1663 };
1664 let last_consent = self.remote_candidates[self.candidate_pairs[selected].remote_index]
1665 .last_consent()
1666 .unwrap_or(self.start_time);
1667 let best = self
1668 .candidate_pairs
1669 .iter()
1670 .enumerate()
1671 .filter(|(index, p)| {
1672 *index != selected
1673 && p.nominated
1674 && p.valid
1675 && p.state == CandidatePairState::Succeeded
1676 && p.remote_index != self.candidate_pairs[selected].remote_index
1677 && self.remote_candidates[p.remote_index]
1678 .last_authenticated()
1679 .is_some_and(|heard| heard > last_consent)
1680 })
1681 .max_by_key(|(_, p)| p.priority())
1682 .map(|(index, _)| index);
1683 if let Some(pair_index) = best {
1684 debug!(
1685 "[{}]: consent lost on {}: moving to the nominated pair {}",
1686 self.get_name(),
1687 self.candidate_pairs[selected],
1688 self.candidate_pairs[pair_index]
1689 );
1690 self.set_selected_pair(Some(now), Some(pair_index));
1691 self.conclude();
1692 }
1693 }
1694
1695 pub fn handle_transport_error(
1717 &mut self,
1718 now: Instant,
1719 transport: shared::TransportContext,
1720 error: TransportError,
1721 ) -> bool {
1722 let Some(local_index) =
1723 self.find_local_candidate(transport.local_addr, transport.transport_protocol)
1724 else {
1725 return false;
1726 };
1727 let Some(remote_index) = self.remote_candidates.iter().position(|c| {
1728 c.addr() == transport.peer_addr
1729 && c.network_type().to_protocol() == transport.transport_protocol
1730 }) else {
1731 return false;
1732 };
1733 let is_tcp = transport.transport_protocol == shared::TransportProtocol::TCP;
1734 let mut failed = vec![];
1735 for (index, p) in self.candidate_pairs.iter().enumerate() {
1736 if p.remote_index != remote_index
1737 || p.valid
1738 || p.state == CandidatePairState::Succeeded
1739 || p.state == CandidatePairState::Failed
1740 || Some(index) == self.selected_pair
1741 {
1742 continue;
1743 }
1744 let on_path = self.same_base(p.local_index, local_index);
1745 let fails = match error {
1746 TransportError::IcmpHardError => {
1747 on_path && p.state == CandidatePairState::InProgress
1748 }
1749 TransportError::ConnectionFailed => is_tcp && on_path,
1750 TransportError::NotStun => is_tcp,
1751 };
1752 if fails {
1753 failed.push(index);
1754 }
1755 }
1756 if error == TransportError::NotStun
1757 && !failed.iter().any(|&index| {
1758 self.candidate_pairs[index].state == CandidatePairState::InProgress
1759 && self.same_base(self.candidate_pairs[index].local_index, local_index)
1760 })
1761 {
1762 return false;
1764 }
1765 for &index in &failed {
1766 let p = self.candidate_pairs[index];
1767 debug!(
1768 "[{}]: {:?} on {}: the pair failed",
1769 self.get_name(),
1770 error,
1771 p
1772 );
1773 self.pending_binding_requests
1774 .retain(|r| !(r.local_index == p.local_index && r.remote_index == p.remote_index));
1775 self.fail_pair(index);
1776 }
1777 if !failed.is_empty() {
1778 self.maybe_nominate(now);
1779 self.request_connectivity_check();
1780 }
1781 !failed.is_empty()
1782 }
1783
1784 pub fn handle_non_stun_before_validation(
1796 &mut self,
1797 now: Instant,
1798 transport: shared::TransportContext,
1799 ) -> bool {
1800 if transport.transport_protocol != shared::TransportProtocol::TCP {
1801 return false;
1802 }
1803 let opened_here = self
1804 .find_local_candidate(transport.local_addr, transport.transport_protocol)
1805 .is_some_and(|local| {
1806 self.local_candidates[local].tcp_type() == crate::tcp_type::TcpType::Active
1807 });
1808 opened_here && self.handle_transport_error(now, transport, TransportError::NotStun)
1809 }
1810
1811 pub(crate) fn conclude_lite_to_lite(&mut self, now: Instant) {
1823 if self.selected_pair.is_some()
1824 || self.ufrag_pwd.remote_credentials.is_none()
1825 || matches!(
1826 self.connection_state,
1827 ConnectionState::Failed | ConnectionState::Closed
1828 )
1829 {
1830 return;
1831 }
1832 let Some(chosen) =
1833 (0..self.candidate_pairs.len()).max_by_key(|&index| self.lite_pair_preference(index))
1834 else {
1835 return;
1836 };
1837 let several = self.candidate_pairs.len() > 1;
1838 {
1839 let p = &mut self.candidate_pairs[chosen];
1840 p.state = CandidatePairState::Succeeded;
1841 p.valid = true;
1842 p.valid_pair = Some(chosen);
1843 }
1844 self.set_selected_pair(Some(now), Some(chosen));
1845 if several && self.is_controlling && !self.lite_update_raised {
1846 self.lite_update_raised = true;
1847 let p = self.candidate_pairs[chosen];
1848 self.event_outs.push_back(crate::agent::TaggedEvent {
1849 now,
1850 event: crate::agent::Event::LiteCandidateUpdate(
1851 Box::new(self.local_candidates[p.local_index].clone()),
1852 Box::new(self.remote_candidates[p.remote_index].clone()),
1853 ),
1854 });
1855 }
1856 }
1857
1858 fn lite_pair_preference(&self, index: usize) -> (bool, bool, bool, u32, u64) {
1867 use crate::agent::remote_policy::ip_scope;
1868
1869 let p = &self.candidate_pairs[index];
1870 let pinned = self.pinned_local_addr.is_some_and(|pinned| {
1872 let candidate = &self.local_candidates[p.local_index];
1873 candidate.addr() == pinned || candidate.base_addr() == pinned
1874 });
1875 let local = self.local_candidates[p.local_index].base_addr().ip();
1876 let remote = self.remote_candidates[p.remote_index].addr().ip();
1877 let matching_scope = ip_scope(local) == ip_scope(remote);
1878 let is_v6 = matches!(remote.to_canonical(), IpAddr::V6(_));
1879 let common_prefix = match (local.to_canonical(), remote.to_canonical()) {
1880 (IpAddr::V4(a), IpAddr::V4(b)) => (u32::from(a) ^ u32::from(b)).leading_zeros(),
1881 (IpAddr::V6(a), IpAddr::V6(b)) => (u128::from(a) ^ u128::from(b)).leading_zeros(),
1882 _ => 0,
1883 };
1884 (pinned, matching_scope, is_v6, common_prefix, p.priority())
1885 }
1886
1887 pub(crate) fn repeat_nomination(&mut self) {
1891 let Some(selected) = self.selected_pair else {
1892 return;
1893 };
1894 if !self.is_controlling || (self.lite && self.is_controlling) {
1895 return;
1896 }
1897 self.candidate_pairs[selected].nominate = true;
1898 self.enqueue_triggered(selected);
1899 }
1900
1901 pub(crate) fn maybe_nominate(&mut self, now: Instant) {
1906 if !self.is_controlling || self.selected_pair.is_some() || self.nominated_pair.is_some() {
1907 return;
1908 }
1909 let Some(pair_index) = self.get_best_valid_candidate_pair() else {
1910 return;
1911 };
1912 let p = self.candidate_pairs[pair_index];
1913 let checked_local = self
1917 .candidate_pairs
1918 .iter()
1919 .enumerate()
1920 .find(|(index, c)| *index != pair_index && c.valid_pair == Some(pair_index))
1921 .map_or(p.local_index, |(_, c)| c.local_index);
1922 if !self.is_nominatable(now, checked_local, true)
1923 || !self.is_nominatable(now, p.remote_index, false)
1924 {
1925 return;
1926 }
1927 if self.candidate_pair_proposals {
1928 if self.nomination_proposal.is_some() || self.declined_nominations.contains(&pair_index)
1930 {
1931 return;
1932 }
1933 self.nomination_proposal = Some(pair_index);
1934 self.event_outs.push_back(crate::agent::TaggedEvent {
1935 now,
1936 event: crate::agent::Event::CandidatePairNominationProposed(
1937 Box::new(self.local_candidates[p.local_index].clone()),
1938 Box::new(self.remote_candidates[p.remote_index].clone()),
1939 ),
1940 });
1941 return;
1942 }
1943 trace!(
1944 "Nominatable pair found, nominating ({}, {})",
1945 self.local_candidates[p.local_index], self.remote_candidates[p.remote_index],
1946 );
1947 self.candidate_pairs[pair_index].nominate = true;
1948 self.nominated_pair = Some(pair_index);
1949 self.nomination_started = Some(now);
1950 self.enqueue_triggered(pair_index);
1951 }
1952
1953 pub(crate) fn nomination_is_alive(&self, now: Instant, pair_index: usize) -> bool {
1958 let p = &self.candidate_pairs[pair_index];
1959 let heard = self
1960 .remote_candidates
1961 .get(p.remote_index)
1962 .and_then(|r| r.last_authenticated);
1963 let started = self
1964 .nomination_started
1965 .filter(|_| self.nominated_pair == Some(pair_index));
1966 heard
1967 .into_iter()
1968 .chain(started)
1969 .max()
1970 .is_some_and(|at| now.saturating_duration_since(at) < self.consent_expiry())
1971 }
1972
1973 pub(crate) fn expire_unanswered_nomination(&mut self, now: Instant) {
1981 let Some(nominated) = self.nominated_pair else {
1982 return;
1983 };
1984 if self.failed_nomination != FailedNomination::Retry
1985 || !self.is_controlling
1986 || self.selected_pair.is_some()
1987 || self.nomination_is_alive(now, nominated)
1988 {
1989 return;
1990 }
1991 warn!(
1992 "[{}]: nomination of {} is unanswered and the peer is not heard from: the pair failed",
1993 self.get_name(),
1994 self.candidate_pairs[nominated]
1995 );
1996 let p = self.candidate_pairs[nominated];
1997 self.pending_binding_requests
1998 .retain(|r| !(r.local_index == p.local_index && r.remote_index == p.remote_index));
1999 self.fail_pair(nominated);
2000 self.nomination_started = None;
2001 self.maybe_nominate(now);
2002 }
2003
2004 pub(crate) fn checks_in_progress(&self, now: Instant) -> bool {
2011 if !self.triggered_queue.is_empty() {
2012 return true;
2013 }
2014 let expiry = self.consent_expiry();
2015 self.candidate_pairs.iter().any(|p| match p.state {
2016 CandidatePairState::Frozen
2017 | CandidatePairState::Waiting
2018 | CandidatePairState::InProgress => true,
2019 CandidatePairState::Failed | CandidatePairState::Unspecified => false,
2020 CandidatePairState::Succeeded => {
2021 (self.is_controlling && p.valid)
2022 || self
2023 .remote_candidates
2024 .get(p.remote_index)
2025 .and_then(|r| r.last_authenticated)
2026 .is_some_and(|at| now.saturating_duration_since(at) < expiry)
2027 }
2028 })
2029 }
2030
2031 pub(crate) fn conclude(&mut self) {
2037 let Some(selected) = self.selected_pair else {
2038 return;
2039 };
2040 let mut cancel: Vec<(usize, usize)> = vec![];
2041 for (index, p) in self.candidate_pairs.iter_mut().enumerate() {
2042 p.triggered = p.triggered && p.nomination_pending;
2044 p.nominate = false;
2045 if index != selected
2048 && p.state == CandidatePairState::InProgress
2049 && !p.nomination_pending
2050 {
2051 p.state = CandidatePairState::Waiting;
2052 cancel.push((p.local_index, p.remote_index));
2053 }
2054 }
2055 for (local_index, remote_index) in cancel {
2056 self.cancel_transactions(local_index, remote_index);
2057 }
2058 let pairs = &self.candidate_pairs;
2059 self.triggered_queue.retain(|(local_index, remote_index)| {
2060 pairs.iter().any(|p| {
2061 p.triggered && p.local_index == *local_index && p.remote_index == *remote_index
2062 })
2063 });
2064 self.request_connectivity_check();
2067 }
2068
2069 pub(crate) fn update_checklist_failure(&mut self, now: Instant) {
2074 if self.connection_state != ConnectionState::Checking
2075 || self.selected_pair.is_some()
2076 || !self.remote_end_of_candidates
2077 || !self.local_gathering_complete
2078 || !self.mdns_queries.is_empty()
2079 || !self.early_requests.is_empty()
2080 || !self.triggered_queue.is_empty()
2081 {
2082 return;
2083 }
2084 if self
2085 .candidate_pairs
2086 .iter()
2087 .all(|p| p.state == CandidatePairState::Failed)
2088 {
2089 debug!(
2090 "[{}]: every pair failed and no candidate is to come: the checklist failed",
2091 self.get_name()
2092 );
2093 self.update_connection_state(Some(now), ConnectionState::Failed);
2094 }
2095 }
2096
2097 pub(crate) fn lite_keepalive(&mut self, now: Instant) {
2101 let Some(pair_index) = self.selected_pair else {
2102 return;
2103 };
2104 if self.keepalive_interval == Duration::ZERO {
2105 return;
2106 }
2107 let p = self.candidate_pairs[pair_index];
2108 let last_sent = self.local_candidates[p.local_index]
2109 .last_sent()
2110 .unwrap_or(self.start_time);
2111 if now.saturating_duration_since(last_sent) < KEEPALIVE_TR {
2112 return;
2113 }
2114 let mut msg = Message::new();
2115 if let Err(err) = msg.build(&[
2116 Box::new(MessageType::new(METHOD_BINDING, CLASS_INDICATION)),
2117 Box::new(TransactionId::new()),
2118 Box::new(FINGERPRINT),
2119 ]) {
2120 error!("{}", err);
2121 return;
2122 }
2123 self.send_stun(now, &msg, p.local_index, p.remote_index);
2124 }
2125
2126 pub(crate) fn start(&mut self, now: Instant) {
2128 self.nominated_pair = None;
2129 self.start_time = now;
2130 self.next_check_at = now;
2131 }
2132}