Skip to main content

qualia_core_db/p2p/connectivity/
ice_udp.rs

1//! Local UDP STUN Binding check. Nomination is not a connectivity check.
2
3#![cfg(not(target_arch = "wasm32"))]
4
5use std::net::UdpSocket;
6use std::time::Duration;
7
8use crate::p2p::stun_observe::{encode_binding_success_v4, stun_bind, MAGIC};
9
10const BINDING_REQUEST: u16 = 0x0001;
11
12/// Answer one Binding request on `responder` with XOR-MAPPED-ADDRESS.
13fn serve_one_binding(responder: UdpSocket) -> Result<(), String> {
14    responder
15        .set_read_timeout(Some(Duration::from_secs(2)))
16        .map_err(|e| e.to_string())?;
17    let mut buf = [0u8; 512];
18    let (n, from) = responder.recv_from(&mut buf).map_err(|e| e.to_string())?;
19    if n < 20 {
20        return Err("short stun".into());
21    }
22    let typ = u16::from_be_bytes([buf[0], buf[1]]);
23    if typ != BINDING_REQUEST {
24        return Err("not binding request".into());
25    }
26    let magic = u32::from_be_bytes([buf[4], buf[5], buf[6], buf[7]]);
27    if magic != MAGIC {
28        return Err("bad magic".into());
29    }
30    let mut tid = [0u8; 12];
31    tid.copy_from_slice(&buf[8..20]);
32    let success = encode_binding_success_v4(&tid, from)?;
33    responder
34        .send_to(&success, from)
35        .map_err(|e| e.to_string())?;
36    Ok(())
37}
38
39/// Two local UDP sockets exchange a real STUN Binding request/success.
40pub fn local_binding_check() -> Result<std::net::SocketAddr, String> {
41    let checker = UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
42    let responder = UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
43    let peer = responder.local_addr().map_err(|e| e.to_string())?;
44    let th = std::thread::spawn(move || serve_one_binding(responder));
45    let mapped = stun_bind(&checker, peer, Duration::from_secs(2))?;
46    th.join().map_err(|_| "join")??;
47    Ok(mapped)
48}
49
50#[cfg(test)]
51mod tests {
52    use super::*;
53    use crate::net::peer::connectivity::candidates::CandidateKind;
54    use crate::net::peer::connectivity::policy::PathPolicy;
55    use crate::p2p::connectivity::ice::{IceAgent, IceRole};
56
57    #[test]
58    fn binding_check_required_before_nominate() {
59        let mapped = local_binding_check().expect("local STUN Binding");
60        assert!(mapped.ip().is_loopback());
61        let mut ice = IceAgent::new(IceRole::Controlling, PathPolicy::ORDINARY, true, true);
62        assert!(!ice.nominate(CandidateKind::Host, 0));
63        assert!(ice.mark_checked(CandidateKind::Host));
64        assert!(ice.nominate(CandidateKind::Host, 0));
65        assert!(ice.has_succeeded());
66    }
67}