1use crate::IceError;
2use serde::ser::SerializeStruct;
3use serde::{Deserialize, Serialize, Serializer};
4use std::collections::hash_map::DefaultHasher;
5use std::fmt;
6use std::hash::{Hash, Hasher};
7use std::marker::PhantomData;
8use std::net::{IpAddr, SocketAddr};
9use str0m_proto::{Protocol, TcpType};
10
11#[derive(Clone, PartialEq, Eq, Hash)]
16pub struct Candidate {
17 foundation: Option<String>, component_id: u16, proto: Protocol,
39
40 prio: Option<u32>, addr: SocketAddr, base: Option<SocketAddr>, kind: CandidateKind, tcptype: Option<TcpType>,
66
67 raddr: Option<SocketAddr>, ufrag: Option<String>,
84
85 local: SocketAddr,
94
95 local_preference: Option<u32>,
98
99 discarded: bool,
102}
103
104impl fmt::Debug for Candidate {
105 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
106 write!(f, "Candidate({}={}/{}", self.kind, self.addr, self.proto)?;
107 if let Some(base) = self.base {
108 if base != self.addr {
109 write!(f, " base={base}")?;
110 }
111 }
112 if let Some(raddr) = self.raddr {
113 write!(f, " raddr={raddr}")?;
114 }
115 write!(f, " prio={}", self.prio())?;
116 if self.discarded {
117 write!(f, " discarded")?;
118 }
119 write!(f, ")")
120 }
121}
122
123impl Candidate {
124 pub fn builder() -> CandidateBuilder<NoProtocol, NoRoute> {
152 CandidateBuilder {
153 protocol_state: NoProtocol(()),
154 route_state: NoRoute(()),
155 foundation: None,
156 component_id: 1, prio: None,
158 tcptype: None,
159 raddr: None,
160 ufrag: None,
161 local_preference: None,
162 }
163 }
164
165 #[allow(clippy::too_many_arguments)]
166 fn new(
167 foundation: Option<String>,
168 component_id: u16,
169 proto: Protocol,
170 prio: Option<u32>,
171 addr: SocketAddr,
172 base: Option<SocketAddr>,
173 kind: CandidateKind,
174 raddr: Option<SocketAddr>,
175 tcptype: Option<TcpType>,
176 ufrag: Option<String>,
177 local: SocketAddr,
178 ) -> Self {
179 Candidate {
180 foundation,
181 component_id,
182 proto,
183 prio,
184 addr,
185 base,
186 kind,
187 raddr,
188 tcptype,
189 ufrag,
190 local,
191 local_preference: None,
192 discarded: false,
193 }
194 }
195
196 #[allow(clippy::too_many_arguments)]
197 pub fn from_parts(
198 foundation: String,
199 component_id: u16,
200 proto: Protocol,
201 prio: u32,
202 addr: SocketAddr,
203 kind: CandidateKind,
204 raddr: Option<SocketAddr>,
205 tcptype: Option<TcpType>,
206 ufrag: Option<String>,
207 ) -> Self {
208 Candidate::new(
209 Some(foundation),
210 component_id,
211 proto,
212 Some(prio),
213 addr,
214 None,
215 kind,
216 raddr,
217 tcptype,
218 ufrag,
219 match kind {
220 CandidateKind::Host => addr,
221 CandidateKind::PeerReflexive
222 | CandidateKind::ServerReflexive
223 | CandidateKind::Relayed => Self::arbitrary_raddr(addr),
224 },
225 )
226 }
227
228 pub fn host(addr: SocketAddr, proto: impl TryInto<Protocol>) -> Result<Self, IceError> {
232 if !is_valid_ip(addr.ip()) {
233 return Err(IceError::BadCandidate(format!("invalid ip {}", addr.ip())));
234 }
235
236 Ok(Candidate::new(
237 None,
238 1, parse_proto(proto)?,
240 None,
241 addr,
242 Some(addr),
243 CandidateKind::Host,
244 None,
245 None,
246 None,
247 addr,
248 ))
249 }
250
251 pub fn server_reflexive(
257 addr: SocketAddr,
258 base: SocketAddr,
259 proto: impl TryInto<Protocol>,
260 ) -> Result<Self, IceError> {
261 if !is_valid_ip(addr.ip()) {
262 return Err(IceError::BadCandidate(format!("invalid ip {}", addr.ip())));
263 }
264
265 if addr.is_ipv4() != base.is_ipv4() {
266 return Err(IceError::BadCandidate(
267 "addr and base are different IP versions".to_owned(),
268 ));
269 }
270
271 Ok(Candidate::new(
272 None,
273 1, parse_proto(proto)?,
275 None,
276 addr,
277 Some(base),
278 CandidateKind::ServerReflexive,
279 Some(Self::arbitrary_raddr(addr)),
280 None,
281 None,
282 base,
283 ))
284 }
285
286 pub fn relayed(
297 addr: SocketAddr,
298 local: SocketAddr,
299 proto: impl TryInto<Protocol>,
300 ) -> Result<Self, IceError> {
301 if !is_valid_ip(addr.ip()) {
302 return Err(IceError::BadCandidate(format!("invalid ip {}", addr.ip())));
303 }
304
305 Ok(Candidate::new(
306 None,
307 1, parse_proto(proto)?,
309 None,
310 addr,
311 Some(addr),
312 CandidateKind::Relayed,
313 Some(Self::arbitrary_raddr(addr)),
314 None,
315 None,
316 local,
317 ))
318 }
319
320 pub fn from_sdp_string(s: &str) -> Result<Self, IceError> {
325 crate::parse::parse_candidate(s)
326 }
327
328 pub(crate) fn peer_reflexive(
334 proto: impl TryInto<Protocol>,
335 addr: SocketAddr,
336 base: SocketAddr,
337 prio: u32,
338 found: Option<String>,
339 ufrag: String,
340 ) -> Self {
341 Candidate::new(
342 found,
343 1, parse_proto(proto).expect("internal call to have correct protocol"),
345 Some(prio),
346 addr,
347 Some(base),
348 CandidateKind::PeerReflexive,
349 None,
350 None,
351 Some(ufrag),
352 base,
353 )
354 }
355
356 fn arbitrary_raddr(s: SocketAddr) -> SocketAddr {
368 use std::net::{Ipv4Addr, Ipv6Addr, SocketAddrV4, SocketAddrV6};
369 match s {
370 SocketAddr::V4(_) => SocketAddr::V4(SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)),
371 SocketAddr::V6(_) => SocketAddr::V6(SocketAddrV6::new(Ipv6Addr::UNSPECIFIED, 0, 0, 0)),
372 }
373 }
374
375 #[cfg(test)]
376 pub(crate) fn test_peer_rflx(
377 addr: SocketAddr,
378 base: SocketAddr,
379 proto: impl TryInto<Protocol>,
380 ) -> Self {
381 Candidate::new(
382 None,
383 1, parse_proto(proto).expect("internal test to have correct protocol"),
385 None,
386 addr,
387 Some(base),
388 CandidateKind::PeerReflexive,
389 None,
390 None,
391 None,
392 base,
393 )
394 }
395
396 pub(crate) fn foundation(&self) -> String {
400 if let Some(v) = &self.foundation {
401 return v.clone();
402 }
403
404 let mut hasher = DefaultHasher::new();
407
408 self.kind.hash(&mut hasher);
411
412 self.base().ip().hash(&mut hasher);
414
415 if let Some(raddr) = self.raddr {
419 raddr.ip().hash(&mut hasher);
420 }
421
422 self.proto.hash(&mut hasher);
424
425 let hash = hasher.finish();
426
427 format!("{:08x}{hash:x}", self.prio().to_be())
428 }
429
430 pub fn prio(&self) -> u32 {
435 self.do_prio(false)
436 }
437
438 pub(crate) fn prio_prflx(&self) -> u32 {
439 self.do_prio(true)
440 }
441
442 fn do_prio(&self, as_prflx: bool) -> u32 {
443 if let Some(prio) = &self.prio {
445 return *prio;
446 }
447
448 let kind = if as_prflx {
449 CandidateKind::PeerReflexive
450 } else {
451 self.kind
452 };
453
454 let type_preference = match (kind, self.proto) {
460 (CandidateKind::Host, Protocol::Udp) => 126,
461 (CandidateKind::PeerReflexive, Protocol::Udp) => 110,
462 (CandidateKind::ServerReflexive, _) => 100,
463 (CandidateKind::Host, _) => 90,
464 (CandidateKind::PeerReflexive, _) => 80,
465 (CandidateKind::Relayed, Protocol::Udp) => 2,
466 (CandidateKind::Relayed, Protocol::Tcp) => 1,
467 (CandidateKind::Relayed, _) => 0,
468 };
469
470 let prio =
479 type_preference << 24 | self.local_preference() << 8 | (256 - self.component_id as u32);
480
481 assert!(prio >= 1 && prio < 2_u32.pow(31));
484
485 prio
486 }
487
488 pub(crate) fn local_preference(&self) -> u32 {
489 self.local_preference
490 .unwrap_or_else(|| if self.addr.is_ipv6() { 65_535 } else { 65_534 })
491 }
492
493 pub(crate) fn component_id(&self) -> u16 {
494 self.component_id
495 }
496
497 pub fn addr(&self) -> SocketAddr {
499 self.addr
500 }
501
502 pub fn local(&self) -> SocketAddr {
513 self.local
514 }
515
516 pub fn proto(&self) -> Protocol {
519 self.proto
520 }
521
522 pub(crate) fn base(&self) -> SocketAddr {
523 self.base.unwrap_or(self.addr)
524 }
525
526 pub(crate) fn raddr(&self) -> Option<SocketAddr> {
527 self.raddr
528 }
529
530 pub fn tcptype(&self) -> Option<TcpType> {
532 self.tcptype
533 }
534
535 pub fn kind(&self) -> CandidateKind {
537 self.kind
538 }
539
540 pub(crate) fn set_local_preference(&mut self, v: u32) {
541 self.local_preference = Some(v);
542 }
543
544 pub(crate) fn set_discarded(&mut self, discarded: bool) {
545 self.discarded = discarded;
546 }
547
548 pub(crate) fn discarded(&self) -> bool {
549 self.discarded
550 }
551
552 pub fn set_ufrag(&mut self, ufrag: &str) {
553 self.ufrag = Some(ufrag.into());
554 }
555
556 pub fn ufrag(&self) -> Option<&str> {
557 self.ufrag.as_deref()
558 }
559
560 pub(crate) fn clear_ufrag(&mut self) {
561 self.ufrag = None;
562 }
563
564 pub fn to_sdp_string(&self) -> String {
566 let mut s = format!(
567 "candidate:{} {} {} {} {} {} typ {}",
568 self.foundation(),
569 self.component_id,
570 self.proto,
571 self.prio(),
572 self.addr.ip(),
573 self.addr.port(),
574 self.kind
575 );
576 if let Some(raddr) = &self.raddr {
577 s.push_str(&format!(" raddr {} rport {}", raddr.ip(), raddr.port()))
578 }
579 if let Some(tcptype) = &self.tcptype {
582 s.push_str(&format!(" tcptype {}", tcptype));
583 }
584 if let Some(ufrag) = &self.ufrag {
585 s.push_str(&format!(" ufrag {}", ufrag));
586 }
587 s
588 }
589}
590
591impl fmt::Display for Candidate {
592 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
593 write!(f, "{}", self.to_sdp_string())
594 }
595}
596
597fn parse_proto(proto: impl TryInto<Protocol>) -> Result<Protocol, IceError> {
598 proto
599 .try_into()
600 .map_err(|_| IceError::BadCandidate("invalid protocol".into()))
601}
602
603#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
605pub enum CandidateKind {
606 Host,
608 PeerReflexive,
610 ServerReflexive,
612 Relayed,
614}
615
616impl fmt::Display for CandidateKind {
617 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
618 let x = match self {
619 CandidateKind::Host => "host",
620 CandidateKind::PeerReflexive => "prflx",
621 CandidateKind::ServerReflexive => "srflx",
622 CandidateKind::Relayed => "relay",
623 };
624 write!(f, "{x}")
625 }
626}
627
628fn is_valid_ip(ip: IpAddr) -> bool {
629 match ip {
630 IpAddr::V4(v) => {
631 !v.is_link_local() && !v.is_broadcast() && !v.is_multicast() && !v.is_unspecified()
632 }
633 IpAddr::V6(v) => !v.is_multicast() && !v.is_unspecified(),
634 }
635}
636
637impl Serialize for Candidate {
651 fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
652 where
653 S: Serializer,
654 {
655 let mut o = serializer.serialize_struct("CandidateInfo", 4)?;
656 o.serialize_field("candidate", &self.to_sdp_string())?;
657 o.serialize_field("sdpMid", &None::<()>)?;
658 o.serialize_field("sdpMLineIndex", &0)?;
659 o.serialize_field("usernameFragment", &self.ufrag())?;
660 o.end()
661 }
662}
663
664impl<'de> Deserialize<'de> for Candidate {
668 fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
669 where
670 D: serde::Deserializer<'de>,
671 {
672 #[derive(Deserialize)]
673 #[serde(rename_all = "camelCase")]
674 struct CandidateInfo {
675 candidate: String,
676 username_fragment: Option<String>,
677 }
678
679 let CandidateInfo {
680 candidate,
681 username_fragment,
682 } = CandidateInfo::deserialize(deserializer)?;
683
684 let mut candidate =
685 Candidate::from_sdp_string(&candidate).map_err(serde::de::Error::custom)?;
686
687 if let Some(ufrag) = username_fragment {
688 candidate.set_ufrag(&ufrag);
689 }
690
691 Ok(candidate)
692 }
693}
694
695#[doc(hidden)]
696pub struct NoProtocol(());
698
699#[doc(hidden)]
700pub struct HasProtocol<P> {
702 _marker: PhantomData<P>,
703 protocol: Protocol,
704}
705
706#[doc(hidden)]
707pub struct Udp(());
709
710#[doc(hidden)]
711pub struct Tcp(());
713
714#[doc(hidden)]
715pub struct NoRoute(());
717
718#[doc(hidden)]
719pub struct HasRoute {
721 kind: CandidateKind,
722 addr: SocketAddr,
723 base: SocketAddr,
724 local: SocketAddr,
725}
726
727pub struct CandidateBuilder<P, R> {
732 foundation: Option<String>,
733 component_id: u16,
734 prio: Option<u32>,
735 tcptype: Option<TcpType>,
736 raddr: Option<SocketAddr>,
737 ufrag: Option<String>,
738 local_preference: Option<u32>,
739
740 protocol_state: P,
741 route_state: R,
742}
743
744impl CandidateBuilder<NoProtocol, NoRoute> {
746 pub fn udp(self) -> CandidateBuilder<HasProtocol<Udp>, NoRoute> {
748 self.into_has_protocol(Protocol::Udp)
749 }
750
751 pub fn tcp(self) -> CandidateBuilder<HasProtocol<Tcp>, NoRoute> {
753 self.into_has_protocol(Protocol::Tcp)
754 }
755
756 pub fn ssl_tcp(self) -> CandidateBuilder<HasProtocol<Tcp>, NoRoute> {
758 self.into_has_protocol(Protocol::SslTcp)
759 }
760
761 pub fn tls(self) -> CandidateBuilder<HasProtocol<Tcp>, NoRoute> {
763 self.into_has_protocol(Protocol::Tls)
764 }
765
766 fn into_has_protocol<NewP>(self, p: Protocol) -> CandidateBuilder<HasProtocol<NewP>, NoRoute> {
767 CandidateBuilder {
768 protocol_state: HasProtocol {
769 _marker: PhantomData,
770 protocol: p,
771 },
772 route_state: self.route_state,
773 foundation: self.foundation,
774 component_id: self.component_id,
775 prio: self.prio,
776 tcptype: self.tcptype,
777 raddr: self.raddr,
778 ufrag: self.ufrag,
779 local_preference: self.local_preference,
780 }
781 }
782}
783
784impl<P> CandidateBuilder<HasProtocol<P>, NoRoute> {
786 pub fn host(self, addr: SocketAddr) -> CandidateBuilder<HasProtocol<P>, HasRoute> {
788 self.into_has_route(CandidateKind::Host, addr, addr, addr, None)
789 }
790
791 pub fn server_reflexive(
794 self,
795 addr: SocketAddr,
796 base: SocketAddr,
797 ) -> CandidateBuilder<HasProtocol<P>, HasRoute> {
798 self.into_has_route(
799 CandidateKind::ServerReflexive,
800 addr,
801 base,
802 base,
803 Some(Candidate::arbitrary_raddr(addr)),
804 )
805 }
806
807 pub fn relayed(
810 self,
811 addr: SocketAddr,
812 local: SocketAddr,
813 ) -> CandidateBuilder<HasProtocol<P>, HasRoute> {
814 self.into_has_route(
815 CandidateKind::Relayed,
816 addr,
817 addr,
818 local,
819 Some(Candidate::arbitrary_raddr(addr)),
820 )
821 }
822
823 fn into_has_route(
824 self,
825 kind: CandidateKind,
826 addr: SocketAddr,
827 base: SocketAddr,
828 local: SocketAddr,
829 raddr: Option<SocketAddr>,
830 ) -> CandidateBuilder<HasProtocol<P>, HasRoute> {
831 CandidateBuilder {
832 protocol_state: self.protocol_state,
833 route_state: HasRoute {
834 kind,
835 addr,
836 base,
837 local,
838 },
839 raddr,
840 foundation: self.foundation,
841 component_id: self.component_id,
842 prio: self.prio,
843 tcptype: self.tcptype,
844 ufrag: self.ufrag,
845 local_preference: self.local_preference,
846 }
847 }
848}
849
850impl<P> CandidateBuilder<HasProtocol<P>, HasRoute> {
852 pub fn build(self) -> Result<Candidate, IceError> {
854 let route = &self.route_state;
855 if !is_valid_ip(route.addr.ip()) {
856 return Err(IceError::BadCandidate(format!(
857 "Invalid IP: {}",
858 route.addr.ip()
859 )));
860 }
861
862 if route.addr.is_ipv4() != route.base.is_ipv4() {
863 return Err(IceError::BadCandidate(format!(
864 "address IP version mismatch: addr={} base={}",
865 route.addr.ip(),
866 route.base.ip(),
867 )));
868 }
869
870 Ok(Candidate::new(
871 self.foundation,
872 self.component_id,
873 self.protocol_state.protocol,
874 self.prio,
875 route.addr,
876 Some(route.base),
877 route.kind,
878 self.raddr,
879 self.tcptype,
880 self.ufrag,
881 route.local,
882 ))
883 }
884}
885
886impl<R> CandidateBuilder<HasProtocol<Tcp>, R> {
887 pub fn tcptype(mut self, t: TcpType) -> Self {
889 self.tcptype = Some(t);
890 self
891 }
892}
893
894#[cfg(test)]
895mod tests {
896 use super::*;
897
898 #[test]
899 fn basic_serialize_deserialize() {
900 let socket_addr = "1.2.3.4:9876".parse().unwrap();
901 let candidates = [
902 Candidate::host(socket_addr, Protocol::Udp).unwrap(),
903 Candidate::host(socket_addr, Protocol::Tcp).unwrap(),
904 Candidate::builder()
905 .tcp()
906 .host(socket_addr)
907 .tcptype(TcpType::Passive)
908 .build()
909 .unwrap(),
910 ];
911
912 for c1 in &candidates {
913 let json = serde_json::to_string(&c1).unwrap();
914 let c2: Candidate = serde_json::from_str(&json).unwrap();
915 assert_eq!(c1.proto, c2.proto);
916 assert_eq!(c1.tcptype, c2.tcptype);
917
918 assert_eq!(c1.to_string(), c2.to_string());
920 }
921 }
922
923 #[test]
924 fn serialize() {
925 let socket_addr = "1.2.3.4:9876".parse().unwrap();
926 let mut candidate = Candidate::host(socket_addr, Protocol::Udp).unwrap();
927 let json = no_hash(serde_json::to_string(&candidate).unwrap());
928 let got: serde_json::Value = serde_json::from_str(&json).unwrap();
929 let expected = serde_json::json!({
930 "candidate": "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host",
931 "sdpMid": null,
932 "sdpMLineIndex": 0,
933 "usernameFragment": null
934 });
935 assert_eq!(got, expected);
936
937 candidate.ufrag = Some("ufrag".to_string());
939 let json = no_hash(serde_json::to_string(&candidate).unwrap());
940 let got: serde_json::Value = serde_json::from_str(&json).unwrap();
941 let expected = serde_json::json!({
942 "candidate": "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host ufrag ufrag",
943 "sdpMid": null,
944 "sdpMLineIndex": 0,
945 "usernameFragment": "ufrag"
946 });
947 assert_eq!(got, expected);
948 }
949
950 fn no_hash(mut s: String) -> String {
951 let f = s.find("candidate:").unwrap();
952 let t = s.find(" 1 ").unwrap();
953 s.replace_range((f + 10)..t, "---");
954 s
955 }
956
957 #[test]
958 fn deserialize() {
959 let json = serde_json::json!({
960 "candidate": "candidate:12044049749558888150 1 udp 2130706175 1.2.3.4 9876 typ host ufrag ufrag",
961 "sdpMid": "ignored",
962 "sdpMLineIndex": 123,
963 "usernameFragment": "ufrag"
964 }).to_string();
965 let candidate: Candidate = serde_json::from_str(&json).unwrap();
966 assert_eq!(candidate.ufrag(), Some("ufrag"));
967 assert_eq!(candidate.addr().to_string(), "1.2.3.4:9876");
968 assert_eq!(candidate.base().to_string(), "1.2.3.4:9876");
969 assert_eq!(candidate.kind(), CandidateKind::Host);
970 assert_eq!(candidate.proto(), Protocol::Udp);
971 assert_eq!(candidate.prio(), 2130706175);
972 assert_eq!(candidate.component_id(), 1);
973 assert_eq!(candidate.raddr(), None);
974 assert!(!candidate.discarded());
975 }
976
977 #[test]
978 fn to_string() {
979 let local_addr = "7.8.9.0:2345".parse().unwrap();
980 let socket_addr = "1.2.3.4:9876".parse().unwrap();
981 let mut candidate = Candidate::host(socket_addr, Protocol::Udp).unwrap();
982 assert_eq!(
983 no_hash(candidate.to_string()),
984 "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host"
985 );
986
987 candidate.ufrag = Some("ufrag".into());
988 assert_eq!(
989 no_hash(candidate.to_string()),
990 "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host ufrag ufrag"
991 );
992
993 candidate.raddr = Some("5.5.5.5:5555".parse().unwrap());
994 assert_eq!(
995 no_hash(candidate.to_string()),
996 "candidate:--- 1 udp 2130706175 1.2.3.4 9876 typ host raddr 5.5.5.5 rport 5555 ufrag ufrag"
997 );
998
999 let candidate = Candidate::relayed(socket_addr, local_addr, Protocol::SslTcp).unwrap();
1002 assert_eq!(
1003 no_hash(candidate.to_string()),
1004 "candidate:--- 1 ssltcp 16776959 1.2.3.4 9876 typ relay raddr 0.0.0.0 rport 0"
1005 );
1006 }
1007
1008 #[test]
1009 fn new_from_sdp_string() {
1010 let candidate = Candidate::from_sdp_string(
1011 "candidate:fffeff7e5e895846293d220a 1 udp 2130706175 1.2.3.4 9876 typ host ufrag myuserfrag",
1012 )
1013 .unwrap();
1014
1015 assert_eq!(candidate.ufrag(), Some("myuserfrag"));
1016 assert_eq!(candidate.addr().to_string(), "1.2.3.4:9876");
1017 }
1018
1019 #[test]
1020 fn spoofed_raddr() {
1021 let local_addr = "7.8.9.0:2345".parse().unwrap();
1022 let socket_addr = "1.2.3.4:9876".parse().unwrap();
1023 let base_addr = "5.6.7.8:4321".parse().unwrap();
1024
1025 let host = Candidate::host(socket_addr, Protocol::Udp).unwrap();
1026 assert!(host.raddr().is_none());
1027
1028 let relay = Candidate::relayed(socket_addr, local_addr, Protocol::Udp).unwrap();
1030 assert!(relay.raddr().is_some());
1031 let srflx = Candidate::server_reflexive(socket_addr, base_addr, Protocol::Udp).unwrap();
1032 assert!(srflx.raddr().is_some_and(|raddr| raddr != base_addr));
1033
1034 let prflx = Candidate::peer_reflexive(
1035 Protocol::Udp,
1036 socket_addr,
1037 base_addr,
1038 1000,
1039 None,
1040 "ufrag".into(),
1041 );
1042 assert!(prflx.raddr().is_none());
1043 }
1044
1045 #[test]
1046 fn bad_candidate() {
1047 let s = "candidate:12344 bad value";
1048 assert!(Candidate::from_sdp_string(s).is_err());
1049 }
1050
1051 #[test]
1052 fn tcp_candidates_sanity() {
1053 let socket_addr = "1.2.3.4:9876".parse().unwrap();
1054 let candidates = [
1055 Candidate::host(socket_addr, Protocol::Tcp).unwrap(),
1056 Candidate::builder()
1057 .tcp()
1058 .host(socket_addr)
1059 .build()
1060 .unwrap(),
1061 Candidate::builder()
1062 .tcp()
1063 .host(socket_addr)
1064 .tcptype(TcpType::Passive)
1065 .build()
1066 .unwrap(),
1067 Candidate::builder()
1068 .ssl_tcp()
1069 .host(socket_addr)
1070 .tcptype(TcpType::Active)
1071 .build()
1072 .unwrap(),
1073 Candidate::builder()
1074 .tls()
1075 .host(socket_addr)
1076 .tcptype(TcpType::So)
1077 .build()
1078 .unwrap(),
1079 ];
1080
1081 assert!(!candidates[0].to_sdp_string().contains("tcptype"));
1082 assert!(!candidates[1].to_sdp_string().contains("tcptype"));
1083 assert!(candidates[2].to_sdp_string().contains("tcptype passive"));
1084 assert!(candidates[3].to_sdp_string().contains("tcptype active"));
1085 assert!(candidates[4].to_sdp_string().contains("tcptype so"));
1086 }
1087
1088 #[test]
1089 fn lexical_ordering_of_sdp_is_follows_priority() {
1090 let mut candidates = Vec::from([
1091 host("1.1.1.1:0"),
1092 host("2.2.2.2:0"),
1093 srflx("3.3.3.3:0", "4.4.4.4:0"),
1094 srflx("5.5.5.5:0", "6.6.6.6:0"),
1095 relay("8.8.8.8:0", "9.9.9.9:0"),
1096 relay("7.7.7.7:0", "9.9.9.9:0"),
1097 ]);
1098 candidates.sort();
1099
1100 assert!(candidates[0].contains("relay"));
1101 assert!(candidates[1].contains("relay"));
1102 assert!(candidates[2].contains("srflx"));
1103 assert!(candidates[3].contains("srflx"));
1104 assert!(candidates[4].contains("host"));
1105 assert!(candidates[5].contains("host"));
1106 }
1107
1108 #[test]
1109 fn srflx_candidate_disallows_mixed_ip_versions() {
1110 let error = Candidate::server_reflexive(
1111 "10.0.0.1:1000".parse().unwrap(),
1112 "[::1]:1000".parse().unwrap(),
1113 "udp",
1114 )
1115 .unwrap_err();
1116
1117 assert_eq!(
1118 error.to_string(),
1119 "ICE bad candidate: addr and base are different IP versions"
1120 );
1121 }
1122
1123 fn host(socket: &str) -> String {
1124 Candidate::host(socket.parse().unwrap(), "udp")
1125 .unwrap()
1126 .to_sdp_string()
1127 }
1128
1129 fn srflx(addr: &str, base: &str) -> String {
1130 Candidate::server_reflexive(addr.parse().unwrap(), base.parse().unwrap(), "udp")
1131 .unwrap()
1132 .to_sdp_string()
1133 }
1134
1135 fn relay(addr: &str, local: &str) -> String {
1136 Candidate::relayed(addr.parse().unwrap(), local.parse().unwrap(), "udp")
1137 .unwrap()
1138 .to_sdp_string()
1139 }
1140
1141 #[test]
1142 fn builder_matches_api_host() {
1143 let addr = "1.2.3.4:1234".parse().unwrap();
1144
1145 let api = Candidate::host(addr, Protocol::Udp).unwrap();
1147 let builder = Candidate::builder().udp().host(addr).build().unwrap();
1148 assert_eq!(api, builder);
1149
1150 let api = Candidate::host(addr, Protocol::Tcp).unwrap();
1152 let builder = Candidate::builder().tcp().host(addr).build().unwrap();
1153 assert_eq!(api, builder);
1154 }
1155
1156 #[test]
1157 fn builder_matches_api_server_reflexive() {
1158 let addr = "95.1.1.1:5000".parse().unwrap();
1159 let base = "192.168.1.50:5000".parse().unwrap();
1160
1161 let api = Candidate::server_reflexive(addr, base, Protocol::Udp).unwrap();
1162 let builder = Candidate::builder()
1163 .udp()
1164 .server_reflexive(addr, base)
1165 .build()
1166 .unwrap();
1167
1168 assert_eq!(api, builder);
1169 }
1170
1171 #[test]
1172 fn builder_matches_api_relayed() {
1173 let addr = "1.2.3.4:3478".parse().unwrap(); let local = "192.168.1.50:5000".parse().unwrap(); let api = Candidate::relayed(addr, local, Protocol::Udp).unwrap();
1177 let builder = Candidate::builder()
1178 .udp()
1179 .relayed(addr, local)
1180 .build()
1181 .unwrap();
1182
1183 assert_eq!(api, builder);
1184 }
1185
1186 #[test]
1187 fn builder_consistency_errors() {
1188 let v4 = "1.2.3.4:1234".parse().unwrap();
1189 let v6 = "[2001:db8::1]:1234".parse().unwrap();
1190
1191 let api_err = Candidate::server_reflexive(v4, v6, Protocol::Udp);
1193 let builder_err = Candidate::builder().udp().server_reflexive(v4, v6).build();
1195
1196 assert!(api_err.is_err());
1197 assert!(builder_err.is_err());
1198 }
1199}