Skip to main content

qualia_core_db/p2p/
mesh_probe.rs

1//! Internet mesh-probe connect path as a library (no `qualia-cli` / OpenSSL).
2//!
3//! Cursor cloud images may lack `libssl-dev`, so the connect half of the
4//! two-host test must run from `qualia-core-db`. Listen still uses `qualia-cli`
5//! on a reachable host. See `qdnf-imp/internet-two-host.md`.
6
7#![cfg(not(target_arch = "wasm32"))]
8
9use std::net::{SocketAddr, ToSocketAddrs};
10use std::time::{Duration, Instant};
11
12use sha2::{Digest, Sha256};
13
14use crate::net::qdnf::frame::{encode_frame, FrameHeader};
15use crate::net::qdnf::registries::{FrameType, NextProtocol};
16use crate::p2p::mesh_datagram::{self, ports};
17use crate::p2p::wireguard_runtime::WgTunnel;
18use crate::p2p::wireguard_userspace::WgKeypair;
19
20/// Same domain as `qualia-cli mesh-probe` (`v1` role + passphrase).
21pub fn derive_probe_secret(role: &str, pass: &str) -> [u8; 32] {
22    let mut hasher = Sha256::new();
23    hasher.update(b"qualia-mesh-probe:v1:");
24    hasher.update(role.as_bytes());
25    hasher.update(b":");
26    hasher.update(pass.as_bytes());
27    let digest = hasher.finalize();
28    let mut out = [0u8; 32];
29    out.copy_from_slice(&digest);
30    out
31}
32
33/// Result of one connect attempt. `handshake` is the only success bit that matters.
34#[derive(Debug, Clone, Copy, PartialEq, Eq)]
35pub struct ConnectReport {
36    pub handshake: bool,
37    pub sent_qdnf: bool,
38}
39
40/// Connector role `b` toward a listener that used role `a` and the same `pass`.
41pub fn connect_probe(
42    pass: &str,
43    peer: &str,
44    qdnf: bool,
45    timeout: Duration,
46) -> Result<ConnectReport, String> {
47    let my_keys = WgKeypair::from_secret_bytes(derive_probe_secret("b", pass));
48    let peer_keys = WgKeypair::from_secret_bytes(derive_probe_secret("a", pass));
49    let endpoint: SocketAddr = peer
50        .to_socket_addrs()
51        .map_err(|e| e.to_string())?
52        .next()
53        .ok_or_else(|| format!("could not resolve '{peer}'"))?;
54
55    let bind: SocketAddr = "0.0.0.0:0"
56        .parse::<SocketAddr>()
57        .map_err(|e| e.to_string())?;
58    let mut tunnel = WgTunnel::bind(&my_keys, peer_keys.public, bind, 2)?;
59    tunnel.set_read_timeout(Some(Duration::from_millis(500)))?;
60    tunnel.set_peer_endpoint(endpoint);
61    tunnel.initiate_handshake()?;
62
63    let deadline = Instant::now() + timeout;
64    while !tunnel.has_session() {
65        if Instant::now() >= deadline {
66            return Ok(ConnectReport {
67                handshake: false,
68                sent_qdnf: false,
69            });
70        }
71        let _ = tunnel.pump()?;
72        let _ = tunnel.tick()?;
73    }
74
75    let mut sent_qdnf = false;
76    if qdnf {
77        let header = FrameHeader::new(FrameType::DiscoveryBeacon, NextProtocol::QLink);
78        let mut wire = [0u8; 128];
79        let n = encode_frame(&header, &[], &mut wire).map_err(|e| e.to_string())?;
80        let packet = mesh_datagram::encode_datagram(ports::QDNF, ports::QDNF, &wire[..n]);
81        sent_qdnf = tunnel.send_packet(&packet)?;
82        let until = Instant::now() + Duration::from_millis(400);
83        while Instant::now() < until {
84            let _ = tunnel.pump()?;
85        }
86    }
87    Ok(ConnectReport {
88        handshake: true,
89        sent_qdnf,
90    })
91}
92
93#[cfg(test)]
94mod tests {
95    use super::*;
96
97    #[test]
98    fn probe_secrets_differ_by_role() {
99        let a = derive_probe_secret("a", "phrase");
100        let b = derive_probe_secret("b", "phrase");
101        assert_ne!(a, b);
102        assert_eq!(a, derive_probe_secret("a", "phrase"));
103    }
104
105    /// Set `QDNF_LISTEN_ADDR` and `QDNF_MESH_PASS` to execute the internet connect half.
106    /// Absent env: skip. Present env: handshake must succeed.
107    #[test]
108    fn internet_connect_if_env_set() {
109        let Ok(peer) = std::env::var("QDNF_LISTEN_ADDR") else {
110            return;
111        };
112        if peer.is_empty() {
113            return;
114        }
115        let pass = std::env::var("QDNF_MESH_PASS").unwrap_or_default();
116        assert!(
117            !pass.is_empty(),
118            "QDNF_LISTEN_ADDR is set; also set QDNF_MESH_PASS"
119        );
120        let report =
121            connect_probe(&pass, &peer, true, Duration::from_secs(20)).expect("connect_probe");
122        assert!(
123            report.handshake,
124            "internet WireGuard handshake failed toward {peer}"
125        );
126        assert!(report.sent_qdnf, "QDNF QFrame was not transmitted");
127    }
128}