1use std::collections::{HashSet, VecDeque};
3use std::fmt;
4use std::net::SocketAddr;
5use std::ops::RangeInclusive;
6use std::panic::{RefUnwindSafe, UnwindSafe};
7use std::sync::Arc;
8use std::time::{Duration, Instant};
9
10use serde::{Deserialize, Serialize};
11
12use crate::Sha1HmacProvider;
13use crate::preference::default_local_preference;
14use crate::stun::{Class as StunClass, Method as StunMethod, StunTiming};
15use crate::stun::{StunMessage, StunPacket, TransId};
16use str0m_proto::{DATAGRAM_MTU_TARGET, DATAGRAM_MTU_WARN, Id, Transmit};
17use str0m_proto::{NonCryptographicRng, Pii, Protocol};
18
19use crate::candidate::{Candidate, CandidateKind};
20use crate::pair::{CandidatePair, CheckState, PairId};
21
22const LITE_NOMINATION_FRESH: Duration = Duration::from_secs(3);
26
27#[derive(Debug)]
33pub struct IceAgent {
34 last_now: Option<Instant>,
38
39 timing_advance: Duration,
44
45 ice_lite: bool,
51
52 max_candidate_pairs: Option<usize>,
55
56 has_exceeded_max_candidate_pairs: bool,
58
59 local_credentials: IceCreds,
61
62 remote_credentials: Option<IceCreds>,
64
65 controlling: bool,
67
68 control_tie_breaker: u64,
72
73 state: IceConnectionState,
75
76 local_candidates: Vec<Candidate>,
80
81 remote_candidates: Vec<Candidate>,
83
84 candidate_pairs: Vec<CandidatePair>,
86
87 transmit: VecDeque<Transmit>,
89
90 events: VecDeque<IceAgentEvent>,
92
93 stun_server_queue: VecDeque<StunRequest>,
96
97 discovered_recv: HashSet<(Protocol, SocketAddr)>,
100
101 nominated_send: Option<PairId>,
104
105 stats: IceAgentStats,
107
108 sha1_hmac_provider: &'static dyn Sha1HmacProvider,
110
111 timing_config: StunTiming,
113
114 local_preference: LocalPreferenceHolder,
116
117 mtu: RangeInclusive<usize>,
120}
121
122impl UnwindSafe for IceAgent {}
125impl RefUnwindSafe for IceAgent {}
126
127struct LocalPreferenceHolder(Arc<dyn LocalPreference>);
129
130pub trait LocalPreference: RefUnwindSafe + Send + Sync + 'static {
132 fn calculate(&self, c: &Candidate, same_kind: usize) -> u32;
139}
140
141impl<F> LocalPreference for F
143where
144 F: Fn(&Candidate, usize) -> u32 + RefUnwindSafe + Send + Sync + 'static,
145{
146 fn calculate(&self, c: &Candidate, same_kind: usize) -> u32 {
147 (self)(c, same_kind)
148 }
149}
150
151#[derive(Debug)]
152struct StunRequest {
153 now: Instant,
154 proto: Protocol,
155 source: SocketAddr,
156 destination: SocketAddr,
157 trans_id: TransId,
158 prio: u32,
159 use_candidate: bool,
160 remote_ufrag: String,
161 ice_controlling: Option<u64>,
162 ice_controlled: Option<u64>,
163}
164
165impl StunRequest {
166 fn role_conflict_tiebreaker(&self, controlling: bool) -> Option<u64> {
167 if controlling {
168 self.ice_controlling
169 } else {
170 self.ice_controlled
171 }
172 }
173}
174
175fn role_name(controlling: bool) -> &'static str {
176 if controlling {
177 "controlling"
178 } else {
179 "controlled"
180 }
181}
182
183fn is_valid_peer_addr(addr: SocketAddr) -> bool {
186 addr.port() != 0 && !addr.ip().to_canonical().is_unspecified()
187}
188
189const REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION: &str = "tmp_prflx";
190
191#[derive(Debug, Clone, Copy, PartialEq, Eq)]
197pub enum IceConnectionState {
198 New,
200
201 Checking,
206
207 Connected,
212
213 Completed,
216
217 Disconnected,
222 }
233
234impl IceConnectionState {
235 pub fn is_connected(&self) -> bool {
237 use IceConnectionState::*;
238 matches!(self, Connected | Completed)
239 }
240
241 pub fn is_disconnected(&self) -> bool {
243 *self == IceConnectionState::Disconnected
244 }
245}
246
247#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
251pub struct IceCreds {
252 pub ufrag: String,
254 pub pass: String,
256}
257
258#[derive(Debug, Clone, Copy, Default, PartialEq, Eq)]
259pub struct IceAgentStats {
260 pub bind_request_sent: u64,
261 pub bind_success_recv: u64,
262 pub bind_request_recv: u64,
263 pub discovered_recv_count: u64,
264 pub nomination_send_count: u64,
265}
266
267#[derive(Debug, PartialEq, Eq)]
269pub enum IceAgentEvent {
270 IceRestart(IceCreds),
272
273 IceConnectionStateChange(IceConnectionState),
278
279 DiscoveredRecv {
287 proto: Protocol,
289 source: SocketAddr,
291 },
292
293 NominatedSend {
299 proto: Protocol,
301 source: SocketAddr,
306 destination: SocketAddr,
308 },
309}
310
311impl IceCreds {
312 pub fn new() -> Self {
314 let ufrag = Id::<16>::random().to_string();
319 let pass = Id::<22>::random().to_string();
320 IceCreds { ufrag, pass }
321 }
322}
323
324impl IceAgent {
325 #[cfg(feature = "sha1")]
329 pub fn new(local_credentials: IceCreds) -> Self {
330 Self::with_hmac(local_credentials, &crate::DefaultSha1HmacProvider)
331 }
332
333 pub fn with_hmac(
335 local_credentials: IceCreds,
336 sha1_hmac_provider: &'static dyn Sha1HmacProvider,
337 ) -> Self {
338 IceAgent {
339 last_now: None,
340 ice_lite: false,
341 max_candidate_pairs: None,
342 has_exceeded_max_candidate_pairs: false,
343 local_credentials,
344 remote_credentials: None,
345 controlling: false,
346 control_tie_breaker: NonCryptographicRng::u64(),
347 state: IceConnectionState::New,
348 local_candidates: vec![],
349 remote_candidates: vec![],
350 candidate_pairs: vec![],
351 transmit: VecDeque::new(),
352 events: VecDeque::new(),
353 stun_server_queue: VecDeque::new(),
354 discovered_recv: HashSet::new(),
355 nominated_send: None,
356 stats: IceAgentStats::default(),
357 timing_advance: Duration::from_millis(50),
358 timing_config: StunTiming::default(),
359 local_preference: LocalPreferenceHolder(Arc::new(default_local_preference)),
360 sha1_hmac_provider,
361 mtu: DATAGRAM_MTU_TARGET..=DATAGRAM_MTU_WARN,
362 }
363 }
364
365 pub fn set_mtu(&mut self, mtu: RangeInclusive<usize>) {
367 self.mtu = mtu;
368 }
369
370 pub fn mtu(&self) -> usize {
372 *self.mtu.start()
373 }
374
375 pub fn mtu_warn(&self) -> usize {
377 *self.mtu.end()
378 }
379
380 pub fn set_control_tie_breaker(&mut self, tie_breaker: u64) {
385 self.control_tie_breaker = tie_breaker;
386 }
387
388 pub fn set_max_candidate_pairs(&mut self, max: usize) {
392 self.max_candidate_pairs = Some(max);
393 self.has_exceeded_max_candidate_pairs = false; }
395
396 pub fn ice_lite(&self) -> bool {
400 self.ice_lite
401 }
402
403 pub fn set_ice_lite(&mut self, enabled: bool) {
407 self.ice_lite = enabled;
408 }
409
410 pub fn set_timing_advance(&mut self, duration: Duration) {
417 self.timing_advance = duration
418 }
419
420 pub fn local_credentials(&self) -> &IceCreds {
422 &self.local_credentials
423 }
424
425 pub fn set_local_credentials(&mut self, r: IceCreds) {
427 if self.local_credentials != r {
428 debug!("Set local credentials: {:?}", Pii(&r));
429 self.local_credentials = r;
430 }
431 }
432
433 pub fn set_initial_stun_rto(&mut self, timeout: Duration) {
441 if self.timing_config.initial_rto == timeout {
442 return;
443 }
444
445 self.timing_config.initial_rto = timeout;
446
447 debug!("initial_rto = {timeout:?}");
448
449 self.bust_candidate_pair_timeout_caches();
450 }
451
452 pub fn set_max_stun_rto(&mut self, timeout: Duration) {
463 if self.timing_config.max_rto == timeout {
464 return;
465 }
466
467 self.timing_config.max_rto = timeout;
468
469 debug!("max_rto = {timeout:?}");
470
471 self.bust_candidate_pair_timeout_caches();
472 }
473
474 pub fn set_max_stun_retransmits(&mut self, num: usize) {
478 if self.timing_config.max_retransmits == num {
479 return;
480 }
481
482 self.timing_config.max_retransmits = num;
483
484 debug!("max_retransmits = {num}");
485 }
486
487 pub fn set_local_preference(&mut self, p: impl LocalPreference) {
491 self.local_preference = LocalPreferenceHolder(Arc::new(p));
492 }
493
494 fn bust_candidate_pair_timeout_caches(&mut self) {
495 for pair in self.candidate_pairs.iter_mut() {
496 pair.reset_cached_next_attempt_time();
497 }
498 }
499
500 pub fn ice_timeout(&self) -> Duration {
503 self.timing_config.timeout()
504 }
505
506 pub fn local_candidates(&self) -> impl Iterator<Item = Candidate> + Clone + '_ {
510 self.local_candidates
511 .iter()
512 .filter(|c| !c.discarded())
513 .cloned()
514 }
515
516 pub fn remote_candidates(&self) -> impl Iterator<Item = Candidate> + Clone + '_ {
518 self.remote_candidates
519 .iter()
520 .filter(|c| !c.discarded())
521 .cloned()
522 }
523
524 pub fn has_viable_remote_candidate(&self, addr: SocketAddr) -> bool {
527 self.candidate_pairs
528 .iter()
529 .filter(|cand| cand.state() == CheckState::Succeeded)
530 .any(|pair| self.remote_candidates[pair.remote_idx()].addr() == addr)
531 }
532
533 pub fn remote_credentials(&self) -> Option<&IceCreds> {
535 self.remote_credentials.as_ref()
536 }
537
538 pub fn set_remote_credentials(&mut self, r: IceCreds) {
540 if self.remote_credentials.as_ref() != Some(&r) {
541 debug!("Set remote credentials: {:?}", Pii(&r));
542 self.remote_credentials = Some(r);
543 }
544 }
545
546 pub fn find_pair_for_equivalent_remote_candidate(
548 &self,
549 c: &Candidate,
550 ) -> Option<&CandidatePair> {
551 self.candidate_pairs.iter().find(|pair| {
552 let o = &self.remote_candidates[pair.remote_idx()];
553 c.addr() == o.addr()
554 && c.base() == o.base()
555 && c.proto() == o.proto()
556 && c.kind() == o.kind()
557 && c.raddr() == o.raddr()
558 })
559 }
560
561 fn stun_credentials(&self, reply: bool) -> (String, String) {
576 let local = &self.local_credentials;
577
578 let (left, right, peer_pass) = if reply {
579 ("not_used", "not_used", "not_used")
580 } else {
581 let peer = self
582 .remote_credentials
583 .as_ref()
584 .expect("Remote ICE credentials");
585 (&peer.ufrag[..], &local.ufrag[..], &peer.pass[..])
586 };
587
588 let username = format!("{left}:{right}");
589 let password = if reply {
590 local.pass.clone()
591 } else {
592 peer_pass.into()
593 };
594
595 (username, password)
596 }
597
598 #[allow(unused)]
600 pub fn controlling(&self) -> bool {
601 self.controlling
602 }
603
604 pub fn set_controlling(&mut self, v: bool) {
609 self.controlling = v;
610 }
611
612 pub fn state(&self) -> IceConnectionState {
614 self.state
615 }
616
617 #[allow(unused)]
621 pub fn stats(&self) -> IceAgentStats {
622 self.stats
623 }
624
625 pub fn add_local_candidate(&mut self, mut c: Candidate) -> Option<&Candidate> {
633 let ip = c.addr().ip();
634
635 if self.ice_lite {
636 if c.kind() != CandidateKind::Host {
638 debug!("Reject non-host candidate due to ice-lite mode: {:?}", c);
639 return None;
640 }
641 }
642
643 let same_kind = self
645 .local_candidates
646 .iter()
647 .filter(|v| v.kind() == c.kind())
648 .filter(|v| v.addr().is_ipv6() == ip.is_ipv6())
649 .count();
650
651 let pref = self.local_preference.0.calculate(&c, same_kind);
653 trace!("Calculated local preference: {}", pref);
654 c.set_local_preference(pref);
655
656 c.set_ufrag(&self.local_credentials.ufrag);
658
659 let maybe_redundant =
666 self.local_candidates.iter_mut().enumerate().find(|(_, v)| {
667 v.addr() == c.addr() && v.base() == c.base() && v.proto() == c.proto()
668 });
669
670 let local_idx = if let Some((idx, other)) = maybe_redundant {
671 if other.discarded() && c.kind() == other.kind() && c.raddr() == other.raddr() {
672 debug!("Re-enable previously discarded local: {:?}", other);
673 other.set_discarded(false);
674 idx
675 } else {
676 if c.prio() < other.prio() {
677 debug!(
679 "Reject redundant candidate, current: {:?} rejected: {:?}",
680 Pii(&other),
681 Pii(&c)
682 );
683 return None;
684 }
685
686 debug!(
688 "Replace redundant candidate, current: {:?} replaced with: {:?}",
689 Pii(&other),
690 Pii(&c)
691 );
692 other.set_discarded(true);
693 self.discard_candidate_pairs_by_local(idx);
694
695 let new_idx = self.local_candidates.len();
696
697 debug!("Add local candidate ({new_idx}): {:?}", Pii(&c));
698 self.local_candidates.push(c);
699
700 new_idx
701 }
702 } else {
703 let new_idx = self.local_candidates.len();
704
705 debug!("Add local candidate ({new_idx}): {:?}", Pii(&c));
706 self.local_candidates.push(c);
707
708 new_idx
709 };
710
711 let remote_idxs: Vec<_> = self
713 .remote_candidates
714 .iter()
715 .enumerate()
716 .filter(|(_, v)| !v.discarded() && v.addr().is_ipv4() == ip.is_ipv4())
717 .map(|(i, _)| i)
718 .collect();
719
720 self.form_pairs(&[local_idx], &remote_idxs);
730
731 Some(&self.local_candidates[local_idx])
734 }
735
736 pub fn add_remote_candidate(&mut self, mut c: Candidate) {
741 if c.component_id() != 1 {
744 debug!("Reject candidate for component other than 1: {:?}", Pii(&c));
745 return;
746 }
747
748 if !is_valid_peer_addr(c.addr()) {
749 debug!("Reject candidate that can't reach the peer: {:?}", Pii(&c));
750 return;
751 }
752
753 if let Some(creds) = &self.remote_credentials {
754 if let Some(ufrag) = c.ufrag() {
755 if ufrag != creds.ufrag {
756 debug!(
757 "Reject candidate with ufrag mismatch: {} != {}",
758 Pii(&ufrag),
759 Pii(&creds.ufrag)
760 );
761 return;
762 }
763 }
764 }
765
766 c.clear_ufrag();
769
770 let existing_pair = self.find_pair_for_equivalent_remote_candidate(&c);
771 let existing_candidate =
772 existing_pair.map(|p| (p.remote_idx(), &self.remote_candidates[p.remote_idx()]));
773
774 let existing_idx = match existing_candidate {
775 Some((_, o)) if !o.discarded() => {
776 trace!(
779 "Ignoring candidate({c:?}) that exactly matches existing non-discarded candidate"
780 );
781 return;
782 }
783 Some((i, o)) if o.discarded() => Some(i),
784 _ => None,
785 };
786
787 let existing_prflx = self
788 .remote_candidates
789 .iter_mut()
790 .enumerate()
791 .find(|(_, v)| {
792 v.foundation() == REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION
793 && v.kind() == CandidateKind::PeerReflexive
794 && v.addr() == c.addr()
795 });
796
797 let ipv4 = c.addr().is_ipv4();
798
799 let remote_idx = if let Some((idx, existing)) = existing_prflx {
800 debug!(
803 "Replace peer reflexive candidate, current: {:?} replaced with: {:?}",
804 Pii(&existing),
805 Pii(&c)
806 );
807 *existing = c;
808 idx
809 } else {
810 let existing_discarded = existing_idx.and_then(|idx| {
811 let o = &mut self.remote_candidates[idx];
812
813 o.discarded().then_some((idx, o))
814 });
815
816 if let Some((idx, other)) = existing_discarded {
817 debug!("Re-enable previously discarded remote: {:?}", Pii(&other));
818 other.set_discarded(false);
819 idx
820 } else {
821 let new_idx = self.remote_candidates.len();
822
823 debug!("Add remote candidate ({new_idx}): {:?}", Pii(&c));
824 self.remote_candidates.push(c);
825
826 new_idx
827 }
828 };
829
830 let local_idxs: Vec<_> = self
832 .local_candidates
833 .iter()
834 .enumerate()
835 .filter(|(_, v)| !v.discarded() && v.addr().is_ipv4() == ipv4)
836 .map(|(i, _)| i)
837 .collect();
838
839 let remote_idxs = [remote_idx];
840 self.form_pairs(&local_idxs, &remote_idxs);
841 }
842
843 fn form_pairs(&mut self, local_idxs: &[usize], remote_idxs: &[usize]) {
845 for pair in &mut self.candidate_pairs {
847 pair.update_kinds(&self.local_candidates, &self.remote_candidates);
848 }
849
850 for local_idx in local_idxs {
851 'outer: for remote_idx in remote_idxs {
852 let local = &self.local_candidates[*local_idx];
853 let remote = &self.remote_candidates[*remote_idx];
854
855 if local.proto() != remote.proto() {
857 continue 'outer;
858 }
859
860 let prio =
861 CandidatePair::calculate_prio(self.controlling, remote.prio(), local.prio());
862 let mut pair =
863 CandidatePair::new(*local_idx, local.kind(), *remote_idx, remote.kind(), prio);
864
865 trace!("Form pair local: {:?} remote: {:?}", local, remote);
866
867 for (check_idx, check) in self.candidate_pairs.iter().enumerate() {
874 let check_local = check.local_candidate(&self.local_candidates);
875 let check_remote = check.remote_candidate(&self.remote_candidates);
876
877 let redundant = local.base() == check_local.base()
878 && remote.addr() == check_remote.addr()
879 && local.proto() == check_local.proto()
880 && remote.proto() == check_remote.proto();
881
882 if redundant {
883 if check.prio() >= pair.prio() {
884 debug!(
887 "Reject redundant pair, current: {:?} rejected: {:?}",
888 Pii(&check),
889 Pii(&pair)
890 );
891 } else {
892 pair.copy_nominated_and_success_state(&self.candidate_pairs[check_idx]);
894
895 debug!(
896 "Replace redundant pair, current: {:?} replaced with: {:?}",
897 Pii(&check),
898 Pii(&pair)
899 );
900
901 if self.ice_lite {
902 debug!("Retain incoming binding requests for pair");
903 pair.copy_remote_binding_requests(&self.candidate_pairs[check_idx]);
904 }
905
906 self.candidate_pairs[check_idx] = pair;
907 }
908
909 continue 'outer;
913 }
914 }
915
916 debug!("Add new pair {:?}", Pii(&pair));
917
918 self.candidate_pairs.push(pair);
920 }
921 }
922
923 self.candidate_pairs.sort();
926
927 let max = self.max_candidate_pairs.unwrap_or(100);
935
936 let num_pairs = self.candidate_pairs.len();
937 if num_pairs > max && !self.has_exceeded_max_candidate_pairs {
938 warn!(%max, %num_pairs, "Exceeded max number of candidate pairs");
939 self.has_exceeded_max_candidate_pairs = true;
940 }
941
942 while self.candidate_pairs.len() > max {
943 let pair = self.candidate_pairs.pop();
944 debug!("Remove overflow pair {:?}", Pii(&pair));
945 }
946 }
947
948 pub fn invalidate_candidate(&mut self, c: &Candidate) -> bool {
958 if let Some((idx, other)) = self.local_candidates.iter_mut().enumerate().find(|(_, v)| {
959 v.addr() == c.addr()
960 && v.base() == c.base()
961 && v.raddr() == c.raddr()
962 && v.kind() == c.kind()
963 && v.proto() == c.proto()
964 }) {
965 if !other.discarded() {
966 debug!("Local candidate to discard {:?}", Pii(&other));
967 other.set_discarded(true);
968 self.discard_candidate_pairs_by_local(idx);
969 return true;
970 }
971 }
972
973 if let Some((idx, other)) = self
974 .remote_candidates
975 .iter_mut()
976 .enumerate()
977 .find(|(_, v)| {
978 v.addr() == c.addr()
979 && v.base() == c.base()
980 && v.raddr() == c.raddr()
981 && v.kind() == c.kind()
982 && v.proto() == c.proto()
983 })
984 {
985 if !other.discarded() {
986 debug!("Remote candidate to discard {:?}", Pii(&other));
987 other.set_discarded(true);
988 self.discard_candidate_pairs_by_remote(idx);
989 return true;
990 }
991 }
992
993 debug!("No local or remote candidate found: {:?}", Pii(&c));
994 false
995 }
996
997 #[allow(unused)]
1004 pub fn ice_restart(&mut self, local_credentials: IceCreds, keep_local_candidates: bool) {
1005 self.remote_credentials = None;
1013 self.remote_candidates.clear();
1014 self.candidate_pairs.clear();
1015 self.has_exceeded_max_candidate_pairs = false;
1016 self.transmit.clear();
1017 self.events.clear();
1018 self.discovered_recv.clear();
1019
1020 if keep_local_candidates {
1021 for c in &mut self.local_candidates {
1024 c.set_ufrag(&local_credentials.ufrag)
1025 }
1026 } else {
1027 self.local_candidates.clear();
1028 }
1029
1030 self.local_credentials = local_credentials;
1031
1032 self.emit_event(IceAgentEvent::IceRestart(self.local_credentials.clone()));
1033 self.set_connection_state(IceConnectionState::Checking, "ice restart");
1034 }
1035
1036 pub fn recreate_candidate_pairs(&mut self) {
1040 self.candidate_pairs.clear();
1041
1042 let local_idxs: Vec<_> = self
1043 .local_candidates
1044 .iter()
1045 .enumerate()
1046 .filter(|(_, v)| !v.discarded())
1047 .map(|(i, _)| i)
1048 .collect();
1049 let remote_idxs: Vec<_> = self
1050 .remote_candidates
1051 .iter()
1052 .enumerate()
1053 .filter(|(_, v)| !v.discarded())
1054 .map(|(i, _)| i)
1055 .collect();
1056
1057 self.form_pairs(&local_idxs, &remote_idxs);
1058 self.set_connection_state(IceConnectionState::Checking, "recreate candidate pairs");
1059 }
1060
1061 fn discard_candidate_pairs_by_local(&mut self, local_idx: usize) {
1063 trace!("Discard pairs for local candidate index: {:?}", local_idx);
1064 self.candidate_pairs.retain(|c| c.local_idx() != local_idx);
1065 }
1066
1067 fn discard_candidate_pairs_by_remote(&mut self, remote: usize) {
1069 trace!("Discard pairs for remote candidate index: {:?}", remote);
1070 self.candidate_pairs.retain(|c| c.remote_idx() != remote);
1071 }
1072
1073 pub fn accepts_message(&self, message: &StunMessage<'_>) -> bool {
1080 trace!("Check if accepts message: {:?}", message);
1081
1082 let sha1_hmac =
1083 |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads);
1084
1085 let do_integrity_check = |is_request: bool| -> bool {
1086 let (_, password) = self.stun_credentials(is_request);
1087 let integrity_passed = message.verify(password.as_bytes(), sha1_hmac);
1088
1089 if integrity_passed {
1091 trace!("Message accepted");
1092 } else {
1093 trace!("Message rejected, integrity check failed");
1094 }
1095 integrity_passed
1096 };
1097
1098 let method = message.method();
1099 let class = message.class();
1100 match (method, class) {
1101 (StunMethod::Binding, StunClass::Indication) => {
1102 false
1106 }
1107 (StunMethod::Binding, StunClass::Request) => {
1108 let (local, remote) = message.split_username().unwrap();
1113
1114 let local_creds = self.local_credentials();
1115 if local != local_creds.ufrag {
1116 trace!(
1117 "Message rejected, local user mismatch: {} != {}",
1118 local, local_creds.ufrag
1119 );
1120 return false;
1121 }
1122
1123 if let Some(remote_creds) = &self.remote_credentials {
1124 if remote != remote_creds.ufrag {
1125 trace!(
1126 "Message rejected, remote user mismatch: {} != {}",
1127 remote, remote_creds.ufrag
1128 );
1129 return false;
1130 }
1131 }
1132
1133 do_integrity_check(true)
1134 }
1135 (StunMethod::Binding, StunClass::Success | StunClass::Failure) => {
1136 let belongs_to_a_candidate_pair = self
1137 .candidate_pairs
1138 .iter()
1139 .any(|pair| pair.binding_attempt(message.trans_id()).is_some());
1140
1141 if !belongs_to_a_candidate_pair {
1142 trace!(
1143 "Message rejected, transaction ID does not belong to any of our candidate pairs"
1144 );
1145 return false;
1146 }
1147
1148 do_integrity_check(false)
1149 }
1150 (StunMethod::Binding, StunClass::Unknown) => {
1151 trace!("Message rejected, unknown STUN class");
1153 false
1154 }
1155 (StunMethod::Unknown, _) => {
1156 trace!("Message rejected, unknown STUN method");
1158 false
1159 }
1160 (
1161 StunMethod::Allocate
1162 | StunMethod::Refresh
1163 | StunMethod::Send
1164 | StunMethod::Data
1165 | StunMethod::CreatePermission
1166 | StunMethod::ChannelBind,
1167 _,
1168 ) => {
1169 trace!("Message rejected, TURN method({method:?}) unexpected in this context");
1171 false
1172 }
1173 }
1174 }
1175
1176 pub fn handle_packet(&mut self, now: Instant, packet: StunPacket) -> bool {
1180 trace!("Handle receive: {:?}", &packet.message);
1181
1182 if !is_valid_peer_addr(packet.source) {
1184 debug!(
1185 "Drop STUN message from invalid address: {}",
1186 Pii(packet.source)
1187 );
1188 return false;
1189 }
1190
1191 if !self.accepts_message(&packet.message) {
1194 debug!("Message not accepted");
1195 return false;
1196 }
1197
1198 if packet.message.is_binding_request() {
1199 self.stun_server_handle_message(now, &packet);
1200 } else if packet.message.is_successful_binding_response() {
1201 self.stun_client_handle_response(now, packet.message);
1202 } else if packet.message.is_failed_binding_response() {
1203 self.stun_client_handle_error(packet.message);
1204 }
1205
1206 self.emit_event(IceAgentEvent::DiscoveredRecv {
1207 proto: packet.proto,
1208 source: packet.source,
1209 });
1210
1211 true
1214 }
1215
1216 pub fn handle_timeout(&mut self, now: Instant) {
1221 if self.state == IceConnectionState::New {
1224 self.emit_event(IceAgentEvent::IceRestart(self.local_credentials.clone()));
1225 }
1226
1227 self.evaluate_state(now);
1228
1229 if self.remote_credentials.is_some() {
1231 let queue = &mut self.stun_server_queue;
1232
1233 while let Some(peek) = queue.front() {
1235 if now - peek.now >= self.timing_config.timeout() {
1236 let r = queue.pop_front();
1237 trace!("Drop too old enqueued STUN request: {:?}", r.unwrap());
1238 } else {
1239 break;
1240 }
1241 }
1242
1243 if let Some(req) = self.stun_server_queue.pop_front() {
1244 debug!("Handle enqueued STUN request: {:?}", Pii(&req));
1245 self.stun_server_handle_request(req);
1246 return;
1247 }
1248 }
1249
1250 self.last_now = Some(now);
1251
1252 self.evaluate_nomination(now);
1253
1254 let mut any_pruned = false;
1256 self.candidate_pairs.retain(|p| {
1257 let keep = if self.ice_lite {
1258 p.is_ice_lite_alive(now)
1259 } else {
1260 p.is_still_possible(now, &self.timing_config)
1261 };
1262 if !keep {
1263 debug!("Remove failed pair: {:?}", Pii(&p));
1264 any_pruned = true;
1265 }
1266 keep
1267 });
1268 if any_pruned {
1269 self.evaluate_nomination(now);
1270 self.evaluate_state(now);
1271 }
1272
1273 if self.remote_credentials.is_none() {
1274 trace!("Stop timeout due to missing remote credentials");
1275 return;
1276 }
1277
1278 if self.ice_lite {
1279 for p in &mut self.candidate_pairs {
1284 if p.remote_binding_request_time().is_none() {
1285 p.increase_remote_binding_requests(now);
1286 }
1287 }
1288
1289 trace!("Stop timeout since ice-lite do no checks");
1290 return;
1291 }
1292
1293 let next = self
1295 .candidate_pairs
1296 .iter_mut()
1297 .enumerate()
1298 .map(|(i, c)| (i, c.next_binding_attempt(now, &self.timing_config)))
1299 .min_by_key(|(_, t)| *t);
1300
1301 if let Some((idx, deadline)) = next {
1302 if now >= deadline {
1303 let pair = &self.candidate_pairs[idx];
1304 trace!("Handle next triggered pair: {:?}", pair);
1305 self.stun_client_binding_request(now, idx);
1306 } else {
1307 }
1309 }
1310 }
1311
1312 pub fn poll_transmit(&mut self) -> Option<Transmit> {
1314 let x = self.transmit.pop_front();
1315 if let Some(x) = &x {
1316 if x.contents.len() > self.mtu_warn() {
1317 warn!("ICE above MTU {}: {}", self.mtu_warn(), x.contents.len());
1318 }
1319 trace!("Poll transmit: {:?}", x);
1320 }
1321 x
1322 }
1323
1324 pub fn poll_timeout(&mut self) -> Option<Instant> {
1331 let last_now = self.last_now?;
1333
1334 let has_request = !self.stun_server_queue.is_empty();
1335 let has_transmit = !self.transmit.is_empty();
1336
1337 if has_request || has_transmit {
1339 return Some(last_now + self.timing_advance);
1340 }
1341
1342 let maybe_next = if self.ice_lite {
1344 None
1346 } else {
1347 self.candidate_pairs
1348 .iter_mut()
1349 .map(|c| c.next_binding_attempt(last_now, &self.timing_config))
1350 .min()
1351 };
1352
1353 let next = if let Some(next) = maybe_next {
1355 if next < last_now + self.timing_advance {
1356 last_now + self.timing_advance
1357 } else {
1358 next
1359 }
1360 } else {
1361 last_now + Duration::from_secs(3)
1363 };
1364
1365 Some(next)
1366 }
1367
1368 fn emit_event(&mut self, event: IceAgentEvent) {
1369 if let IceAgentEvent::DiscoveredRecv { proto, source } = event {
1370 if !self.discovered_recv.insert((proto, source)) {
1371 return;
1373 }
1374 self.stats.discovered_recv_count += 1;
1375 } else if matches!(event, IceAgentEvent::NominatedSend { .. }) {
1376 self.stats.nomination_send_count += 1;
1377 }
1378
1379 trace!("Enqueueing event: {:?}", event);
1380 self.events.push_back(event);
1381 }
1382
1383 pub fn poll_event(&mut self) -> Option<IceAgentEvent> {
1385 let x = self.events.pop_front();
1386 if x.is_some() {
1387 trace!("Poll event: {:?}", x);
1388 }
1389 x
1390 }
1391
1392 fn stun_server_handle_message(&mut self, now: Instant, packet: &StunPacket) {
1393 let message = &packet.message;
1394 let prio = message
1395 .prio()
1396 .expect("STUN request prio");
1398 let use_candidate = message.use_candidate();
1399
1400 if use_candidate {
1401 trace!("Binding request sent USE-CANDIDATE");
1402 }
1403
1404 let trans_id = message.trans_id();
1405
1406 let (_, remote_ufrag) = message.split_username().unwrap();
1408
1409 let req = StunRequest {
1412 now,
1413 proto: packet.proto,
1414 source: packet.source,
1415 destination: packet.destination,
1416 trans_id,
1417 prio,
1418 use_candidate,
1419 remote_ufrag: remote_ufrag.into(),
1420 ice_controlling: message.ice_controlling(),
1421 ice_controlled: message.ice_controlled(),
1422 };
1423
1424 if self.remote_credentials.is_some() {
1425 self.stun_server_handle_request(req);
1426 } else {
1427 debug!(
1428 "Enqueue STUN request due to missing remote credentials: {:?}",
1429 Pii(&req)
1430 );
1431
1432 let queue = &mut self.stun_server_queue;
1433
1434 queue.push_back(req);
1438
1439 while queue.len() > 100 {
1441 let r = queue.pop_front();
1442 debug!("Remove overflow STUN request {:?}", Pii(&r));
1443 }
1444
1445 }
1454 }
1455
1456 fn stun_server_handle_request(&mut self, req: StunRequest) {
1457 let remote_creds = self.remote_credentials.as_ref().expect("Remote ICE creds");
1458 if req.remote_ufrag != remote_creds.ufrag {
1459 debug!(
1462 "STUN request rejected, remote user mismatch (enqueued): {} != {}",
1463 Pii(&req.remote_ufrag),
1464 Pii(&remote_creds.ufrag)
1465 );
1466 return;
1467 }
1468
1469 let local_idx = match self.local_candidates.iter().position(|v| {
1474 matches!(v.kind(), CandidateKind::Host | CandidateKind::Relayed)
1475 && v.addr() == req.destination
1476 && v.proto() == req.proto
1477 }) {
1478 Some(i) => i,
1479 None => {
1480 debug!(
1485 "Discarding STUN request on unknown interface: {}",
1486 Pii(req.destination)
1487 );
1488 return;
1489 }
1490 };
1491
1492 if let Some(peer_tb) = req.role_conflict_tiebreaker(self.controlling) {
1495 debug!(
1496 "Role conflict on {} role: ours={}, peer={}",
1497 role_name(self.controlling),
1498 self.control_tie_breaker,
1499 peer_tb,
1500 );
1501
1502 if self.control_tie_breaker >= peer_tb {
1503 self.send_role_conflict_reply(&req);
1504 return;
1505 }
1506
1507 self.switch_role(!self.controlling);
1508 }
1509
1510 if req.use_candidate && self.controlling {
1511 debug!("STUN request rejected, USE-CANDIDATE when local is controlling");
1513 return;
1514 }
1515
1516 self.stats.bind_request_recv += 1;
1517
1518 let found_in_remote = self
1522 .remote_candidates
1523 .iter()
1524 .enumerate()
1525 .filter(|(_, c)| !c.discarded() && c.proto() == req.proto && c.addr() == req.source)
1526 .max_by_key(|(_, c)| c.prio());
1529
1530 let remote_idx = if let Some((idx, _)) = found_in_remote {
1531 trace!("Remote candidate for STUN request found");
1532 idx
1533 } else {
1534 let maybe_discarded = self
1535 .remote_candidates
1536 .iter()
1537 .any(|c| c.discarded() && c.proto() == req.proto && c.addr() == req.source);
1538
1539 if maybe_discarded {
1540 trace!("STUN request ignored because remote candidate is discarded");
1543 return;
1544 }
1545
1546 let c = Candidate::peer_reflexive(
1554 req.proto,
1555 req.source,
1556 req.source,
1557 req.prio,
1558 Some(REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION.into()),
1564 self.local_credentials.ufrag.clone(),
1565 );
1566
1567 debug!(
1568 "Created peer reflexive remote candidate from STUN request: {:?}",
1569 Pii(&c)
1570 );
1571
1572 self.remote_candidates.push(c);
1575
1576 self.remote_candidates.len() - 1
1577 };
1578
1579 let maybe_pair = self
1580 .candidate_pairs
1581 .iter_mut()
1582 .find(|p| p.local_idx() == local_idx && p.remote_idx() == remote_idx);
1583
1584 if let Some(pair) = maybe_pair {
1585 trace!("Found existing pair for STUN request: {:?}", pair);
1587
1588 } else {
1594 let local = &self.local_candidates[local_idx];
1596 let remote = &self.remote_candidates[remote_idx];
1597
1598 if local.discarded() {
1599 return; }
1601
1602 let prio = CandidatePair::calculate_prio(self.controlling, remote.prio(), local.prio());
1603
1604 let pair = CandidatePair::new(local_idx, local.kind(), remote_idx, remote.kind(), prio);
1608
1609 debug!("Created new pair for STUN request: {:?}", Pii(&pair));
1610
1611 self.candidate_pairs.push(pair);
1612 self.candidate_pairs.sort();
1613 }
1614
1615 let pair = self
1616 .candidate_pairs
1617 .iter_mut()
1618 .find(|p| p.local_idx() == local_idx && p.remote_idx() == remote_idx)
1619 .unwrap();
1621
1622 let local = pair.local_candidate(&self.local_candidates);
1623 let proto = local.proto();
1624 let local_addr = local.base();
1625 let remote = pair.remote_candidate(&self.remote_candidates);
1626 let remote_addr = remote.addr();
1627
1628 pair.increase_remote_binding_requests(req.now);
1629
1630 if self.ice_lite && !self.controlling {
1631 pair.record_remote_binding_request_success();
1650 }
1651
1652 if !self.controlling && !pair.is_nominated() && req.use_candidate {
1653 pair.nominate(self.ice_lite);
1658 }
1659
1660 let renominated = self.ice_lite && !self.controlling && req.use_candidate;
1668 if renominated {
1669 pair.record_use_candidate(req.now);
1670 }
1671
1672 if self.controlling && pair.state() == CheckState::Succeeded {
1673 self.evaluate_nomination(req.now);
1675 } else if renominated {
1676 self.evaluate_nomination(req.now);
1677 }
1678
1679 let (_, password) = self.stun_credentials(true);
1680
1681 let reply = StunMessage::binding_reply(req.trans_id, req.source);
1682
1683 trace!(
1684 "Send STUN reply: {} -> {} {:?}",
1685 local_addr, remote_addr, reply
1686 );
1687
1688 let mut buf = vec![0_u8; self.mtu()];
1689
1690 let sha1_hmac =
1691 |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads);
1692 let n = reply
1693 .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac)
1694 .expect("IO error writing STUN reply");
1695 buf.truncate(n);
1696
1697 let trans = Transmit {
1698 proto,
1699 source: local_addr,
1700 destination: remote_addr,
1701 contents: buf.into(),
1702 };
1703
1704 self.transmit.push_back(trans);
1705 }
1706
1707 fn send_role_conflict_reply(&mut self, req: &StunRequest) {
1708 let (_, password) = self.stun_credentials(true);
1709
1710 let reply = StunMessage::binding_role_conflict_reply(req.trans_id);
1711
1712 debug!(
1713 "Reply 487 Role Conflict (keep {} role): {} -> {}",
1714 role_name(self.controlling),
1715 req.destination,
1716 req.source,
1717 );
1718
1719 let mut buf = vec![0_u8; self.mtu()];
1720
1721 let sha1_hmac =
1722 |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads);
1723 let n = reply
1724 .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac)
1725 .expect("IO error writing STUN error reply");
1726 buf.truncate(n);
1727
1728 let trans = Transmit {
1729 proto: req.proto,
1730 source: req.destination,
1731 destination: req.source,
1732 contents: buf.into(),
1733 };
1734
1735 self.transmit.push_back(trans);
1736 }
1737
1738 fn switch_role(&mut self, controlling: bool) {
1741 if self.controlling == controlling {
1742 return;
1743 }
1744
1745 debug!(
1746 "Switch role: {} -> {}",
1747 role_name(self.controlling),
1748 role_name(controlling),
1749 );
1750
1751 self.controlling = controlling;
1752
1753 for i in 0..self.candidate_pairs.len() {
1754 let local_idx = self.candidate_pairs[i].local_idx();
1755 let remote_idx = self.candidate_pairs[i].remote_idx();
1756 let local_prio = self.local_candidates[local_idx].prio();
1757 let remote_prio = self.remote_candidates[remote_idx].prio();
1758 let new_prio = CandidatePair::calculate_prio(controlling, remote_prio, local_prio);
1759 self.candidate_pairs[i].set_prio(new_prio);
1760 }
1761 self.candidate_pairs.sort();
1762 }
1763
1764 fn stun_client_binding_request(&mut self, now: Instant, pair_idx: usize) {
1765 let (username, password) = self.stun_credentials(false);
1766
1767 let pair = &mut self.candidate_pairs[pair_idx];
1768 let local = pair.local_candidate(&self.local_candidates);
1769 let remote = pair.remote_candidate(&self.remote_candidates);
1770 let prio = local.prio_prflx();
1771 let use_candidate = self.controlling && pair.is_nominated();
1773
1774 let trans_id = pair.new_attempt(now, &self.timing_config, self.controlling);
1775
1776 self.stats.bind_request_sent += 1;
1777
1778 let binding = StunMessage::binding_request(
1779 &username,
1780 trans_id,
1781 self.controlling,
1782 self.control_tie_breaker,
1783 prio,
1784 use_candidate,
1785 );
1786
1787 trace!(
1788 "Send STUN request: {} -> {} {:?}",
1789 local.base(),
1790 remote.addr(),
1791 binding
1792 );
1793
1794 let mut buf = vec![0_u8; self.mtu()];
1795
1796 let sha1_hmac =
1797 |key: &[u8], payloads: &[&[u8]]| self.sha1_hmac_provider.sha1_hmac(key, payloads);
1798 let n = binding
1799 .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac)
1800 .expect("IO error writing STUN reply");
1801 buf.truncate(n);
1802
1803 let trans = Transmit {
1804 proto: local.proto(),
1805 source: local.base(),
1806 destination: remote.addr(),
1807 contents: buf.into(),
1808 };
1809
1810 self.transmit.push_back(trans);
1811 }
1812
1813 fn stun_client_handle_error(&mut self, message: StunMessage<'_>) {
1820 let Some((code, _)) = message.error_code() else {
1821 return;
1822 };
1823 if code != 487 {
1824 debug!("Ignoring binding error response with code {code}");
1825 return;
1826 }
1827
1828 let trans_id = message.trans_id();
1829 let attempt = self
1830 .candidate_pairs
1831 .iter()
1832 .find_map(|p| p.binding_attempt(trans_id));
1833
1834 let Some(attempt) = attempt else {
1835 debug!("Ignore 487 for unknown transaction id");
1836 return;
1837 };
1838
1839 if attempt.controlling() != self.controlling {
1840 debug!(
1841 "Ignore stale 487 (request was sent as {}, we are now {})",
1842 role_name(attempt.controlling()),
1843 role_name(self.controlling),
1844 );
1845 return;
1846 }
1847
1848 debug!(
1849 "Got 487 Role Conflict, switching from {}",
1850 role_name(self.controlling),
1851 );
1852 self.switch_role(!self.controlling);
1853 }
1854
1855 fn stun_client_handle_response(&mut self, now: Instant, message: StunMessage<'_>) {
1856 let trans_id = message.trans_id();
1858 let maybe_pair = self
1859 .candidate_pairs
1860 .iter_mut()
1861 .find(|p| p.binding_attempt(trans_id).is_some());
1862
1863 self.stats.bind_success_recv += 1;
1864
1865 let pair = match maybe_pair {
1866 Some(v) => v,
1867 None => {
1871 debug!("No pair found for STUN response: {:?}", message);
1872 return;
1873 }
1874 };
1875
1876 let mapped_address = message
1881 .mapped_address()
1882 .expect("Mapped address in STUN response");
1884
1885 let found_in_local = self
1886 .local_candidates
1887 .iter()
1888 .enumerate()
1889 .find(|(_, c)| c.addr() == mapped_address);
1890
1891 let (pair, valid_idx) = if let Some((valid_idx, _)) = found_in_local {
1892 trace!(
1897 "Found local candidate for mapped address: {}",
1898 mapped_address
1899 );
1900 (pair, valid_idx)
1901 } else {
1902 let local_sent_from = pair.local_candidate(&self.local_candidates);
1903
1904 let prio = local_sent_from.prio_prflx();
1915
1916 let base = local_sent_from.base();
1919
1920 let candidate = Candidate::peer_reflexive(
1922 local_sent_from.proto(),
1923 mapped_address,
1924 base,
1925 prio,
1926 None,
1927 self.local_credentials.ufrag.clone(),
1928 );
1929
1930 debug!(
1931 "Created local peer reflexive candidate for mapped address: {}",
1932 Pii(&mapped_address)
1933 );
1934
1935 self.local_candidates.push(candidate);
1946
1947 let idx = self.local_candidates.len() - 1;
1948
1949 (pair, idx)
1950 };
1951
1952 pair.record_binding_response(now, trans_id, valid_idx);
1953
1954 self.evaluate_nomination(now);
1956
1957 self.evaluate_state(now);
1959 }
1960
1961 fn evaluate_nomination(&mut self, now: Instant) {
1962 let nominated_pair_priority = self.nominated_pair_priority();
1963
1964 let best_prio = if self.controlling {
1965 self.candidate_pairs
1968 .iter_mut()
1969 .filter(|p| p.state() == CheckState::Succeeded)
1970 .max_by_key(|p| p.prio())
1971 } else if self.ice_lite {
1972 let fresh = |p: &CandidatePair| {
1980 p.last_use_candidate()
1981 .is_some_and(|t| now.saturating_duration_since(t) < LITE_NOMINATION_FRESH)
1982 };
1983 let any_fresh = self
1984 .candidate_pairs
1985 .iter()
1986 .any(|p| p.is_nominated() && fresh(p));
1987 self.candidate_pairs
1988 .iter_mut()
1989 .filter(|p| p.is_nominated() && (!any_fresh || fresh(p)))
1990 .max_by_key(|p| p.prio())
1991 } else {
1992 self.candidate_pairs
1998 .iter_mut()
1999 .filter(|p| p.is_nominated() && p.state() == CheckState::Succeeded)
2000 .max_by_key(|p| p.prio())
2001 };
2002
2003 if let Some(best_prio) = best_prio {
2004 if self.ice_lite && !self.controlling {
2005 if self.nominated_send == Some(best_prio.id()) {
2006 return;
2007 }
2008 } else if let Some(nominated) = nominated_pair_priority {
2009 if nominated == best_prio.prio() {
2010 return;
2014 }
2015 }
2016 trace!("Nominating best candidate");
2017
2018 if !best_prio.is_nominated() && (self.controlling || self.ice_lite) {
2019 best_prio.nominate(self.ice_lite);
2021 }
2022
2023 let local = best_prio.local_candidate(&self.local_candidates);
2024 let remote = best_prio.remote_candidate(&self.remote_candidates);
2025
2026 self.nominated_send = Some(best_prio.id());
2027 self.emit_event(IceAgentEvent::NominatedSend {
2028 proto: local.proto(),
2029 source: local.base(),
2030 destination: remote.addr(),
2031 })
2032 }
2033 }
2034
2035 fn nominated_pair_priority(&self) -> Option<u64> {
2036 let id = self.nominated_send?;
2037
2038 self.candidate_pairs
2039 .iter()
2040 .find_map(|p| (p.id() == id).then_some(p.prio()))
2041 }
2042
2043 fn nominated_pair(&self) -> Option<&CandidatePair> {
2044 let id = self.nominated_send?;
2045 self.candidate_pairs.iter().find(|p| p.id() == id)
2046 }
2047
2048 pub fn nominated_pair_rtt(&self) -> Option<Duration> {
2062 self.nominated_pair().and_then(|p| p.last_successful_rtt())
2063 }
2064
2065 pub fn nominated_pair_total_rtt(&self) -> Option<Duration> {
2076 self.nominated_pair().map(|p| p.total_round_trip_time())
2077 }
2078
2079 pub fn nominated_pair_responses_received(&self) -> Option<u64> {
2088 self.nominated_pair().map(|p| p.responses_received())
2089 }
2090
2091 fn set_connection_state(&mut self, state: IceConnectionState, reason: &'static str) {
2092 if self.state != state {
2093 debug!("State change ({}): {:?} -> {:?}", reason, self.state, state);
2094 self.state = state;
2095 self.emit_event(IceAgentEvent::IceConnectionStateChange(state));
2096 }
2097 }
2098
2099 fn evaluate_state(&mut self, now: Instant) {
2100 use IceConnectionState::*;
2101
2102 let mut any_nomination = false;
2103 let mut any_still_possible = false;
2104
2105 for p in &self.candidate_pairs {
2106 if p.is_nominated() && p.state() == CheckState::Succeeded {
2110 any_nomination = true;
2111 } else if p.is_still_possible(now, &self.timing_config) {
2112 any_still_possible = true;
2113 }
2114 }
2115
2116 if self.remote_candidates.is_empty() || self.local_candidates.is_empty() {
2120 any_still_possible = true;
2121 }
2122
2123 match self.state {
2124 New => {
2125 self.set_connection_state(Checking, "new connection");
2126 }
2127 Checking | Disconnected => {
2128 if any_nomination {
2129 if self.ice_lite {
2130 self.set_connection_state(Completed, "got nomination in ice lite");
2131 return;
2132 }
2133 if any_still_possible {
2134 self.set_connection_state(Connected, "got nomination, still trying others");
2135 } else {
2136 self.set_connection_state(Completed, "got nomination, no others to try");
2137 }
2138 } else if !any_still_possible {
2139 self.set_connection_state(Disconnected, "no possible pairs");
2140 } else {
2141 self.set_connection_state(Checking, "got new possible");
2142 }
2143 }
2144 Connected => {
2145 if any_nomination {
2146 if !any_still_possible {
2147 self.set_connection_state(Completed, "no more possible to try");
2148 }
2149 } else if any_still_possible {
2150 self.set_connection_state(Checking, "got new possible");
2151 } else {
2152 self.set_connection_state(Disconnected, "none nominated");
2153 }
2154 }
2155 Completed => {
2156 if any_nomination {
2157 if any_still_possible && !self.ice_lite {
2158 self.set_connection_state(Connected, "got new possible");
2159 }
2160 } else if any_still_possible {
2161 self.set_connection_state(Checking, "got new possible");
2162 } else {
2163 self.set_connection_state(Disconnected, "none nominated");
2164 }
2165 }
2166 }
2167 }
2168}
2169
2170impl fmt::Debug for LocalPreferenceHolder {
2171 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
2172 f.debug_tuple("LocalPreferenceHolder").finish()
2173 }
2174}
2175
2176#[cfg(test)]
2177mod test {
2178 use super::*;
2179 use crate::DefaultSha1HmacProvider;
2180 use std::{iter, net::SocketAddr};
2181
2182 fn host(s: impl Into<String>, proto: impl TryInto<Protocol>) -> Candidate {
2183 let s: String = s.into();
2184 Candidate::host(s.parse().unwrap(), proto).unwrap()
2185 }
2186
2187 impl IceAgent {
2188 pub(crate) fn num_candidate_pairs(&self) -> usize {
2189 self.candidate_pairs.len()
2190 }
2191
2192 fn pair_indexes(&self) -> Vec<(usize, usize)> {
2193 self.candidate_pairs
2194 .iter()
2195 .map(|c| (c.local_idx(), c.remote_idx()))
2196 .collect()
2197 }
2198 }
2199
2200 fn new_test_agent() -> IceAgent {
2201 IceAgent::new(IceCreds::new())
2202 }
2203
2204 fn ipv4_1() -> SocketAddr {
2205 "1.2.3.4:5000".parse().unwrap()
2206 }
2207 fn ipv4_2() -> SocketAddr {
2208 "2.3.4.5:5000".parse().unwrap()
2209 }
2210 fn ipv4_3() -> SocketAddr {
2211 "3.4.5.6:5000".parse().unwrap()
2212 }
2213 fn ipv4_4() -> SocketAddr {
2214 "4.5.6.7:5000".parse().unwrap()
2215 }
2216 fn ipv6_1() -> SocketAddr {
2217 "[1001::]:5000".parse().unwrap()
2218 }
2219 fn ipv6_2() -> SocketAddr {
2220 "[1002::]:5000".parse().unwrap()
2221 }
2222
2223 #[test]
2224 fn local_preference_host() {
2225 let mut agent = new_test_agent();
2226
2227 agent
2228 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2229 .unwrap();
2230 agent
2231 .add_local_candidate(Candidate::host(ipv6_1(), "udp").unwrap())
2232 .unwrap();
2233 agent
2234 .add_local_candidate(Candidate::host(ipv6_2(), "udp").unwrap())
2235 .unwrap();
2236 agent
2237 .add_local_candidate(Candidate::host(ipv4_2(), "udp").unwrap())
2238 .unwrap();
2239
2240 let v: Vec<_> = agent
2241 .local_candidates
2242 .iter()
2243 .map(|c| c.local_preference())
2244 .collect();
2245
2246 assert_eq!(v, vec![65534, 65535, 65533, 65532]);
2247 }
2248
2249 #[test]
2250 fn discard_adding_redundant() {
2251 let mut agent = new_test_agent();
2252
2253 let x2 = agent.add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap());
2257 assert!(x2.is_some());
2258
2259 let x1 = agent.add_local_candidate(Candidate::test_peer_rflx(ipv4_1(), ipv4_1(), "udp"));
2261 assert!(x1.is_none());
2262 }
2263
2264 #[test]
2265 fn does_not_invalidate_local_candidate_with_same_ip_but_different_kind() {
2266 let mut agent = new_test_agent();
2267 let host = Candidate::host(ipv4_1(), "udp").unwrap();
2268 let srflx = Candidate::server_reflexive(ipv4_1(), ipv4_1(), "udp").unwrap();
2269
2270 agent.add_local_candidate(host.clone()).unwrap();
2271 let invalidated = agent.invalidate_candidate(&srflx);
2272 assert!(!invalidated);
2273
2274 let invalidated = agent.invalidate_candidate(&host);
2275 assert!(invalidated);
2276 }
2277
2278 #[test]
2279 fn does_not_invalidate_local_candidate_with_same_ip_but_different_protocol() {
2280 let mut agent = new_test_agent();
2281 let udp = Candidate::host(ipv4_1(), "udp").unwrap();
2282 let tcp = Candidate::host(ipv4_1(), "tcp").unwrap();
2283
2284 agent.add_local_candidate(udp.clone()).unwrap();
2285 agent.add_local_candidate(tcp.clone()).unwrap();
2286
2287 let invalidated = agent.invalidate_candidate(&tcp);
2288 assert!(invalidated);
2289
2290 let udp_discarded = agent
2291 .local_candidates
2292 .iter()
2293 .find(|v| {
2294 v.addr() == udp.addr()
2295 && v.base() == udp.base()
2296 && v.raddr() == udp.raddr()
2297 && v.kind() == udp.kind()
2298 && v.proto() == udp.proto()
2299 })
2300 .unwrap()
2301 .discarded();
2302 assert!(!udp_discarded);
2303
2304 let tcp_discarded = agent
2305 .local_candidates
2306 .iter()
2307 .find(|v| {
2308 v.addr() == tcp.addr()
2309 && v.base() == tcp.base()
2310 && v.raddr() == tcp.raddr()
2311 && v.kind() == tcp.kind()
2312 && v.proto() == tcp.proto()
2313 })
2314 .unwrap()
2315 .discarded();
2316 assert!(tcp_discarded);
2317
2318 let invalidated = agent.invalidate_candidate(&udp);
2319 assert!(invalidated);
2320 let udp_discarded = agent
2321 .local_candidates
2322 .iter()
2323 .find(|v| {
2324 v.addr() == udp.addr()
2325 && v.base() == udp.base()
2326 && v.raddr() == udp.raddr()
2327 && v.kind() == udp.kind()
2328 && v.proto() == udp.proto()
2329 })
2330 .unwrap()
2331 .discarded();
2332 assert!(udp_discarded);
2333 }
2334
2335 #[test]
2336 fn does_not_invalidate_remote_candidate_with_same_ip_but_different_kind() {
2337 let mut agent = new_test_agent();
2338 let host = Candidate::host(ipv4_1(), "udp").unwrap();
2339 let srflx = Candidate::server_reflexive(ipv4_1(), ipv4_1(), "udp").unwrap();
2340
2341 agent.add_remote_candidate(host.clone());
2342 let invalidated = agent.invalidate_candidate(&srflx);
2343
2344 assert!(!invalidated);
2345
2346 let invalidated = agent.invalidate_candidate(&host);
2347 assert!(invalidated);
2348 }
2349
2350 #[test]
2351 fn does_not_invalidate_remote_candidate_with_same_ip_but_different_protocol() {
2352 let mut agent = new_test_agent();
2353 let udp = Candidate::host(ipv4_1(), "udp").unwrap();
2354 let tcp = Candidate::host(ipv4_1(), "tcp").unwrap();
2355
2356 agent.add_remote_candidate(udp.clone());
2357 agent.add_remote_candidate(tcp.clone());
2358
2359 let invalidated = agent.invalidate_candidate(&tcp);
2360 assert!(invalidated);
2361
2362 let udp_discarded = agent
2363 .remote_candidates
2364 .iter()
2365 .find(|v| {
2366 v.addr() == udp.addr()
2367 && v.base() == udp.base()
2368 && v.raddr() == udp.raddr()
2369 && v.kind() == udp.kind()
2370 && v.proto() == udp.proto()
2371 })
2372 .unwrap()
2373 .discarded();
2374 assert!(!udp_discarded);
2375
2376 let tcp_discarded = agent
2377 .remote_candidates
2378 .iter()
2379 .find(|v| {
2380 v.addr() == tcp.addr()
2381 && v.base() == tcp.base()
2382 && v.raddr() == tcp.raddr()
2383 && v.kind() == tcp.kind()
2384 && v.proto() == tcp.proto()
2385 })
2386 .unwrap()
2387 .discarded();
2388 assert!(tcp_discarded);
2389
2390 let invalidated = agent.invalidate_candidate(&udp);
2391 assert!(invalidated);
2392 let udp_discarded = agent
2393 .remote_candidates
2394 .iter()
2395 .find(|v| {
2396 v.addr() == udp.addr()
2397 && v.base() == udp.base()
2398 && v.raddr() == udp.raddr()
2399 && v.kind() == udp.kind()
2400 && v.proto() == udp.proto()
2401 })
2402 .unwrap()
2403 .discarded();
2404 assert!(udp_discarded);
2405 }
2406
2407 #[test]
2408 fn discard_adding_redundant_by_address_and_protocol() {
2409 let mut agent = new_test_agent();
2410
2411 assert!(
2413 agent
2414 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2415 .is_some()
2416 );
2417 assert!(
2418 agent
2419 .add_local_candidate(Candidate::host(ipv4_1(), "tcp").unwrap())
2420 .is_some()
2421 );
2422 assert!(
2423 agent
2424 .add_local_candidate(Candidate::host(ipv4_1(), "ssltcp").unwrap())
2425 .is_some()
2426 );
2427
2428 assert!(
2430 agent
2431 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2432 .is_none()
2433 );
2434 assert!(
2435 agent
2436 .add_local_candidate(Candidate::host(ipv4_1(), "ssltcp").unwrap())
2437 .is_none()
2438 );
2439
2440 assert!(
2442 agent
2443 .add_local_candidate(Candidate::host(ipv4_2(), "udp").unwrap())
2444 .is_some()
2445 );
2446 assert!(
2447 agent
2448 .add_local_candidate(Candidate::host(ipv4_2(), "ssltcp").unwrap())
2449 .is_some()
2450 );
2451 }
2452
2453 #[test]
2454 fn discard_already_added_redundant() {
2455 let mut agent = new_test_agent();
2456
2457 let x1 = agent.add_local_candidate(Candidate::test_peer_rflx(ipv4_1(), ipv4_1(), "udp"));
2462 assert!(x1.is_some());
2463
2464 let x2 = agent.add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap());
2465 assert!(x2.is_some());
2466
2467 let v: Vec<_> = agent
2468 .local_candidates
2469 .iter()
2470 .map(|v| v.discarded())
2471 .collect();
2472
2473 assert_eq!(v, vec![true, false]);
2474 }
2475
2476 #[test]
2477 fn form_pairs() {
2478 let mut agent = new_test_agent();
2479
2480 agent
2482 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2483 .unwrap();
2484 agent
2486 .add_local_candidate(Candidate::test_peer_rflx(ipv4_4(), ipv4_2(), "udp"))
2487 .unwrap();
2488 agent
2490 .add_local_candidate(Candidate::host(ipv4_1(), "tcp").unwrap())
2491 .unwrap();
2492
2493 agent.add_remote_candidate(Candidate::test_peer_rflx(ipv4_4(), ipv4_3(), "udp"));
2495 agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2497 agent.add_remote_candidate(Candidate::host(ipv4_3(), "tcp").unwrap());
2499
2500 assert_eq!(
2508 agent.pair_indexes(),
2509 [(0, 1), (0, 0), (1, 1), (1, 0), (2, 2)]
2510 );
2511 }
2512
2513 #[test]
2514 fn form_pairs_skip_redundant() {
2515 let mut agent = new_test_agent();
2516
2517 agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2518 agent.add_remote_candidate(Candidate::host(ipv4_3(), "tcp").unwrap());
2519 agent
2520 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2521 .unwrap();
2522
2523 assert_eq!(agent.pair_indexes(), [(0, 0)]);
2525
2526 agent
2528 .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp"))
2529 .unwrap();
2530
2531 assert_eq!(agent.pair_indexes(), [(0, 0)]);
2532
2533 agent
2535 .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "tcp"))
2536 .unwrap();
2537
2538 assert_eq!(agent.pair_indexes(), [(0, 0), (2, 1)]);
2539 }
2540
2541 #[test]
2542 fn form_pairs_replace_redundant() {
2543 let mut agent = new_test_agent();
2544
2545 agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2546 agent
2547 .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp"))
2548 .unwrap();
2549
2550 assert_eq!(agent.pair_indexes(), [(0, 0)]);
2551
2552 agent
2555 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2556 .unwrap();
2557
2558 assert_eq!(agent.pair_indexes(), [(1, 0)]);
2559 }
2560
2561 #[test]
2562 fn form_pairs_replace_remote_redundant() {
2563 let mut agent = new_test_agent();
2564 agent.set_ice_lite(true);
2565
2566 let c = Candidate::peer_reflexive(
2568 "udp",
2569 ipv4_3(),
2570 ipv4_3(),
2571 123,
2572 Some(REMOTE_PEER_REFLEXIVE_TEMP_FOUNDATION.into()),
2573 "".to_string(),
2574 );
2575
2576 agent.add_remote_candidate(c);
2577 agent
2578 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2579 .unwrap();
2580
2581 assert_eq!(agent.pair_indexes(), [(0, 0)]);
2582
2583 let now = Instant::now();
2584 agent.candidate_pairs[0].nominate(true);
2585 agent.candidate_pairs[0].increase_remote_binding_requests(now);
2586
2587 agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2589
2590 assert_eq!(agent.pair_indexes(), [(0, 0)]);
2592
2593 let pair = &agent.candidate_pairs[0];
2594 assert!(pair.is_nominated());
2595
2596 let (req, time) = pair.remote_binding_requests();
2597 assert_eq!(req, 1);
2598 assert_eq!(time, Some(now));
2599 }
2600
2601 #[test]
2602 fn form_pairs_skip_invalidated_local() {
2603 let mut agent = new_test_agent();
2604
2605 let local = Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp");
2606
2607 agent.add_local_candidate(local.clone()).unwrap();
2608 agent.invalidate_candidate(&local);
2609
2610 agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2611
2612 assert_eq!(agent.pair_indexes(), []);
2614 }
2615
2616 #[test]
2617 fn form_pairs_skip_invalidated_remote() {
2618 let mut agent = new_test_agent();
2619
2620 let remote = Candidate::host(ipv4_3(), "udp").unwrap();
2621
2622 agent.add_remote_candidate(remote.clone());
2623 agent.invalidate_candidate(&remote);
2624
2625 agent
2626 .add_local_candidate(Candidate::test_peer_rflx(ipv4_2(), ipv4_1(), "udp"))
2627 .unwrap();
2628
2629 assert_eq!(agent.pair_indexes(), []);
2631 }
2632
2633 #[test]
2634 fn poll_time_must_timing_advance() {
2635 let mut agent = new_test_agent();
2636 agent
2637 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2638 .unwrap();
2639 agent.add_remote_candidate(Candidate::host(ipv4_3(), "udp").unwrap());
2640
2641 let now1 = Instant::now();
2642 agent.handle_timeout(now1);
2643 let now2 = agent.poll_timeout().unwrap();
2644
2645 assert!(now2 - now1 == Duration::from_millis(50));
2646 }
2647
2648 #[test]
2649 fn no_disconnect_before_remote_candidates() {
2650 let mut agent = new_test_agent();
2651
2652 let now = Instant::now();
2653 agent.handle_timeout(now);
2654
2655 while let Some(ev) = agent.poll_event() {
2656 if let IceAgentEvent::IceConnectionStateChange(s) = ev {
2657 assert!(s != IceConnectionState::Disconnected);
2658 }
2659 }
2660
2661 agent.handle_timeout(now + Duration::from_millis(200));
2662 while let Some(ev) = agent.poll_event() {
2663 if let IceAgentEvent::IceConnectionStateChange(s) = ev {
2664 assert!(s != IceConnectionState::Disconnected);
2665 }
2666 }
2667 }
2668
2669 #[test]
2670 fn does_not_accept_response_with_unknown_transaction_id() {
2671 let mut agent = new_test_agent();
2672 let remote_creds = IceCreds::new();
2673 let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
2674 remote_candidate.set_ufrag(&remote_creds.ufrag);
2675
2676 agent.set_remote_credentials(remote_creds.clone());
2677 agent
2678 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2679 .unwrap();
2680 agent.add_remote_candidate(remote_candidate);
2681 agent.handle_timeout(Instant::now());
2682
2683 let payload = Vec::from(agent.poll_transmit().unwrap().contents);
2684 let stun_message = StunMessage::parse(&payload).unwrap();
2685
2686 let valid_reply =
2687 make_authenticated_stun_reply(stun_message.trans_id(), ipv4_4(), &remote_creds.pass);
2688 let fake_reply =
2689 make_authenticated_stun_reply(TransId::new(), ipv4_4(), &remote_creds.pass);
2690
2691 assert!(!agent.accepts_message(&StunMessage::parse(&fake_reply).unwrap()));
2692 assert!(agent.accepts_message(&StunMessage::parse(&valid_reply).unwrap()));
2693 }
2694
2695 #[test]
2696 fn ignore_binding_indication() {
2697 const BINDING: &[u8] = &[
2712 0x00, 0x11, 0x00, 0x08, 0x21, 0x12, 0xa4, 0x42, 0xfb, 0x98, 0x59, 0xe6, 0x7d, 0xa4,
2713 0xbc, 0x99, 0x1c, 0x0c, 0xab, 0x8f, 0x80, 0x28, 0x00, 0x04, 0xed, 0x80, 0xc2, 0x97,
2714 ];
2715 let stun_msg = StunMessage::parse(BINDING).unwrap();
2716
2717 let agent = new_test_agent();
2718 assert!(!agent.accepts_message(&stun_msg));
2719 }
2720
2721 #[test]
2722 fn queues_stun_binding_before_remote_creds() {
2723 let mut agent = new_test_agent();
2724 agent
2725 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2726 .unwrap();
2727
2728 let remote_creds = IceCreds::new();
2729 let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
2730 remote_candidate.set_ufrag(&remote_creds.ufrag);
2731 let prio = remote_candidate.prio();
2732 agent.add_remote_candidate(remote_candidate);
2733
2734 let serialized_req = make_serialized_binding_request(
2735 &agent.local_credentials,
2736 &remote_creds,
2737 !agent.controlling(),
2738 prio,
2739 );
2740 let binding_req = StunMessage::parse(&serialized_req).unwrap();
2741
2742 assert!(agent.accepts_message(&binding_req));
2744 agent.handle_packet(
2745 Instant::now(),
2746 StunPacket {
2747 message: binding_req,
2748 source: ipv4_3(),
2749 destination: ipv4_1(),
2750 proto: Protocol::Udp,
2751 },
2752 );
2753
2754 agent.handle_timeout(Instant::now());
2756 assert!(agent.poll_transmit().is_none());
2757
2758 agent.set_remote_credentials(remote_creds.clone());
2759 agent.handle_timeout(Instant::now());
2760
2761 let payload = Vec::from(agent.poll_transmit().unwrap().contents);
2763 let stun_message = StunMessage::parse(&payload).unwrap();
2764 assert!(stun_message.is_successful_binding_response());
2765 }
2766
2767 #[test]
2774 pub fn ignores_stale_487_after_role_swap() {
2775 let mut agent = new_test_agent();
2776 agent.set_controlling(true);
2777 let remote_creds = IceCreds::new();
2778 agent.set_remote_credentials(remote_creds.clone());
2779 agent
2780 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2781 .unwrap();
2782 let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
2783 remote_candidate.set_ufrag(&remote_creds.ufrag);
2784 agent.add_remote_candidate(remote_candidate);
2785
2786 agent.handle_timeout(Instant::now());
2788 let req_payload = Vec::from(agent.poll_transmit().unwrap().contents);
2789 let trans_id = StunMessage::parse(&req_payload).unwrap().trans_id();
2790
2791 agent.set_controlling(false);
2794
2795 let reply = make_role_conflict_reply(trans_id, &remote_creds.pass);
2798 agent.handle_packet(
2799 Instant::now(),
2800 StunPacket {
2801 proto: Protocol::Udp,
2802 source: ipv4_3(),
2803 destination: ipv4_1(),
2804 message: StunMessage::parse(&reply).unwrap(),
2805 },
2806 );
2807
2808 assert!(
2809 !agent.controlling(),
2810 "stale 487 must not flip role back to controlling"
2811 );
2812 }
2813
2814 #[test]
2815 pub fn discards_packet_from_unknown_candidate() {
2816 let mut agent = new_test_agent();
2817 let remote_creds = IceCreds::new();
2818 agent.set_remote_credentials(remote_creds.clone());
2819
2820 let request =
2821 make_serialized_binding_request(&agent.local_credentials, &remote_creds, false, 0);
2822
2823 agent.handle_packet(
2824 Instant::now(),
2825 StunPacket {
2826 proto: Protocol::Udp,
2827 source: ipv4_1(),
2828 destination: ipv4_2(),
2829 message: StunMessage::parse(&request).unwrap(),
2830 },
2831 );
2832
2833 assert!(agent.poll_transmit().is_none());
2834 }
2835
2836 #[test]
2837 fn ignores_remote_candidates_that_cant_reach_the_peer() {
2838 for addr in [
2839 "3.4.5.6 0",
2840 "0.0.0.0 5000",
2841 ":: 5000",
2842 "::ffff:0.0.0.0 5000",
2843 ] {
2844 let mut agent = new_test_agent();
2845 agent.set_remote_credentials(IceCreds::new());
2846 for local in [ipv4_1(), ipv6_1()] {
2847 agent
2848 .add_local_candidate(Candidate::host(local, "udp").unwrap())
2849 .unwrap();
2850 }
2851
2852 let sdp = format!("candidate:1 1 udp 2130706431 {addr} typ host");
2853 agent.add_remote_candidate(Candidate::from_sdp_string(&sdp).unwrap());
2854
2855 assert_eq!(agent.remote_candidates().count(), 0, "{addr}");
2856 assert_eq!(agent.num_candidate_pairs(), 0, "{addr}");
2857 agent.handle_timeout(Instant::now());
2858 assert!(agent.poll_transmit().is_none(), "{addr}");
2859 }
2860 }
2861
2862 #[test]
2863 fn ignores_binding_requests_from_addresses_that_cant_be_replied_to() {
2864 for (source, destination) in [
2865 ("3.4.5.6:0", ipv4_1()),
2866 ("0.0.0.0:5000", ipv4_1()),
2867 ("[::]:5000", ipv6_1()),
2868 ("[::ffff:0.0.0.0]:5000", ipv6_1()),
2869 ] {
2870 let mut agent = new_test_agent();
2871 for local in [ipv4_1(), ipv6_1()] {
2872 agent
2873 .add_local_candidate(Candidate::host(local, "udp").unwrap())
2874 .unwrap();
2875 }
2876 let remote_creds = IceCreds::new();
2877 agent.set_remote_credentials(remote_creds.clone());
2878
2879 let request = make_serialized_binding_request(
2880 &agent.local_credentials,
2881 &remote_creds,
2882 !agent.controlling(),
2883 1,
2884 );
2885
2886 agent.handle_packet(
2887 Instant::now(),
2888 StunPacket {
2889 proto: Protocol::Udp,
2890 source: source.parse().unwrap(),
2891 destination,
2892 message: StunMessage::parse(&request).unwrap(),
2893 },
2894 );
2895
2896 assert_eq!(agent.remote_candidates().count(), 0, "{source}");
2898 assert!(agent.poll_transmit().is_none(), "{source}");
2899 }
2900 }
2901
2902 #[test]
2903 pub fn no_disconnect_missing_local_candidates() {
2904 let mut agent = new_test_agent();
2905 agent.set_remote_credentials(IceCreds::new().clone());
2906
2907 agent.add_remote_candidate(host("1.1.1.1:1000", "udp"));
2908 agent.handle_timeout(Instant::now());
2909 agent.handle_timeout(Instant::now() + Duration::from_millis(100));
2910
2911 let events = iter::from_fn(|| agent.poll_event()).collect::<Vec<_>>();
2912 assert!(!events.contains(&IceAgentEvent::IceConnectionStateChange(
2913 IceConnectionState::Disconnected
2914 )));
2915 }
2916
2917 #[test]
2918 fn discarded_local_candidates_are_not_returned() {
2919 let mut agent = new_test_agent();
2920 let host1 = Candidate::host(ipv4_1(), "udp").unwrap();
2921 let host2 = Candidate::host(ipv4_2(), "udp").unwrap();
2922
2923 let host1 = agent.add_local_candidate(host1.clone()).unwrap().clone();
2924 let host2 = agent.add_local_candidate(host2.clone()).unwrap().clone();
2925 agent.invalidate_candidate(&host1);
2926
2927 assert_eq!(agent.local_candidates().collect::<Vec<_>>(), vec![host2]);
2928 }
2929
2930 #[test]
2931 fn discarded_remote_candidates_are_not_returned() {
2932 let mut agent = new_test_agent();
2933 let host1 = Candidate::host(ipv4_1(), "udp").unwrap();
2934 let host2 = Candidate::host(ipv4_2(), "udp").unwrap();
2935
2936 agent.add_remote_candidate(host1.clone());
2937 agent.add_remote_candidate(host2.clone());
2938 agent.invalidate_candidate(&host1);
2939
2940 assert_eq!(agent.remote_candidates().collect::<Vec<_>>(), vec![host2]);
2941 }
2942
2943 #[test]
2944 fn ice_lite_remote_candidate_viable_after_binding_request() {
2945 let mut agent = new_test_agent();
2946 agent.set_ice_lite(true);
2947 agent.set_controlling(false);
2948 agent
2949 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2950 .unwrap();
2951
2952 let remote_creds = IceCreds::new();
2953 agent.set_remote_credentials(remote_creds.clone());
2954
2955 let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
2956 remote_candidate.set_ufrag(&remote_creds.ufrag);
2957 let prio = remote_candidate.prio();
2958 agent.add_remote_candidate(remote_candidate);
2959
2960 assert!(!agent.has_viable_remote_candidate(ipv4_3()));
2962
2963 let serialized_req = make_serialized_binding_request(
2964 &agent.local_credentials,
2965 &remote_creds,
2966 true, prio,
2968 );
2969 let binding_req = StunMessage::parse(&serialized_req).unwrap();
2970
2971 let now = Instant::now();
2972 assert!(agent.handle_packet(
2973 now,
2974 StunPacket {
2975 message: binding_req,
2976 source: ipv4_3(),
2977 destination: ipv4_1(),
2978 proto: Protocol::Udp,
2979 },
2980 ));
2981
2982 assert!(agent.has_viable_remote_candidate(ipv4_3()));
2987 }
2988
2989 #[test]
2990 fn ice_lite_validation_survives_trickle() {
2991 let mut agent = new_test_agent();
2992 agent.set_ice_lite(true);
2993 agent.set_controlling(false);
2994 agent
2995 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
2996 .unwrap();
2997 let remote_creds = IceCreds::new();
2998 agent.set_remote_credentials(remote_creds.clone());
2999 let remote = Candidate::host(ipv4_3(), "udp").unwrap();
3001 let serialized = make_serialized_binding_request(
3002 &agent.local_credentials,
3003 &remote_creds,
3004 true,
3005 remote.prio() - 1,
3006 );
3007 assert!(agent.handle_packet(
3008 Instant::now(),
3009 StunPacket {
3010 message: StunMessage::parse(&serialized).unwrap(),
3011 source: ipv4_3(),
3012 destination: ipv4_1(),
3013 proto: Protocol::Udp,
3014 }
3015 ));
3016 assert!(agent.has_viable_remote_candidate(ipv4_3()));
3017 agent.add_remote_candidate(remote);
3019 assert!(
3020 agent.has_viable_remote_candidate(ipv4_3()),
3021 "trickling the real candidate must retain validated ingress"
3022 );
3023 }
3024
3025 #[test]
3026 fn ice_lite_controlling_does_not_nominate_on_a_binding_request() {
3027 let mut agent = new_test_agent();
3033 agent.set_ice_lite(true);
3034 agent.set_controlling(true);
3035 agent
3036 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
3037 .unwrap();
3038
3039 let remote_creds = IceCreds::new();
3040 agent.set_remote_credentials(remote_creds.clone());
3041
3042 let mut remote_candidate = Candidate::host(ipv4_3(), "udp").unwrap();
3043 remote_candidate.set_ufrag(&remote_creds.ufrag);
3044 let prio = remote_candidate.prio();
3045 agent.add_remote_candidate(remote_candidate);
3046
3047 let serialized_req = make_serialized_binding_request(
3048 &agent.local_credentials,
3049 &remote_creds,
3050 false, prio,
3052 );
3053 let binding_req = StunMessage::parse(&serialized_req).unwrap();
3054
3055 assert!(agent.handle_packet(
3056 Instant::now(),
3057 StunPacket {
3058 message: binding_req,
3059 source: ipv4_3(),
3060 destination: ipv4_1(),
3061 proto: Protocol::Udp,
3062 },
3063 ));
3064
3065 assert!(!agent.has_viable_remote_candidate(ipv4_3()));
3066 assert!(
3067 !agent
3068 .events
3069 .iter()
3070 .any(|e| matches!(e, IceAgentEvent::NominatedSend { .. })),
3071 "a single binding request must not choose the send address"
3072 );
3073 }
3074
3075 #[test]
3076 fn ice_lite_controlled_follows_a_fresh_nomination() {
3077 let mut agent = new_test_agent();
3085 agent.set_ice_lite(true);
3086 agent.set_controlling(false);
3087 agent
3088 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
3089 .unwrap();
3090 let remote_creds = IceCreds::new();
3091 agent.set_remote_credentials(remote_creds.clone());
3092 let mut host = Candidate::host(ipv4_3(), "udp").unwrap();
3093 host.set_ufrag(&remote_creds.ufrag);
3094 let host_prio = host.prio();
3095 agent.add_remote_candidate(host);
3096
3097 let nominate = |agent: &mut IceAgent, now: Instant, source: SocketAddr, prio: u32| {
3098 let username = format!("{}:{}", agent.local_credentials.ufrag, remote_creds.ufrag);
3099 let req = StunMessage::binding_request(&username, TransId::new(), true, 0, prio, true);
3100 let bytes = serialize_stun_msg(req, &agent.local_credentials.pass);
3101 assert!(agent.handle_packet(
3102 now,
3103 StunPacket {
3104 message: StunMessage::parse(&bytes).unwrap(),
3105 source,
3106 destination: ipv4_1(),
3107 proto: Protocol::Udp,
3108 },
3109 ));
3110 };
3111 let sends_to = |agent: &IceAgent| {
3112 agent.events.iter().rev().find_map(|e| match e {
3113 IceAgentEvent::NominatedSend { destination, .. } => Some(*destination),
3114 _ => None,
3115 })
3116 };
3117
3118 let t0 = Instant::now();
3119 nominate(&mut agent, t0, ipv4_3(), host_prio);
3120 assert_eq!(sends_to(&agent), Some(ipv4_3()));
3121
3122 let rebound = SocketAddr::new(ipv4_3().ip(), ipv4_3().port() + 1);
3125 nominate(
3126 &mut agent,
3127 t0 + Duration::from_secs(1),
3128 rebound,
3129 host_prio - 1000,
3130 );
3131 assert_eq!(sends_to(&agent), Some(ipv4_3()));
3132
3133 agent.handle_timeout(t0 + LITE_NOMINATION_FRESH + Duration::from_millis(100));
3135 assert_eq!(
3136 sends_to(&agent),
3137 Some(rebound),
3138 "egress follows the pair still nominated"
3139 );
3140
3141 nominate(&mut agent, t0 + Duration::from_secs(4), ipv4_3(), host_prio);
3144 assert_eq!(sends_to(&agent), Some(ipv4_3()));
3145 }
3146
3147 #[test]
3148 fn ice_lite_controlled_picks_only_succeeded_pairs() {
3149 let mut agent = new_test_agent();
3155 agent.set_ice_lite(true);
3156 agent.set_controlling(false);
3157 agent
3158 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
3159 .unwrap();
3160 let remote_creds = IceCreds::new();
3161 agent.set_remote_credentials(remote_creds.clone());
3162
3163 let mut silent =
3165 Candidate::from_sdp_string("candidate:1 1 udp 2130706431 3.4.5.6 5000 typ host")
3166 .unwrap();
3167 silent.set_ufrag(&remote_creds.ufrag);
3168 let silent_addr = silent.addr();
3169 agent.add_remote_candidate(silent);
3170
3171 let request = |agent: &mut IceAgent, now: Instant, source: SocketAddr, nominate: bool| {
3172 let username = format!("{}:{}", agent.local_credentials.ufrag, remote_creds.ufrag);
3173 let req =
3174 StunMessage::binding_request(&username, TransId::new(), true, 0, 1000, nominate);
3175 let bytes = serialize_stun_msg(req, &agent.local_credentials.pass);
3176 assert!(agent.handle_packet(
3177 now,
3178 StunPacket {
3179 message: StunMessage::parse(&bytes).unwrap(),
3180 source,
3181 destination: ipv4_1(),
3182 proto: Protocol::Udp,
3183 },
3184 ));
3185 };
3186 let sends_to = |agent: &IceAgent| {
3187 agent.events.iter().rev().find_map(|e| match e {
3188 IceAgentEvent::NominatedSend { destination, .. } => Some(*destination),
3189 _ => None,
3190 })
3191 };
3192 let send_pair_succeeded = |agent: &IceAgent| {
3193 let id = agent.nominated_send.expect("a send pair");
3194 let pair = agent
3195 .candidate_pairs
3196 .iter()
3197 .find(|p| p.id() == id)
3198 .expect("the send pair exists");
3199 pair.state() == CheckState::Succeeded && pair.is_nominated()
3200 };
3201
3202 let t0 = Instant::now();
3203 agent.handle_timeout(t0);
3204 assert_eq!(sends_to(&agent), None, "nothing to send on yet");
3205
3206 request(&mut agent, t0, ipv4_4(), false);
3208 agent.handle_timeout(t0 + Duration::from_millis(100));
3209 assert_eq!(sends_to(&agent), None, "a pair that was not nominated");
3210
3211 request(&mut agent, t0 + Duration::from_millis(200), ipv4_2(), true);
3213 assert_eq!(sends_to(&agent), Some(ipv4_2()));
3214 assert!(send_pair_succeeded(&agent));
3215
3216 for ms in [500, 2_000, 5_000] {
3217 agent.handle_timeout(t0 + Duration::from_millis(ms));
3218 assert_ne!(sends_to(&agent), Some(silent_addr), "at {ms} ms");
3219 assert_ne!(sends_to(&agent), Some(ipv4_4()), "at {ms} ms");
3220 if agent.nominated_send.is_some() {
3221 assert!(send_pair_succeeded(&agent), "at {ms} ms");
3222 }
3223 }
3224 }
3225
3226 #[test]
3227 fn controlled_sends_only_on_a_nominated_pair_whose_check_succeeded() {
3228 let mut agent = new_test_agent();
3234 agent.set_controlling(false);
3235 agent
3236 .add_local_candidate(Candidate::host(ipv4_1(), "udp").unwrap())
3237 .unwrap();
3238
3239 let remote_creds = IceCreds::new();
3240 agent.set_remote_credentials(remote_creds.clone());
3241
3242 let mut dead =
3243 Candidate::from_sdp_string("candidate:1 1 udp 2130706431 3.4.5.6 5000 typ host")
3244 .unwrap();
3245 dead.set_ufrag(&remote_creds.ufrag);
3246 let mut alive =
3247 Candidate::from_sdp_string("candidate:2 1 udp 1694498815 4.5.6.7 5000 typ host")
3248 .unwrap();
3249 alive.set_ufrag(&remote_creds.ufrag);
3250 let (dead_prio, alive_prio) = (dead.prio(), alive.prio());
3251 assert!(dead_prio > alive_prio);
3252 agent.add_remote_candidate(dead);
3253 agent.add_remote_candidate(alive);
3254
3255 let nominate = |agent: &mut IceAgent, now: Instant, source: SocketAddr, prio: u32| {
3256 let username = format!("{}:{}", agent.local_credentials.ufrag, remote_creds.ufrag);
3257 let req = StunMessage::binding_request(&username, TransId::new(), true, 0, prio, true);
3258 let req = serialize_stun_msg(req, &agent.local_credentials.pass);
3259 assert!(agent.handle_packet(
3260 now,
3261 StunPacket {
3262 message: StunMessage::parse(&req).unwrap(),
3263 source,
3264 destination: ipv4_1(),
3265 proto: Protocol::Udp,
3266 },
3267 ));
3268 };
3269
3270 let answer_alive = |agent: &mut IceAgent, now: Instant| {
3272 let mut replies = vec![];
3273 while let Some(t) = agent.poll_transmit() {
3274 let msg = StunMessage::parse(&t.contents).unwrap();
3275 if t.destination == ipv4_4() && msg.is_binding_request() {
3276 replies.push(make_authenticated_stun_reply(
3277 msg.trans_id(),
3278 ipv4_1(),
3279 &remote_creds.pass,
3280 ));
3281 }
3282 }
3283 for reply in replies {
3284 agent.handle_packet(
3285 now,
3286 StunPacket {
3287 message: StunMessage::parse(&reply).unwrap(),
3288 source: ipv4_4(),
3289 destination: ipv4_1(),
3290 proto: Protocol::Udp,
3291 },
3292 );
3293 }
3294 };
3295
3296 let nominated_sends = |agent: &mut IceAgent| {
3297 let mut v = vec![];
3298 while let Some(e) = agent.poll_event() {
3299 if let IceAgentEvent::NominatedSend { destination, .. } = e {
3300 v.push(destination);
3301 }
3302 }
3303 v
3304 };
3305
3306 let mut now = Instant::now();
3307 agent.handle_timeout(now);
3308
3309 nominate(&mut agent, now, ipv4_3(), dead_prio);
3310 for _ in 0..20 {
3311 answer_alive(&mut agent, now);
3312 now += Duration::from_millis(50);
3313 agent.handle_timeout(now);
3314 }
3315 assert_eq!(
3316 nominated_sends(&mut agent),
3317 vec![],
3318 "a nominated pair whose check has not succeeded must not be used"
3319 );
3320
3321 nominate(&mut agent, now, ipv4_4(), alive_prio);
3322 for _ in 0..20 {
3323 answer_alive(&mut agent, now);
3324 now += Duration::from_millis(50);
3325 agent.handle_timeout(now);
3326 }
3327 assert_eq!(nominated_sends(&mut agent), vec![ipv4_4()]);
3328 }
3329
3330 fn make_serialized_binding_request(
3331 local_creds: &IceCreds,
3332 remote_creds: &IceCreds,
3333 controlling: bool,
3334 prio: u32,
3335 ) -> Vec<u8> {
3336 let username = format!("{}:{}", local_creds.ufrag, remote_creds.ufrag);
3337 let binding_req =
3338 StunMessage::binding_request(&username, TransId::new(), controlling, 0, prio, false);
3339 serialize_stun_msg(binding_req, &local_creds.pass)
3340 }
3341
3342 fn make_authenticated_stun_reply(tx_id: TransId, addr: SocketAddr, password: &str) -> Vec<u8> {
3343 let reply = StunMessage::binding_reply(tx_id, addr);
3344 serialize_stun_msg(reply, password)
3345 }
3346
3347 fn make_role_conflict_reply(tx_id: TransId, password: &str) -> Vec<u8> {
3348 let reply = StunMessage::binding_role_conflict_reply(tx_id);
3349 serialize_stun_msg(reply, password)
3350 }
3351
3352 fn serialize_stun_msg(msg: StunMessage<'_>, password: &str) -> Vec<u8> {
3355 let mut buf = vec![0_u8; DATAGRAM_MTU_TARGET];
3356
3357 let sha1_hmac =
3358 |key: &[u8], payloads: &[&[u8]]| DefaultSha1HmacProvider.sha1_hmac(key, payloads);
3359 let n = msg
3360 .to_bytes(Some(password.as_bytes()), &mut buf, sha1_hmac)
3361 .expect("IO error writing STUN message");
3362 buf.truncate(n);
3363
3364 buf
3365 }
3366
3367 #[test]
3368 fn set_mtu_updates_mtu() {
3369 let mut agent = IceAgent::new(IceCreds::new());
3370 assert_eq!(agent.mtu(), DATAGRAM_MTU_TARGET);
3371 assert_eq!(agent.mtu_warn(), DATAGRAM_MTU_WARN);
3372
3373 agent.set_mtu(900..=1280);
3374 assert_eq!(agent.mtu(), 900);
3375 assert_eq!(agent.mtu_warn(), 1280);
3376 }
3377}