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/// The type preference of a UDP-tunnelled TCP candidate (RFC 6544 Section 4.2: "the
198/// RECOMMENDED type preferences for the new candidate types defined in this document ... are
199/// 105 for NAT-assisted candidates and 75 for UDP-tunneled candidates").
200pub const UDP_TUNNELLED_TYPE_PREFERENCE: u16 = 75;
201
202/// Whether `ip` is a Teredo address, 2001::/32 (RFC 4380 Section 2.6): an address of a UDP
203/// tunnel (RFC 6544 Section 5.4).
204pub fn is_teredo(ip: std::net::IpAddr) -> bool {
205    match ip {
206        std::net::IpAddr::V6(v6) => v6.segments()[..2] == [0x2001, 0],
207        std::net::IpAddr::V4(_) => false,
208    }
209}
210
211#[derive(Clone, Debug)]
212/// One ICE candidate: a transport address this agent can be reached at, or can reach a peer
213/// at, together with its type, priority and liveness bookkeeping.
214pub struct Candidate {
215    pub(crate) id: String,
216    pub(crate) network_type: NetworkType,
217    pub(crate) candidate_type: CandidateType,
218
219    pub(crate) component: u16,
220    pub(crate) address: String,
221    pub(crate) port: u16,
222    pub(crate) related_address: Option<CandidateRelatedAddress>,
223    pub(crate) tcp_type: TcpType,
224
225    pub(crate) resolved_addr: SocketAddr,
226
227    /// When traffic was last sent on this candidate, or `None` if none ever has been.
228    pub(crate) last_sent: Option<Instant>,
229    /// When traffic was last received on this candidate, or `None` if none ever has been.
230    pub(crate) last_received: Option<Instant>,
231    /// When an authenticated (MESSAGE-INTEGRITY checked) Binding request or response last
232    /// arrived from this candidate. Consent freshness (RFC 7675) is judged on this alone, so
233    /// unauthenticated traffic from the address cannot keep a dead pair alive.
234    pub(crate) last_authenticated: Option<Instant>,
235    /// When an authenticated success response to one of our own pending Binding requests last
236    /// arrived from this candidate. This is consent (RFC 7675 §5.1): the peer's own requests do
237    /// not grant it.
238    pub(crate) last_consent: Option<Instant>,
239
240    pub(crate) foundation_override: String,
241    pub(crate) priority_override: u32,
242    /// Where this candidate stands among the local candidates of its type (0 is the most
243    /// preferred): the local preference is the largest value less this rank. `None` until the
244    /// application or the agent ranks it. See [`Candidate::set_local_preference_rank`].
245    pub(crate) local_preference_rank: Option<u16>,
246    /// The related address (the base) is a host address hidden behind an mDNS name: it is
247    /// not signalled. See [`Candidate::signalled_related_address`].
248    pub(crate) hide_related_address: bool,
249    /// A local candidate the agent holds but has not been told is conveyed to the peer yet:
250    /// it is not paired until it is (RFC 8838 Section 10). See
251    /// [`Agent::add_unconveyed_local_candidate`](crate::agent::Agent::add_unconveyed_local_candidate).
252    pub(crate) unconveyed: bool,
253    /// A local candidate gathered (or gathered again) while an ICE restart is staged
254    /// ([`Agent::generate_restart_credentials`](crate::agent::Agent::generate_restart_credentials)):
255    /// it is the new generation's, so the restart keeps it even when it discards the previous
256    /// generation's local candidates.
257    pub(crate) restart_generation: bool,
258    /// A local candidate new to the agent that arrived while a restart was staged and the
259    /// current session had nominated a pair: it is not paired in that session (RFC 8838
260    /// Section 13), only in the one the restart begins.
261    pub(crate) awaiting_restart: bool,
262    /// A local candidate withdrawn
263    /// ([`Agent::withdraw_local_candidate`](crate::agent::Agent::withdraw_local_candidate)):
264    /// never paired again, nor signalled; its pairs other than the one carrying the data are
265    /// removed; the next restart drops it.
266    pub(crate) withdrawn: bool,
267
268    pub(crate) network: String,
269
270    pub(crate) url: Option<String>,
271}
272
273impl Default for Candidate {
274    fn default() -> Self {
275        Self {
276            id: String::new(),
277            network_type: NetworkType::Unspecified,
278            candidate_type: CandidateType::default(),
279
280            component: 0,
281            address: String::new(),
282            port: 0,
283            related_address: None,
284            tcp_type: TcpType::default(),
285
286            resolved_addr: SocketAddr::new(IpAddr::from([0, 0, 0, 0]), 0),
287
288            last_sent: None,
289            last_received: None,
290            last_authenticated: None,
291            last_consent: None,
292
293            foundation_override: String::new(),
294            priority_override: 0,
295            local_preference_rank: None,
296            hide_related_address: false,
297            unconveyed: false,
298            restart_generation: false,
299            awaiting_restart: false,
300            withdrawn: false,
301            network: String::new(),
302
303            url: None,
304        }
305    }
306}
307
308// String makes the candidateBase printable
309impl fmt::Display for Candidate {
310    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
311        if let Some(related_address) = self.related_address() {
312            write!(
313                f,
314                "{} {} {}:{}{}",
315                self.network_type(),
316                self.candidate_type(),
317                self.address(),
318                self.port(),
319                related_address,
320            )
321        } else {
322            write!(
323                f,
324                "{} {} {}:{}",
325                self.network_type(),
326                self.candidate_type(),
327                self.address(),
328                self.port(),
329            )
330        }
331    }
332}
333
334impl Candidate {
335    /// The candidate's foundation (RFC 8445 Section 5.1.1.3): two candidates have the same one
336    /// when they have the same type, their bases have the same IP address (ports may differ),
337    /// they came from the same STUN or TURN server (reflexive and relayed ones) and they use
338    /// the same transport protocol.
339    ///
340    /// A host candidate's base is itself (an mDNS name stands for its address); a reflexive
341    /// candidate's base is its related address; a relayed candidate's base is the relayed
342    /// address. A foundation groups equivalent candidates; it is deterministic bookkeeping
343    /// rather than a secret, random identifier. CRC-32C is therefore intentional here.
344    pub fn foundation(&self) -> String {
345        if !self.foundation_override.is_empty() {
346            return self.foundation_override.clone();
347        }
348
349        let base = match (self.candidate_type, &self.related_address) {
350            (CandidateType::ServerReflexive | CandidateType::PeerReflexive, Some(related))
351                if !related.address.is_empty() =>
352            {
353                related.address.as_str()
354            }
355            _ => self.address.as_str(),
356        };
357
358        let mut buf = vec![];
359        buf.extend_from_slice(self.candidate_type().to_string().as_bytes());
360        buf.extend_from_slice(base.as_bytes());
361        buf.extend_from_slice(self.network_type().to_string().as_bytes());
362        if let Some(url) = &self.url {
363            buf.extend_from_slice(url.as_bytes());
364        }
365
366        let checksum = Crc::<u32>::new(&CRC_32_ISCSI).checksum(&buf);
367
368        format!("{checksum}")
369    }
370
371    /// Returns Candidate ID.
372    pub fn id(&self) -> &str {
373        self.id.as_str()
374    }
375
376    /// Returns candidate component.
377    pub fn component(&self) -> u16 {
378        self.component
379    }
380
381    /// Sets candidate component.
382    pub fn set_component(&mut self, component: u16) {
383        self.component = component;
384    }
385
386    /// A local candidate the agent does not pair yet: not conveyed to the peer, or waiting
387    /// for the restart it was gathered for.
388    pub(crate) fn held_from_pairing(&self) -> bool {
389        self.unconveyed || self.awaiting_restart || self.withdrawn
390    }
391
392    /// When traffic was last received on this candidate.
393    ///
394    /// `None` until the first packet arrives. A freshly constructed or freshly parsed candidate
395    /// has not received anything, and previously said it had — it was seeded with the
396    /// construction instant, which also meant every candidate constructor needed a clock.
397    pub fn last_received(&self) -> Option<Instant> {
398        self.last_received
399    }
400
401    /// When traffic was last sent on this candidate, or `None` if none ever has been.
402    pub fn last_sent(&self) -> Option<Instant> {
403        self.last_sent
404    }
405
406    /// Returns candidate NetworkType.
407    pub fn network_type(&self) -> NetworkType {
408        self.network_type
409    }
410
411    /// Returns Candidate Address.
412    pub fn address(&self) -> &str {
413        self.address.as_str()
414    }
415
416    /// Returns Candidate Port.
417    pub fn port(&self) -> u16 {
418        self.port
419    }
420
421    /// Computes the priority for this ICE Candidate.
422    pub fn priority(&self) -> u32 {
423        if self.priority_override != 0 {
424            return self.priority_override;
425        }
426
427        // The local preference MUST be an integer from 0 (lowest preference) to
428        // 65535 (highest preference) inclusive.  When there is only a single IP
429        // address, this value SHOULD be set to 65535.  If there are multiple
430        // candidates for a particular component for a particular data stream
431        // that have the same type, the local preference MUST be unique for each
432        // one.
433        (1 << 24) * u32::from(self.type_preference(self.candidate_type()))
434            + (1 << 8) * u32::from(self.local_preference())
435            + 256u32.saturating_sub(u32::from(self.component()))
436    }
437
438    /// The type preference of `candidate_type` on this candidate's transport. RFC 6544
439    /// section 4.2: "the type preferences for the preferred transport protocol candidates
440    /// SHOULD be increased and/or the type preferences for the other transport protocol
441    /// candidates SHOULD be decreased ... changing type preference values by one for the other
442    /// transport protocol candidates is enough" when the candidate type matters more, and "For
443    /// RTP-based media streams, it is RECOMMENDED that UDP candidates are preferred over TCP
444    /// candidates". A TCP candidate takes the UDP type preference less one (host 125,
445    /// peer-reflexive 109, server-reflexive 99): a TCP host candidate still outranks a UDP
446    /// server-reflexive one, a UDP candidate outranks the TCP one of its type. A relayed TCP
447    /// candidate stays at 0 ("relayed candidates are still preferred lower than the other
448    /// candidate types"), below the UDP relayed one by its local preference.
449    ///
450    /// A TCP host candidate on a Teredo address (2001::/32, RFC 4380) is a UDP-tunnelled
451    /// candidate (RFC 6544 Section 5.4: it "may appear to applications as host candidates from
452    /// a local pseudo-interface. Treating these candidates as host candidates results in
453    /// incorrect prioritization ... Implementations may attempt to detect pseudo-interfaces,
454    /// e.g., from the address prefix of the interface"): it takes the type preference Section
455    /// 4.2 recommends for UDP-tunnelled candidates, [`UDP_TUNNELLED_TYPE_PREFERENCE`].
456    pub fn type_preference(&self, candidate_type: CandidateType) -> u16 {
457        if candidate_type == CandidateType::Host
458            && self.network_type().is_tcp()
459            && is_teredo(self.addr().ip())
460        {
461            return UDP_TUNNELLED_TYPE_PREFERENCE;
462        }
463        let preference = candidate_type.preference();
464        if self.network_type().is_tcp() {
465            preference.saturating_sub(1)
466        } else {
467            preference
468        }
469    }
470
471    /// The priority this candidate would have as a peer-reflexive one: the value of the
472    /// PRIORITY attribute in a connectivity check sent from it (RFC 8445 Section 7.1.1). The
473    /// peer-reflexive type preference (of its transport, RFC 6544 section 4.2), with this
474    /// candidate's local preference and component.
475    pub fn peer_reflexive_priority(&self) -> u32 {
476        (u32::from(self.type_preference(CandidateType::PeerReflexive)) << 24)
477            | (self.priority() & 0x00ff_ffff)
478    }
479
480    /// Returns `Option<CandidateRelatedAddress>`.
481    pub fn related_address(&self) -> Option<CandidateRelatedAddress> {
482        self.related_address.as_ref().cloned()
483    }
484
485    /// Returns candidate type.
486    pub fn candidate_type(&self) -> CandidateType {
487        self.candidate_type
488    }
489
490    /// The TCP role for ICE-TCP candidates; `Unspecified` for UDP.
491    pub fn tcp_type(&self) -> TcpType {
492        self.tcp_type
493    }
494
495    /// Sets the TCP role of an ICE-TCP candidate of any type (RFC 6544 Section 4.5: every TCP
496    /// candidate is signalled with a `tcptype`).
497    pub fn set_tcp_type(&mut self, tcp_type: TcpType) {
498        self.tcp_type = tcp_type;
499    }
500
501    /// The STUN or TURN server this candidate was gathered from, if any.
502    pub fn url(&self) -> Option<&str> {
503        self.url.as_deref()
504    }
505
506    /// Returns the string representation of the ICECandidate.
507    pub fn marshal(&self) -> String {
508        let mut val = format!(
509            "{} {} {} {} {} {} typ {}",
510            self.foundation(),
511            self.component(),
512            self.network_type().network_short(),
513            self.priority(),
514            self.address(),
515            self.port(),
516            self.candidate_type()
517        );
518
519        // RFC 8839 Section 5.1: rel-addr and rel-port come before the extension attributes,
520        // of which `tcptype` (RFC 6544 Section 4.5) is one, for every candidate type.
521        if let Some(related_address) = self.signalled_related_address() {
522            val += format!(
523                " raddr {} rport {}",
524                related_address.address, related_address.port,
525            )
526            .as_str();
527        }
528
529        if self.tcp_type != TcpType::Unspecified {
530            val += format!(" tcptype {}", self.tcp_type()).as_str();
531        }
532
533        val
534    }
535
536    /// The related address to signal and to show in statistics: the candidate's own, or,
537    /// when its base is a host address hidden behind an mDNS name, `0.0.0.0` (`::`) and port
538    /// 9 (draft-ietf-mmusic-mdns-ice-candidates Section 3.1.2.2: "the agent MUST set the
539    /// rel-addr and rel-port fields of the candidate to 0.0.0.0/:: and 9").
540    pub fn signalled_related_address(&self) -> Option<CandidateRelatedAddress> {
541        let related = self.related_address()?;
542        if !self.hide_related_address {
543            return Some(related);
544        }
545        Some(CandidateRelatedAddress {
546            address: if self.network_type().is_ipv6() {
547                "::".to_owned()
548            } else {
549                "0.0.0.0".to_owned()
550            },
551            port: 9,
552        })
553    }
554
555    /// The candidate's socket address.
556    pub fn addr(&self) -> SocketAddr {
557        self.resolved_addr
558    }
559
560    /// Returns the candidate's base address: the local transport address the
561    /// candidate was derived from, i.e. the address packets for this candidate
562    /// must be sent from (RFC 8445 §5.1.1).
563    ///
564    /// For server-reflexive and peer-reflexive candidates this is the related
565    /// (host) address; for host and relay candidates the base is the candidate
566    /// address itself.
567    pub fn base_addr(&self) -> SocketAddr {
568        match self.candidate_type {
569            CandidateType::ServerReflexive | CandidateType::PeerReflexive => self
570                .related_address
571                .as_ref()
572                .and_then(|ra| {
573                    ra.address
574                        .parse::<IpAddr>()
575                        .ok()
576                        .map(|ip| SocketAddr::new(ip, ra.port))
577                })
578                .unwrap_or(self.resolved_addr),
579            _ => self.resolved_addr,
580        }
581    }
582
583    /// Records traffic on this candidate, updating its last-sent or last-received time.
584    ///
585    /// Feeds consent freshness — a pair that stops seeing traffic is eventually abandoned.
586    pub fn seen(&mut self, now: Instant, outbound: bool) {
587        if outbound {
588            self.set_last_sent(now);
589        } else {
590            self.set_last_received(now);
591        }
592    }
593
594    /// Used to compare two candidateBases.
595    pub fn equal(&self, other: &Candidate) -> bool {
596        self.network_type() == other.network_type()
597            && self.candidate_type() == other.candidate_type()
598            && self.address() == other.address()
599            && self.port() == other.port()
600            && self.tcp_type() == other.tcp_type()
601            && self.related_address() == other.related_address()
602    }
603
604    /// Returns true if this candidate can be paired with `other` according to
605    /// ICE candidate pairing rules.
606    ///
607    /// Candidates must share the same network type (protocol and address family)
608    /// and have compatible TCP types (RFC 6544). UDP candidates use
609    /// `TcpType::Unspecified`.
610    pub(crate) fn can_pair_with(&self, other: &Candidate) -> bool {
611        if self.network_type() != other.network_type() {
612            return false;
613        }
614
615        match (self.tcp_type(), other.tcp_type()) {
616            (TcpType::Active, TcpType::Passive) => true,
617            (TcpType::Passive, TcpType::Active) => true,
618            (TcpType::SimultaneousOpen, TcpType::SimultaneousOpen) => true,
619            (TcpType::Unspecified, TcpType::Unspecified) => true, // UDP candidates
620            _ => false,
621        }
622    }
623
624    /// Sets the resolved IP, deriving the network type from it.
625    ///
626    /// # Errors
627    ///
628    /// Fails if `ip`'s family does not match this candidate's network type.
629    pub fn set_ip(&mut self, ip: &IpAddr) -> Result<()> {
630        self.network_type = determine_network_type(&self.network, ip)?;
631        self.resolved_addr = SocketAddr::new(*ip, self.port); //TODO:  create_addr(network_type, *ip, self.port);
632        Ok(())
633    }
634}
635
636impl Candidate {
637    /// When an authenticated Binding request or response last arrived from this candidate.
638    pub fn last_authenticated(&self) -> Option<Instant> {
639        self.last_authenticated
640    }
641
642    /// When a success response to one of our Binding requests last arrived from this candidate:
643    /// the last time the peer granted consent (RFC 7675).
644    pub fn last_consent(&self) -> Option<Instant> {
645        self.last_consent
646    }
647
648    /// Records that traffic was received on this candidate at `now`.
649    pub fn set_last_received(&mut self, now: Instant) {
650        self.last_received = Some(now);
651    }
652
653    /// Records that traffic was sent on this candidate at `now`.
654    pub fn set_last_sent(&mut self, now: Instant) {
655        self.last_sent = Some(now);
656    }
657
658    /// Ranks this candidate among the local candidates of its type: 0 is the most preferred
659    /// (local preference 65535 for UDP, other-pref 8191 for TCP), each further rank one less.
660    ///
661    /// RFC 8445 Section 5.1.2.1 wants a unique local preference for each candidate of a type,
662    /// and RFC 8421 wants candidates from an unreliable interface last. A candidate the
663    /// application does not rank (and gives no priority) is ranked by
664    /// [`Agent::add_local_candidate`](crate::Agent::add_local_candidate), in the order it is
665    /// added, IPv4 and IPv6 interleaved.
666    pub fn set_local_preference_rank(&mut self, rank: u16) {
667        self.local_preference_rank = Some(rank);
668    }
669
670    /// The rank set by [`Candidate::set_local_preference_rank`] or by the agent.
671    pub fn local_preference_rank(&self) -> Option<u16> {
672        self.local_preference_rank
673    }
674
675    /// Returns the local preference for this candidate.
676    pub fn local_preference(&self) -> u16 {
677        let rank = self.local_preference_rank.unwrap_or(0);
678        if self.network_type().is_tcp() {
679            // RFC 6544, section 4.2
680            //
681            // In Section 4.1.2.1 of [RFC5245], a recommended formula for UDP ICE
682            // candidate prioritization is defined.  For TCP candidates, the same
683            // formula and candidate type preferences SHOULD be used, and the
684            // RECOMMENDED type preferences for the new candidate types defined in
685            // this document (see Section 5) are 105 for NAT-assisted candidates and
686            // 75 for UDP-tunneled candidates.
687            //
688            // (...)
689            //
690            // With TCP candidates, the local preference part of the recommended
691            // priority formula is updated to also include the directionality
692            // (active, passive, or simultaneous-open) of the TCP connection.  The
693            // RECOMMENDED local preference is then defined as:
694            //
695            //     local preference = (2^13) * direction-pref + other-pref
696            //
697            // The direction-pref MUST be between 0 and 7 (both inclusive), with 7
698            // being the most preferred.  The other-pref MUST be between 0 and 8191
699            // (both inclusive), with 8191 being the most preferred.  It is
700            // RECOMMENDED that the host, UDP-tunneled, and relayed TCP candidates
701            // have the direction-pref assigned as follows: 6 for active, 4 for
702            // passive, and 2 for S-O.  For the NAT-assisted and server reflexive
703            // candidates, the RECOMMENDED values are: 6 for S-O, 4 for active, and
704            // 2 for passive.
705            //
706            // (...)
707            //
708            // If any two candidates have the same type-preference and direction-
709            // pref, they MUST have a unique other-pref.  With this specification,
710            // this usually only happens with multi-homed hosts, in which case
711            // other-pref is the preference for the particular IP address from which
712            // the candidate was obtained.  When there is only a single IP address,
713            // this value SHOULD be set to the maximum allowed value (8191).
714            let other_pref: u16 = 8191u16.saturating_sub(rank);
715
716            let direction_pref: u16 = match self.candidate_type() {
717                CandidateType::Host | CandidateType::Relay => match self.tcp_type() {
718                    TcpType::Active => 6,
719                    TcpType::Passive => 4,
720                    TcpType::SimultaneousOpen => 2,
721                    TcpType::Unspecified => 0,
722                },
723                CandidateType::PeerReflexive | CandidateType::ServerReflexive => {
724                    match self.tcp_type() {
725                        TcpType::SimultaneousOpen => 6,
726                        TcpType::Active => 4,
727                        TcpType::Passive => 2,
728                        TcpType::Unspecified => 0,
729                    }
730                }
731                CandidateType::Unspecified => 0,
732            };
733
734            (1 << 13) * direction_pref + other_pref
735        } else {
736            DEFAULT_LOCAL_PREFERENCE.saturating_sub(rank)
737        }
738    }
739}
740
741/// Whether two local candidates compete for local preferences: same type, component,
742/// transport and TCP direction (RFC 8445 Section 5.1.2.1, RFC 6544 Section 4.2), neither with a
743/// whole priority of its own.
744pub(crate) fn same_rank_group(a: &Candidate, b: &Candidate) -> bool {
745    a.candidate_type() == b.candidate_type()
746        && a.component() == b.component()
747        && a.network_type().is_tcp() == b.network_type().is_tcp()
748        && a.tcp_type() == b.tcp_type()
749        && a.priority_override == 0
750        && b.priority_override == 0
751}
752
753/// Ranks a set of local candidates gathered together, as RFC 8421 Section 4 recommends for a
754/// dual-stack host: within each type, the IPv6 candidates get a head start of
755/// `Hi = (N_4 + N_6) / N_4` places ("If a host has two IPv4 addresses and six IPv6 addresses,
756/// it will insert an IPv4 address after four IPv6 addresses"), then the two families
757/// alternate, so that both get checks early. Candidates that have a rank or a priority keep
758/// it, and their ranks are not given out again (RFC 8445 Section 5.1.2.1: unique local
759/// preferences); a set of one family is ranked in its order, the first keeping 65535 (Section
760/// 5.1.2.1: "When there is only a single IP address, this value SHOULD be set to 65535").
761///
762/// For candidates added one at a time the agent can only rank in the order they come (a
763/// priority once signalled does not change); an application that has its host candidates
764/// together ranks them here before it signals them, or adds them with
765/// [`Agent::add_local_candidates`](crate::Agent::add_local_candidates), which does this
766/// against the candidates the agent holds.
767pub fn rank_local_candidates(candidates: &mut [Candidate]) {
768    assign_dual_stack_ranks(&[], candidates);
769}
770
771/// [`rank_local_candidates`] for `batch`, with the ranks of `held` (candidates already
772/// ranked) taken.
773pub(crate) fn assign_dual_stack_ranks(held: &[Candidate], batch: &mut [Candidate]) {
774    let unranked = |c: &Candidate| c.priority_override == 0 && c.local_preference_rank.is_none();
775    let mut done = vec![false; batch.len()];
776    for first in 0..batch.len() {
777        if done[first] || !unranked(&batch[first]) {
778            continue;
779        }
780        // The group of `first`: its unranked members in the batch, by family, in order.
781        let members: Vec<usize> = (first..batch.len())
782            .filter(|&i| {
783                !done[i] && unranked(&batch[i]) && same_rank_group(&batch[first], &batch[i])
784            })
785            .collect();
786        for &i in &members {
787            done[i] = true;
788        }
789        let (v6, v4): (Vec<usize>, Vec<usize>) = members
790            .iter()
791            .partition(|&&i| batch[i].network_type().is_ipv6());
792        let head_start = if v4.is_empty() {
793            v6.len()
794        } else {
795            (v4.len() + v6.len()) / v4.len()
796        };
797        let mut order: Vec<usize> = v6.iter().take(head_start).copied().collect();
798        let (mut rest6, mut rest4) = (v6.iter().skip(head_start), v4.iter());
799        loop {
800            let (a, b) = (rest4.next(), rest6.next());
801            if a.is_none() && b.is_none() {
802                break;
803            }
804            order.extend(a.into_iter().chain(b).copied());
805        }
806        let mut taken: Vec<u16> = held
807            .iter()
808            .chain(batch.iter())
809            .filter(|c| same_rank_group(&batch[first], c))
810            .filter_map(|c| c.local_preference_rank)
811            .collect();
812        let mut rank = 0u16;
813        for i in order {
814            while taken.contains(&rank) {
815                rank = rank.saturating_add(1);
816            }
817            batch[i].local_preference_rank = Some(rank);
818            taken.push(rank);
819        }
820    }
821}
822
823/// Creates a Candidate from its string representation.
824pub fn unmarshal_candidate(raw: &str) -> Result<Candidate> {
825    let split: Vec<&str> = raw.split_whitespace().collect();
826    if split.len() < 8 {
827        return Err(Error::Other(format!(
828            "{:?} ({})",
829            Error::ErrAttributeTooShortIceCandidate,
830            split.len()
831        )));
832    }
833
834    // Foundation
835    let foundation = split[0].to_owned();
836
837    // Component: RFC 8445 §5.1.1.1 numbers components from 1 to 256, and priority() relies on
838    // the bound (its last term is `256 - component`).
839    let component: u16 = split[1].parse()?;
840    if !(1..=256).contains(&component) {
841        return Err(Error::Other(format!(
842            "{:?}: component {component} is outside 1..=256",
843            Error::ErrParseComponent
844        )));
845    }
846
847    // Network
848    let network = split[2].to_owned();
849
850    // Priority
851    let priority: u32 = split[3].parse()?;
852
853    // Address
854    let address = split[4].to_owned();
855
856    // Port
857    let port: u16 = split[5].parse()?;
858
859    let typ = split[7];
860
861    let mut rel_addr = String::new();
862    let mut rel_port = 0;
863    let mut tcp_type = TcpType::Unspecified;
864
865    if split.len() > 8 {
866        let mut split2 = &split[8..];
867
868        if split2[0] == "raddr" {
869            if split2.len() < 4 {
870                return Err(Error::Other(format!(
871                    "{:?}: incorrect length",
872                    Error::ErrParseRelatedAddr
873                )));
874            }
875
876            // RelatedAddress
877            split2[1].clone_into(&mut rel_addr);
878
879            // RelatedPort
880            rel_port = split2[3].parse()?;
881            split2 = &split2[4..];
882        }
883
884        // The extension attributes are name / value pairs in any order (RFC 8839 Section
885        // 5.1); `tcptype` (RFC 6544 Section 4.5) is one of them, for every candidate type.
886        for extension in split2.chunks(2) {
887            if extension[0] == "tcptype" {
888                if extension.len() < 2 {
889                    return Err(Error::Other(format!(
890                        "{:?}: incorrect length",
891                        Error::ErrParseType
892                    )));
893                }
894                tcp_type = TcpType::from(extension[1]);
895            }
896        }
897    }
898
899    match typ {
900        "host" => {
901            let config = CandidateHostConfig {
902                base_config: CandidateConfig {
903                    network,
904                    address,
905                    port,
906                    component,
907                    priority,
908                    foundation,
909                    ..CandidateConfig::default()
910                },
911                tcp_type,
912            };
913            config.new_candidate_host()
914        }
915        "srflx" => {
916            let config = CandidateServerReflexiveConfig {
917                base_config: CandidateConfig {
918                    network,
919                    address,
920                    port,
921                    component,
922                    priority,
923                    foundation,
924                    ..CandidateConfig::default()
925                },
926                rel_addr,
927                rel_port,
928                url: None,
929            };
930            config.new_candidate_server_reflexive().map(|mut c| {
931                c.tcp_type = tcp_type;
932                c
933            })
934        }
935        "prflx" => {
936            let config = CandidatePeerReflexiveConfig {
937                base_config: CandidateConfig {
938                    network,
939                    address,
940                    port,
941                    component,
942                    priority,
943                    foundation,
944                    ..CandidateConfig::default()
945                },
946                rel_addr,
947                rel_port,
948            };
949
950            config.new_candidate_peer_reflexive().map(|mut c| {
951                c.tcp_type = tcp_type;
952                c
953            })
954        }
955        "relay" => {
956            let config = CandidateRelayConfig {
957                base_config: CandidateConfig {
958                    network,
959                    address,
960                    port,
961                    component,
962                    priority,
963                    foundation,
964                    ..CandidateConfig::default()
965                },
966                rel_addr,
967                rel_port,
968                url: None,
969            };
970            config.new_candidate_relay().map(|mut c| {
971                c.tcp_type = tcp_type;
972                c
973            })
974        }
975        _ => Err(Error::Other(format!(
976            "{:?} ({})",
977            Error::ErrUnknownCandidateType,
978            typ
979        ))),
980    }
981}