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