Skip to main content

rtci_ice/candidate/
mod.rs

1//! ICE candidates: the addresses an agent can be reached at.
2//!
3//! A [`Candidate`](crate::candidate::Candidate) pairs a transport address with a [`CandidateType`](crate::candidate::CandidateType) — host, server-reflexive,
4//! peer-reflexive or relay — and the bookkeeping ICE needs: a priority, a foundation, and
5//! last-sent/last-received times that feed consent freshness.
6//!
7//! Type drives priority, and priority drives check order: host candidates are tried first
8//! because they need no traversal, relay candidates last because they always cost an extra hop.
9//! The [`foundation`](crate::candidate::Candidate::foundation) groups candidates that share a base and transport,
10//! so redundant checks can be skipped.
11//!
12//! Each type has its own constructor module (`candidate_host`, `candidate_relay`, …), all
13//! built on the shared [`CandidateConfig`](crate::candidate::CandidateConfig).
14
15#[cfg(test)]
16mod candidate_pair_test;
17#[cfg(test)]
18mod candidate_test;
19
20// Upstream's candidate_relay_test and candidate_server_reflexive_test ran a TURN server in
21// process; they live on as tests/testenv_ice.rs (test_relay_only_connection_{udp,tcp,tls},
22// test_server_reflexive_only_connection), against coturn through real NATs.
23
24/// Host candidates: an address on a local interface.
25pub mod candidate_host;
26/// A local/remote candidate pair and its check state.
27pub mod candidate_pair;
28/// Peer-reflexive candidates, learned from an inbound check's source address.
29pub mod candidate_peer_reflexive;
30/// Relay candidates, allocated on a TURN server.
31pub mod candidate_relay;
32/// Server-reflexive candidates, learned from a STUN Binding response.
33pub mod candidate_server_reflexive;
34
35use crate::network_type::NetworkType;
36use crate::tcp_type::TcpType;
37use crc::{CRC_32_ISCSI, Crc};
38use serde::{Deserialize, Serialize};
39use shared::error::*;
40use std::fmt;
41use std::net::{IpAddr, SocketAddr};
42use std::time::Instant;
43
44use crate::candidate::candidate_host::CandidateHostConfig;
45use crate::candidate::candidate_peer_reflexive::CandidatePeerReflexiveConfig;
46use crate::candidate::candidate_relay::CandidateRelayConfig;
47use crate::candidate::candidate_server_reflexive::CandidateServerReflexiveConfig;
48use crate::network_type::determine_network_type;
49
50pub(crate) const RECEIVE_MTU: usize = 8192;
51pub(crate) const DEFAULT_LOCAL_PREFERENCE: u16 = 65535;
52
53/// Indicates that the candidate is used for RTP.
54pub(crate) const COMPONENT_RTP: u16 = 1;
55/// Indicates that the candidate is used for RTCP (RFC 8445 Section 5.1.1.1: component 2).
56pub(crate) const COMPONENT_RTCP: u16 = 2;
57
58/// The largest candidate priority (RFC 8445 Section 5.1.2: 1 to 2^31 - 1).
59pub(crate) const MAX_CANDIDATE_PRIORITY: u32 = (1 << 31) - 1;
60
61/// The component and priority of a candidate being constructed, checked against RFC 8445
62/// Sections 5.1.2 and 5.1.2.1: a component is 1 to 256 (0, the `Default`, means RTP, 1), and a
63/// given priority is at most 2^31 - 1 (0 means "compute it").
64pub(crate) fn checked_component_and_priority(config: &CandidateConfig) -> Result<u16> {
65    if config.priority > MAX_CANDIDATE_PRIORITY {
66        return Err(Error::Other(format!(
67            "{:?}: priority {} is above 2^31 - 1",
68            Error::ErrParsePriority,
69            config.priority
70        )));
71    }
72    match config.component {
73        0 => Ok(COMPONENT_RTP),
74        1..=256 => Ok(config.component),
75        other => Err(Error::Other(format!(
76            "{:?}: component {other} is outside 1..=256",
77            Error::ErrParseComponent
78        ))),
79    }
80}
81
82/// Represents the type of candidate `CandidateType` enum.
83#[derive(Default, Clone, Copy, Debug, PartialEq, Eq, Serialize, Deserialize)]
84#[non_exhaustive]
85pub enum CandidateType {
86    #[default]
87    #[serde(rename = "unspecified")]
88    /// No candidate type was set.
89    Unspecified,
90    #[serde(rename = "host")]
91    /// An address on one of this host's own interfaces.
92    ///
93    /// Highest priority: reachable without traversal when both peers share a network.
94    Host,
95    #[serde(rename = "srflx")]
96    /// This host's address as seen by a STUN server — its public mapping through the NAT.
97    ServerReflexive,
98    #[serde(rename = "prflx")]
99    /// An address learned from a peer's inbound connectivity check.
100    ///
101    /// Discovered during checking rather than gathering, when a NAT maps a different port per
102    /// destination.
103    PeerReflexive,
104    #[serde(rename = "relay")]
105    /// An address allocated on a TURN server, which forwards on this host's behalf.
106    ///
107    /// Lowest priority: it always costs an extra hop.
108    Relay,
109}
110
111// String makes CandidateType printable
112impl fmt::Display for CandidateType {
113    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
114        let s = match *self {
115            CandidateType::Host => "host",
116            CandidateType::ServerReflexive => "srflx",
117            CandidateType::PeerReflexive => "prflx",
118            CandidateType::Relay => "relay",
119            CandidateType::Unspecified => "Unknown candidate type",
120        };
121        write!(f, "{s}")
122    }
123}
124
125impl CandidateType {
126    /// Returns the preference weight of a `CandidateType`.
127    ///
128    /// 4.1.2.2.  Guidelines for Choosing Type and Local Preferences
129    /// The RECOMMENDED values are 126 for host candidates, 100
130    /// for server reflexive candidates, 110 for peer reflexive candidates,
131    /// and 0 for relayed candidates.
132    #[must_use]
133    pub const fn preference(self) -> u16 {
134        match self {
135            Self::Host => 126,
136            Self::PeerReflexive => 110,
137            Self::ServerReflexive => 100,
138            Self::Relay | CandidateType::Unspecified => 0,
139        }
140    }
141}
142
143pub(crate) fn contains_candidate_type(
144    candidate_type: CandidateType,
145    candidate_type_list: &[CandidateType],
146) -> bool {
147    if candidate_type_list.is_empty() {
148        return false;
149    }
150    for ct in candidate_type_list {
151        if *ct == candidate_type {
152            return true;
153        }
154    }
155    false
156}
157
158/// Convey transport addresses related to the candidate, useful for diagnostics and other purposes.
159#[derive(PartialEq, Eq, Debug, Clone)]
160pub struct CandidateRelatedAddress {
161    /// The address of the related candidate — the base this one was derived from.
162    /// The candidate's address.
163    pub address: String,
164    /// The port of the related candidate.
165    /// The candidate's port.
166    pub port: u16,
167}
168
169// String makes CandidateRelatedAddress printable
170impl fmt::Display for CandidateRelatedAddress {
171    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
172        write!(f, " related {}:{}", self.address, self.port)
173    }
174}
175
176#[derive(Default)]
177/// The fields common to every candidate type, used when constructing one.
178pub struct CandidateConfig {
179    /// A unique identifier for this candidate; generated when left empty.
180    pub candidate_id: String,
181    /// The transport, `udp` or `tcp`.
182    pub network: String,
183    /// The candidate's address.
184    pub address: String,
185    /// The candidate's port.
186    pub port: u16,
187    /// The RTP component id: `1` for RTP, `2` for RTCP when not multiplexed.
188    pub component: u16,
189    /// The candidate priority; computed from the type and local preference when zero.
190    pub priority: u32,
191    /// The foundation, which groups candidates that share a base and transport.
192    ///
193    /// Pairs with the same foundation are checked together, so redundant checks are avoided.
194    pub foundation: String,
195}
196
197#[derive(Clone, Debug)]
198/// One ICE candidate: a transport address this agent can be reached at, or can reach a peer
199/// at, together with its type, priority and liveness bookkeeping.
200pub struct Candidate {
201    pub(crate) id: String,
202    pub(crate) network_type: NetworkType,
203    pub(crate) candidate_type: CandidateType,
204
205    pub(crate) component: u16,
206    pub(crate) address: String,
207    pub(crate) port: u16,
208    pub(crate) related_address: Option<CandidateRelatedAddress>,
209    pub(crate) tcp_type: TcpType,
210
211    pub(crate) resolved_addr: SocketAddr,
212
213    /// When traffic was last sent on this candidate, or `None` if none ever has been.
214    pub(crate) last_sent: Option<Instant>,
215    /// When traffic was last received on this candidate, or `None` if none ever has been.
216    pub(crate) last_received: Option<Instant>,
217    /// When an authenticated (MESSAGE-INTEGRITY checked) Binding request or response last
218    /// arrived from this candidate. Consent freshness (RFC 7675) is judged on this alone, so
219    /// unauthenticated traffic from the address cannot keep a dead pair alive.
220    pub(crate) last_authenticated: Option<Instant>,
221    /// When an authenticated success response to one of our own pending Binding requests last
222    /// arrived from this candidate. This is consent (RFC 7675 §5.1): the peer's own requests do
223    /// not grant it.
224    pub(crate) last_consent: Option<Instant>,
225
226    pub(crate) foundation_override: String,
227    pub(crate) priority_override: u32,
228    /// Where this candidate stands among the local candidates of its type (0 is the most
229    /// preferred): the local preference is the largest value less this rank. `None` until the
230    /// application or the agent ranks it. See [`Candidate::set_local_preference_rank`].
231    pub(crate) local_preference_rank: Option<u16>,
232    /// The related address (the base) is a host address hidden behind an mDNS name: it is
233    /// not signalled. See [`Candidate::signalled_related_address`].
234    pub(crate) hide_related_address: bool,
235    /// A local candidate the agent holds but has not been told is conveyed to the peer yet:
236    /// it is not paired until it is (RFC 8838 Section 10). See
237    /// [`Agent::add_unconveyed_local_candidate`](crate::agent::Agent::add_unconveyed_local_candidate).
238    pub(crate) unconveyed: bool,
239    /// A local candidate gathered (or gathered again) while an ICE restart is staged
240    /// ([`Agent::generate_restart_credentials`](crate::agent::Agent::generate_restart_credentials)):
241    /// it is the new generation's, so the restart keeps it even when it discards the previous
242    /// generation's local candidates.
243    pub(crate) restart_generation: bool,
244    /// A local candidate new to the agent that arrived while a restart was staged and the
245    /// current session had nominated a pair: it is not paired in that session (RFC 8838
246    /// Section 13), only in the one the restart begins.
247    pub(crate) awaiting_restart: bool,
248
249    pub(crate) network: String,
250
251    pub(crate) url: Option<String>,
252}
253
254impl Default for Candidate {
255    fn default() -> Self {
256        Self {
257            id: String::new(),
258            network_type: NetworkType::Unspecified,
259            candidate_type: CandidateType::default(),
260
261            component: 0,
262            address: String::new(),
263            port: 0,
264            related_address: None,
265            tcp_type: TcpType::default(),
266
267            resolved_addr: SocketAddr::new(IpAddr::from([0, 0, 0, 0]), 0),
268
269            last_sent: None,
270            last_received: None,
271            last_authenticated: None,
272            last_consent: None,
273
274            foundation_override: String::new(),
275            priority_override: 0,
276            local_preference_rank: None,
277            hide_related_address: false,
278            unconveyed: false,
279            restart_generation: false,
280            awaiting_restart: false,
281            network: String::new(),
282
283            url: None,
284        }
285    }
286}
287
288// String makes the candidateBase printable
289impl fmt::Display for Candidate {
290    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
291        if let Some(related_address) = self.related_address() {
292            write!(
293                f,
294                "{} {} {}:{}{}",
295                self.network_type(),
296                self.candidate_type(),
297                self.address(),
298                self.port(),
299                related_address,
300            )
301        } else {
302            write!(
303                f,
304                "{} {} {}:{}",
305                self.network_type(),
306                self.candidate_type(),
307                self.address(),
308                self.port(),
309            )
310        }
311    }
312}
313
314impl Candidate {
315    /// The candidate's foundation (RFC 8445 Section 5.1.1.3): two candidates have the same one
316    /// when they have the same type, their bases have the same IP address (ports may differ),
317    /// they came from the same STUN or TURN server (reflexive and relayed ones) and they use
318    /// the same transport protocol.
319    ///
320    /// A host candidate's base is itself (an mDNS name stands for its address); a reflexive
321    /// candidate's base is its related address; a relayed candidate's base is the relayed
322    /// address. A foundation groups equivalent candidates; it is deterministic bookkeeping
323    /// rather than a secret, random identifier. CRC-32C is therefore intentional here.
324    pub fn foundation(&self) -> String {
325        if !self.foundation_override.is_empty() {
326            return self.foundation_override.clone();
327        }
328
329        let base = match (self.candidate_type, &self.related_address) {
330            (CandidateType::ServerReflexive | CandidateType::PeerReflexive, Some(related))
331                if !related.address.is_empty() =>
332            {
333                related.address.as_str()
334            }
335            _ => self.address.as_str(),
336        };
337
338        let mut buf = vec![];
339        buf.extend_from_slice(self.candidate_type().to_string().as_bytes());
340        buf.extend_from_slice(base.as_bytes());
341        buf.extend_from_slice(self.network_type().to_string().as_bytes());
342        if let Some(url) = &self.url {
343            buf.extend_from_slice(url.as_bytes());
344        }
345
346        let checksum = Crc::<u32>::new(&CRC_32_ISCSI).checksum(&buf);
347
348        format!("{checksum}")
349    }
350
351    /// Returns Candidate ID.
352    pub fn id(&self) -> &str {
353        self.id.as_str()
354    }
355
356    /// Returns candidate component.
357    pub fn component(&self) -> u16 {
358        self.component
359    }
360
361    /// Sets candidate component.
362    pub fn set_component(&mut self, component: u16) {
363        self.component = component;
364    }
365
366    /// A local candidate the agent does not pair yet: not conveyed to the peer, or waiting
367    /// for the restart it was gathered for.
368    pub(crate) fn held_from_pairing(&self) -> bool {
369        self.unconveyed || self.awaiting_restart
370    }
371
372    /// When traffic was last received on this candidate.
373    ///
374    /// `None` until the first packet arrives. A freshly constructed or freshly parsed candidate
375    /// has not received anything, and previously said it had — it was seeded with the
376    /// construction instant, which also meant every candidate constructor needed a clock.
377    pub fn last_received(&self) -> Option<Instant> {
378        self.last_received
379    }
380
381    /// When traffic was last sent on this candidate, or `None` if none ever has been.
382    pub fn last_sent(&self) -> Option<Instant> {
383        self.last_sent
384    }
385
386    /// Returns candidate NetworkType.
387    pub fn network_type(&self) -> NetworkType {
388        self.network_type
389    }
390
391    /// Returns Candidate Address.
392    pub fn address(&self) -> &str {
393        self.address.as_str()
394    }
395
396    /// Returns Candidate Port.
397    pub fn port(&self) -> u16 {
398        self.port
399    }
400
401    /// Computes the priority for this ICE Candidate.
402    pub fn priority(&self) -> u32 {
403        if self.priority_override != 0 {
404            return self.priority_override;
405        }
406
407        // The local preference MUST be an integer from 0 (lowest preference) to
408        // 65535 (highest preference) inclusive.  When there is only a single IP
409        // address, this value SHOULD be set to 65535.  If there are multiple
410        // candidates for a particular component for a particular data stream
411        // that have the same type, the local preference MUST be unique for each
412        // one.
413        (1 << 24) * u32::from(self.type_preference(self.candidate_type()))
414            + (1 << 8) * u32::from(self.local_preference())
415            + 256u32.saturating_sub(u32::from(self.component()))
416    }
417
418    /// The type preference of `candidate_type` on this candidate's transport. RFC 6544
419    /// section 4.2: "the type preferences for the preferred transport protocol candidates
420    /// SHOULD be increased and/or the type preferences for the other transport protocol
421    /// candidates SHOULD be decreased ... changing type preference values by one for the other
422    /// transport protocol candidates is enough" when the candidate type matters more, and "For
423    /// RTP-based media streams, it is RECOMMENDED that UDP candidates are preferred over TCP
424    /// candidates". A TCP candidate takes the UDP type preference less one (host 125,
425    /// peer-reflexive 109, server-reflexive 99): a TCP host candidate still outranks a UDP
426    /// server-reflexive one, a UDP candidate outranks the TCP one of its type. A relayed TCP
427    /// candidate stays at 0 ("relayed candidates are still preferred lower than the other
428    /// candidate types"), below the UDP relayed one by its local preference.
429    pub fn type_preference(&self, candidate_type: CandidateType) -> u16 {
430        let preference = candidate_type.preference();
431        if self.network_type().is_tcp() {
432            preference.saturating_sub(1)
433        } else {
434            preference
435        }
436    }
437
438    /// The priority this candidate would have as a peer-reflexive one: the value of the
439    /// PRIORITY attribute in a connectivity check sent from it (RFC 8445 Section 7.1.1). The
440    /// peer-reflexive type preference (of its transport, RFC 6544 section 4.2), with this
441    /// candidate's local preference and component.
442    pub fn peer_reflexive_priority(&self) -> u32 {
443        (u32::from(self.type_preference(CandidateType::PeerReflexive)) << 24)
444            | (self.priority() & 0x00ff_ffff)
445    }
446
447    /// Returns `Option<CandidateRelatedAddress>`.
448    pub fn related_address(&self) -> Option<CandidateRelatedAddress> {
449        self.related_address.as_ref().cloned()
450    }
451
452    /// Returns candidate type.
453    pub fn candidate_type(&self) -> CandidateType {
454        self.candidate_type
455    }
456
457    /// The TCP role for ICE-TCP candidates; `Unspecified` for UDP.
458    pub fn tcp_type(&self) -> TcpType {
459        self.tcp_type
460    }
461
462    /// Sets the TCP role of an ICE-TCP candidate of any type (RFC 6544 Section 4.5: every TCP
463    /// candidate is signalled with a `tcptype`).
464    pub fn set_tcp_type(&mut self, tcp_type: TcpType) {
465        self.tcp_type = tcp_type;
466    }
467
468    /// The STUN or TURN server this candidate was gathered from, if any.
469    pub fn url(&self) -> Option<&str> {
470        self.url.as_deref()
471    }
472
473    /// Returns the string representation of the ICECandidate.
474    pub fn marshal(&self) -> String {
475        let mut val = format!(
476            "{} {} {} {} {} {} typ {}",
477            self.foundation(),
478            self.component(),
479            self.network_type().network_short(),
480            self.priority(),
481            self.address(),
482            self.port(),
483            self.candidate_type()
484        );
485
486        // RFC 8839 Section 5.1: rel-addr and rel-port come before the extension attributes,
487        // of which `tcptype` (RFC 6544 Section 4.5) is one, for every candidate type.
488        if let Some(related_address) = self.signalled_related_address() {
489            val += format!(
490                " raddr {} rport {}",
491                related_address.address, related_address.port,
492            )
493            .as_str();
494        }
495
496        if self.tcp_type != TcpType::Unspecified {
497            val += format!(" tcptype {}", self.tcp_type()).as_str();
498        }
499
500        val
501    }
502
503    /// The related address to signal and to show in statistics: the candidate's own, or,
504    /// when its base is a host address hidden behind an mDNS name, `0.0.0.0` (`::`) and port
505    /// 9 (draft-ietf-mmusic-mdns-ice-candidates Section 3.1.2.2: "the agent MUST set the
506    /// rel-addr and rel-port fields of the candidate to 0.0.0.0/:: and 9").
507    pub fn signalled_related_address(&self) -> Option<CandidateRelatedAddress> {
508        let related = self.related_address()?;
509        if !self.hide_related_address {
510            return Some(related);
511        }
512        Some(CandidateRelatedAddress {
513            address: if self.network_type().is_ipv6() {
514                "::".to_owned()
515            } else {
516                "0.0.0.0".to_owned()
517            },
518            port: 9,
519        })
520    }
521
522    /// The candidate's socket address.
523    pub fn addr(&self) -> SocketAddr {
524        self.resolved_addr
525    }
526
527    /// Returns the candidate's base address: the local transport address the
528    /// candidate was derived from, i.e. the address packets for this candidate
529    /// must be sent from (RFC 8445 §5.1.1).
530    ///
531    /// For server-reflexive and peer-reflexive candidates this is the related
532    /// (host) address; for host and relay candidates the base is the candidate
533    /// address itself.
534    pub fn base_addr(&self) -> SocketAddr {
535        match self.candidate_type {
536            CandidateType::ServerReflexive | CandidateType::PeerReflexive => self
537                .related_address
538                .as_ref()
539                .and_then(|ra| {
540                    ra.address
541                        .parse::<IpAddr>()
542                        .ok()
543                        .map(|ip| SocketAddr::new(ip, ra.port))
544                })
545                .unwrap_or(self.resolved_addr),
546            _ => self.resolved_addr,
547        }
548    }
549
550    /// Records traffic on this candidate, updating its last-sent or last-received time.
551    ///
552    /// Feeds consent freshness — a pair that stops seeing traffic is eventually abandoned.
553    pub fn seen(&mut self, now: Instant, outbound: bool) {
554        if outbound {
555            self.set_last_sent(now);
556        } else {
557            self.set_last_received(now);
558        }
559    }
560
561    /// Used to compare two candidateBases.
562    pub fn equal(&self, other: &Candidate) -> bool {
563        self.network_type() == other.network_type()
564            && self.candidate_type() == other.candidate_type()
565            && self.address() == other.address()
566            && self.port() == other.port()
567            && self.tcp_type() == other.tcp_type()
568            && self.related_address() == other.related_address()
569    }
570
571    /// Returns true if this candidate can be paired with `other` according to
572    /// ICE candidate pairing rules.
573    ///
574    /// Candidates must share the same network type (protocol and address family)
575    /// and have compatible TCP types (RFC 6544). UDP candidates use
576    /// `TcpType::Unspecified`.
577    pub(crate) fn can_pair_with(&self, other: &Candidate) -> bool {
578        if self.network_type() != other.network_type() {
579            return false;
580        }
581
582        match (self.tcp_type(), other.tcp_type()) {
583            (TcpType::Active, TcpType::Passive) => true,
584            (TcpType::Passive, TcpType::Active) => true,
585            (TcpType::SimultaneousOpen, TcpType::SimultaneousOpen) => true,
586            (TcpType::Unspecified, TcpType::Unspecified) => true, // UDP candidates
587            _ => false,
588        }
589    }
590
591    /// Sets the resolved IP, deriving the network type from it.
592    ///
593    /// # Errors
594    ///
595    /// Fails if `ip`'s family does not match this candidate's network type.
596    pub fn set_ip(&mut self, ip: &IpAddr) -> Result<()> {
597        self.network_type = determine_network_type(&self.network, ip)?;
598        self.resolved_addr = SocketAddr::new(*ip, self.port); //TODO:  create_addr(network_type, *ip, self.port);
599        Ok(())
600    }
601}
602
603impl Candidate {
604    /// When an authenticated Binding request or response last arrived from this candidate.
605    pub fn last_authenticated(&self) -> Option<Instant> {
606        self.last_authenticated
607    }
608
609    /// When a success response to one of our Binding requests last arrived from this candidate:
610    /// the last time the peer granted consent (RFC 7675).
611    pub fn last_consent(&self) -> Option<Instant> {
612        self.last_consent
613    }
614
615    /// Records that traffic was received on this candidate at `now`.
616    pub fn set_last_received(&mut self, now: Instant) {
617        self.last_received = Some(now);
618    }
619
620    /// Records that traffic was sent on this candidate at `now`.
621    pub fn set_last_sent(&mut self, now: Instant) {
622        self.last_sent = Some(now);
623    }
624
625    /// Ranks this candidate among the local candidates of its type: 0 is the most preferred
626    /// (local preference 65535 for UDP, other-pref 8191 for TCP), each further rank one less.
627    ///
628    /// RFC 8445 Section 5.1.2.1 wants a unique local preference for each candidate of a type,
629    /// and RFC 8421 wants candidates from an unreliable interface last. A candidate the
630    /// application does not rank (and gives no priority) is ranked by
631    /// [`Agent::add_local_candidate`](crate::Agent::add_local_candidate), in the order it is
632    /// added, IPv4 and IPv6 interleaved.
633    pub fn set_local_preference_rank(&mut self, rank: u16) {
634        self.local_preference_rank = Some(rank);
635    }
636
637    /// The rank set by [`Candidate::set_local_preference_rank`] or by the agent.
638    pub fn local_preference_rank(&self) -> Option<u16> {
639        self.local_preference_rank
640    }
641
642    /// Returns the local preference for this candidate.
643    pub fn local_preference(&self) -> u16 {
644        let rank = self.local_preference_rank.unwrap_or(0);
645        if self.network_type().is_tcp() {
646            // RFC 6544, section 4.2
647            //
648            // In Section 4.1.2.1 of [RFC5245], a recommended formula for UDP ICE
649            // candidate prioritization is defined.  For TCP candidates, the same
650            // formula and candidate type preferences SHOULD be used, and the
651            // RECOMMENDED type preferences for the new candidate types defined in
652            // this document (see Section 5) are 105 for NAT-assisted candidates and
653            // 75 for UDP-tunneled candidates.
654            //
655            // (...)
656            //
657            // With TCP candidates, the local preference part of the recommended
658            // priority formula is updated to also include the directionality
659            // (active, passive, or simultaneous-open) of the TCP connection.  The
660            // RECOMMENDED local preference is then defined as:
661            //
662            //     local preference = (2^13) * direction-pref + other-pref
663            //
664            // The direction-pref MUST be between 0 and 7 (both inclusive), with 7
665            // being the most preferred.  The other-pref MUST be between 0 and 8191
666            // (both inclusive), with 8191 being the most preferred.  It is
667            // RECOMMENDED that the host, UDP-tunneled, and relayed TCP candidates
668            // have the direction-pref assigned as follows: 6 for active, 4 for
669            // passive, and 2 for S-O.  For the NAT-assisted and server reflexive
670            // candidates, the RECOMMENDED values are: 6 for S-O, 4 for active, and
671            // 2 for passive.
672            //
673            // (...)
674            //
675            // If any two candidates have the same type-preference and direction-
676            // pref, they MUST have a unique other-pref.  With this specification,
677            // this usually only happens with multi-homed hosts, in which case
678            // other-pref is the preference for the particular IP address from which
679            // the candidate was obtained.  When there is only a single IP address,
680            // this value SHOULD be set to the maximum allowed value (8191).
681            let other_pref: u16 = 8191u16.saturating_sub(rank);
682
683            let direction_pref: u16 = match self.candidate_type() {
684                CandidateType::Host | CandidateType::Relay => match self.tcp_type() {
685                    TcpType::Active => 6,
686                    TcpType::Passive => 4,
687                    TcpType::SimultaneousOpen => 2,
688                    TcpType::Unspecified => 0,
689                },
690                CandidateType::PeerReflexive | CandidateType::ServerReflexive => {
691                    match self.tcp_type() {
692                        TcpType::SimultaneousOpen => 6,
693                        TcpType::Active => 4,
694                        TcpType::Passive => 2,
695                        TcpType::Unspecified => 0,
696                    }
697                }
698                CandidateType::Unspecified => 0,
699            };
700
701            (1 << 13) * direction_pref + other_pref
702        } else {
703            DEFAULT_LOCAL_PREFERENCE.saturating_sub(rank)
704        }
705    }
706}
707
708/// Whether two local candidates compete for local preferences: same type, component,
709/// transport and TCP direction (RFC 8445 Section 5.1.2.1, RFC 6544 Section 4.2), neither with a
710/// whole priority of its own.
711pub(crate) fn same_rank_group(a: &Candidate, b: &Candidate) -> bool {
712    a.candidate_type() == b.candidate_type()
713        && a.component() == b.component()
714        && a.network_type().is_tcp() == b.network_type().is_tcp()
715        && a.tcp_type() == b.tcp_type()
716        && a.priority_override == 0
717        && b.priority_override == 0
718}
719
720/// Ranks a set of local candidates gathered together, as RFC 8421 Section 4 recommends for a
721/// dual-stack host: within each type, the IPv6 candidates get a head start of
722/// `Hi = (N_4 + N_6) / N_4` places ("If a host has two IPv4 addresses and six IPv6 addresses,
723/// it will insert an IPv4 address after four IPv6 addresses"), then the two families
724/// alternate, so that both get checks early. Candidates that have a rank or a priority keep
725/// it, and their ranks are not given out again (RFC 8445 Section 5.1.2.1: unique local
726/// preferences); a set of one family is ranked in its order, the first keeping 65535 (Section
727/// 5.1.2.1: "When there is only a single IP address, this value SHOULD be set to 65535").
728///
729/// For candidates added one at a time the agent can only rank in the order they come (a
730/// priority once signalled does not change); an application that has its host candidates
731/// together ranks them here before it signals them, or adds them with
732/// [`Agent::add_local_candidates`](crate::Agent::add_local_candidates), which does this
733/// against the candidates the agent holds.
734pub fn rank_local_candidates(candidates: &mut [Candidate]) {
735    assign_dual_stack_ranks(&[], candidates);
736}
737
738/// [`rank_local_candidates`] for `batch`, with the ranks of `held` (candidates already
739/// ranked) taken.
740pub(crate) fn assign_dual_stack_ranks(held: &[Candidate], batch: &mut [Candidate]) {
741    let unranked = |c: &Candidate| c.priority_override == 0 && c.local_preference_rank.is_none();
742    let mut done = vec![false; batch.len()];
743    for first in 0..batch.len() {
744        if done[first] || !unranked(&batch[first]) {
745            continue;
746        }
747        // The group of `first`: its unranked members in the batch, by family, in order.
748        let members: Vec<usize> = (first..batch.len())
749            .filter(|&i| {
750                !done[i] && unranked(&batch[i]) && same_rank_group(&batch[first], &batch[i])
751            })
752            .collect();
753        for &i in &members {
754            done[i] = true;
755        }
756        let (v6, v4): (Vec<usize>, Vec<usize>) = members
757            .iter()
758            .partition(|&&i| batch[i].network_type().is_ipv6());
759        let head_start = if v4.is_empty() {
760            v6.len()
761        } else {
762            (v4.len() + v6.len()) / v4.len()
763        };
764        let mut order: Vec<usize> = v6.iter().take(head_start).copied().collect();
765        let (mut rest6, mut rest4) = (v6.iter().skip(head_start), v4.iter());
766        loop {
767            let (a, b) = (rest4.next(), rest6.next());
768            if a.is_none() && b.is_none() {
769                break;
770            }
771            order.extend(a.into_iter().chain(b).copied());
772        }
773        let mut taken: Vec<u16> = held
774            .iter()
775            .chain(batch.iter())
776            .filter(|c| same_rank_group(&batch[first], c))
777            .filter_map(|c| c.local_preference_rank)
778            .collect();
779        let mut rank = 0u16;
780        for i in order {
781            while taken.contains(&rank) {
782                rank = rank.saturating_add(1);
783            }
784            batch[i].local_preference_rank = Some(rank);
785            taken.push(rank);
786        }
787    }
788}
789
790/// Creates a Candidate from its string representation.
791pub fn unmarshal_candidate(raw: &str) -> Result<Candidate> {
792    let split: Vec<&str> = raw.split_whitespace().collect();
793    if split.len() < 8 {
794        return Err(Error::Other(format!(
795            "{:?} ({})",
796            Error::ErrAttributeTooShortIceCandidate,
797            split.len()
798        )));
799    }
800
801    // Foundation
802    let foundation = split[0].to_owned();
803
804    // Component: RFC 8445 §5.1.1.1 numbers components from 1 to 256, and priority() relies on
805    // the bound (its last term is `256 - component`).
806    let component: u16 = split[1].parse()?;
807    if !(1..=256).contains(&component) {
808        return Err(Error::Other(format!(
809            "{:?}: component {component} is outside 1..=256",
810            Error::ErrParseComponent
811        )));
812    }
813
814    // Network
815    let network = split[2].to_owned();
816
817    // Priority
818    let priority: u32 = split[3].parse()?;
819
820    // Address
821    let address = split[4].to_owned();
822
823    // Port
824    let port: u16 = split[5].parse()?;
825
826    let typ = split[7];
827
828    let mut rel_addr = String::new();
829    let mut rel_port = 0;
830    let mut tcp_type = TcpType::Unspecified;
831
832    if split.len() > 8 {
833        let mut split2 = &split[8..];
834
835        if split2[0] == "raddr" {
836            if split2.len() < 4 {
837                return Err(Error::Other(format!(
838                    "{:?}: incorrect length",
839                    Error::ErrParseRelatedAddr
840                )));
841            }
842
843            // RelatedAddress
844            split2[1].clone_into(&mut rel_addr);
845
846            // RelatedPort
847            rel_port = split2[3].parse()?;
848            split2 = &split2[4..];
849        }
850
851        // The extension attributes are name / value pairs in any order (RFC 8839 Section
852        // 5.1); `tcptype` (RFC 6544 Section 4.5) is one of them, for every candidate type.
853        for extension in split2.chunks(2) {
854            if extension[0] == "tcptype" {
855                if extension.len() < 2 {
856                    return Err(Error::Other(format!(
857                        "{:?}: incorrect length",
858                        Error::ErrParseType
859                    )));
860                }
861                tcp_type = TcpType::from(extension[1]);
862            }
863        }
864    }
865
866    match typ {
867        "host" => {
868            let config = CandidateHostConfig {
869                base_config: CandidateConfig {
870                    network,
871                    address,
872                    port,
873                    component,
874                    priority,
875                    foundation,
876                    ..CandidateConfig::default()
877                },
878                tcp_type,
879            };
880            config.new_candidate_host()
881        }
882        "srflx" => {
883            let config = CandidateServerReflexiveConfig {
884                base_config: CandidateConfig {
885                    network,
886                    address,
887                    port,
888                    component,
889                    priority,
890                    foundation,
891                    ..CandidateConfig::default()
892                },
893                rel_addr,
894                rel_port,
895                url: None,
896            };
897            config.new_candidate_server_reflexive().map(|mut c| {
898                c.tcp_type = tcp_type;
899                c
900            })
901        }
902        "prflx" => {
903            let config = CandidatePeerReflexiveConfig {
904                base_config: CandidateConfig {
905                    network,
906                    address,
907                    port,
908                    component,
909                    priority,
910                    foundation,
911                    ..CandidateConfig::default()
912                },
913                rel_addr,
914                rel_port,
915            };
916
917            config.new_candidate_peer_reflexive().map(|mut c| {
918                c.tcp_type = tcp_type;
919                c
920            })
921        }
922        "relay" => {
923            let config = CandidateRelayConfig {
924                base_config: CandidateConfig {
925                    network,
926                    address,
927                    port,
928                    component,
929                    priority,
930                    foundation,
931                    ..CandidateConfig::default()
932                },
933                rel_addr,
934                rel_port,
935                url: None,
936            };
937            config.new_candidate_relay().map(|mut c| {
938                c.tcp_type = tcp_type;
939                c
940            })
941        }
942        _ => Err(Error::Other(format!(
943            "{:?} ({})",
944            Error::ErrUnknownCandidateType,
945            typ
946        ))),
947    }
948}