Skip to main content

qualia_core_db/p2p/connectivity/
turn.rs

1//! TURN Allocate encode/decode (RFC 8656 subset). Not a TURN server.
2
3#![cfg(not(target_arch = "wasm32"))]
4
5use std::net::{Ipv4Addr, SocketAddr, SocketAddrV4};
6
7use crate::p2p::stun_observe::MAGIC;
8
9const ALLOCATE_REQUEST: u16 = 0x0003;
10const ALLOCATE_SUCCESS: u16 = 0x0103;
11const ATTR_XOR_RELAYED: u16 = 0x0016;
12const ATTR_LIFETIME: u16 = 0x000D;
13const FAMILY_IPV4: u8 = 0x01;
14
15/// Encodes `allocate_request` into the caller buffer.
16pub fn encode_allocate_request(tid: &[u8; 12], out: &mut [u8]) -> Result<usize, &'static str> {
17    if out.len() < 20 {
18        return Err("capacity");
19    }
20    out[..20].fill(0);
21    out[0..2].copy_from_slice(&ALLOCATE_REQUEST.to_be_bytes());
22    out[2..4].copy_from_slice(&0u16.to_be_bytes());
23    out[4..8].copy_from_slice(&MAGIC.to_be_bytes());
24    out[8..20].copy_from_slice(tid);
25    Ok(20)
26}
27
28/// Encodes `allocate_success` into the caller buffer.
29pub fn encode_allocate_success(
30    tid: &[u8; 12],
31    relayed: SocketAddr,
32    lifetime_secs: u32,
33    out: &mut [u8],
34) -> Result<usize, &'static str> {
35    let SocketAddr::V4(v4) = relayed else {
36        return Err("ipv4 fixture");
37    };
38    if out.len() < 44 {
39        return Err("capacity");
40    }
41    out[..44].fill(0);
42    out[0..2].copy_from_slice(&ALLOCATE_SUCCESS.to_be_bytes());
43    out[2..4].copy_from_slice(&24u16.to_be_bytes());
44    out[4..8].copy_from_slice(&MAGIC.to_be_bytes());
45    out[8..20].copy_from_slice(tid);
46    out[20..22].copy_from_slice(&ATTR_XOR_RELAYED.to_be_bytes());
47    out[22..24].copy_from_slice(&8u16.to_be_bytes());
48    out[25] = FAMILY_IPV4;
49    let xport = v4.port() ^ ((MAGIC >> 16) as u16);
50    out[26..28].copy_from_slice(&xport.to_be_bytes());
51    let oct = v4.ip().octets();
52    let cookie = MAGIC.to_be_bytes();
53    for i in 0..4 {
54        out[28 + i] = oct[i] ^ cookie[i];
55    }
56    out[32..34].copy_from_slice(&ATTR_LIFETIME.to_be_bytes());
57    out[34..36].copy_from_slice(&4u16.to_be_bytes());
58    out[36..40].copy_from_slice(&lifetime_secs.to_be_bytes());
59    Ok(44)
60}
61
62/// Parses `xor-relayed-v4`.
63pub fn parse_xor_relayed_v4(msg: &[u8], tid: &[u8; 12]) -> Result<SocketAddr, &'static str> {
64    if msg.len() < 32 {
65        return Err("truncated");
66    }
67    let typ = u16::from_be_bytes([msg[0], msg[1]]);
68    if typ != ALLOCATE_SUCCESS {
69        return Err("not allocate success");
70    }
71    if u32::from_be_bytes([msg[4], msg[5], msg[6], msg[7]]) != MAGIC {
72        return Err("magic");
73    }
74    if &msg[8..20] != tid {
75        return Err("tid");
76    }
77    let xport = u16::from_be_bytes([msg[26], msg[27]]) ^ ((MAGIC >> 16) as u16);
78    let cookie = MAGIC.to_be_bytes();
79    let mut ip = [0u8; 4];
80    ip.copy_from_slice(&msg[28..32]);
81    for i in 0..4 {
82        ip[i] ^= cookie[i];
83    }
84    Ok(SocketAddr::V4(SocketAddrV4::new(
85        Ipv4Addr::new(ip[0], ip[1], ip[2], ip[3]),
86        xport,
87    )))
88}
89
90/// A WSS circuit is not a TURN allocation.
91pub const fn wss_is_not_turn() -> bool {
92    true
93}
94
95#[cfg(test)]
96mod tests {
97    use super::*;
98
99    #[test]
100    fn allocate_round_trip() {
101        let tid = [9u8; 12];
102        let mut req = [0u8; 20];
103        assert_eq!(encode_allocate_request(&tid, &mut req).unwrap(), 20);
104        let mut suc = [0u8; 44];
105        let relayed = "198.51.100.8:3478".parse().unwrap();
106        encode_allocate_success(&tid, relayed, 600, &mut suc).unwrap();
107        assert_eq!(parse_xor_relayed_v4(&suc, &tid).unwrap(), relayed);
108        assert!(wss_is_not_turn());
109    }
110}