Move mesh networking logic into the SDK and fix lifecycle bugs

SDK:
- Add build_config/migrate_config, mesh_cidrs, route_generation, health
  and start_bridged; expose abi_info (capability revision 2).
- Add wait_routes long-poll; stop wakes waiters, and context_free now
  stops the network immediately instead of waiting for waiters to time out.

Hosts:
- Dart: waitRoutes(), MeshProxySession route watcher, ABI capability check.
- Android: fix a deadlock where every VPN request waited on its own
  single-thread worker; requests are now async, status is served from a
  snapshot, and combined mode reports Partial when the mesh stops.
- macOS helper: mesh-only unified mode stops when the mesh is lost;
  installed_subnet_routes excludes the overlay.
- Lab: restore Partial sessions, write migrated profiles back, remove the
  unreachable TOML import dialog; native test now connects via the form.

Docs updated accordingly.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
shenlei
2026-10-15 18:17:42 +09:00
co-authored by Claude Opus 5.5
parent 29d236f3fe
commit dc1bfc99d2
34 changed files with 1724 additions and 715 deletions
@@ -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, true)?;
meshport::check_local_overlap(&meshport_easytier::parse_config(&system_config)?)?;
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"
@@ -68,11 +68,10 @@ pub fn run() -> Result<()> {
ensure!(started.elapsed() < Duration::from_secs(10), "peer discovery timeout");
tokio::time::sleep(Duration::from_millis(100)).await;
}
while !vpn.snapshot().await["platform_network"]["subnet_routes"].as_array()
.is_some_and(|routes| routes.iter().any(|r| r == "10.253.78.0/24")) {
ensure!(started.elapsed() < Duration::from_secs(10), "advertised subnet learning timeout");
tokio::time::sleep(Duration::from_millis(100)).await;
}
let mut routes = vpn.watch_mesh_routes();
tokio::time::timeout(Duration::from_secs(10).saturating_sub(started.elapsed()),
routes.wait_for(|r| r.cidrs.iter().any(|c| c == "10.253.78.0/24")))
.await.context("advertised subnet learning timeout")??;
tokio::time::sleep(Duration::from_secs(2)).await;
// Ordinary OS TCP socket: no MeshPort data-plane API on the client.
let route = Command::new("/sbin/route").args(["-n", "get", "10.253.78.2"]).output()?;
+36 -40
View File
@@ -241,6 +241,7 @@ pub(super) struct Unified {
profile: Value,
protected: BTreeSet<String>,
active: BTreeSet<String>,
overlay_network: Option<String>,
physical: String,
mesh: bool,
running: bool,
@@ -300,31 +301,14 @@ fn physical_interface(internet: bool) -> Result<String> {
}
Ok(interface)
}
/// The SDK's canonical mesh destinations: overlay network plus accepted subnets.
pub(super) 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)
snapshot["platform_network"]["mesh_cidrs"]
.as_array()
.context("mesh routes unavailable")?
.iter()
.map(|value| Ok(value.as_str().context("invalid mesh route")?.to_owned()))
.collect()
}
impl Unified {
pub fn active(&self) -> bool {
@@ -363,26 +347,25 @@ impl Unified {
.unwrap()
.request(json!({"op":"configure_cache","directory":"/var/run"}))?;
let result = (|| -> Result<Value> {
let mut active = BTreeSet::new();
if self.mesh {
let config = request["toml"].as_str().context("configuration missing")?;
let validation = super::call(id, &json!({"op":"validate","toml":config}))?;
let bridge = super::call(
id,
&json!({"op":"start_bridged","toml":config,
"check_local_overlap":true,"require_static_overlay":true}),
)?;
ensure!(
validation["ok"] == true && validation["data"]["runtime_mode"] == "application",
"unified VPN requires application-mode MeshPort"
bridge["ok"] == true,
"mesh startup failed: {}",
bridge["error"].as_str().unwrap_or("unknown error")
);
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();
self.overlay_network = bridge["data"]["overlay"]["network"]
.as_str()
.map(str::to_owned);
active = prefixes(&json!({"platform_network": bridge["data"]}))?;
}
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()?);
@@ -411,7 +394,13 @@ impl Unified {
}
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" {
// Like Android: mesh-only has nothing left to serve once the mesh is
// gone (the caller then stops the session); combined keeps the proxy.
ensure!(
self.profile["feature"] != "mesh" || snapshot["health"]["mesh_routable"] == true,
"mesh network stopped unexpectedly"
);
let active = if self.mesh && snapshot["health"]["mesh_routable"] == true {
prefixes(&snapshot)?
} else {
BTreeSet::new()
@@ -434,7 +423,13 @@ impl Unified {
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);
// Same meaning on every platform: advertised subnets only, not the overlay.
let installed: Vec<_> = self
.active
.iter()
.filter(|cidr| Some(*cidr) != self.overlay_network.as_ref())
.collect();
snapshot["platform_network"]["installed_subnet_routes"] = json!(installed);
snapshot["platform_network"]["protected_subnets"] = json!(self.protected);
Ok(json!({"ok":true,"data":snapshot}))
}
@@ -449,6 +444,7 @@ impl Unified {
self.physical_route.take();
self.protected.clear();
self.active.clear();
self.overlay_network = None;
if let Some(error) = proxy_error {
return Err(error);
}
@@ -41,7 +41,7 @@ pub fn run() -> Result<()> {
loop {
let snapshot = unified.status(id.0)?;
if snapshot["data"]["peer_count"].as_u64().unwrap_or(0) > 0
&& snapshot["data"]["platform_network"]["subnet_routes"]
&& snapshot["data"]["platform_network"]["mesh_cidrs"]
.as_array()
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
{
+5 -46
View File
@@ -37,55 +37,14 @@ mod mac {
Ok(decoded?)
}
}
fn overlap_preflight(config: &str, require_system: bool) -> Result<()> {
// Overlap with existing interfaces is checked by the SDK when a system
// VPN starts; the helper only refuses configurations it must not run.
fn require_system_mode(config: &str) -> Result<()> {
let config = meshport_easytier::parse_config(config)?;
ensure!(
!require_system || !config.get_flags().no_tun,
!config.get_flags().no_tun,
"helper accepts only system_vpn mode"
);
let overlay = config.get_ipv4().context("static overlay IPv4 required")?;
let mut head = std::ptr::null_mut();
unsafe {
ensure!(
libc::getifaddrs(&mut head) == 0,
"cannot inspect existing interfaces"
);
let mut p = head;
let mut conflict = false;
while !p.is_null() {
let row = &*p;
if !row.ifa_addr.is_null()
&& !row.ifa_netmask.is_null()
&& (*row.ifa_addr).sa_family as i32 == libc::AF_INET
{
let a = &*(row.ifa_addr as *const libc::sockaddr_in);
let m = &*(row.ifa_netmask as *const libc::sockaddr_in);
let ip = u32::from_be(a.sin_addr.s_addr);
let mask = u32::from_be(m.sin_addr.s_addr);
let networks =
std::iter::once((overlay.first_address(), overlay.network_length())).chain(
config
.get_routes()
.unwrap_or_default()
.into_iter()
.map(|r| (r.first_address(), r.network_length())),
);
if networks.into_iter().any(|(base, prefix)| {
let overlay_mask = u32::MAX << (32 - prefix);
ip & mask & overlay_mask == u32::from(base) & mask & overlay_mask
}) {
conflict = true;
break;
}
}
p = row.ifa_next;
}
libc::freeifaddrs(head);
ensure!(
!conflict,
"overlay or selected subnet overlaps an existing interface; choose another subnet or stop the conflicting VPN"
);
}
Ok(())
}
fn dispatch(
@@ -116,7 +75,7 @@ mod mac {
}
match request["op"].as_str() {
Some("start") => {
overlap_preflight(request["toml"].as_str().context("missing toml")?, true)?
require_system_mode(request["toml"].as_str().context("missing toml")?)?
}
Some("stop" | "status" | "probe" | "validate" | "diagnostics_enable") => {}
_ => bail!("operation unavailable in system VPN helper"),