Skip to main content

qualia_core_db/p2p/connectivity/
ice.rs

1//! Bounded ICE checklist. Procedure for UDP/TURN, not a second transport.
2
3#![cfg(not(target_arch = "wasm32"))]
4
5use crate::net::peer::connectivity::candidates::{
6    gather_permitted, AddrFamily, CandidateKind, CandidateTables, PairState,
7};
8use crate::net::peer::connectivity::path::{consent_fresh, resolve_role_conflict};
9use crate::net::peer::connectivity::planner::{tick, Schedule, Scheduled};
10use crate::net::peer::connectivity::policy::PathPolicy;
11use crate::net::peer::connectivity::state::ConnSlot;
12use crate::p2p::stun_observe::{encode_binding_success_v4, parse_xor_mapped_v4};
13
14#[derive(Debug, Clone, Copy, PartialEq, Eq)]
15pub enum IceRole {
16    Controlling,
17    Controlled,
18}
19
20pub struct IceAgent {
21    pub role: IceRole,
22    pub policy: PathPolicy,
23    pub tables: CandidateTables,
24    pub slot: ConnSlot,
25    pub schedule: Schedule,
26}
27
28impl IceAgent {
29    /// Creates a default `IceAgent`.
30    pub fn new(role: IceRole, policy: PathPolicy, has_v6: bool, has_v4: bool) -> Self {
31        let mut tables = gather_permitted(policy, has_v6, has_v4);
32        let mut i = 0;
33        while i < tables.local_len {
34            if let Some(c) = tables.local[i] {
35                let _ = tables.push_remote(c);
36            }
37            i += 1;
38        }
39        tables.form_pairs(matches!(role, IceRole::Controlling));
40        Self {
41            role,
42            policy,
43            tables,
44            slot: ConnSlot::new(1),
45            schedule: Schedule::new(),
46        }
47    }
48
49    /// Next ICE candidate.
50    pub fn next(&mut self, now_ms: u64) -> Scheduled {
51        tick(
52            &mut self.slot,
53            &mut self.schedule,
54            self.policy,
55            now_ms,
56            &self.tables,
57        )
58        .unwrap_or(Scheduled::Close)
59    }
60
61    /// Record that a real STUN/TURN transaction succeeded for `kind`.
62    pub fn mark_checked(&mut self, kind: CandidateKind) -> bool {
63        let mut i = 0;
64        while i < self.tables.pair_len {
65            if let Some(mut p) = self.tables.pairs[i] {
66                if let Some(l) = self.tables.local[p.local_idx as usize] {
67                    if l.kind == kind && p.state == PairState::Waiting {
68                        p.checked = true;
69                        self.tables.pairs[i] = Some(p);
70                        return true;
71                    }
72                }
73            }
74            i += 1;
75        }
76        false
77    }
78
79    /// Nominate only a pair that already passed a connectivity check.
80    pub fn nominate(&mut self, kind: CandidateKind, now_ms: u64) -> bool {
81        if kind != CandidateKind::Relayed && !self.policy.allows_direct_probes() {
82            return false;
83        }
84        if kind == CandidateKind::Host
85            && matches!(self.family_of_first_host(), Some(AddrFamily::V4))
86            && !self.schedule.ipv4_eligible(self.policy)
87        {
88            let _ = now_ms;
89            return false;
90        }
91        let mut i = 0;
92        while i < self.tables.pair_len {
93            if let Some(mut p) = self.tables.pairs[i] {
94                if let Some(l) = self.tables.local[p.local_idx as usize] {
95                    if l.kind == kind && p.state == PairState::Waiting && p.checked {
96                        p.state = PairState::Succeeded;
97                        self.tables.pairs[i] = Some(p);
98                        return true;
99                    }
100                }
101            }
102            i += 1;
103        }
104        false
105    }
106
107    fn family_of_first_host(&self) -> Option<AddrFamily> {
108        let mut i = 0;
109        while i < self.tables.local_len {
110            if let Some(c) = self.tables.local[i] {
111                if c.kind == CandidateKind::Host {
112                    return Some(c.family);
113                }
114            }
115            i += 1;
116        }
117        None
118    }
119
120    /// `true` when `succeeded` present.
121    pub fn has_succeeded(&self) -> bool {
122        let mut i = 0;
123        while i < self.tables.pair_len {
124            if self.tables.pairs[i].is_some_and(|p| p.state == PairState::Succeeded) {
125                return true;
126            }
127            i += 1;
128        }
129        false
130    }
131
132    /// RFC 8445 role conflict: larger tie-breaker stays controlling.
133    pub fn apply_role_conflict(&mut self, local_tie: u64, remote_tie: u64) {
134        self.role = if resolve_role_conflict(local_tie, remote_tie) {
135            IceRole::Controlling
136        } else {
137            IceRole::Controlled
138        };
139    }
140
141    /// RFC 7675: a nominated pair without fresh consent cannot keep sending.
142    pub fn nominated_may_send(&self, last_ok_ms: u64, now_ms: u64) -> bool {
143        self.has_succeeded() && consent_fresh(last_ok_ms, now_ms)
144    }
145}
146
147/// STUN Binding success still parses after a same-socket observe (fixture).
148pub fn stun_check_roundtrip() -> bool {
149    let tid = [2u8; 12];
150    let mapped = "203.0.113.9:3478".parse().unwrap();
151    let msg = encode_binding_success_v4(&tid, mapped).unwrap();
152    parse_xor_mapped_v4(&msg, &tid).is_ok()
153}
154
155#[cfg(test)]
156mod tests {
157    use super::*;
158
159    #[test]
160    fn relay_only_cannot_nominate_host() {
161        let mut a = IceAgent::new(IceRole::Controlling, PathPolicy::RELAY_ONLY, true, true);
162        assert_eq!(a.next(0), Scheduled::CheckRelay);
163        assert!(!a.nominate(CandidateKind::Host, 0));
164        assert!(
165            !a.nominate(CandidateKind::Relayed, 0),
166            "nominate without a check must fail"
167        );
168        assert!(a.mark_checked(CandidateKind::Relayed));
169        assert!(a.nominate(CandidateKind::Relayed, 0));
170        assert!(a.has_succeeded());
171        assert!(stun_check_roundtrip());
172    }
173
174    #[test]
175    fn ordinary_races_relay_before_direct() {
176        let mut a = IceAgent::new(IceRole::Controlling, PathPolicy::ORDINARY, true, true);
177        assert_eq!(a.next(0), Scheduled::CheckRelay);
178        assert_eq!(a.next(0), Scheduled::CheckDirectV6);
179    }
180
181    #[test]
182    fn role_conflict_and_consent_freshness() {
183        let mut a = IceAgent::new(IceRole::Controlled, PathPolicy::ORDINARY, true, true);
184        a.apply_role_conflict(10, 1);
185        assert_eq!(a.role, IceRole::Controlling);
186        a.apply_role_conflict(1, 10);
187        assert_eq!(a.role, IceRole::Controlled);
188        assert!(a.mark_checked(CandidateKind::Relayed));
189        assert!(a.nominate(CandidateKind::Relayed, 0));
190        assert!(a.nominated_may_send(0, 4_999));
191        assert!(!a.nominated_may_send(0, 30_000));
192    }
193}