qualia_core_db/p2p/connectivity/
turn_local.rs1#![cfg(not(target_arch = "wasm32"))]
4
5use std::net::{SocketAddr, UdpSocket};
6use std::time::Duration;
7
8use super::turn::{encode_allocate_request, encode_allocate_success, parse_xor_relayed_v4};
9use crate::p2p::stun_observe::MAGIC;
10
11const SEND_IND: u16 = 0x0016;
12const DATA_IND: u16 = 0x0017;
13const ATTR_XOR_PEER: u16 = 0x0012;
14const ATTR_DATA: u16 = 0x0013;
15const FAMILY_IPV4: u8 = 0x01;
16
17fn xor_addr(addr: SocketAddr, out: &mut [u8]) -> Result<usize, &'static str> {
18 let SocketAddr::V4(v4) = addr else {
19 return Err("ipv4");
20 };
21 if out.len() < 8 {
22 return Err("capacity");
23 }
24 out[..8].fill(0);
25 out[1] = FAMILY_IPV4;
26 let xport = v4.port() ^ ((MAGIC >> 16) as u16);
27 out[2..4].copy_from_slice(&xport.to_be_bytes());
28 let oct = v4.ip().octets();
29 let cookie = MAGIC.to_be_bytes();
30 for i in 0..4 {
31 out[4 + i] = oct[i] ^ cookie[i];
32 }
33 Ok(8)
34}
35
36fn parse_xor_addr(val: &[u8]) -> Result<SocketAddr, &'static str> {
37 if val.len() < 8 || val[1] != FAMILY_IPV4 {
38 return Err("xor-addr");
39 }
40 let xport = u16::from_be_bytes([val[2], val[3]]) ^ ((MAGIC >> 16) as u16);
41 let cookie = MAGIC.to_be_bytes();
42 let mut ip = [0u8; 4];
43 ip.copy_from_slice(&val[4..8]);
44 for i in 0..4 {
45 ip[i] ^= cookie[i];
46 }
47 format!("{}.{}.{}.{}:{}", ip[0], ip[1], ip[2], ip[3], xport)
48 .parse()
49 .map_err(|_| "parse")
50}
51
52fn encode_send(
53 tid: &[u8; 12],
54 peer: SocketAddr,
55 data: &[u8],
56 out: &mut [u8],
57) -> Result<usize, &'static str> {
58 let pad = (4 - (data.len() % 4)) % 4;
59 let n = 20 + 12 + 4 + data.len() + pad;
60 if out.len() < n {
61 return Err("capacity");
62 }
63 out[..n].fill(0);
64 out[0..2].copy_from_slice(&SEND_IND.to_be_bytes());
65 out[2..4].copy_from_slice(&((n - 20) as u16).to_be_bytes());
66 out[4..8].copy_from_slice(&MAGIC.to_be_bytes());
67 out[8..20].copy_from_slice(tid);
68 out[20..22].copy_from_slice(&ATTR_XOR_PEER.to_be_bytes());
69 out[22..24].copy_from_slice(&8u16.to_be_bytes());
70 xor_addr(peer, &mut out[24..32])?;
71 out[32..34].copy_from_slice(&ATTR_DATA.to_be_bytes());
72 out[34..36].copy_from_slice(&(data.len() as u16).to_be_bytes());
73 out[36..36 + data.len()].copy_from_slice(data);
74 Ok(n)
75}
76
77fn encode_data(
78 tid: &[u8; 12],
79 peer: SocketAddr,
80 data: &[u8],
81 out: &mut [u8],
82) -> Result<usize, &'static str> {
83 let pad = (4 - (data.len() % 4)) % 4;
84 let n = 20 + 12 + 4 + data.len() + pad;
85 if out.len() < n {
86 return Err("capacity");
87 }
88 out[..n].fill(0);
89 out[0..2].copy_from_slice(&DATA_IND.to_be_bytes());
90 out[2..4].copy_from_slice(&((n - 20) as u16).to_be_bytes());
91 out[4..8].copy_from_slice(&MAGIC.to_be_bytes());
92 out[8..20].copy_from_slice(tid);
93 out[20..22].copy_from_slice(&ATTR_XOR_PEER.to_be_bytes());
94 out[22..24].copy_from_slice(&8u16.to_be_bytes());
95 xor_addr(peer, &mut out[24..32])?;
96 out[32..34].copy_from_slice(&ATTR_DATA.to_be_bytes());
97 out[34..36].copy_from_slice(&(data.len() as u16).to_be_bytes());
98 out[36..36 + data.len()].copy_from_slice(data);
99 Ok(n)
100}
101
102fn parse_send_or_data(msg: &[u8]) -> Result<(u16, [u8; 12], SocketAddr, Vec<u8>), &'static str> {
103 if msg.len() < 36 {
104 return Err("truncated");
105 }
106 let typ = u16::from_be_bytes([msg[0], msg[1]]);
107 if typ != SEND_IND && typ != DATA_IND {
108 return Err("not send/data");
109 }
110 let mut tid = [0u8; 12];
111 tid.copy_from_slice(&msg[8..20]);
112 let peer = parse_xor_addr(&msg[24..32])?;
113 let dlen = u16::from_be_bytes([msg[34], msg[35]]) as usize;
114 if msg.len() < 36 + dlen {
115 return Err("data truncated");
116 }
117 Ok((typ, tid, peer, msg[36..36 + dlen].to_vec()))
118}
119
120pub fn local_allocate_and_forward(payload: &[u8]) -> Result<Vec<u8>, String> {
122 let hub = UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
123 let hub_addr = hub.local_addr().map_err(|e| e.to_string())?;
124 let a = UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
125 let b = UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
126 a.set_read_timeout(Some(Duration::from_secs(2)))
127 .map_err(|e| e.to_string())?;
128 b.set_read_timeout(Some(Duration::from_secs(2)))
129 .map_err(|e| e.to_string())?;
130 hub.set_read_timeout(Some(Duration::from_millis(400)))
131 .map_err(|e| e.to_string())?;
132
133 let tid_a = [1u8; 12];
134 let tid_b = [2u8; 12];
135 let mut req = [0u8; 20];
136 encode_allocate_request(&tid_a, &mut req).map_err(|e| e.to_string())?;
137 a.send_to(&req, hub_addr).map_err(|e| e.to_string())?;
138 encode_allocate_request(&tid_b, &mut req).map_err(|e| e.to_string())?;
139 b.send_to(&req, hub_addr).map_err(|e| e.to_string())?;
140
141 let relay_a = UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
142 let relay_b = UdpSocket::bind("127.0.0.1:0").map_err(|e| e.to_string())?;
143 let ra = relay_a.local_addr().map_err(|e| e.to_string())?;
144 let rb = relay_b.local_addr().map_err(|e| e.to_string())?;
145
146 let mut a_client = None;
147 let mut b_client = None;
148 let mut buf = [0u8; 2048];
149 for _ in 0..8 {
150 let Ok((n, from)) = hub.recv_from(&mut buf) else {
151 continue;
152 };
153 let typ = u16::from_be_bytes([buf[0], buf[1]]);
154 if typ == 0x0003 {
155 let tid: [u8; 12] = buf[8..20].try_into().unwrap();
156 let relayed = if a_client.is_none() { ra } else { rb };
157 if a_client.is_none() {
158 a_client = Some(from);
159 } else {
160 b_client = Some(from);
161 }
162 let mut suc = [0u8; 44];
163 encode_allocate_success(&tid, relayed, 600, &mut suc).map_err(|e| e.to_string())?;
164 hub.send_to(&suc, from).map_err(|e| e.to_string())?;
165 } else if typ == SEND_IND {
166 let (_t, tid, peer, data) = parse_send_or_data(&buf[..n]).map_err(|e| e.to_string())?;
167 let dest = if peer == rb {
168 b_client.ok_or("b missing")?
169 } else {
170 a_client.ok_or("a missing")?
171 };
172 let mut data_msg = [0u8; 2048];
173 let dn = encode_data(&tid, from, &data, &mut data_msg).map_err(|e| e.to_string())?;
174 hub.send_to(&data_msg[..dn], dest)
175 .map_err(|e| e.to_string())?;
176 }
177 }
178
179 let mut rbuf = [0u8; 64];
180 let (n, _) = a.recv_from(&mut rbuf).map_err(|e| e.to_string())?;
181 let got_a = parse_xor_relayed_v4(&rbuf[..n], &tid_a).map_err(|e| e.to_string())?;
182 assert_eq!(got_a, ra);
183 let (n, _) = b.recv_from(&mut rbuf).map_err(|e| e.to_string())?;
184 let got_b = parse_xor_relayed_v4(&rbuf[..n], &tid_b).map_err(|e| e.to_string())?;
185 assert_eq!(got_b, rb);
186
187 let mut send = [0u8; 2048];
188 let tid_s = [3u8; 12];
189 let sn = encode_send(&tid_s, rb, payload, &mut send).map_err(|e| e.to_string())?;
190 a.send_to(&send[..sn], hub_addr)
191 .map_err(|e| e.to_string())?;
192
193 for _ in 0..6 {
195 let Ok((n, from)) = hub.recv_from(&mut buf) else {
196 continue;
197 };
198 if u16::from_be_bytes([buf[0], buf[1]]) == SEND_IND {
199 let (_t, tid, peer, data) = parse_send_or_data(&buf[..n]).map_err(|e| e.to_string())?;
200 let dest = if peer == rb {
201 b_client.ok_or("b missing")?
202 } else {
203 from
204 };
205 let mut data_msg = [0u8; 2048];
206 let dn = encode_data(&tid, from, &data, &mut data_msg).map_err(|e| e.to_string())?;
207 hub.send_to(&data_msg[..dn], dest)
208 .map_err(|e| e.to_string())?;
209 break;
210 }
211 }
212
213 let (n, _) = b.recv_from(&mut buf).map_err(|e| e.to_string())?;
214 let (_t, _tid, _peer, data) = parse_send_or_data(&buf[..n]).map_err(|e| e.to_string())?;
215 Ok(data)
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221
222 #[test]
223 fn allocate_then_send_reaches_peer() {
224 let got = local_allocate_and_forward(b"turn-ok").expect("local TURN");
225 assert_eq!(got, b"turn-ok");
226 }
227}