Skip to main content

is/
candidate.rs

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/// ICE candidates are network addresses used to connect to a peer.
12///
13/// There are different kinds of ICE candidates. The simplest kind is a
14/// host candidate which is a socket address on a local (host) network interface.
15#[derive(Clone, PartialEq, Eq, Hash)]
16pub struct Candidate {
17    /// An arbitrary string used in the freezing algorithm to
18    /// group similar candidates.
19    ///
20    /// It is the same for two candidates that
21    /// have the same type, base IP address, protocol (UDP, TCP, etc.),
22    /// and STUN or TURN server.  If any of these are different, then the
23    /// foundation will be different.
24    ///
25    /// For remote, this is communicated,  and locally it's calculated.
26    foundation: Option<String>, // 1-32 "ice chars", ALPHA / DIGIT / "+" / "/"
27
28    /// A component is a piece of a data stream.
29    ///
30    /// A data stream may require multiple components, each of which has to
31    /// work in order for the data stream as a whole to work.  For RTP/RTCP
32    /// data streams, unless RTP and RTCP are multiplexed in the same port,
33    /// there are two components per data stream -- one for RTP, and one
34    /// for RTCP.
35    component_id: u16, // 1 for RTP, 2 for RTCP
36
37    /// Protocol for the candidate.
38    proto: Protocol,
39
40    /// Priority.
41    ///
42    /// For remote, this is communicated, and locally it's (mostly) calculated.
43    /// For local peer reflexive it is set.
44    prio: Option<u32>, // 1-10 digits
45
46    /// The actual address to use. This might be a host address, server reflex, relay etc.
47    addr: SocketAddr, // ip/port
48
49    /// The base address
50    ///
51    /// "Base" refers to the address an agent sends from for a
52    /// particular candidate.  Thus, as a degenerate case, host candidates
53    /// also have a base, but it's the same as the host candidate.
54    ///
55    /// * host - same as `addr`, i.e the local interface address
56    /// * peer/server reflexive - the local interface address
57    /// * relay - same as `addr`, the allocation on the TURN server
58    base: Option<SocketAddr>, // the "base" used for local candidates.
59
60    /// Type of candidate.
61    kind: CandidateKind, // host/srflx/prflx/relay
62
63    /// TCP connection role specified by the optional `tcptype` ICE candidate
64    /// extension.
65    tcptype: Option<TcpType>,
66
67    /// Related address.
68    ///
69    /// For server-reflexive candidates, this is the internal IP/port the candidate corresponds to
70    /// (the one behind the NAT, usually). For relay candidates, this is the mapped address selected
71    /// by the TURN server.
72    raddr: Option<SocketAddr>, // ip/port
73
74    /// Ufrag.
75    ///
76    /// This is used to tie an ice candidate to a specific ICE session. It's important
77    /// when trickle ICE is used in conjunction with ice restart, since it must be
78    /// possible the ice agent to know whether a candidate appearing belongs to
79    /// the current or previous session.
80    ///
81    /// This value is only set for incoming candidates. Once we use the candidate inside
82    /// pairs, the field is blanked to not be confusing during ice-restarts.
83    ufrag: Option<String>,
84
85    /// The address of the local interface.
86    ///
87    /// * host - same as `addr`
88    /// * peer/server reflexive - same as `base`
89    /// * relay - set explicitly
90    ///
91    /// This is an extension to the ICE spec that we use to track
92    /// local interfaces also for relayed candidates.
93    local: SocketAddr,
94
95    /// The ice agent might assign a local preference if we have multiple candidates
96    /// that are the same type.
97    local_preference: Option<u32>,
98
99    /// If we discarded this candidate (for example due to being redundant
100    /// against another candidate).
101    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    /// Starts the typesafe builder.
125    ///
126    /// # Example
127    ///
128    /// ```
129    /// # use is::Candidate;
130    /// # use is::IceError;
131    /// # use str0m_proto::TcpType;
132    /// # use std::net::SocketAddr;
133    ///
134    /// let addr: SocketAddr = "192.168.1.1:12345".parse().unwrap();
135    ///
136    /// // A standard UDP host candidate
137    /// let udp_host = Candidate::builder()
138    ///     .udp()
139    ///     .host(addr)
140    ///     .build()?;
141    ///
142    /// // A TCP host candidate with a passive role
143    /// let tcp_host = Candidate::builder()
144    ///     .tcp()
145    ///     .host(addr)
146    ///     .tcptype(TcpType::Passive)
147    ///     .build()?;
148    ///
149    /// # Ok::<(), IceError>(())
150    /// ```
151    pub fn builder() -> CandidateBuilder<NoProtocol, NoRoute> {
152        CandidateBuilder {
153            protocol_state: NoProtocol(()),
154            route_state: NoRoute(()),
155            foundation: None,
156            component_id: 1, // Default RTP
157            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    /// Creates a host ICE candidate.
229    ///
230    /// Host candidates are local sockets directly on the host.
231    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, // only RTP
239            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    /// Creates a server reflexive ICE candidate.
252    ///
253    /// Server reflexive candidates are local sockets mapped to external ip discovered
254    /// via a STUN binding request.
255    /// The `base` is the local interface that this address corresponds to.
256    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, // only RTP
274            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    /// Creates a relayed ICE candidate.
287    ///
288    /// Relayed candidates are server sockets relaying traffic to a local socket.
289    /// Allocate a TURN addr to use as a local candidate.
290    ///
291    /// * `addr` - The TURN server's allocated address for relaying traffic.
292    ///   This is the address used for communication with the peer.
293    /// * `local` - The local interface address for this candidate.
294    ///   This is the address from which the TURN allocation request was sent.
295    /// * `proto` - The transport protocol to use (UDP, TCP, etc.).
296    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, // only RTP
308            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    /// Creates a new ICE candidate from a candidate attribute string.
321    ///
322    /// Expects the format from RFC 5245 section 15.1, e.g.
323    /// `candidate:1 1 udp 2113929471 203.0.113.100 10100 typ host`.
324    pub fn from_sdp_string(s: &str) -> Result<Self, IceError> {
325        crate::parse::parse_candidate(s)
326    }
327
328    /// Creates a peer reflexive ICE candidate.
329    ///
330    /// Peer reflexive candidates are NAT:ed addresses discovered via STUN
331    /// binding responses. `addr` is the discovered address. `base` is the local
332    /// (host) address inside the NAT we used to get this response.
333    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, // only RTP
344            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    /// Create an arbitrary socket address, matching the format of the input address,
357    /// for placement in the `raddr` field.
358    ///
359    /// For non-host candidates, Firefox (and perhaps others) require the SDP string to
360    /// contain `raddr` and `rport` to correctly parse. While we could put honest values
361    /// here, those honest values are likely private IP addresses that we would rather not
362    /// expose to the world. Instead, browsers often spoof values to go here instead, and
363    /// we do the same.
364    ///
365    /// Note that `raddr` and `rport` are only for diagnostic purposes, and have no
366    /// bearing on ICE connectivity checks.
367    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, // only RTP
384            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    /// Candidate foundation.
397    ///
398    /// For local candidates this is calculated.
399    pub(crate) fn foundation(&self) -> String {
400        if let Some(v) = &self.foundation {
401            return v.clone();
402        }
403
404        // Two candidates have the same foundation when all of the
405        // following are true:
406        let mut hasher = DefaultHasher::new();
407
408        //  o  They have the same type (host, relayed, server reflexive, or peer
409        //     reflexive).
410        self.kind.hash(&mut hasher);
411
412        //  o  Their bases have the same IP address (the ports can be different).
413        self.base().ip().hash(&mut hasher);
414
415        //  o  For reflexive and relayed candidates, the STUN or TURN servers
416        //     used to obtain them have the same IP address (the IP address used
417        //     by the agent to contact the STUN or TURN server).
418        if let Some(raddr) = self.raddr {
419            raddr.ip().hash(&mut hasher);
420        }
421
422        //  o  They were obtained using the same transport protocol (TCP, UDP).
423        self.proto.hash(&mut hasher);
424
425        let hash = hasher.finish();
426
427        format!("{:08x}{hash:x}", self.prio().to_be())
428    }
429
430    /// Returns the priority value for the specified ICE candidate.
431    ///
432    /// The priority is a positive integer between 1 and 2^31 - 1 (inclusive), calculated
433    /// according to the ICE specification defined in RFC 8445, Section 5.1.2.
434    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        // Remote candidates have their prio calculated on their side.
444        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        // Per RFC5245 Sec. 4.1.2.1, the RECOMMENDED values for type preferences are
455        // 126 for host candidates, 110 for peer-reflexive candidates, 100 for
456        // server-reflexive candidates, and 0 for relayed candidates. The variations
457        // for non-UDP protocols are taken from libwebrtc:
458        // <https://webrtc.googlesource.com/src/+/refs/heads/main/p2p/base/port.h#68>
459        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        // The recommended formula combines a preference for the candidate type
471        // (server reflexive, peer reflexive, relayed, and host), a preference
472        // for the IP address for which the candidate was obtained, and a
473        // component ID using the following formula:
474        //
475        // priority = (2^24)*(type preference) +
476        //     (2^8)*(local preference) +
477        //     (2^0)*(256 - component ID)
478        let prio =
479            type_preference << 24 | self.local_preference() << 8 | (256 - self.component_id as u32);
480
481        // https://datatracker.ietf.org/doc/html/rfc8445#section-5.1.2
482        // MUST be a positive integer between 1 and (2**31 - 1)
483        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    /// Returns the address for the specified ICE candidate.
498    pub fn addr(&self) -> SocketAddr {
499        self.addr
500    }
501
502    /// Returns the _local_ address of this ICE candidate.
503    ///
504    /// This is an extension to the ICE spec that we use to track
505    /// local interfaces also for relayed candidates.
506    /// Specifically, for relayed candidates, the local interface
507    /// is the address the agent uses to communicate with the TURN
508    /// server using the TURN protocol.
509    ///
510    /// For all other candidates, this refers to either the
511    /// candidate itself (host) or the base (srflx/prflx).
512    pub fn local(&self) -> SocketAddr {
513        self.local
514    }
515
516    /// Returns a reference to the String containing the transport protocol of
517    /// the ICE candidate. For example tcp/udp/..
518    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    /// Returns the candidate's TCP role. Refer to [`TcpType`] for more details.
531    pub fn tcptype(&self) -> Option<TcpType> {
532        self.tcptype
533    }
534
535    /// Returns the kind of this candidate.
536    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    /// Generates a candidate attribute string.
565    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        // https://datatracker.ietf.org/doc/html/rfc6544#section-4.5
580        // the RFC requires tcptype to be defined strictly after raddr if exists.
581        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/// Type of candidate.
604#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
605pub enum CandidateKind {
606    /// Host (local network interface)
607    Host,
608    /// Prflx (Peer reflexive)
609    PeerReflexive,
610    /// Srflx (STUN)
611    ServerReflexive,
612    /// Relay (TURN)
613    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
637/// Serialize [Candidate] into candidate info.
638///
639/// Always set `sdpMid` to null and `sdpMLineIndex` to 0, as we only support one media line.
640///
641/// e.g. serde_json would produce:
642/// ```json
643/// {
644///  "candidate": "candidate:12044049749558888150 1 udp 2130706175 1.2.3.4 1234 typ host",
645///  "sdpMid": null,
646///  "sdpMLineIndex": 0
647///  "usernameFragment": "ufrag"
648/// }
649/// ```
650impl 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
664/// Deserialize [Candidate] from a candidate info.
665///
666/// Similar to [Candidate::serialize], we drop `sdpMid` and `sdpMLineIndex` when parsing.
667impl<'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)]
696/// Marker for a builder requiring a protocol selection.
697pub struct NoProtocol(());
698
699#[doc(hidden)]
700/// State indicating a transport protocol has been assigned to the builder.
701pub struct HasProtocol<P> {
702    _marker: PhantomData<P>,
703    protocol: Protocol,
704}
705
706#[doc(hidden)]
707/// Marker for a builder using the UDP protocol.
708pub struct Udp(());
709
710#[doc(hidden)]
711/// Marker for a builder using a TCP-based protocol.
712pub struct Tcp(());
713
714#[doc(hidden)]
715/// Marker indicating the candidate's network route (addresses and kind) is not yet defined.
716pub struct NoRoute(());
717
718#[doc(hidden)]
719/// State containing the network route and addresses required to build a candidate.
720pub struct HasRoute {
721    kind: CandidateKind,
722    addr: SocketAddr,
723    base: SocketAddr,
724    local: SocketAddr,
725}
726
727/// A typesafe builder for constructing a [`Candidate`].
728///
729/// This builder uses the Type State Pattern to enforce correct construction order and
730/// protocol-specific constraints (such as preventing `tcptype` on UDP).
731pub 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
744// Step 1: Protocol Selection
745impl CandidateBuilder<NoProtocol, NoRoute> {
746    /// Sets the protocol to UDP.
747    pub fn udp(self) -> CandidateBuilder<HasProtocol<Udp>, NoRoute> {
748        self.into_has_protocol(Protocol::Udp)
749    }
750
751    /// Sets the protocol to standard TCP.
752    pub fn tcp(self) -> CandidateBuilder<HasProtocol<Tcp>, NoRoute> {
753        self.into_has_protocol(Protocol::Tcp)
754    }
755
756    /// Sets the protocol to SSL-over-TCP.
757    pub fn ssl_tcp(self) -> CandidateBuilder<HasProtocol<Tcp>, NoRoute> {
758        self.into_has_protocol(Protocol::SslTcp)
759    }
760
761    /// Sets the protocol to TLS.
762    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
784// Step 2: Route Selection
785impl<P> CandidateBuilder<HasProtocol<P>, NoRoute> {
786    /// Configures as a host candidate.
787    pub fn host(self, addr: SocketAddr) -> CandidateBuilder<HasProtocol<P>, HasRoute> {
788        self.into_has_route(CandidateKind::Host, addr, addr, addr, None)
789    }
790
791    /// Configures as a Server Reflexive (STUN) candidate.
792    /// `base` and `addr` must use the same IP version.
793    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    /// Configures as a Relayed (TURN) candidate.
808    /// Base is set to `addr`, and `local` is the interface address.
809    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
850// Step 3: Final General Configurations and Build
851impl<P> CandidateBuilder<HasProtocol<P>, HasRoute> {
852    /// Consumes the builder and returns a [`Candidate`].
853    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    /// Configures the TCP type (active, passive, so).
888    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            // Can't test equality because foundation is calculated on the fly. Use string compare instead.
919            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        // Add a username fragment
938        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 base_addr = "5.6.7.8:4321".parse().unwrap();
1000
1001        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        // We're not picky on the exact choice, but it must not be the private base
1029        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        // UDP Host
1146        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        // TCP Host
1151        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(); // TURN relay addr
1174        let local = "192.168.1.50:5000".parse().unwrap(); // Local interface
1175
1176        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        // API returns error on mixed versions
1192        let api_err = Candidate::server_reflexive(v4, v6, Protocol::Udp);
1193        // Builder should return same error type
1194        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}