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:
shenlei
2026-10-12 10:06:15 +09:00
co-authored by Claude Haiku 5.5
parent 10b10e5bdf
commit 2f185f914d
123 changed files with 12180 additions and 326 deletions
+2 -1
View File
@@ -12,5 +12,6 @@ libc = "0.2"
meshport.workspace = true
tokio.workspace = true
easytier.workspace = true
# The local self-test gateway must forward its mapped subnet's UDP traffic.
easytier = { workspace = true, features = ["proxy-packet"] }
easytier-core.workspace = true
@@ -38,7 +38,7 @@ pub fn run() -> Result<()> {
let port = std::net::UdpSocket::bind("127.0.0.1:0")?.local_addr()?.port();
let identity = "[network_identity]\nnetwork_name = 'meshport-vpn-self-test'\nnetwork_secret = 'test-only'\n";
let system_config = format!("ipv4 = '10.253.77.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n{identity}[runtime]\nmode = 'system_vpn'");
super::overlap_preflight(&system_config)?;
super::overlap_preflight(&system_config, true)?;
stage("starting application server");
let server_config = easytier::common::config::TomlConfigLoader::new_from_str(&format!(
"ipv4 = '10.253.78.2/24'\nstun_servers = []\nstun_servers_v6 = []\nlisteners = ['udp://127.0.0.1:{port}']\n[[proxy_network]]\ncidr = '10.253.78.0/24'\n{identity}[flags]\nno_tun = true\nuse_smoltcp = true"
@@ -0,0 +1,337 @@
use anyhow::{Context, Result, ensure};
use serde_json::{Value, json};
use std::{
collections::BTreeSet,
ffi::{CStr, CString},
io::Write,
path::PathBuf,
process::{Child, Command, Stdio},
};
// The privileged helper loads only its packaged sibling library. Go runtimes
// cannot safely be unloaded with dlclose while their runtime threads exist.
struct Proxy {
handle: u64,
call: unsafe extern "C" fn(u64, *const libc::c_char) -> *mut libc::c_char,
free_string: unsafe extern "C" fn(*mut libc::c_char),
free: unsafe extern "C" fn(u64),
}
impl Proxy {
fn open() -> Result<Self> {
let executable = std::env::current_exe()?.canonicalize()?;
let path: PathBuf = executable
.parent()
.context("helper bundle missing")?
.join("../Frameworks/libmeshport_proxy.dylib")
.canonicalize()?;
let name = CString::new(path.as_os_str().as_encoded_bytes())?;
unsafe {
let library = libc::dlopen(name.as_ptr(), libc::RTLD_NOW | libc::RTLD_LOCAL);
ensure!(!library.is_null(), "packaged proxy library unavailable");
fn symbol(library: *mut libc::c_void, name: &str) -> Result<*mut libc::c_void> {
let name = CString::new(name)?;
let symbol = unsafe { libc::dlsym(library, name.as_ptr()) };
ensure!(!symbol.is_null(), "proxy ABI symbol unavailable");
Ok(symbol)
}
let new: unsafe extern "C" fn() -> u64 =
std::mem::transmute(symbol(library, "meshport_proxy_context_new")?);
let version: unsafe extern "C" fn() -> u32 =
std::mem::transmute(symbol(library, "meshport_proxy_abi_version")?);
ensure!(version() == 1, "proxy ABI incompatible");
let handle = new();
ensure!(handle != 0, "proxy context unavailable");
Ok(Self {
handle,
call: std::mem::transmute(symbol(library, "meshport_proxy_call")?),
free_string: std::mem::transmute(symbol(library, "meshport_proxy_string_free")?),
free: std::mem::transmute(symbol(library, "meshport_proxy_context_free")?),
})
}
}
fn request(&self, request: Value) -> Result<Value> {
let encoded = request.to_string();
ensure!(encoded.len() <= 65536, "proxy request exceeds limit");
let encoded = CString::new(encoded)?;
unsafe {
let reply = (self.call)(self.handle, encoded.as_ptr());
ensure!(!reply.is_null(), "proxy response missing");
let parsed = serde_json::from_slice::<Value>(CStr::from_ptr(reply).to_bytes());
(self.free_string)(reply);
let parsed = parsed?;
ensure!(
parsed["ok"] == true,
"{}",
parsed["error"].as_str().unwrap_or("proxy engine failed")
);
Ok(parsed["data"].clone())
}
}
}
impl Drop for Proxy {
fn drop(&mut self) {
unsafe { (self.free)(self.handle) }
}
}
struct DnsGuard {
child: Child,
}
impl DnsGuard {
fn install() -> Result<Self> {
let mut child = Command::new("/usr/sbin/scutil")
.stdin(Stdio::piped())
.stdout(Stdio::null())
.stderr(Stdio::null())
.spawn()?;
let key = format!(
"State:/Network/Service/MeshPort-{}-Unified/DNS",
std::process::id()
);
let input = child.stdin.as_mut().context("DNS control unavailable")?;
writeln!(
input,
"open\nd.init\nd.add ServerAddresses * 172.19.0.2\nd.add SupplementalMatchDomains * \"\"\nd.add SupplementalMatchOrders # 1\nadd {key} temporary"
)?;
input.flush()?;
let guard = Self { child };
// Verify our exact temporary key; do not inspect or modify saved service DNS.
for _ in 0..20 {
let output = Command::new("/usr/sbin/scutil")
.stdin(Stdio::piped())
.stdout(Stdio::piped())
.spawn()?;
let mut output = output;
writeln!(output.stdin.take().unwrap(), "show {key}\nquit")?;
let response = output.wait_with_output()?;
if String::from_utf8_lossy(&response.stdout).contains("172.19.0.2") {
return Ok(guard);
}
std::thread::sleep(std::time::Duration::from_millis(50));
}
anyhow::bail!("temporary system DNS registration failed")
}
}
impl Drop for DnsGuard {
fn drop(&mut self) {
if let Some(mut input) = self.child.stdin.take() {
let _ = writeln!(input, "quit");
}
let _ = self.child.wait();
}
}
#[derive(Default)]
pub(super) struct Unified {
dns: Option<DnsGuard>,
proxy: Option<Proxy>,
profile: Value,
protected: BTreeSet<String>,
active: BTreeSet<String>,
physical: String,
mesh: bool,
running: bool,
}
fn physical_interface(internet: bool) -> Result<String> {
let route = Command::new("/sbin/route")
.args(["-n", "get", "1.1.1.1"])
.output()?;
ensure!(route.status.success(), "physical route unavailable");
let text = String::from_utf8(route.stdout)?;
let interface = text
.lines()
.find_map(|line| line.trim().strip_prefix("interface:").map(str::trim))
.context("physical interface unavailable")?;
let interface = if interface.starts_with("utun") && !internet {
let interfaces = Command::new("/sbin/ifconfig").arg("-l").output()?;
let interfaces = String::from_utf8(interfaces.stdout)?;
let physical = interfaces
.split_whitespace()
.filter(|name| name.starts_with("en") || name.starts_with("bridge"))
.find(|name| {
Command::new("/sbin/route")
.args(["-n", "get", "-ifscope", name, "default"])
.output()
.is_ok_and(|output| output.status.success())
})
.context("physical scoped gateway unavailable")?;
physical.to_owned()
} else {
interface.to_owned()
};
ensure!(
!interface.starts_with("utun") && interface != "lo0",
"another VPN owns the default route; stop its TUN before starting internet unified VPN"
);
ensure!(
interface.chars().all(|c| c.is_ascii_alphanumeric()),
"invalid physical interface"
);
// Do not allow sing-tun to replace another owner's split-default routes.
let table = Command::new("/usr/sbin/netstat").args(["-rn"]).output()?;
let text = String::from_utf8(table.stdout)?;
for line in text.lines().filter(|_| internet) {
let destination = line.split_whitespace().next().unwrap_or("");
ensure!(
![
"0/1",
"128.0/1",
"0.0.0.0/1",
"128.0.0.0/1",
"::/1",
"8000::/1"
]
.contains(&destination),
"split default routes already installed by another VPN"
);
}
Ok(interface)
}
fn prefixes(snapshot: &Value) -> Result<BTreeSet<String>> {
let mut result = BTreeSet::new();
let address = snapshot["ipv4"]
.as_str()
.context("static mesh IPv4 required for unified VPN")?;
let prefix: std::net::Ipv4Addr = address
.split('/')
.next()
.context("invalid mesh IPv4")?
.parse()?;
let bits: u32 = address.split('/').nth(1).unwrap_or("24").parse()?;
ensure!((16..=32).contains(&bits), "unsupported mesh prefix");
result.insert(format!(
"{}/{}",
std::net::Ipv4Addr::from(u32::from(prefix) & (u32::MAX << (32 - bits))),
bits
));
if snapshot["platform_network"]["subnet_routes_scope"] == "accepted_projection" {
if let Some(routes) = snapshot["platform_network"]["subnet_routes"].as_array() {
for value in routes {
result.insert(value.as_str().context("invalid accepted route")?.into());
}
}
}
Ok(result)
}
impl Unified {
pub fn active(&self) -> bool {
self.running
}
pub fn start(&mut self, id: u64, request: &Value) -> Result<Value> {
ensure!(!self.running, "unified VPN already started");
self.physical = physical_interface(request["unified_profile"]["feature"] != "mesh")?;
self.profile = request["unified_profile"].clone();
ensure!(self.profile.is_object(), "proxy profile required");
// Host-owned fields cannot come from client profile input.
for field in [
"tun",
"desktop_tun",
"physical_interface",
"mesh_cidrs",
"protected_cidrs",
"mesh_socks",
"listen_port",
] {
ensure!(
self.profile.get(field).is_none(),
"unexpected host-owned proxy field"
);
}
self.mesh = self.profile["feature"] != "proxy";
self.proxy = Some(Proxy::open()?);
self.proxy
.as_ref()
.unwrap()
.request(json!({"op":"configure_cache","directory":"/var/run"}))?;
let result = (|| -> Result<Value> {
if self.mesh {
let config = request["toml"].as_str().context("configuration missing")?;
let validation = super::call(id, &json!({"op":"validate","toml":config}))?;
ensure!(
validation["ok"] == true && validation["data"]["runtime_mode"] == "application",
"unified VPN requires application-mode MeshPort"
);
super::overlap_preflight(config, false)?;
let start = super::call(id, &json!({"op":"start","toml":config}))?;
ensure!(start["ok"] == true, "mesh startup failed");
let bridge = super::call(id, &json!({"op":"socks_start"}))?;
ensure!(bridge["ok"] == true, "mesh bridge startup failed");
self.profile["mesh_socks"] = bridge["data"]["listen"].clone();
}
let snapshot = super::call(id, &json!({"op":"status"}))?["data"].clone();
let active = if self.mesh {
prefixes(&snapshot)?
} else {
BTreeSet::new()
};
self.restart(active)?;
if self.profile["feature"] != "mesh" {
self.dns = Some(DnsGuard::install()?);
}
self.running = true;
Ok(json!({"ok":true,"data":{"started":true}}))
})();
if result.is_err() {
let _ = self.stop(id);
}
result
}
fn restart(&mut self, active: BTreeSet<String>) -> Result<()> {
let proxy = self.proxy.as_ref().context("proxy unavailable")?;
proxy.request(json!({"op":"stop"}))?;
self.protected.extend(active.iter().cloned());
let mut config = self.profile.clone();
config["listen_port"] = json!(10818);
config["mesh_cidrs"] = json!(active);
config["protected_cidrs"] = json!(self.protected);
config["desktop_tun"] = json!(true);
config["physical_interface"] = json!(self.physical);
proxy.request(json!({"op":"start","config":config}))?;
self.active = active;
Ok(())
}
pub fn status(&mut self, id: u64) -> Result<Value> {
let mut snapshot = super::call(id, &json!({"op":"status"}))?["data"].clone();
let active = if self.mesh && snapshot["state"] == "Running" {
prefixes(&snapshot)?
} else {
BTreeSet::new()
};
if active != self.active {
self.restart(active.clone())?;
}
let proxy = self
.proxy
.as_ref()
.context("proxy unavailable")?
.request(json!({"op":"status"}))?;
ensure!(proxy["state"] == "Running", "proxy stopped unexpectedly");
snapshot["state"] = json!(if self.mesh && active.is_empty() {
"Partial"
} else {
"Running"
});
snapshot["runtime_mode"] = json!("unified_vpn");
snapshot["proxy"] = proxy;
snapshot["platform_network"]["ready"] = json!(true);
snapshot["platform_network"]["route_installation"] = json!("macos_unified_tun");
snapshot["platform_network"]["installed_subnet_routes"] = json!(self.active);
snapshot["platform_network"]["protected_subnets"] = json!(self.protected);
Ok(json!({"ok":true,"data":snapshot}))
}
pub fn stop(&mut self, id: u64) -> Result<()> {
self.running = false;
self.dns.take();
let proxy_error = self
.proxy
.take()
.and_then(|proxy| proxy.request(json!({"op":"stop"})).err());
let network = super::call(id, &json!({"op":"stop"}));
self.protected.clear();
self.active.clear();
if let Some(error) = proxy_error {
return Err(error);
}
network?;
Ok(())
}
}
@@ -0,0 +1,192 @@
//! Real OS sockets through sing-box TUN -> Rust SOCKS -> EasyTier application stack.
use anyhow::{Context, Result, ensure};
use serde_json::json;
use std::{
io::{Read, Write},
net::{TcpStream, UdpSocket},
process::Command,
time::{Duration, Instant},
};
use tokio::io::{AsyncReadExt, AsyncWriteExt};
pub fn run() -> Result<()> {
let runtime = tokio::runtime::Runtime::new()?;
let port = UdpSocket::bind("127.0.0.1:0")?.local_addr()?.port();
let identity =
"[network_identity]\nnetwork_name='unified-tun-self-test'\nnetwork_secret='test-only'\n";
let server_config = easytier::common::config::TomlConfigLoader::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"
))?;
let server = {
let _entered = runtime.enter();
easytier::instance::factory::create_native_instance(server_config)?
};
runtime.block_on(server.start())?;
let id = super::ContextHandle(meshport_ffi::meshport_context_new());
let mut unified = super::unified::Unified::default();
let before = Command::new("/sbin/route")
.args(["-n", "get", "default"])
.output()?
.stdout;
let result = (|| -> Result<()> {
let config = 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"
);
unified
.start(
id.0,
&json!({"toml":config,"unified_profile":{"feature":"mesh"}}),
)
.context("unified startup")?;
let deadline = Instant::now();
loop {
let snapshot = unified.status(id.0)?;
if snapshot["data"]["peer_count"].as_u64().unwrap_or(0) > 0
&& snapshot["data"]["platform_network"]["subnet_routes"]
.as_array()
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
{
break;
}
ensure!(
deadline.elapsed() < Duration::from_secs(12),
"peer discovery timeout"
);
std::thread::sleep(Duration::from_millis(200));
}
// PeerAdded precedes route convergence; let the overlay advertise its
// data plane before probing an ordinary OS socket.
std::thread::sleep(Duration::from_secs(2));
for target in ["10.253.88.2", "10.253.88.129", "172.19.0.1"] {
let output = Command::new("/sbin/route")
.args(["-n", "get", target])
.output()?;
println!(
"self-test route {target}: {}",
String::from_utf8_lossy(&output.stdout)
);
}
let interfaces = Command::new("/sbin/ifconfig").output()?;
for block in String::from_utf8_lossy(&interfaces.stdout).split("\nutun") {
if block.contains("inet 172.19.0.1 ") {
println!("self-test TUN interface: {block}");
}
}
let mut listener =
runtime.block_on(server.data_plane_tcp_bind(7007, Duration::from_secs(5)))?;
let tcp_echo = runtime.spawn(async move {
let (mut conn, _) = listener.accept().await?;
let mut data = [0; 128];
let n = conn.read(&mut data).await?;
conn.write_all(&data[..n]).await?;
// Dropping smoltcp immediately can discard its buffered reply.
let _ = conn.read(&mut data).await;
Ok::<_, anyhow::Error>(())
});
// SDK UDP sockets expose outbound flows, not an inbound UDP server.
// A mapped remote subnet exercises the real gateway used by applications.
let udp = runtime.block_on(tokio::net::UdpSocket::bind("127.0.0.1:0"))?;
let udp_target = format!("10.253.88.129:{}", udp.local_addr()?.port());
let udp_echo = runtime.spawn(async move {
let mut data = [0; 128];
loop {
let (n, address) = udp.recv_from(&mut data).await?;
println!("self-test UDP server received {n} bytes from {address}");
udp.send_to(&data[..n], address).await?;
}
#[allow(unreachable_code)]
Ok::<_, anyhow::Error>(())
});
let udp_probe = super::call(
id.0,
&json!({"op":"probe", "target":udp_target, "protocol":"UDP", "echo":true, "timeout_ms":3000}),
)?;
println!("self-test native UDP probe: {udp_probe}");
let mut tcp =
TcpStream::connect_timeout(&"10.253.88.2:7007".parse()?, Duration::from_secs(5))
.context("OS TCP connect")?;
tcp.set_read_timeout(Some(Duration::from_secs(5)))?;
tcp.write_all(b"unified TCP")?;
let mut buffer = [0; 11];
tcp.read_exact(&mut buffer).context("OS TCP echo receive")?;
println!("PASS: OS TCP echo through unified TUN");
ensure!(&buffer == b"unified TCP", "TCP mismatch");
drop(tcp);
let udp = UdpSocket::bind("0.0.0.0:0")?;
udp.set_read_timeout(Some(Duration::from_secs(1)))?;
let mut buffer = [0; 128];
let mut received = None;
for _ in 0..5 {
udp.send_to(b"unified UDP", &udp_target)?;
match udp.recv_from(&mut buffer) {
Ok((n, _)) => {
received = Some(n);
break;
}
Err(e)
if matches!(
e.kind(),
std::io::ErrorKind::WouldBlock | std::io::ErrorKind::TimedOut
) =>
{
()
}
Err(e) => return Err(e).context("OS UDP echo receive"),
}
}
if received.is_none() {
println!(
"self-test bridge counters: {}",
super::call(id.0, &json!({"op":"socks_status"}))?
);
println!("self-test UDP task finished: {}", udp_echo.is_finished());
}
let n = received.context("OS UDP echo timed out after five probes")?;
ensure!(&buffer[..n] == b"unified UDP", "UDP mismatch");
udp_echo.abort();
runtime.block_on(async {
tcp_echo.await??;
Ok::<_, anyhow::Error>(())
})?;
ensure!(
unified.status(id.0)?["data"]["platform_network"]["ready"] == true,
"unified status not ready"
);
Ok(())
})();
if let Err(error) = &result {
eprintln!("self-test failure: {error:#}");
}
let stopped = unified.stop(id.0);
runtime.block_on(server.stop());
if let Err(error) = &stopped {
eprintln!("self-test cleanup failure: {error:#}");
}
ensure!(
Command::new("/sbin/route")
.args(["-n", "get", "default"])
.output()?
.stdout
== before,
"default route changed"
);
let route = Command::new("/sbin/route")
.args(["-n", "get", "10.253.88.2"])
.output()?;
ensure!(
!String::from_utf8_lossy(&route.stdout).contains("172.19.0.1"),
"unified test route still installed"
);
let route = Command::new("/sbin/route")
.args(["-n", "get", "10.253.88.129"])
.output()?;
ensure!(
!String::from_utf8_lossy(&route.stdout).contains("172.19.0.1"),
"learned subnet test route still installed"
);
result?;
stopped?;
println!(
"PASS: OS TCP/UDP -> sing-box TUN -> MeshPort SOCKS -> EasyTier; stop removed test route and preserved default route"
);
Ok(())
}
+36 -5
View File
@@ -2,6 +2,8 @@
#[cfg(target_os = "macos")]
mod mac {
mod self_test;
mod unified;
mod unified_test;
use anyhow::{Context, Result, bail, ensure};
use meshport_easytier::ConfigLoader;
use std::{
@@ -35,10 +37,10 @@ mod mac {
Ok(decoded?)
}
}
fn overlap_preflight(config: &str) -> Result<()> {
fn overlap_preflight(config: &str, require_system: bool) -> Result<()> {
let config = meshport_easytier::parse_config(config)?;
ensure!(
!config.get_flags().no_tun,
!require_system || !config.get_flags().no_tun,
"helper accepts only system_vpn mode"
);
let overlay = config.get_ipv4().context("static overlay IPv4 required")?;
@@ -86,11 +88,35 @@ mod mac {
}
Ok(())
}
fn dispatch(id: u64, request: serde_json::Value) -> serde_json::Value {
fn dispatch(
id: u64,
unified: &mut unified::Unified,
request: serde_json::Value,
) -> serde_json::Value {
let result = (|| -> Result<serde_json::Value> {
if request["op"] == "start" && request.get("unified_profile").is_some() {
return unified.start(id, &request);
}
if unified.active() {
match request["op"].as_str() {
Some("status") => {
let status = unified.status(id);
if status.is_err() {
let _ = unified.stop(id);
}
return status;
}
Some("stop") => {
unified.stop(id)?;
return Ok(serde_json::json!({"ok":true,"data":{}}));
}
Some("start") => bail!("unified VPN already started"),
_ => {}
}
}
match request["op"].as_str() {
Some("start") => {
overlap_preflight(request["toml"].as_str().context("missing toml")?)?
overlap_preflight(request["toml"].as_str().context("missing toml")?, true)?
}
Some("stop" | "status" | "probe" | "validate" | "diagnostics_enable") => {}
_ => bail!("operation unavailable in system VPN helper"),
@@ -100,6 +126,7 @@ mod mac {
result.unwrap_or_else(|e| serde_json::json!({"ok": false, "error": e.to_string()}))
}
fn serve(id: u64, reader: &mut impl Read, writer: &mut impl Write) -> Result<()> {
let mut unified = unified::Unified::default();
let mut line = Vec::new();
let mut last = Instant::now();
loop {
@@ -132,13 +159,14 @@ mod mac {
let request = serde_json::from_slice(&line)?;
line.clear();
*BUSY_SINCE.lock().unwrap() = Some(Instant::now());
let response = dispatch(id, request);
let response = dispatch(id, &mut unified, request);
*BUSY_SINCE.lock().unwrap() = None;
serde_json::to_writer(&mut *writer, &response)?;
writer.write_all(b"\n")?;
writer.flush()?;
}
}
unified.stop(id)?;
Ok(())
}
pub fn run() -> Result<()> {
@@ -167,6 +195,9 @@ mod mac {
});
*BUSY_SINCE.lock().unwrap() = Some(Instant::now());
let args: Vec<_> = std::env::args().skip(1).collect();
if args == ["--self-test-unified"] {
return unified_test::run();
}
if args == ["--self-test"] {
*BUSY_SINCE.lock().unwrap() = None;
return self_test::run();