Snapshot uncommitted work: proxy UI, sing-box integration, socks bridge
- 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>
This commit is contained in:
co-authored by
Claude Haiku 5.5
parent
10b10e5bdf
commit
2f185f914d
@@ -10,6 +10,7 @@ crate-type = ["cdylib", "staticlib", "rlib"]
|
||||
[dependencies]
|
||||
meshport.workspace = true
|
||||
meshport-easytier.workspace = true
|
||||
meshport-socks.workspace = true
|
||||
anyhow.workspace = true
|
||||
serde_json.workspace = true
|
||||
tokio.workspace = true
|
||||
@@ -19,3 +20,7 @@ tracing-subscriber = { version = "0.3", default-features = false, features = ["s
|
||||
[features]
|
||||
default = []
|
||||
system-vpn = ["meshport/system-vpn"]
|
||||
|
||||
[dev-dependencies]
|
||||
easytier = { workspace = true, features = ["proxy-packet"] }
|
||||
easytier-core.workspace = true
|
||||
|
||||
@@ -26,12 +26,18 @@ static CONTEXTS: LazyLock<Mutex<HashMap<u64, Arc<Context>>>> =
|
||||
LazyLock::new(|| Mutex::new(HashMap::new()));
|
||||
struct Context {
|
||||
runtime: Runtime,
|
||||
network: Mutex<Option<Network>>,
|
||||
network: Mutex<Option<Arc<Network>>>,
|
||||
socks: Mutex<Option<meshport_socks::Bridge>>,
|
||||
tcp: tokio::sync::Mutex<HashMap<u64, meshport::TcpStream>>,
|
||||
udp: tokio::sync::Mutex<HashMap<u64, meshport::UdpSocket>>,
|
||||
}
|
||||
impl Drop for Context {
|
||||
fn drop(&mut self) {
|
||||
if let Ok(slot) = self.socks.get_mut()
|
||||
&& let Some(mut bridge) = slot.take()
|
||||
{
|
||||
let _ = self.runtime.block_on(bridge.stop());
|
||||
}
|
||||
if let Ok(slot) = self.network.get_mut()
|
||||
&& let Some(n) = slot.take()
|
||||
{
|
||||
@@ -60,6 +66,7 @@ pub extern "C" fn meshport_context_new() -> u64 {
|
||||
Arc::new(Context {
|
||||
runtime,
|
||||
network: Mutex::new(None),
|
||||
socks: Mutex::new(None),
|
||||
tcp: tokio::sync::Mutex::new(HashMap::new()),
|
||||
udp: tokio::sync::Mutex::new(HashMap::new()),
|
||||
}),
|
||||
@@ -105,7 +112,22 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
|
||||
"peers": config.get_peers().iter().map(|peer| peer.uri.to_string()).collect::<Vec<_>>(),
|
||||
"enable_ipv6": flags.enable_ipv6,
|
||||
"latency_first": flags.latency_first,
|
||||
"optimization": optimization
|
||||
"optimization": optimization,
|
||||
"listeners": config.get_listener_uris().iter().map(|uri| uri.to_string()).collect::<Vec<_>>(),
|
||||
"stun_servers": config.get_stun_servers(),
|
||||
"stun_servers_v6": config.get_stun_servers_v6(),
|
||||
"flags": {
|
||||
"default_protocol": flags.default_protocol,
|
||||
"disable_p2p": flags.disable_p2p,
|
||||
"disable_tcp_hole_punching": flags.disable_tcp_hole_punching,
|
||||
"disable_udp_hole_punching": flags.disable_udp_hole_punching,
|
||||
"disable_sym_hole_punching": flags.disable_sym_hole_punching,
|
||||
"p2p_only": flags.p2p_only,
|
||||
"lazy_p2p": flags.lazy_p2p,
|
||||
"need_p2p": flags.need_p2p,
|
||||
"private_mode": flags.private_mode,
|
||||
"foreign_relay_bps_limit": flags.foreign_relay_bps_limit.to_string()
|
||||
}
|
||||
});
|
||||
}
|
||||
return Ok(result);
|
||||
@@ -136,10 +158,13 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
|
||||
let config = request["toml"]
|
||||
.as_str()
|
||||
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
|
||||
*network = Some(context.runtime.block_on(Network::start(config))?);
|
||||
*network = Some(Arc::new(context.runtime.block_on(Network::start(config))?));
|
||||
Ok(json!({"engine_started": true}))
|
||||
}
|
||||
"stop" => {
|
||||
if let Some(mut bridge) = context.socks.lock().unwrap().take() {
|
||||
context.runtime.block_on(bridge.stop())?;
|
||||
}
|
||||
context.tcp.blocking_lock().clear();
|
||||
context.udp.blocking_lock().clear();
|
||||
if let Some(n) = network.take() {
|
||||
@@ -147,6 +172,61 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
|
||||
}
|
||||
Ok(json!({"stopped": true}))
|
||||
}
|
||||
"socks_start" => {
|
||||
let n = network
|
||||
.as_ref()
|
||||
.ok_or_else(|| anyhow::anyhow!("network is stopped"))?;
|
||||
let mut slot = context.socks.lock().unwrap();
|
||||
anyhow::ensure!(slot.is_none(), "SOCKS bridge already started");
|
||||
let port = match request.get("port") {
|
||||
Some(value) => u16::try_from(
|
||||
value
|
||||
.as_u64()
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid port"))?,
|
||||
)?,
|
||||
None => 0,
|
||||
};
|
||||
let max_sessions = match request.get("max_sessions") {
|
||||
Some(value) => usize::try_from(
|
||||
value
|
||||
.as_u64()
|
||||
.ok_or_else(|| anyhow::anyhow!("invalid session limit"))?,
|
||||
)?,
|
||||
None => 128,
|
||||
};
|
||||
let options = meshport_socks::Options {
|
||||
listen: std::net::SocketAddrV4::new(std::net::Ipv4Addr::LOCALHOST, port),
|
||||
max_sessions,
|
||||
..Default::default()
|
||||
};
|
||||
let bridge = context
|
||||
.runtime
|
||||
.block_on(meshport_socks::Bridge::start(n.clone(), options))?;
|
||||
let address = bridge.local_addr().to_string();
|
||||
*slot = Some(bridge);
|
||||
Ok(
|
||||
json!({"running": true, "listen": address, "tcp": true, "udp": true, "ipv4_only": true, "dns_resolution": false}),
|
||||
)
|
||||
}
|
||||
"socks_stop" => {
|
||||
if let Some(mut bridge) = context.socks.lock().unwrap().take() {
|
||||
context.runtime.block_on(bridge.stop())?;
|
||||
}
|
||||
Ok(json!({"stopped": true}))
|
||||
}
|
||||
"socks_status" => {
|
||||
let slot = context.socks.lock().unwrap();
|
||||
Ok(match slot.as_ref() {
|
||||
Some(bridge) => {
|
||||
let s = bridge.snapshot();
|
||||
json!({"running": s.running, "listen": bridge.local_addr().to_string(),
|
||||
"active_sessions": s.active_sessions, "accepted_sessions": s.accepted_sessions,
|
||||
"completed_sessions": s.completed_sessions, "failed_sessions": s.failed_sessions,
|
||||
"refused_at_capacity": s.refused_at_capacity, "dropped_udp_packets": s.dropped_udp_packets})
|
||||
}
|
||||
None => json!({"running": false, "active_sessions": 0}),
|
||||
})
|
||||
}
|
||||
"status" => match network.as_ref() {
|
||||
Some(n) => {
|
||||
let mut snapshot = context.runtime.block_on(n.snapshot());
|
||||
@@ -390,6 +470,10 @@ mod tests {
|
||||
&json!({"op": "validate", "toml": config, "include_profile": true}).to_string(),
|
||||
);
|
||||
assert_eq!(projected["ok"], true);
|
||||
assert_eq!(
|
||||
projected["data"]["profile"]["flags"]["foreign_relay_bps_limit"],
|
||||
"18446744073709551615"
|
||||
);
|
||||
assert_eq!(
|
||||
projected["data"]["profile"]["network_secret"],
|
||||
"test-only-secret"
|
||||
@@ -401,4 +485,72 @@ mod tests {
|
||||
);
|
||||
meshport_context_free(id);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn socks_control_lifecycle_and_context_cleanup() {
|
||||
use std::io::{Read, Write};
|
||||
let id = meshport_context_new();
|
||||
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], false);
|
||||
let config = "ipv4 = '10.253.83.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[network_identity]\nnetwork_name = 'socks-ffi-test'\nnetwork_secret = 'test-only'\n";
|
||||
assert_eq!(
|
||||
call(id, &json!({"op":"start", "toml":config}).to_string())["ok"],
|
||||
true
|
||||
);
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_start","port":65536}"#)["ok"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_start","max_sessions":0}"#)["ok"],
|
||||
false
|
||||
);
|
||||
let started = call(id, r#"{"op":"socks_start"}"#);
|
||||
assert_eq!(started["ok"], true);
|
||||
let address = started["data"]["listen"].as_str().unwrap();
|
||||
let mut control = std::net::TcpStream::connect(address).unwrap();
|
||||
control
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.unwrap();
|
||||
control.write_all(&[5, 1, 0]).unwrap();
|
||||
let mut reply = [0; 2];
|
||||
control.read_exact(&mut reply).unwrap();
|
||||
assert_eq!(reply, [5, 0]);
|
||||
// A native session waiting for its request does not hold the ABI lock.
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_status"}"#)["data"]["active_sessions"],
|
||||
1
|
||||
);
|
||||
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
|
||||
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], false);
|
||||
assert_eq!(call(id, r#"{"op":"socks_stop"}"#)["ok"], true);
|
||||
assert_eq!(control.read(&mut [0]).unwrap(), 0);
|
||||
assert!(std::net::TcpStream::connect(address).is_err());
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_status"}"#)["data"]["running"],
|
||||
false
|
||||
);
|
||||
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
|
||||
assert_eq!(call(id, r#"{"op":"socks_start"}"#)["ok"], true);
|
||||
assert_eq!(call(id, r#"{"op":"stop"}"#)["ok"], true);
|
||||
assert_eq!(
|
||||
call(id, r#"{"op":"socks_status"}"#)["data"]["running"],
|
||||
false
|
||||
);
|
||||
assert_eq!(
|
||||
call(id, &json!({"op":"start", "toml":config}).to_string())["ok"],
|
||||
true
|
||||
);
|
||||
let restarted = call(id, r#"{"op":"socks_start"}"#);
|
||||
let address = restarted["data"]["listen"].as_str().unwrap();
|
||||
let mut control = std::net::TcpStream::connect(address).unwrap();
|
||||
control
|
||||
.set_read_timeout(Some(Duration::from_secs(3)))
|
||||
.unwrap();
|
||||
control.write_all(&[5, 1, 0]).unwrap();
|
||||
control.read_exact(&mut reply).unwrap();
|
||||
meshport_context_free(id);
|
||||
assert_eq!(control.read(&mut [0]).unwrap(), 0);
|
||||
// No lingering listener after context destruction.
|
||||
std::net::TcpListener::bind(address).unwrap();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -0,0 +1,77 @@
|
||||
use easytier::instance::factory::create_native_instance;
|
||||
use easytier_core::config::toml::TomlConfig;
|
||||
use serde_json::{Value, json};
|
||||
use std::ffi::{CStr, CString};
|
||||
fn call(id: u64, request: Value) -> Value {
|
||||
let input = CString::new(request.to_string()).unwrap();
|
||||
unsafe {
|
||||
let reply = meshport_ffi::meshport_call(id, input.as_ptr());
|
||||
let result = serde_json::from_slice(CStr::from_ptr(reply).to_bytes()).unwrap();
|
||||
meshport_ffi::meshport_string_free(reply);
|
||||
result
|
||||
}
|
||||
}
|
||||
use std::time::Duration;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
#[test]
|
||||
fn ffi_udp_through_adjacent_mapped_subnet() {
|
||||
let runtime = tokio::runtime::Runtime::new().unwrap();
|
||||
let _entered = runtime.enter();
|
||||
let setup = async {
|
||||
let port = UdpSocket::bind("127.0.0.1:0")
|
||||
.await
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
let identity =
|
||||
"[network_identity]\nnetwork_name='unified-udp-fixture'\nnetwork_secret='test-only'\n";
|
||||
let server_config = TomlConfig::new_from_str(&format!(
|
||||
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
)).unwrap();
|
||||
let server = create_native_instance(server_config).unwrap();
|
||||
server.start().await.unwrap();
|
||||
let client = format!(
|
||||
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
);
|
||||
(server, client)
|
||||
};
|
||||
let (server, client) = runtime.block_on(setup);
|
||||
drop(_entered);
|
||||
let id = meshport_ffi::meshport_context_new();
|
||||
assert_eq!(call(id, json!({"op":"start", "toml":client}))["ok"], true);
|
||||
let deadline = std::time::Instant::now();
|
||||
loop {
|
||||
if call(id, json!({"op":"status"}))["data"]["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
assert!(deadline.elapsed() < Duration::from_secs(15));
|
||||
std::thread::sleep(Duration::from_millis(100));
|
||||
}
|
||||
let (target, echo): (std::net::SocketAddr, _) = runtime.block_on(async {
|
||||
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let target = format!("10.253.88.129:{}", udp.local_addr().unwrap().port())
|
||||
.parse()
|
||||
.unwrap();
|
||||
let echo = tokio::spawn(async move {
|
||||
let mut buffer = [0; 128];
|
||||
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
|
||||
udp.send_to(&buffer[..n], source).await.unwrap();
|
||||
});
|
||||
(target, echo)
|
||||
});
|
||||
let result = call(
|
||||
id,
|
||||
json!({"op":"probe", "target":target.to_string(), "protocol":"UDP", "echo":true, "timeout_ms":3000}),
|
||||
);
|
||||
|
||||
echo.abort();
|
||||
call(id, json!({"op":"stop"}));
|
||||
meshport_ffi::meshport_context_free(id);
|
||||
runtime.block_on(server.stop());
|
||||
assert_eq!(result["ok"], true, "FFI UDP failed: {result}");
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
[package]
|
||||
name = "meshport-socks"
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
|
||||
[dependencies]
|
||||
meshport.workspace = true
|
||||
anyhow.workspace = true
|
||||
tokio.workspace = true
|
||||
|
||||
[dev-dependencies]
|
||||
meshport-easytier.workspace = true
|
||||
easytier = { workspace = true, features = ["smoltcp", "proxy-packet"] }
|
||||
easytier-core.workspace = true
|
||||
tokio = { workspace = true, features = ["signal", "process"] }
|
||||
serde_json.workspace = true
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
//! Run with an application-mode TOML file; never prints its credentials.
|
||||
use anyhow::{Context, Result};
|
||||
use meshport::Network;
|
||||
use meshport_socks::{Bridge, Options};
|
||||
use std::{
|
||||
net::{Ipv4Addr, SocketAddrV4},
|
||||
sync::Arc,
|
||||
};
|
||||
|
||||
#[tokio::main]
|
||||
async fn main() -> Result<()> {
|
||||
let mut arguments = std::env::args().skip(1);
|
||||
let path = arguments
|
||||
.next()
|
||||
.context("usage: local_bridge CONFIG.toml [PORT]")?;
|
||||
let port = arguments
|
||||
.next()
|
||||
.map(|s| s.parse::<u16>())
|
||||
.transpose()?
|
||||
.unwrap_or(0);
|
||||
anyhow::ensure!(arguments.next().is_none(), "too many arguments");
|
||||
let config = std::fs::read_to_string(path).context("cannot read configuration")?;
|
||||
let network = Arc::new(Network::start(&config).await?);
|
||||
let result = async {
|
||||
let mut bridge = Bridge::start(
|
||||
network.clone(),
|
||||
Options {
|
||||
listen: SocketAddrV4::new(Ipv4Addr::LOCALHOST, port),
|
||||
..Default::default()
|
||||
},
|
||||
)
|
||||
.await?;
|
||||
println!("MeshPort SOCKS5 IPv4 TCP/UDP: {}", bridge.local_addr());
|
||||
println!("Waiting for Ctrl-C; engine startup does not guarantee remote reachability.");
|
||||
let signal = tokio::signal::ctrl_c().await;
|
||||
bridge.stop().await?;
|
||||
signal?;
|
||||
Ok::<_, anyhow::Error>(())
|
||||
}
|
||||
.await;
|
||||
network.stop().await;
|
||||
result
|
||||
}
|
||||
@@ -0,0 +1,395 @@
|
||||
//! Local IPv4 SOCKS5 bridge to the MeshPort application data plane.
|
||||
//! No DNS or ordinary internet fallback. This is a restricted internal bridge,
|
||||
//! not a public SOCKS service (no GSSAPI, password authentication, or BIND).
|
||||
mod protocol;
|
||||
|
||||
use anyhow::{Result, ensure};
|
||||
use meshport::Network;
|
||||
use protocol::*;
|
||||
use std::{
|
||||
collections::HashSet,
|
||||
net::{Ipv4Addr, SocketAddr, SocketAddrV4},
|
||||
sync::{
|
||||
Arc,
|
||||
atomic::{AtomicU64, AtomicUsize, Ordering},
|
||||
},
|
||||
time::Duration,
|
||||
};
|
||||
use tokio::{
|
||||
io::{AsyncReadExt, AsyncWriteExt, copy, split},
|
||||
net::{TcpListener, TcpStream, UdpSocket},
|
||||
sync::{Semaphore, watch},
|
||||
task::{JoinHandle, JoinSet},
|
||||
time::{Instant, sleep_until, timeout},
|
||||
};
|
||||
|
||||
#[derive(Clone, Debug)]
|
||||
pub struct Options {
|
||||
pub listen: SocketAddrV4,
|
||||
pub max_sessions: usize,
|
||||
pub handshake_timeout: Duration,
|
||||
pub connect_timeout: Duration,
|
||||
/// Grace period for the remaining direction after either side reaches EOF.
|
||||
pub tcp_close_timeout: Duration,
|
||||
pub udp_idle_timeout: Duration,
|
||||
pub udp_io_timeout: Duration,
|
||||
pub max_udp_targets: usize,
|
||||
}
|
||||
|
||||
impl Default for Options {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
listen: SocketAddrV4::new(Ipv4Addr::LOCALHOST, 0),
|
||||
max_sessions: 128,
|
||||
handshake_timeout: Duration::from_secs(5),
|
||||
connect_timeout: Duration::from_secs(10),
|
||||
tcp_close_timeout: Duration::from_secs(30),
|
||||
udp_idle_timeout: Duration::from_secs(120),
|
||||
udp_io_timeout: Duration::from_secs(5),
|
||||
max_udp_targets: 64,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Default)]
|
||||
struct Counters {
|
||||
active: AtomicUsize,
|
||||
accepted: AtomicU64,
|
||||
completed: AtomicU64,
|
||||
failed: AtomicU64,
|
||||
refused_at_capacity: AtomicU64,
|
||||
dropped_udp: AtomicU64,
|
||||
}
|
||||
|
||||
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
|
||||
pub struct Snapshot {
|
||||
pub running: bool,
|
||||
pub active_sessions: usize,
|
||||
pub accepted_sessions: u64,
|
||||
pub completed_sessions: u64,
|
||||
pub failed_sessions: u64,
|
||||
pub refused_at_capacity: u64,
|
||||
pub dropped_udp_packets: u64,
|
||||
}
|
||||
|
||||
struct Active(Arc<Counters>);
|
||||
impl Drop for Active {
|
||||
fn drop(&mut self) {
|
||||
self.0.active.fetch_sub(1, Ordering::Relaxed);
|
||||
}
|
||||
}
|
||||
|
||||
/// Owns the listener and its sessions, but not the supplied network.
|
||||
/// Stop the bridge before stopping the network. Dropping aborts all sessions;
|
||||
/// `stop` additionally waits for resources to be released.
|
||||
pub struct Bridge {
|
||||
address: SocketAddrV4,
|
||||
shutdown: watch::Sender<bool>,
|
||||
task: Option<JoinHandle<std::io::Result<()>>>,
|
||||
counters: Arc<Counters>,
|
||||
}
|
||||
|
||||
impl Bridge {
|
||||
pub async fn start(network: Arc<Network>, options: Options) -> Result<Self> {
|
||||
ensure!(
|
||||
options.listen.ip().is_loopback(),
|
||||
"SOCKS bridge must bind IPv4 loopback"
|
||||
);
|
||||
ensure!(
|
||||
options.max_sessions > 0 && options.max_sessions <= 4096,
|
||||
"invalid session limit"
|
||||
);
|
||||
ensure!(
|
||||
options.max_udp_targets > 0 && options.max_udp_targets <= 1024,
|
||||
"invalid UDP target limit"
|
||||
);
|
||||
ensure!(
|
||||
!options.handshake_timeout.is_zero()
|
||||
&& !options.connect_timeout.is_zero()
|
||||
&& !options.tcp_close_timeout.is_zero()
|
||||
&& !options.udp_idle_timeout.is_zero()
|
||||
&& !options.udp_io_timeout.is_zero(),
|
||||
"timeouts must be positive"
|
||||
);
|
||||
let status = network.snapshot().await;
|
||||
ensure!(
|
||||
status["application_only"] == true,
|
||||
"SOCKS bridge requires application mode"
|
||||
);
|
||||
ensure!(status["state"] == "Running", "network is not running");
|
||||
let listener = TcpListener::bind(options.listen).await?;
|
||||
let SocketAddr::V4(address) = listener.local_addr()? else {
|
||||
unreachable!()
|
||||
};
|
||||
let counters = Arc::new(Counters::default());
|
||||
let (shutdown, rx) = watch::channel(false);
|
||||
let task = tokio::spawn(serve(listener, network, options, rx, counters.clone()));
|
||||
Ok(Self {
|
||||
address,
|
||||
shutdown,
|
||||
task: Some(task),
|
||||
counters,
|
||||
})
|
||||
}
|
||||
|
||||
pub fn local_addr(&self) -> SocketAddrV4 {
|
||||
self.address
|
||||
}
|
||||
|
||||
pub fn snapshot(&self) -> Snapshot {
|
||||
let c = &self.counters;
|
||||
Snapshot {
|
||||
running: self.task.as_ref().is_some_and(|task| !task.is_finished()),
|
||||
active_sessions: c.active.load(Ordering::Relaxed),
|
||||
accepted_sessions: c.accepted.load(Ordering::Relaxed),
|
||||
completed_sessions: c.completed.load(Ordering::Relaxed),
|
||||
failed_sessions: c.failed.load(Ordering::Relaxed),
|
||||
refused_at_capacity: c.refused_at_capacity.load(Ordering::Relaxed),
|
||||
dropped_udp_packets: c.dropped_udp.load(Ordering::Relaxed),
|
||||
}
|
||||
}
|
||||
|
||||
pub async fn stop(&mut self) -> Result<()> {
|
||||
self.shutdown.send_replace(true);
|
||||
if let Some(task) = self.task.take() {
|
||||
task.await??;
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for Bridge {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown.send_replace(true);
|
||||
if let Some(task) = &self.task {
|
||||
task.abort();
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
async fn serve(
|
||||
listener: TcpListener,
|
||||
network: Arc<Network>,
|
||||
options: Options,
|
||||
mut shutdown: watch::Receiver<bool>,
|
||||
counters: Arc<Counters>,
|
||||
) -> std::io::Result<()> {
|
||||
let permits = Arc::new(Semaphore::new(options.max_sessions));
|
||||
let mut sessions = JoinSet::new();
|
||||
let result = loop {
|
||||
tokio::select! {
|
||||
biased;
|
||||
_ = shutdown.changed() => break Ok(()),
|
||||
_ = sessions.join_next(), if !sessions.is_empty() => {},
|
||||
accepted = listener.accept() => {
|
||||
let (stream, peer) = match accepted { Ok(v) => v, Err(e) => break Err(e) };
|
||||
let Ok(permit) = permits.clone().try_acquire_owned() else {
|
||||
counters.refused_at_capacity.fetch_add(1, Ordering::Relaxed);
|
||||
drop(stream);
|
||||
continue;
|
||||
};
|
||||
let SocketAddr::V4(peer) = peer else { continue; };
|
||||
counters.active.fetch_add(1, Ordering::Relaxed);
|
||||
counters.accepted.fetch_add(1, Ordering::Relaxed);
|
||||
let active = Active(counters.clone());
|
||||
let c = counters.clone();
|
||||
let network = network.clone();
|
||||
let options = options.clone();
|
||||
sessions.spawn(async move {
|
||||
let _permit = permit;
|
||||
let _active = active;
|
||||
if session(stream, peer, network, options, &c).await.is_err() {
|
||||
c.failed.fetch_add(1, Ordering::Relaxed);
|
||||
} else {
|
||||
c.completed.fetch_add(1, Ordering::Relaxed);
|
||||
}
|
||||
});
|
||||
}
|
||||
}
|
||||
};
|
||||
drop(listener);
|
||||
sessions.shutdown().await;
|
||||
result
|
||||
}
|
||||
|
||||
fn empty_address() -> SocketAddrV4 {
|
||||
SocketAddrV4::new(Ipv4Addr::UNSPECIFIED, 0)
|
||||
}
|
||||
|
||||
async fn session(
|
||||
mut stream: TcpStream,
|
||||
peer: SocketAddrV4,
|
||||
network: Arc<Network>,
|
||||
options: Options,
|
||||
counters: &Counters,
|
||||
) -> Result<()> {
|
||||
let request = timeout(options.handshake_timeout, async {
|
||||
ensure!(negotiate(&mut stream).await?, "no acceptable SOCKS method");
|
||||
Ok::<_, anyhow::Error>(request(&mut stream).await?)
|
||||
})
|
||||
.await??;
|
||||
let request = match request {
|
||||
Ok(request) => request,
|
||||
Err(code) => {
|
||||
reply(&mut stream, code, empty_address()).await?;
|
||||
anyhow::bail!("unsupported SOCKS request");
|
||||
}
|
||||
};
|
||||
if request.command == 1 {
|
||||
if !valid_target(request.address) {
|
||||
reply(&mut stream, DENIED, empty_address()).await?;
|
||||
anyhow::bail!("invalid mesh destination");
|
||||
}
|
||||
let result = timeout(
|
||||
options.connect_timeout,
|
||||
network.connect_tcp(request.address.into(), options.connect_timeout),
|
||||
)
|
||||
.await;
|
||||
let mut overlay = match result {
|
||||
Ok(Ok(stream)) => stream,
|
||||
error => {
|
||||
let code = match &error {
|
||||
Ok(Err(e))
|
||||
if e.downcast_ref::<std::io::Error>()
|
||||
.is_some_and(|e| e.kind() == std::io::ErrorKind::ConnectionRefused) =>
|
||||
{
|
||||
REFUSED
|
||||
}
|
||||
_ => HOST_UNREACHABLE,
|
||||
};
|
||||
reply(&mut stream, code, empty_address()).await?;
|
||||
anyhow::bail!("mesh connection unavailable");
|
||||
}
|
||||
};
|
||||
let SocketAddr::V4(bound) = overlay.local_addr() else {
|
||||
unreachable!()
|
||||
};
|
||||
reply(&mut stream, SUCCESS, bound).await?;
|
||||
relay_tcp(&mut stream, &mut overlay, options.tcp_close_timeout).await?;
|
||||
return Ok(());
|
||||
}
|
||||
if !request.address.ip().is_unspecified() && request.address.ip() != peer.ip() {
|
||||
reply(&mut stream, DENIED, empty_address()).await?;
|
||||
anyhow::bail!("UDP source differs from control connection");
|
||||
}
|
||||
let setup = timeout(options.connect_timeout, async {
|
||||
let SocketAddr::V4(local) = stream.local_addr()? else {
|
||||
unreachable!()
|
||||
};
|
||||
let relay = UdpSocket::bind(SocketAddrV4::new(*local.ip(), 0)).await?;
|
||||
let overlay = network.bind_udp(0, options.connect_timeout).await?;
|
||||
Ok::<_, anyhow::Error>((relay, overlay))
|
||||
})
|
||||
.await;
|
||||
let (relay, overlay) = match setup {
|
||||
Ok(Ok(v)) => v,
|
||||
_ => {
|
||||
reply(&mut stream, FAILURE, empty_address()).await?;
|
||||
anyhow::bail!("UDP setup failed");
|
||||
}
|
||||
};
|
||||
let SocketAddr::V4(bound) = relay.local_addr()? else {
|
||||
unreachable!()
|
||||
};
|
||||
reply(&mut stream, SUCCESS, bound).await?;
|
||||
udp_session(
|
||||
stream,
|
||||
peer,
|
||||
request.address.port(),
|
||||
relay,
|
||||
overlay,
|
||||
options,
|
||||
counters,
|
||||
)
|
||||
.await
|
||||
}
|
||||
|
||||
async fn relay_tcp(
|
||||
local: &mut TcpStream,
|
||||
remote: &mut meshport::TcpStream,
|
||||
close_timeout: Duration,
|
||||
) -> Result<()> {
|
||||
let (mut local_read, mut local_write) = split(local);
|
||||
let (mut remote_read, mut remote_write) = split(remote);
|
||||
let (closed, mut closure) = watch::channel(false);
|
||||
let upload = async {
|
||||
copy(&mut local_read, &mut remote_write).await?;
|
||||
// Notify before native shutdown: a FIN ACK may never arrive after
|
||||
// a route disappears. Permit pending response data a bounded grace.
|
||||
closed.send_replace(true);
|
||||
remote_write.shutdown().await
|
||||
};
|
||||
let download = async {
|
||||
copy(&mut remote_read, &mut local_write).await?;
|
||||
closed.send_replace(true);
|
||||
local_write.shutdown().await
|
||||
};
|
||||
let forwarding = async { tokio::try_join!(upload, download) };
|
||||
tokio::pin!(forwarding);
|
||||
tokio::select! {
|
||||
result = &mut forwarding => { result?; }
|
||||
_ = closure.changed() => { timeout(close_timeout, forwarding).await??; }
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
async fn udp_session(
|
||||
mut control: TcpStream,
|
||||
peer: SocketAddrV4,
|
||||
source_port: u16,
|
||||
relay: UdpSocket,
|
||||
overlay: meshport::UdpSocket,
|
||||
options: Options,
|
||||
counters: &Counters,
|
||||
) -> Result<()> {
|
||||
let mut endpoint = (source_port != 0).then_some(SocketAddrV4::new(*peer.ip(), source_port));
|
||||
let mut targets = HashSet::new();
|
||||
let mut local_buffer = vec![0; 65535];
|
||||
let mut remote_buffer = vec![0; 65535];
|
||||
let mut control_buffer = [0; 1];
|
||||
let mut idle = Instant::now() + options.udp_idle_timeout;
|
||||
loop {
|
||||
tokio::select! {
|
||||
// Association lifetime is tied to its TCP control channel.
|
||||
result = control.read(&mut control_buffer) => {
|
||||
result?;
|
||||
return Ok(()); // EOF or unexpected control payload closes it.
|
||||
}
|
||||
_ = sleep_until(idle) => return Ok(()),
|
||||
result = relay.recv_from(&mut local_buffer) => {
|
||||
let (len, source) = result?;
|
||||
let SocketAddr::V4(source) = source else { continue; };
|
||||
let decoded = udp_request(&local_buffer[..len]);
|
||||
if source.ip() != peer.ip() || endpoint.is_some_and(|e| e != source) || decoded.is_none() {
|
||||
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
let (target, payload) = decoded.unwrap();
|
||||
if !targets.contains(&target) && targets.len() >= options.max_udp_targets {
|
||||
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
}
|
||||
endpoint = Some(source);
|
||||
// Count attempted destinations too: the native socket can register
|
||||
// a flow before a send fails. This bounds its resource growth.
|
||||
targets.insert(target);
|
||||
match timeout(options.udp_io_timeout, overlay.send_to(payload, target.into())).await {
|
||||
Ok(Ok(n)) if n == payload.len() => idle = Instant::now() + options.udp_idle_timeout,
|
||||
_ => { counters.dropped_udp.fetch_add(1, Ordering::Relaxed); }
|
||||
}
|
||||
}
|
||||
result = overlay.recv_from(&mut remote_buffer) => {
|
||||
let (len, source) = result?;
|
||||
let SocketAddr::V4(source) = source else { continue; };
|
||||
let Some(endpoint) = endpoint else { continue; };
|
||||
if !targets.contains(&source) { continue; }
|
||||
let Some(frame) = udp_reply(source, &remote_buffer[..len]) else {
|
||||
counters.dropped_udp.fetch_add(1, Ordering::Relaxed);
|
||||
continue;
|
||||
};
|
||||
timeout(options.udp_io_timeout, relay.send_to(&frame, endpoint)).await??;
|
||||
idle = Instant::now() + options.udp_idle_timeout;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,134 @@
|
||||
use std::net::{Ipv4Addr, SocketAddrV4};
|
||||
use tokio::io::{AsyncRead, AsyncReadExt, AsyncWrite, AsyncWriteExt};
|
||||
|
||||
pub(crate) const SUCCESS: u8 = 0;
|
||||
pub(crate) const FAILURE: u8 = 1;
|
||||
pub(crate) const DENIED: u8 = 2;
|
||||
pub(crate) const HOST_UNREACHABLE: u8 = 4;
|
||||
pub(crate) const REFUSED: u8 = 5;
|
||||
pub(crate) const COMMAND_UNSUPPORTED: u8 = 7;
|
||||
pub(crate) const ADDRESS_UNSUPPORTED: u8 = 8;
|
||||
|
||||
pub(crate) struct Request {
|
||||
pub command: u8,
|
||||
pub address: SocketAddrV4,
|
||||
}
|
||||
|
||||
pub(crate) async fn negotiate<S: AsyncRead + AsyncWrite + Unpin>(
|
||||
s: &mut S,
|
||||
) -> std::io::Result<bool> {
|
||||
let mut header = [0; 2];
|
||||
s.read_exact(&mut header).await?;
|
||||
if header[0] != 5 || header[1] == 0 {
|
||||
return Ok(false);
|
||||
}
|
||||
let mut methods = vec![0; header[1] as usize];
|
||||
s.read_exact(&mut methods).await?;
|
||||
let accepted = methods.contains(&0);
|
||||
s.write_all(&[5, if accepted { 0 } else { 255 }]).await?;
|
||||
Ok(accepted)
|
||||
}
|
||||
|
||||
/// Unsupported address types are deliberately not resolved using system DNS.
|
||||
pub(crate) async fn request<S: AsyncRead + Unpin>(
|
||||
s: &mut S,
|
||||
) -> std::io::Result<Result<Request, u8>> {
|
||||
let mut header = [0; 4];
|
||||
s.read_exact(&mut header).await?;
|
||||
if header[0] != 5 || header[2] != 0 {
|
||||
return Ok(Err(FAILURE));
|
||||
}
|
||||
if !matches!(header[1], 1 | 3) {
|
||||
return Ok(Err(COMMAND_UNSUPPORTED));
|
||||
}
|
||||
if header[3] != 1 {
|
||||
return Ok(Err(ADDRESS_UNSUPPORTED));
|
||||
}
|
||||
let mut address = [0; 6];
|
||||
s.read_exact(&mut address).await?;
|
||||
Ok(Ok(Request {
|
||||
command: header[1],
|
||||
address: decode_address(&address),
|
||||
}))
|
||||
}
|
||||
|
||||
fn decode_address(bytes: &[u8]) -> SocketAddrV4 {
|
||||
SocketAddrV4::new(
|
||||
Ipv4Addr::new(bytes[0], bytes[1], bytes[2], bytes[3]),
|
||||
u16::from_be_bytes([bytes[4], bytes[5]]),
|
||||
)
|
||||
}
|
||||
|
||||
pub(crate) fn address_bytes(address: SocketAddrV4) -> [u8; 6] {
|
||||
let [a, b, c, d] = address.ip().octets();
|
||||
let [hi, lo] = address.port().to_be_bytes();
|
||||
[a, b, c, d, hi, lo]
|
||||
}
|
||||
|
||||
pub(crate) async fn reply<S: AsyncWrite + Unpin>(
|
||||
s: &mut S,
|
||||
code: u8,
|
||||
address: SocketAddrV4,
|
||||
) -> std::io::Result<()> {
|
||||
let mut bytes = vec![5, code, 0, 1];
|
||||
bytes.extend_from_slice(&address_bytes(address));
|
||||
s.write_all(&bytes).await
|
||||
}
|
||||
|
||||
pub(crate) fn valid_target(address: SocketAddrV4) -> bool {
|
||||
address.port() != 0
|
||||
&& !address.ip().is_unspecified()
|
||||
&& !address.ip().is_multicast()
|
||||
&& !address.ip().is_broadcast()
|
||||
&& !address.ip().is_loopback()
|
||||
}
|
||||
|
||||
pub(crate) fn udp_request(bytes: &[u8]) -> Option<(SocketAddrV4, &[u8])> {
|
||||
// No fragmentation, domain resolution, IPv6, or reserved bits.
|
||||
if bytes.len() < 10 || bytes[..4] != [0, 0, 0, 1] || bytes.len() > 65507 {
|
||||
return None;
|
||||
}
|
||||
let address = decode_address(&bytes[4..10]);
|
||||
valid_target(address).then_some((address, &bytes[10..]))
|
||||
}
|
||||
|
||||
pub(crate) fn udp_reply(address: SocketAddrV4, payload: &[u8]) -> Option<Vec<u8>> {
|
||||
if payload.len() > 65497 {
|
||||
return None;
|
||||
}
|
||||
let mut bytes = Vec::with_capacity(10 + payload.len());
|
||||
bytes.extend_from_slice(&[0, 0, 0, 1]);
|
||||
bytes.extend_from_slice(&address_bytes(address));
|
||||
bytes.extend_from_slice(payload);
|
||||
Some(bytes)
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn udp_rejects_malformed_fragmented_and_non_mesh_addresses() {
|
||||
let target = "10.77.0.2:7007".parse().unwrap();
|
||||
let frame = udp_reply(target, b"hello").unwrap();
|
||||
assert_eq!(udp_request(&frame), Some((target, &b"hello"[..])));
|
||||
for length in 0..10 {
|
||||
assert!(udp_request(&frame[..length]).is_none());
|
||||
}
|
||||
for (index, value) in [(0, 1), (1, 1), (2, 1), (3, 3), (3, 4)] {
|
||||
let mut bad = frame.clone();
|
||||
bad[index] = value;
|
||||
assert!(udp_request(&bad).is_none());
|
||||
}
|
||||
for address in [
|
||||
"0.0.0.0:1",
|
||||
"127.0.0.1:1",
|
||||
"224.0.0.1:1",
|
||||
"255.255.255.255:1",
|
||||
"10.0.0.1:0",
|
||||
] {
|
||||
assert!(udp_request(&udp_reply(address.parse().unwrap(), b"x").unwrap()).is_none());
|
||||
}
|
||||
assert!(udp_reply(target, &vec![0; 65498]).is_none());
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,482 @@
|
||||
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();
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
use easytier::instance::factory::create_native_instance;
|
||||
use easytier_core::config::toml::TomlConfig;
|
||||
use meshport::Network;
|
||||
use std::time::Duration;
|
||||
use tokio::net::UdpSocket;
|
||||
|
||||
#[tokio::test(flavor = "multi_thread", worker_threads = 4)]
|
||||
async fn udp_through_adjacent_mapped_subnet() {
|
||||
let port = UdpSocket::bind("127.0.0.1:0")
|
||||
.await
|
||||
.unwrap()
|
||||
.local_addr()
|
||||
.unwrap()
|
||||
.port();
|
||||
let identity =
|
||||
"[network_identity]\nnetwork_name='unified-udp-fixture'\nnetwork_secret='test-only'\n";
|
||||
let server_config = TomlConfig::new_from_str(&format!(
|
||||
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
)).unwrap();
|
||||
let server = create_native_instance(server_config).unwrap();
|
||||
server.start().await.unwrap();
|
||||
let network = Network::start(&format!(
|
||||
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
)).await.unwrap();
|
||||
tokio::time::timeout(Duration::from_secs(15), async {
|
||||
loop {
|
||||
if network.snapshot().await["platform_network"]["subnet_routes"]
|
||||
.as_array()
|
||||
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
tokio::time::sleep(Duration::from_millis(100)).await;
|
||||
}
|
||||
})
|
||||
.await
|
||||
.unwrap();
|
||||
let udp = UdpSocket::bind("127.0.0.1:0").await.unwrap();
|
||||
let target = format!("10.253.88.129:{}", udp.local_addr().unwrap().port())
|
||||
.parse()
|
||||
.unwrap();
|
||||
let echo = tokio::spawn(async move {
|
||||
let mut buffer = [0; 128];
|
||||
let (n, source) = udp.recv_from(&mut buffer).await.unwrap();
|
||||
udp.send_to(&buffer[..n], source).await.unwrap();
|
||||
});
|
||||
let result = network
|
||||
.probe(target, true, true, Duration::from_secs(3))
|
||||
.await;
|
||||
echo.abort();
|
||||
network.stop().await;
|
||||
server.stop().await;
|
||||
assert!(
|
||||
result.is_ok(),
|
||||
"adjacent mapped subnet UDP failed: {result:?}"
|
||||
);
|
||||
}
|
||||
Reference in New Issue
Block a user