- Lab app: proxy panel, node editor, configuration and detail pages, responsive layout, and related tests - Add meshport-socks crate and sing-box bridge scripts/docs - Add singbox_flutter binding and meshport_client_core package - FFI, VPN helper (unified mac path), and Android/macOS runner updates - Docs for architecture, client runtime, UI design, and validation - UI design output artifacts under outputs/ui Co-Authored-By: Claude Haiku 5.5 <noreply@anthropic.com>
483 lines
17 KiB
Rust
483 lines
17 KiB
Rust
use easytier::instance::factory::create_native_instance;
|
|
use easytier_core::config::toml::{ConfigLoader, TomlConfig};
|
|
use meshport::Network;
|
|
use meshport_socks::{Bridge, Options};
|
|
use std::{
|
|
net::SocketAddrV4,
|
|
path::{Path, PathBuf},
|
|
process::Stdio,
|
|
sync::Arc,
|
|
time::{Duration, SystemTime},
|
|
};
|
|
use tokio::{
|
|
io::{AsyncBufReadExt, AsyncReadExt, AsyncWriteExt, BufReader},
|
|
net::{TcpListener, TcpStream, UdpSocket},
|
|
task::JoinSet,
|
|
time::{sleep, timeout},
|
|
};
|
|
|
|
const WAIT: Duration = Duration::from_secs(15);
|
|
|
|
struct ExternalEngine {
|
|
child: tokio::process::Child,
|
|
config_path: PathBuf,
|
|
listen: SocketAddrV4,
|
|
}
|
|
|
|
impl Drop for ExternalEngine {
|
|
fn drop(&mut self) {
|
|
let _ = std::fs::remove_file(&self.config_path);
|
|
}
|
|
}
|
|
|
|
impl ExternalEngine {
|
|
async fn start(binary: &Path, bridge: SocketAddrV4, network: &Network) -> Self {
|
|
let reserved = std::net::TcpListener::bind("127.0.0.1:0").unwrap();
|
|
let listen: SocketAddrV4 = reserved.local_addr().unwrap().to_string().parse().unwrap();
|
|
let stamp = SystemTime::now()
|
|
.duration_since(SystemTime::UNIX_EPOCH)
|
|
.unwrap()
|
|
.as_nanos();
|
|
let config_path = std::env::temp_dir().join(format!(
|
|
"meshport-singbox-{}-{stamp}.json",
|
|
std::process::id()
|
|
));
|
|
let snapshot = network.snapshot().await;
|
|
let mut prefixes = snapshot["platform_network"]["subnet_routes"]
|
|
.as_array()
|
|
.unwrap()
|
|
.clone();
|
|
prefixes.push(snapshot["ipv4"].clone());
|
|
let config = serde_json::json!({"listen_port": listen.port(), "mesh_socks": bridge.to_string(), "mesh_cidrs": prefixes});
|
|
std::fs::write(&config_path, config.to_string()).unwrap();
|
|
drop(reserved);
|
|
let child = tokio::process::Command::new(binary)
|
|
.arg(&config_path)
|
|
.stdout(Stdio::piped())
|
|
.stderr(Stdio::inherit())
|
|
.kill_on_drop(true)
|
|
.spawn()
|
|
.unwrap();
|
|
let mut engine = Self {
|
|
child,
|
|
config_path,
|
|
listen,
|
|
};
|
|
let mut readiness = String::new();
|
|
timeout(
|
|
WAIT,
|
|
BufReader::new(engine.child.stdout.take().unwrap()).read_line(&mut readiness),
|
|
)
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
let ready: serde_json::Value = serde_json::from_str(&readiness).unwrap();
|
|
assert_eq!(ready["state"], "Running");
|
|
engine
|
|
}
|
|
|
|
async fn stop(&mut self) {
|
|
let id = self.child.id().unwrap();
|
|
let status = std::process::Command::new("/bin/kill")
|
|
.args(["-TERM", &id.to_string()])
|
|
.status()
|
|
.unwrap();
|
|
assert!(status.success());
|
|
assert!(
|
|
timeout(WAIT, self.child.wait())
|
|
.await
|
|
.unwrap()
|
|
.unwrap()
|
|
.success()
|
|
);
|
|
assert!(TcpStream::connect(self.listen).await.is_err());
|
|
}
|
|
}
|
|
|
|
fn config(ip: &str, bootstrap: Option<u16>) -> String {
|
|
let peer = bootstrap
|
|
.map(|port| format!("[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n"))
|
|
.unwrap_or_default();
|
|
format!(
|
|
"ipv4 = '{ip}/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = []\n{peer}[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n"
|
|
)
|
|
}
|
|
|
|
async fn negotiate(addr: SocketAddrV4) -> TcpStream {
|
|
let mut s = TcpStream::connect(addr).await.unwrap();
|
|
// Deliberately split protocol fields across writes.
|
|
s.write_all(&[5]).await.unwrap();
|
|
s.write_all(&[1, 0]).await.unwrap();
|
|
let mut reply = [0; 2];
|
|
s.read_exact(&mut reply).await.unwrap();
|
|
assert_eq!(reply, [5, 0]);
|
|
s
|
|
}
|
|
|
|
async fn request(s: &mut TcpStream, command: u8, target: SocketAddrV4) -> (u8, SocketAddrV4) {
|
|
let mut bytes = vec![5, command, 0, 1];
|
|
bytes.extend_from_slice(&target.ip().octets());
|
|
bytes.extend_from_slice(&target.port().to_be_bytes());
|
|
s.write_all(&bytes).await.unwrap();
|
|
let mut reply = [0; 10];
|
|
s.read_exact(&mut reply).await.unwrap();
|
|
assert_eq!([reply[0], reply[2], reply[3]], [5, 0, 1]);
|
|
(
|
|
reply[1],
|
|
SocketAddrV4::new(
|
|
[reply[4], reply[5], reply[6], reply[7]].into(),
|
|
u16::from_be_bytes([reply[8], reply[9]]),
|
|
),
|
|
)
|
|
}
|
|
|
|
fn frame(target: SocketAddrV4, payload: &[u8]) -> Vec<u8> {
|
|
let mut bytes = vec![0, 0, 0, 1];
|
|
bytes.extend_from_slice(&target.ip().octets());
|
|
bytes.extend_from_slice(&target.port().to_be_bytes());
|
|
bytes.extend_from_slice(payload);
|
|
bytes
|
|
}
|
|
|
|
async fn wait_no_sessions(bridge: &Bridge) {
|
|
timeout(WAIT, async {
|
|
while bridge.snapshot().active_sessions != 0 {
|
|
sleep(Duration::from_millis(10)).await;
|
|
}
|
|
})
|
|
.await
|
|
.unwrap();
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
|
async fn concurrent_tcp_udp_over_learned_subnet_and_withdrawal() {
|
|
overlay_check(None).await;
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
|
#[ignore = "requires the built Go engine; run sh scripts/test-singbox-bridge.sh"]
|
|
async fn singbox_to_meshport_tcp_udp_and_withdrawal() {
|
|
let binary = std::env::var_os("MESHPORT_SINGBOX_BIN").expect("MESHPORT_SINGBOX_BIN required");
|
|
overlay_check(Some(PathBuf::from(binary))).await;
|
|
}
|
|
|
|
async fn overlay_check(engine_binary: Option<PathBuf>) {
|
|
let port = std::net::UdpSocket::bind("127.0.0.1:0")
|
|
.unwrap()
|
|
.local_addr()
|
|
.unwrap()
|
|
.port();
|
|
// A real remote gateway maps its advertised private subnet to an OS echo
|
|
// server. Unlike the SDK UDP listener, this accepts unknown first packets.
|
|
let server_config = TomlConfig::new_from_str(&format!(
|
|
"ipv4 = '10.253.81.2/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = ['udp://127.0.0.1:{port}']\n[[proxy_network]]\ncidr = '127.0.0.0/24'\nmapped_cidr = '10.253.79.0/24'\n[network_identity]\nnetwork_name = 'socks-test'\nnetwork_secret = 'test-only'\n[flags]\nno_tun = true\nuse_smoltcp = true"
|
|
)).unwrap();
|
|
let server = create_native_instance(server_config.clone()).unwrap();
|
|
server.start().await.unwrap();
|
|
let network = Arc::new(
|
|
Network::start(&config("10.253.80.11", Some(port)))
|
|
.await
|
|
.unwrap(),
|
|
);
|
|
timeout(WAIT, async {
|
|
while !network.snapshot().await["platform_network"]["subnet_routes"]
|
|
.as_array()
|
|
.unwrap()
|
|
.iter()
|
|
.any(|r| r == "10.253.79.0/24")
|
|
{
|
|
sleep(Duration::from_millis(50)).await;
|
|
}
|
|
})
|
|
.await
|
|
.unwrap();
|
|
let tcp = TcpListener::bind("127.0.0.1:0").await.unwrap();
|
|
let tcp_target: SocketAddrV4 = format!("10.253.79.1:{}", tcp.local_addr().unwrap().port())
|
|
.parse()
|
|
.unwrap();
|
|
let tcp_echo = tokio::spawn(async move {
|
|
let mut children = JoinSet::new();
|
|
loop {
|
|
tokio::select! {
|
|
accepted = tcp.accept() => {
|
|
let (mut s, _) = accepted.unwrap();
|
|
children.spawn(async move {
|
|
let mut buffer = [0; 4096];
|
|
loop {
|
|
let n = s.read(&mut buffer).await.unwrap();
|
|
if n == 0 { break; }
|
|
s.write_all(&buffer[..n]).await.unwrap();
|
|
}
|
|
});
|
|
}
|
|
_ = children.join_next(), if !children.is_empty() => {}
|
|
}
|
|
}
|
|
});
|
|
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
|
let udp_target: SocketAddrV4 = format!("10.253.79.1:{}", udp.local_addr().unwrap().port())
|
|
.parse()
|
|
.unwrap();
|
|
let udp_echo = tokio::spawn(async move {
|
|
let mut buffer = [0; 65535];
|
|
loop {
|
|
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
|
|
udp.send_to(&buffer[..n], source).await.unwrap();
|
|
}
|
|
});
|
|
let mut bridge = Bridge::start(
|
|
network.clone(),
|
|
Options {
|
|
tcp_close_timeout: Duration::from_secs(1),
|
|
..Options::default()
|
|
},
|
|
)
|
|
.await
|
|
.unwrap();
|
|
let mut engine = match engine_binary {
|
|
Some(binary) => Some(ExternalEngine::start(&binary, bridge.local_addr(), &network).await),
|
|
None => None,
|
|
};
|
|
let entry = engine.as_ref().map_or(bridge.local_addr(), |e| e.listen);
|
|
let result = timeout(Duration::from_secs(45), async {
|
|
// An established TCP connection blocked on read does not serialize
|
|
// the other connections or either UDP association.
|
|
let mut idle = negotiate(entry).await;
|
|
assert_eq!(request(&mut idle, 1, tcp_target).await.0, 0);
|
|
let mut clients = JoinSet::new();
|
|
for i in 0..4 {
|
|
let addr = entry;
|
|
clients.spawn(async move {
|
|
let mut s = negotiate(addr).await;
|
|
assert_eq!(request(&mut s, 1, tcp_target).await.0, 0);
|
|
let payload = vec![i; 32768];
|
|
s.write_all(&payload).await.unwrap();
|
|
let mut received = vec![0; payload.len()];
|
|
s.read_exact(&mut received).await.unwrap();
|
|
assert_eq!(received, payload);
|
|
s.shutdown().await.unwrap();
|
|
});
|
|
}
|
|
while let Some(result) = clients.join_next().await {
|
|
result.unwrap();
|
|
}
|
|
let mut associations = Vec::new();
|
|
for payload in [b"first-session".as_slice(), b"second-session".as_slice()] {
|
|
let local = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
|
let mut control = negotiate(entry).await;
|
|
let (code, relay) = request(&mut control, 3, "0.0.0.0:0".parse().unwrap()).await;
|
|
assert_eq!(code, 0);
|
|
local
|
|
.send_to(&frame(udp_target, payload), relay)
|
|
.await
|
|
.unwrap();
|
|
associations.push((control, local, relay, payload));
|
|
}
|
|
for (_, local, _, payload) in &associations {
|
|
let mut buffer = [0; 256];
|
|
let (n, _) = timeout(WAIT, local.recv_from(&mut buffer))
|
|
.await
|
|
.unwrap()
|
|
.unwrap();
|
|
assert_eq!(&buffer[..n], frame(udp_target, payload));
|
|
}
|
|
// The direct bridge enforces endpoint pinning. The outer engine's
|
|
// inbound association policy is independently owned by sing-box.
|
|
let intruder = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
|
let (control, local, relay, _) = associations.remove(0);
|
|
let mut buffer = [0; 128];
|
|
if engine.is_none() {
|
|
intruder
|
|
.send_to(&frame(udp_target, b"injected"), relay)
|
|
.await
|
|
.unwrap();
|
|
assert!(
|
|
timeout(Duration::from_millis(200), local.recv_from(&mut buffer))
|
|
.await
|
|
.is_err()
|
|
);
|
|
let mut fragmented = frame(udp_target, b"fragmented");
|
|
fragmented[2] = 1;
|
|
local.send_to(&fragmented, relay).await.unwrap();
|
|
assert!(
|
|
timeout(Duration::from_millis(200), local.recv_from(&mut buffer))
|
|
.await
|
|
.is_err()
|
|
);
|
|
}
|
|
drop(control);
|
|
let (remaining_control, remaining_local, remaining_relay, _) = associations.remove(0);
|
|
drop(idle);
|
|
if engine.is_none() {
|
|
assert!(bridge.snapshot().dropped_udp_packets >= 2);
|
|
}
|
|
// Removal propagates through the real route plane. A fresh SOCKS
|
|
// request fails rather than reaching the ordinary network.
|
|
server_config.clear_proxy_cidrs();
|
|
let updated =
|
|
easytier_core::instance::CoreInstanceConfig::from_toml(&server_config).unwrap();
|
|
server
|
|
.update_runtime_config(easytier_core::config::runtime::CoreInstanceRuntimeConfig {
|
|
services: updated.connectivity.runtime,
|
|
peer: Arc::new(updated.peer.snapshot),
|
|
})
|
|
.await
|
|
.unwrap();
|
|
timeout(WAIT, async {
|
|
while !network.snapshot().await["platform_network"]["subnet_routes"]
|
|
.as_array()
|
|
.unwrap()
|
|
.is_empty()
|
|
{
|
|
sleep(Duration::from_millis(50)).await;
|
|
}
|
|
})
|
|
.await
|
|
.unwrap();
|
|
let mut rejected = negotiate(entry).await;
|
|
let code = request(&mut rejected, 1, tcp_target).await.0;
|
|
if engine.is_some() && code == 0 {
|
|
// sing-box acknowledges SOCKS before its asynchronous outbound
|
|
// dial. A route failure must then close, never deliver data.
|
|
let closed = timeout(WAIT, rejected.read(&mut buffer)).await.unwrap();
|
|
assert!(matches!(closed, Ok(0) | Err(_)));
|
|
} else {
|
|
assert_ne!(code, 0);
|
|
}
|
|
remaining_local
|
|
.send_to(&frame(udp_target, b"after-withdrawal"), remaining_relay)
|
|
.await
|
|
.unwrap();
|
|
assert!(
|
|
timeout(
|
|
Duration::from_millis(400),
|
|
remaining_local.recv_from(&mut buffer)
|
|
)
|
|
.await
|
|
.is_err()
|
|
);
|
|
drop(remaining_control);
|
|
drop(rejected);
|
|
if engine.is_none() {
|
|
wait_no_sessions(&bridge).await;
|
|
}
|
|
})
|
|
.await;
|
|
if let Some(engine) = &mut engine {
|
|
engine.stop().await;
|
|
}
|
|
bridge.stop().await.unwrap();
|
|
assert_eq!(bridge.snapshot().active_sessions, 0);
|
|
assert!(!bridge.snapshot().running);
|
|
assert!(TcpStream::connect(bridge.local_addr()).await.is_err());
|
|
bridge.stop().await.unwrap();
|
|
// Explicit stop releases the address, allowing a new bridge lifecycle.
|
|
let mut restarted = Bridge::start(
|
|
network.clone(),
|
|
Options {
|
|
listen: bridge.local_addr(),
|
|
..Options::default()
|
|
},
|
|
)
|
|
.await
|
|
.unwrap();
|
|
restarted.stop().await.unwrap();
|
|
network.stop().await;
|
|
server.stop().await;
|
|
tcp_echo.abort();
|
|
udp_echo.abort();
|
|
result.unwrap();
|
|
}
|
|
|
|
#[tokio::test(flavor = "multi_thread", worker_threads = 2)]
|
|
async fn limits_protocol_errors_timeout_and_shutdown() {
|
|
let network = Arc::new(Network::start(&config("10.253.82.11", None)).await.unwrap());
|
|
assert!(
|
|
Bridge::start(
|
|
network.clone(),
|
|
Options {
|
|
listen: "0.0.0.0:0".parse().unwrap(),
|
|
..Options::default()
|
|
}
|
|
)
|
|
.await
|
|
.is_err()
|
|
);
|
|
let mut bridge = Bridge::start(
|
|
network.clone(),
|
|
Options {
|
|
max_sessions: 2,
|
|
handshake_timeout: Duration::from_millis(300),
|
|
udp_idle_timeout: Duration::from_millis(300),
|
|
..Options::default()
|
|
},
|
|
)
|
|
.await
|
|
.unwrap();
|
|
let result = timeout(WAIT, async {
|
|
let mut auth = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
|
auth.write_all(&[5, 1, 2]).await.unwrap();
|
|
let mut selection = [0; 2];
|
|
auth.read_exact(&mut selection).await.unwrap();
|
|
assert_eq!(selection, [5, 255]);
|
|
assert_eq!(auth.read(&mut [0]).await.unwrap(), 0);
|
|
wait_no_sessions(&bridge).await;
|
|
for (bytes, code) in [
|
|
(&[5, 2, 0, 1][..], 7),
|
|
(&[5, 1, 0, 3][..], 8),
|
|
(&[5, 1, 0, 4][..], 8),
|
|
(&[4, 1, 0, 1][..], 1),
|
|
(&[5, 1, 1, 1][..], 1),
|
|
] {
|
|
let mut s = negotiate(bridge.local_addr()).await;
|
|
s.write_all(bytes).await.unwrap();
|
|
let mut response = [0; 10];
|
|
s.read_exact(&mut response).await.unwrap();
|
|
assert_eq!(response[1], code);
|
|
assert_eq!(s.read(&mut [0]).await.unwrap(), 0);
|
|
wait_no_sessions(&bridge).await;
|
|
}
|
|
let mut wrong_source = negotiate(bridge.local_addr()).await;
|
|
assert_eq!(
|
|
request(&mut wrong_source, 3, "127.0.0.2:1".parse().unwrap())
|
|
.await
|
|
.0,
|
|
2
|
|
);
|
|
drop(wrong_source);
|
|
wait_no_sessions(&bridge).await;
|
|
let mut control = negotiate(bridge.local_addr()).await;
|
|
assert_eq!(
|
|
request(&mut control, 3, "0.0.0.0:0".parse().unwrap())
|
|
.await
|
|
.0,
|
|
0
|
|
);
|
|
assert_eq!(control.read(&mut [0]).await.unwrap(), 0); // idle association expiry
|
|
wait_no_sessions(&bridge).await;
|
|
let mut incomplete = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
|
incomplete.write_all(&[5]).await.unwrap();
|
|
assert_eq!(incomplete.read(&mut [0]).await.unwrap(), 0);
|
|
wait_no_sessions(&bridge).await;
|
|
// Exhaust both slots with incomplete handshakes.
|
|
let _a = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
|
let _b = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
|
timeout(Duration::from_millis(200), async {
|
|
while bridge.snapshot().active_sessions < 2 {
|
|
tokio::task::yield_now().await;
|
|
}
|
|
})
|
|
.await
|
|
.unwrap();
|
|
let mut rejected = TcpStream::connect(bridge.local_addr()).await.unwrap();
|
|
assert_eq!(rejected.read(&mut [0]).await.unwrap(), 0);
|
|
assert_eq!(bridge.snapshot().refused_at_capacity, 1);
|
|
bridge.stop().await.unwrap();
|
|
assert_eq!(bridge.snapshot().active_sessions, 0);
|
|
})
|
|
.await;
|
|
bridge.stop().await.unwrap();
|
|
network.stop().await;
|
|
result.unwrap();
|
|
}
|