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
@@ -0,0 +1,197 @@
//! Structured profile <-> TOML. Hosts edit a JSON draft; the SDK owns the
//! mode invariants and the exact configuration text it will accept.
use anyhow::{Context, Result, bail};
use serde_json::Value;
/// Keys removed from saved configurations by earlier releases.
const LEGACY_KEYS: [&str; 1] = ["subnet_routes"];
/// Builds a validated configuration from a form draft. Any `runtime_mode` other
/// than `system_vpn` (including a host's unified VPN) runs the mesh in
/// application mode; transport and encryption invariants are not host choices.
pub fn build_config(profile: &Value) -> Result<String> {
let profile = profile.as_object().context("profile must be an object")?;
let text = |key: &str, default: &str| -> Result<Value> {
match profile.get(key) {
None | Some(Value::Null) => Ok(Value::from(default)),
Some(value @ Value::String(_)) => Ok(value.clone()),
Some(_) => bail!("{key} must be a string"),
}
};
let system = profile.get("runtime_mode").and_then(Value::as_str) == Some("system_vpn");
let mut optimization = match profile.get("optimization") {
None | Some(Value::Null) => serde_json::Map::new(),
Some(Value::Object(map)) => map.clone(),
Some(_) => bail!("optimization must be an object"),
};
optimization
.entry("mode")
.or_insert_with(|| Value::from("adaptive"));
let latency_first = matches!(
optimization.get("mode").and_then(Value::as_str),
Some("adaptive" | "latency")
);
let mut flags = match profile.get("flags") {
None | Some(Value::Null) => serde_json::Map::new(),
Some(Value::Object(map)) => map.clone(),
Some(_) => bail!("flags must be an object"),
};
flags.insert("no_tun".into(), Value::from(!system));
flags.insert("use_smoltcp".into(), Value::from(!system));
flags.insert("enable_encryption".into(), Value::from(true));
flags.insert(
"enable_ipv6".into(),
profile
.get("enable_ipv6")
.filter(|v| !v.is_null())
.cloned()
.unwrap_or(Value::from(true)),
);
flags.insert("latency_first".into(), Value::from(latency_first));
let mut root = serde_json::Map::new();
root.insert("hostname".into(), text("hostname", "MeshPort")?);
if profile.get("dhcp").and_then(Value::as_bool) == Some(true) {
root.insert("dhcp".into(), Value::from(true));
} else {
root.insert("ipv4".into(), text("ipv4", "")?);
}
root.insert(
"listeners".into(),
profile
.get("listeners")
.filter(|v| !v.is_null())
.cloned()
.unwrap_or(Value::Array(vec![])),
);
for key in ["stun_servers", "stun_servers_v6"] {
if let Some(value) = profile.get(key).filter(|v| !v.is_null()) {
root.insert(key.into(), value.clone());
}
}
let peers = match profile.get("peers") {
None | Some(Value::Null) => vec![],
Some(Value::Array(peers)) => peers
.iter()
.map(|uri| serde_json::json!({"uri": uri}))
.collect(),
Some(_) => bail!("peers must be an array"),
};
if !peers.is_empty() {
root.insert("peer".into(), Value::Array(peers));
}
root.insert(
"network_identity".into(),
serde_json::json!({
"network_name": text("network_name", "")?,
"network_secret": text("network_secret", "")?,
}),
);
root.insert("flags".into(), Value::Object(drop_nulls(flags)));
root.insert(
"runtime".into(),
serde_json::json!({"mode": if system { "system_vpn" } else { "application" }}),
);
root.insert(
"optimization".into(),
Value::Object(drop_nulls(optimization)),
);
let value = toml::Value::try_from(Value::Object(root))
.map_err(|_| anyhow::anyhow!("profile contains values TOML cannot represent"))?;
let output =
toml::to_string(&value).map_err(|_| anyhow::anyhow!("cannot encode configuration"))?;
super::parse_config(&output)?;
Ok(output)
}
fn drop_nulls(map: serde_json::Map<String, Value>) -> serde_json::Map<String, Value> {
map.into_iter().filter(|(_, v)| !v.is_null()).collect()
}
/// Removes options earlier releases saved but this SDK no longer accepts.
/// Returns the input unchanged (formatting preserved) when nothing is removed.
pub fn migrate_config(input: &str) -> Result<(String, bool)> {
let mut value: toml::Value =
toml::from_str(input).map_err(|_| anyhow::anyhow!("invalid TOML configuration"))?;
let table = value
.as_table_mut()
.context("configuration must be a TOML table")?;
let mut changed = false;
for key in LEGACY_KEYS {
changed |= table.remove(key).is_some();
if let Some(runtime) = table.get_mut("runtime").and_then(|v| v.as_table_mut()) {
changed |= runtime.remove(key).is_some();
}
}
if !changed {
return Ok((input.to_owned(), false));
}
let output =
toml::to_string(&value).map_err(|_| anyhow::anyhow!("cannot encode configuration"))?;
Ok((output, true))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::ConfigLoader;
use serde_json::json;
fn draft() -> Value {
json!({
"runtime_mode": "unified_vpn",
"ipv4": "10.77.0.11/24",
"network_name": "test",
"network_secret": "test-only",
"flags": {"disable_p2p": true, "foreign_relay_bps_limit": "18446744073709551615", "no_tun": false},
"listeners": ["udp://0.0.0.0:11010"],
"stun_servers": [],
"peers": ["tcp://192.0.2.1:11010"],
"optimization": {"mode": "direct"},
"unknown_projection_field": true,
})
}
#[test]
fn host_modes_force_invariants_and_round_trip() {
let toml = build_config(&draft()).unwrap();
let config = crate::parse_config(&toml).unwrap();
let flags = config.get_flags();
assert!(flags.no_tun && flags.use_smoltcp && flags.enable_encryption);
assert!(flags.disable_p2p && !flags.latency_first && flags.enable_ipv6);
assert_eq!(flags.foreign_relay_bps_limit, u64::MAX);
assert_eq!(config.get_peers().len(), 1);
assert!(toml.contains("stun_servers = []"));
assert!(toml.contains("mode = \"application\""));
let mut system = draft();
system["runtime_mode"] = json!("system_vpn");
let config = crate::parse_config(&build_config(&system).unwrap()).unwrap();
assert!(!config.get_flags().no_tun && !config.get_flags().use_smoltcp);
}
#[test]
fn dhcp_and_defaults() {
let toml = build_config(&json!({"dhcp": true, "ipv4": "", "network_name": "n"})).unwrap();
let config = crate::parse_config(&toml).unwrap();
assert!(config.get_dhcp() && config.get_flags().latency_first);
assert_eq!(config.get_hostname(), "MeshPort");
assert!(build_config(&json!({"network_name": "n", "ipv4": 7})).is_err());
assert!(build_config(&json!({"network_name": ""})).is_err());
}
#[test]
fn legacy_subnet_routes_are_removed_only_when_present() {
let base = "ipv4 = '10.77.0.11'\n[network_identity]\nnetwork_name = 'test'\n";
assert_eq!(migrate_config(base).unwrap(), (base.to_owned(), false));
for legacy in [
format!("subnet_routes = ['192.168.21.0/24']\n{base}"),
format!("{base}[runtime]\nmode = 'system_vpn'\nsubnet_routes = ['192.168.21.0/24']\n"),
] {
assert!(crate::parse_config(&legacy).is_err());
let (migrated, changed) = migrate_config(&legacy).unwrap();
assert!(changed && !migrated.contains("subnet_routes"));
crate::parse_config(&migrated).unwrap();
}
}
}
+274 -34
View File
@@ -16,8 +16,50 @@ pub use easytier_core::peers::meshport_optimization::{Mode, OptimizationPolicy};
#[cfg(target_os = "android")]
pub mod android;
mod config_builder;
mod system_routes;
pub use config_builder::{build_config, migrate_config};
pub use system_routes::mesh_cidrs;
/// Rejects a static overlay that overlaps an address already on this host.
/// DHCP configurations have no overlay yet and pass.
pub fn check_local_overlap(config: &TomlConfig) -> Result<()> {
match config.get_ipv4() {
Some(ip) => system_routes::check_local_overlap(ip.address(), ip.network_length()),
None => Ok(()),
}
}
/// Address plan for the host's virtual interface, derived from a static overlay.
pub fn overlay_projection(config: &TomlConfig) -> serde_json::Value {
config.get_ipv4().map_or(serde_json::Value::Null, |ip| {
overlay_json(ip.address(), ip.network_length())
})
}
fn overlay_json(address: std::net::Ipv4Addr, prefix: u8) -> serde_json::Value {
let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0);
let network = std::net::Ipv4Addr::from(u32::from(address) & mask);
serde_json::json!({
"address": address.to_string(),
"prefix": prefix,
"network": format!("{network}/{prefix}"),
"routable": system_routes::routable_overlay(address, prefix).is_some(),
})
}
/// Destinations to route through the mesh. `generation` increases on every
/// change of `cidrs` so hosts compare one number instead of the sets.
/// `stopped` is set once, with empty routes, when the network stops.
#[derive(Clone, Debug, Default, PartialEq, serde::Serialize)]
pub struct MeshRoutes {
pub generation: u64,
pub cidrs: Vec<String>,
pub subnet_routes: Vec<String>,
pub stopped: bool,
}
pub const REVISION: &str = "7af7bdc16a41d64d58743d15023a63b3eed2102c";
/// Strict mode-aware allowlist. Unknown options fail rather than disappear.
@@ -252,6 +294,117 @@ pub struct Engine {
events: Mutex<Option<EventBusSubscriber>>,
journal: Mutex<Vec<serde_json::Value>>,
event_sequence: Mutex<u64>,
routes: tokio::sync::watch::Sender<MeshRoutes>,
route_task: Mutex<Option<tokio::task::JoinHandle<()>>>,
}
impl Drop for Engine {
fn drop(&mut self) {
if let Some(task) = self.route_task.get_mut().ok().and_then(Option::take) {
task.abort();
}
}
}
async fn current_routes(instance: &NativeCoreInstance) -> (Vec<String>, Vec<String>) {
let accepted = instance
.packet_plane()
.proxy_cidr_diff(&Default::default())
.await
.map(|d| d.current.into_iter().collect::<Vec<_>>())
.unwrap_or_default();
let overlay = instance
.node_snapshot()
.await
.ipv4_addr
.map(|ip| (ip.address(), ip.network_length()));
(
system_routes::mesh_cidrs(overlay, &accepted),
accepted.iter().map(|r| r.to_string()).collect(),
)
}
fn publish_routes(
sender: &tokio::sync::watch::Sender<MeshRoutes>,
cidrs: Vec<String>,
subnet_routes: Vec<String>,
) {
sender.send_if_modified(|current| {
if current.cidrs == cidrs && current.subnet_routes == subnet_routes {
return false;
}
current.generation += 1;
current.cidrs = cidrs;
current.subnet_routes = subnet_routes;
true
});
}
/// Joins link and route views into one row per remote node. A node counts as
/// direct only when it has a direct transport and is its own next hop; the
/// measured link RTT applies only then, otherwise the route estimate does.
fn merge_nodes(
local_peer_id: Option<u64>,
peers: &[serde_json::Value],
routes: &[serde_json::Value],
) -> Vec<serde_json::Value> {
let mut order = Vec::new();
let mut rows: HashMap<u64, serde_json::Value> = HashMap::new();
for route in routes {
if let Some(id) = route["peer_id"].as_u64()
&& rows.insert(id, route.clone()).is_none()
{
order.push(id);
}
}
for peer in peers {
if let Some(id) = peer["peer_id"].as_u64() {
rows.entry(id).or_insert_with(|| {
order.push(id);
serde_json::json!({"peer_id": id})
});
}
}
order
.into_iter()
.filter(|id| Some(*id) != local_peer_id)
.map(|id| {
let route = &rows[&id];
let peer = peers.iter().find(|p| p["peer_id"].as_u64() == Some(id));
let direct_available = peer.is_some_and(|p| p["direct"] == true);
let next_hop = route["next_hop_peer_id"].as_u64();
let direct = direct_available && next_hop.is_none_or(|hop| hop == id);
let measured = peer
.filter(|_| direct)
.and_then(|p| p["latency_ms"].as_f64());
let estimated = route["estimated_latency_ms"].as_f64();
let mut node = route.clone();
node["path"] = serde_json::json!(if direct { "direct" } else { "relay" });
node["direct_available"] = serde_json::json!(direct_available);
node["hole_punched"] =
serde_json::json!(direct && peer.is_some_and(|p| p["hole_punched"] == true));
node["latency_ms"] = serde_json::json!(measured.or(estimated));
node["latency_source"] = serde_json::json!(if measured.is_some() {
Some("link_rtt")
} else if estimated.is_some() {
Some("route_estimate")
} else {
None
});
node["metered"] = serde_json::json!(peer.is_some());
if let Some(peer) = peer {
for key in [
"rx_bytes",
"tx_bytes",
"rx_bytes_per_second",
"tx_bytes_per_second",
] {
node[key] = peer[key].clone();
}
}
node
})
.collect()
}
#[derive(Default)]
@@ -275,6 +428,9 @@ impl Engine {
{
bail!("system_vpn requires a platform VPN build and platform authorization");
}
if mode == RuntimeMode::SystemVpn {
check_local_overlap(&config)?;
}
let optimization = optimization_config(input)?;
let instance = create_native_instance(config.clone())?;
instance
@@ -293,6 +449,21 @@ impl Engine {
instance.stop().await;
return Err(error);
}
let (routes, _) = tokio::sync::watch::channel(MeshRoutes::default());
let (cidrs, subnet_routes) = current_routes(&instance).await;
publish_routes(&routes, cidrs, subnet_routes);
let route_task = tokio::spawn({
let instance = instance.clone();
let routes = routes.clone();
async move {
let mut tick = tokio::time::interval(std::time::Duration::from_secs(1));
loop {
tick.tick().await;
let (cidrs, subnet_routes) = current_routes(&instance).await;
publish_routes(&routes, cidrs, subnet_routes);
}
}
});
Ok(Self {
instance,
config,
@@ -303,8 +474,14 @@ impl Engine {
events: Mutex::new(events),
journal: Mutex::new(Vec::new()),
event_sequence: Mutex::new(0),
routes,
route_task: Mutex::new(Some(route_task)),
})
}
/// Notifies on every change of the destinations to route through the mesh.
pub fn watch_mesh_routes(&self) -> tokio::sync::watch::Receiver<MeshRoutes> {
self.routes.subscribe()
}
pub fn redact_diagnostic(&self, text: &str) -> String {
let secret = self
.config
@@ -326,6 +503,20 @@ impl Engine {
self.instance.attach_tun_fd(fd)
}
pub async fn stop(&self) {
if let Some(task) = self.route_task.lock().unwrap().take() {
task.abort();
}
// Wake route watchers: a stopped network routes nothing.
self.routes.send_if_modified(|routes| {
if routes.stopped {
return false;
}
routes.generation += 1;
routes.cidrs.clear();
routes.subnet_routes.clear();
routes.stopped = true;
true
});
self.instance.stop().await;
*self.interface_name.lock().unwrap() = None;
}
@@ -412,18 +603,10 @@ impl Engine {
.await,
);
}
let subnet_routes = self
.instance
.packet_plane()
.proxy_cidr_diff(&Default::default())
.await
.map(|d| {
d.current
.into_iter()
.map(|r| r.to_string())
.collect::<Vec<_>>()
})
.unwrap_or_default();
let (cidrs, subnet_routes) = current_routes(&self.instance).await;
publish_routes(&self.routes, cidrs, subnet_routes);
let mesh_routes = self.routes.borrow().clone();
let subnet_routes = mesh_routes.subnet_routes.clone();
let mut traffic = self.traffic.lock().unwrap();
let now = Instant::now();
let seconds = traffic
@@ -471,6 +654,22 @@ impl Engine {
traffic.sampled_at = Some(now);
let flags = self.config.get_flags();
let latency_first = flags.latency_first;
let route_rows = routes.iter().map(|r| {
let path_latency = if latency_first {r.path_latency_latency_first.unwrap_or(r.path_latency)} else {r.path_latency};
serde_json::json!({"peer_id": r.peer_id, "hostname": r.hostname,
"ipv4": r.ipv4_addr.as_ref().map(|v| v.to_string()),
"advertised_subnets": r.proxy_cidrs,
"cost": effective_hops.get(&r.peer_id).copied().flatten().map(|hop| if hop == r.peer_id {1} else if latency_first {r.cost_latency_first.unwrap_or(r.cost)} else {r.cost}),
"version": r.version,
"udp_nat_type": r.stun_info.as_ref().map(|s| format!("{:?}", easytier::proto::common::NatType::try_from(s.udp_nat_type).unwrap_or_default())),
"disable_p2p": r.feature_flag.as_ref().map(|f| f.disable_p2p),
"need_p2p": r.feature_flag.as_ref().map(|f| f.need_p2p),
"next_hop_peer_id": effective_hops.get(&r.peer_id).copied().flatten(),
"candidate_next_hop_peer_id": if latency_first { r.next_hop_peer_id_latency_first.unwrap_or(r.next_hop_peer_id) } else { r.next_hop_peer_id },
"estimated_latency_ms": if path_latency > 0 {Some(path_latency)} else {None}
})
}).collect::<Vec<_>>();
let nodes = merge_nodes(Some(u64::from(node.peer_id)), &peer_stats, &route_rows);
let interface_name = self.interface_name.lock().unwrap().clone();
serde_json::json!({
"state": format!("{:?}", self.instance.state()),
@@ -513,21 +712,8 @@ impl Engine {
"tx_bytes_per_second": seconds.filter(|s| *s > 0.0).map(|s| total_tx_delta as f64 / s),
"scope": "tunnel_including_control"
},
"routes": routes.iter().map(|r| {
let path_latency = if latency_first {r.path_latency_latency_first.unwrap_or(r.path_latency)} else {r.path_latency};
serde_json::json!({"peer_id": r.peer_id, "hostname": r.hostname,
"ipv4": r.ipv4_addr.as_ref().map(|v| v.to_string()),
"advertised_subnets": r.proxy_cidrs,
"cost": effective_hops.get(&r.peer_id).copied().flatten().map(|hop| if hop == r.peer_id {1} else if latency_first {r.cost_latency_first.unwrap_or(r.cost)} else {r.cost}),
"version": r.version,
"udp_nat_type": r.stun_info.as_ref().map(|s| format!("{:?}", easytier::proto::common::NatType::try_from(s.udp_nat_type).unwrap_or_default())),
"disable_p2p": r.feature_flag.as_ref().map(|f| f.disable_p2p),
"need_p2p": r.feature_flag.as_ref().map(|f| f.need_p2p),
"next_hop_peer_id": effective_hops.get(&r.peer_id).copied().flatten(),
"candidate_next_hop_peer_id": if latency_first { r.next_hop_peer_id_latency_first.unwrap_or(r.next_hop_peer_id) } else { r.next_hop_peer_id },
"estimated_latency_ms": if path_latency > 0 {Some(path_latency)} else {None}
})
}).collect::<Vec<_>>(),
"routes": route_rows,
"nodes": nodes,
"application_only": self.mode == RuntimeMode::Application,
"runtime_mode": self.mode,
"platform_network": {
@@ -536,7 +722,9 @@ impl Engine {
"route_scope": if !subnet_routes.is_empty() { "overlay_and_remote_subnets" } else { "overlay_only" },
"subnet_route_mode": "automatic",
"route_installation": if self.mode == RuntimeMode::SystemVpn { "system" } else { "sdk_only" },
"subnet_routes": subnet_routes, "subnet_routes_scope": "accepted_projection", "dns_changed": false, "default_route_changed": false
"subnet_routes": subnet_routes, "subnet_routes_scope": "accepted_projection", "dns_changed": false, "default_route_changed": false,
"mesh_cidrs": mesh_routes.cidrs, "route_generation": mesh_routes.generation,
"overlay": node.ipv4_addr.map_or(serde_json::Value::Null, |ip| overlay_json(ip.address(), ip.network_length()))
}, "upstream_revision": REVISION
})
}
@@ -635,6 +823,40 @@ mod tests {
);
}
#[test]
fn nodes_classify_path_and_latency_source() {
use serde_json::json;
let peers = vec![
json!({"peer_id": 2, "direct": true, "hole_punched": true, "latency_ms": 12.5, "rx_bytes": 9}),
json!({"peer_id": 3, "direct": true, "latency_ms": 40.0}),
json!({"peer_id": 5, "direct": false}),
];
let routes = vec![
json!({"peer_id": 1, "hostname": "self"}),
json!({"peer_id": 2, "next_hop_peer_id": 2, "estimated_latency_ms": 30}),
json!({"peer_id": 3, "next_hop_peer_id": 2, "estimated_latency_ms": 55}),
json!({"peer_id": 4, "next_hop_peer_id": 2}),
];
let nodes = merge_nodes(Some(1), &peers, &routes);
let ids: Vec<_> = nodes
.iter()
.map(|n| n["peer_id"].as_u64().unwrap())
.collect();
assert_eq!(ids, vec![2, 3, 4, 5]);
assert_eq!(nodes[0]["path"], "direct");
assert_eq!(nodes[0]["latency_ms"], 12.5);
assert_eq!(nodes[0]["latency_source"], "link_rtt");
assert_eq!(nodes[0]["hole_punched"], true);
assert_eq!(nodes[0]["rx_bytes"], 9);
// Direct link exists but traffic is routed through peer 2.
assert_eq!(nodes[1]["path"], "relay");
assert_eq!(nodes[1]["direct_available"], true);
assert_eq!(nodes[1]["latency_ms"], 55.0);
assert_eq!(nodes[1]["latency_source"], "route_estimate");
assert_eq!(nodes[2]["metered"], false);
assert!(nodes[2]["latency_source"].is_null());
assert_eq!(nodes[3]["path"], "relay");
}
#[test]
fn optimization_configuration_is_strict_and_controls_effective_flags() {
let input = format!(
"{BASE}\n[optimization]\nmode = 'adaptive'\nmin_improvement_ms = 20\nrelay_peer_ids = [10,20]"
@@ -708,7 +930,15 @@ mod tests {
let server = create_native_instance(server_config.clone()).unwrap();
server.start().await.unwrap();
let client = Engine::start(&format!("ipv4 = '10.253.80.11/24'\nlisteners = []\nstun_servers = []\nstun_servers_v6 = []\n[[peer]]\nuri = 'udp://127.0.0.1:{port}'\n{identity}")).await.unwrap();
let mut watch = client.watch_mesh_routes();
assert_eq!(watch.borrow_and_update().cidrs, vec!["10.253.80.0/24"]);
let result = tokio::time::timeout(Duration::from_secs(20), async {
// The watch fires on acceptance without anyone polling snapshots.
watch
.wait_for(|r| r.cidrs == ["10.253.79.0/24", "10.253.80.0/24"])
.await
.unwrap();
let learned_generation = watch.borrow().generation;
loop {
let snapshot = client.snapshot().await;
let routes = snapshot["platform_network"]["subnet_routes"]
@@ -781,16 +1011,26 @@ mod tests {
})
.await
.unwrap();
while !client.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
let withdrawn = watch
.wait_for(|r| r.cidrs == ["10.253.80.0/24"])
.await
.unwrap()
.is_empty()
{
tokio::time::sleep(Duration::from_millis(100)).await;
}
.generation;
assert!(withdrawn > learned_generation);
assert!(
client.snapshot().await["platform_network"]["subnet_routes"]
.as_array()
.unwrap()
.is_empty()
);
})
.await;
let mut on_stop = client.watch_mesh_routes();
let before_stop = on_stop.borrow_and_update().generation;
client.stop().await;
assert!(on_stop.has_changed().unwrap());
let stopped = on_stop.borrow().clone();
assert!(stopped.stopped && stopped.cidrs.is_empty() && stopped.generation > before_stop);
server.stop().await;
assert!(result.is_ok(), "automatic subnet test timed out");
}
@@ -24,6 +24,52 @@ pub fn allowed(route: &Ipv4Cidr, overlay: Ipv4Addr, prefix: u8) -> bool {
local_interfaces_allow(route)
}
/// Overlay network when it can carry routed host traffic: a private IPv4 /16-/32.
pub fn routable_overlay(address: Ipv4Addr, prefix: u8) -> Option<Ipv4Cidr> {
if !(16..=32).contains(&prefix) || !address.is_private() {
return None;
}
let mask = u32::MAX.checked_shl(32 - u32::from(prefix)).unwrap_or(0);
Ipv4Cidr::new(Ipv4Addr::from(u32::from(address) & mask), prefix).ok()
}
/// The canonical, sorted set of destinations hosts must send through the mesh:
/// the routable overlay network plus accepted advertised subnets.
pub fn mesh_cidrs(overlay: Option<(Ipv4Addr, u8)>, accepted: &[Ipv4Cidr]) -> Vec<String> {
let mut result = std::collections::BTreeSet::new();
if let Some(cidr) = overlay.and_then(|(address, prefix)| routable_overlay(address, prefix)) {
result.insert(cidr);
}
result.extend(accepted.iter().copied());
// Always spell the prefix length; host routes would otherwise print bare.
result
.into_iter()
.map(|cidr| format!("{}/{}", cidr.first_address(), cidr.network_length()))
.collect()
}
/// Fails when the overlay overlaps an address already configured on this host,
/// such as the physical LAN or another VPN. Reads interfaces fresh, uncached.
pub fn check_local_overlap(address: Ipv4Addr, prefix: u8) -> anyhow::Result<()> {
use network_interface::{Addr, NetworkInterface, NetworkInterfaceConfig};
let interfaces = NetworkInterface::show()
.map_err(|_| anyhow::anyhow!("cannot inspect existing interfaces"))?;
let conflict = interfaces
.into_iter()
.flat_map(|iface| iface.addr)
.any(|addr| match addr {
Addr::V4(v4) => v4
.netmask
.is_some_and(|mask| overlaps(address, prefix, v4.ip, u32::from(mask))),
_ => false,
});
anyhow::ensure!(
!conflict,
"overlay overlaps an existing interface; choose another subnet or stop the conflicting VPN"
);
Ok(())
}
type InterfaceNetworks = Vec<(Ipv4Addr, u32)>;
type InterfaceCache = Option<(std::time::Instant, Option<InterfaceNetworks>)>;
fn local_interfaces_allow(route: &Ipv4Cidr) -> bool {
@@ -76,6 +122,25 @@ mod tests {
assert!(permitted(&"10.5.0.1/32".parse().unwrap(), overlay, 24));
}
#[test]
fn mesh_cidrs_are_canonical_sorted_and_skip_unroutable_overlays() {
let accepted: Vec<Ipv4Cidr> = vec!["192.168.21.0/24".parse().unwrap()];
assert_eq!(
mesh_cidrs(Some(("10.77.0.11".parse().unwrap(), 24)), &accepted),
vec!["10.77.0.0/24", "192.168.21.0/24"]
);
assert_eq!(
mesh_cidrs(Some(("10.77.0.11".parse().unwrap(), 32)), &[]),
vec!["10.77.0.11/32"]
);
for (address, prefix) in [("8.8.8.8", 24), ("10.0.0.1", 8)] {
assert_eq!(
mesh_cidrs(Some((address.parse().unwrap(), prefix)), &accepted),
vec!["192.168.21.0/24"]
);
}
assert!(mesh_cidrs(None, &[]).is_empty());
}
#[test]
fn detects_physical_subnet_overlap() {
let local = "10.10.8.54".parse().unwrap();
assert!(overlaps(
+347 -41
View File
@@ -15,6 +15,33 @@ use std::{
};
use tokio::runtime::Runtime;
static NEXT: AtomicU64 = AtomicU64::new(1);
/// Additive JSON operation set within ABI v1. Bump when hosts must rely on a
/// newly added operation or field; hosts reject libraries below what they need.
const CAPABILITY_REVISION: u32 = 2;
const OPERATIONS: &[&str] = &[
"abi_info",
"build_config",
"migrate_config",
"validate",
"start",
"start_bridged",
"stop",
"status",
"wait_routes",
"socks_start",
"socks_stop",
"socks_status",
"diagnostics_enable",
"probe",
"quality_sample",
"tcp_connect",
"tcp_write",
"tcp_read",
"udp_bind",
"udp_send",
"udp_receive",
"resource_close",
];
#[cfg(target_os = "android")]
#[unsafe(no_mangle)]
pub extern "C" fn meshport_set_android_socket_protector(
@@ -78,26 +105,134 @@ pub extern "C" fn meshport_context_new() -> u64 {
#[unsafe(no_mangle)]
pub extern "C" fn meshport_context_free(id: u64) {
// Drop outside registry lock; in-flight calls retain an Arc until completion.
let _ = catch_unwind(|| {
let context = CONTEXTS.lock().unwrap().remove(&id);
let _ = catch_unwind(AssertUnwindSafe(|| {
let Some(context) = CONTEXTS.lock().unwrap().remove(&id) else {
return;
};
// Stop now rather than when the last Arc drops: a `wait_routes` call
// holds one without the serial lock, and stopping is what wakes it.
if let Ok(mut network) = context.network.lock() {
let _ = stop_all(&context, &mut network);
}
drop(context);
});
}));
}
fn start_socks(context: &Context, n: &Arc<Network>, request: &Value) -> anyhow::Result<String> {
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(address)
}
fn stop_all(context: &Context, network: &mut Option<Arc<Network>>) -> anyhow::Result<()> {
let bridge = context.socks.lock().unwrap().take();
let result = match bridge {
Some(mut bridge) => context.runtime.block_on(bridge.stop()),
None => Ok(()),
};
context.tcp.blocking_lock().clear();
context.udp.blocking_lock().clear();
if let Some(n) = network.take() {
context.runtime.block_on(n.stop());
}
result
}
fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
let op = request["op"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing op"))?;
if op == "abi_info" {
return Ok(json!({"abi": 1, "revision": CAPABILITY_REVISION, "operations": OPERATIONS}));
}
// Long poll for route changes. Runs outside the serial context lock so a
// host can wait on one thread while issuing other requests on another.
if op == "wait_routes" {
let timeout_ms = request["timeout_ms"].as_u64().unwrap_or(25000);
anyhow::ensure!(
(1..=30000).contains(&timeout_ms),
"timeout_ms must be 1 to 30000"
);
let after = match request.get("after_generation") {
None | Some(Value::Null) => None,
Some(value) => Some(
value
.as_u64()
.ok_or_else(|| anyhow::anyhow!("invalid after_generation"))?,
),
};
let network = context
.network
.lock()
.map_err(|_| anyhow::anyhow!("context lock poisoned"))?
.clone();
let Some(network) = network else {
return Ok(json!({"running": false, "changed": after.is_some(),
"route_generation": null, "mesh_cidrs": [], "subnet_routes": []}));
};
let mut watch = network.watch_mesh_routes();
let changed = context.runtime.block_on(async {
tokio::time::timeout(
Duration::from_millis(timeout_ms),
watch.wait_for(|r| r.stopped || after.is_none_or(|a| r.generation != a)),
)
.await
.is_ok()
});
let routes = watch.borrow().clone();
return Ok(json!({"running": !routes.stopped,
"changed": changed && after.is_some_and(|a| a != routes.generation),
"route_generation": routes.generation, "mesh_cidrs": routes.cidrs,
"subnet_routes": routes.subnet_routes}));
}
if op == "diagnostics_enable" {
return Ok(json!({"enabled": diagnostics::enable(), "scope": "process"}));
}
if op == "build_config" {
return Ok(json!({"toml": meshport::build_config(&request["profile"])?}));
}
if op == "migrate_config" {
let input = request["toml"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
let (toml, changed) = meshport::migrate_config(input)?;
return Ok(json!({"toml": toml, "changed": changed}));
}
if op == "validate" {
use meshport_easytier::ConfigLoader;
let input = request["toml"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
let config = meshport::validate_config(input)?;
if request["check_local_overlap"].as_bool() == Some(true) {
meshport::check_local_overlap(&config)?;
}
let flags = config.get_flags();
let mut result = json!({"valid": true, "runtime_mode": if flags.no_tun {"application"} else {"system_vpn"}});
let mut result = json!({"valid": true, "runtime_mode": if flags.no_tun {"application"} else {"system_vpn"},
"overlay": meshport::overlay_projection(&config)});
// Only return credentials when the local caller explicitly requests a
// form projection. Ordinary validation remains free of credentials.
if request["include_profile"].as_bool() == Some(true) {
@@ -158,52 +293,64 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
let config = request["toml"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
if request["check_local_overlap"].as_bool() == Some(true) {
meshport::check_local_overlap(&meshport::validate_config(config)?)?;
}
*network = Some(Arc::new(context.runtime.block_on(Network::start(config))?));
Ok(json!({"engine_started": true}))
}
// Application-mode network plus SOCKS bridge as one step, for hosts that
// route traffic into the mesh. Either both run or neither does.
"start_bridged" => {
use meshport_easytier::ConfigLoader;
anyhow::ensure!(
network.is_none(),
"already started; stop before applying a new configuration"
);
let input = request["toml"]
.as_str()
.ok_or_else(|| anyhow::anyhow!("missing toml"))?;
let config = meshport::validate_config(input)?;
anyhow::ensure!(
config.get_flags().no_tun,
"bridged routing requires application-mode MeshPort"
);
let overlay = meshport::overlay_projection(&config);
anyhow::ensure!(
!overlay.is_null() || request["require_static_overlay"].as_bool() != Some(true),
"static mesh IPv4 required for bridged routing"
);
anyhow::ensure!(
overlay.is_null() || overlay["routable"] == true,
"bridged routing requires a private IPv4 overlay with prefix /16 through /32"
);
if request["check_local_overlap"].as_bool() == Some(true) {
meshport::check_local_overlap(&config)?;
}
let n = Arc::new(context.runtime.block_on(Network::start(input))?);
*network = Some(n.clone());
let listen = match start_socks(context, &n, &request) {
Ok(listen) => listen,
Err(error) => {
let _ = stop_all(context, &mut network);
return Err(error);
}
};
let routes = n.watch_mesh_routes().borrow().clone();
Ok(
json!({"engine_started": true, "listen": listen, "overlay": overlay,
"mesh_cidrs": routes.cidrs, "route_generation": routes.generation}),
)
}
"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() {
context.runtime.block_on(n.stop());
}
stop_all(context, &mut network)?;
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);
let address = start_socks(context, n, &request)?;
Ok(
json!({"running": true, "listen": address, "tcp": true, "udp": true, "ipv4_only": true, "dns_resolution": false}),
)
@@ -240,9 +387,24 @@ fn dispatch(context: &Context, request: Value) -> anyhow::Result<Value> {
})
.collect::<Vec<_>>();
snapshot["diagnostic_traces"] = json!(traces);
let engine_running = snapshot["state"] == "Running";
let bridge_running = context
.socks
.lock()
.unwrap()
.as_ref()
.is_some_and(|b| b.snapshot().running);
// mesh_routable: traffic a host routes to mesh_cidrs via the
// bridge can currently be delivered.
snapshot["health"] = json!({"engine_running": engine_running,
"bridge_running": bridge_running,
"mesh_routable": engine_running && bridge_running});
Ok(snapshot)
}
None => Ok(json!({"state": "Stopped", "peer_count": 0, "application_only": true})),
None => Ok(
json!({"state": "Stopped", "peer_count": 0, "application_only": true,
"health": {"engine_running": false, "bridge_running": false, "mesh_routable": false}}),
),
},
"quality_sample" => {
let network = network
@@ -486,6 +648,150 @@ mod tests {
meshport_context_free(id);
}
#[test]
fn config_build_and_migration_are_sdk_operations() {
let id = meshport_context_new();
let built = call(
id,
&json!({"op": "build_config", "profile": {"runtime_mode": "unified_vpn",
"ipv4": "10.79.0.11/24", "network_name": "n", "network_secret": "s"}})
.to_string(),
);
assert_eq!(built["ok"], true);
let toml = built["data"]["toml"].as_str().unwrap();
let validated = call(id, &json!({"op": "validate", "toml": toml}).to_string());
assert_eq!(validated["data"]["runtime_mode"], "application");
assert_eq!(validated["data"]["overlay"]["network"], "10.79.0.0/24");
let legacy = format!("{toml}\nsubnet_routes = ['192.168.21.0/24']\n");
let migrated = call(
id,
&json!({"op": "migrate_config", "toml": legacy}).to_string(),
);
assert_eq!(migrated["data"]["changed"], true);
let migrated = migrated["data"]["toml"].as_str().unwrap();
assert_eq!(
call(id, &json!({"op": "validate", "toml": migrated}).to_string())["ok"],
true
);
meshport_context_free(id);
}
#[test]
fn bridged_start_is_atomic_and_reports_routes_and_health() {
let id = meshport_context_new();
let base = "listeners = []\nstun_servers = []\nstun_servers_v6 = []\n[network_identity]\nnetwork_name = 'bridged-ffi-test'\nnetwork_secret = 'test-only'\n";
let system = format!("ipv4 = '10.253.84.11/24'\n{base}[runtime]\nmode = 'system_vpn'\n");
let wide = format!("ipv4 = '10.253.84.11/8'\n{base}");
let dhcp = format!("dhcp = true\n{base}");
for (config, static_required) in [(system, false), (wide, false), (dhcp, true)] {
let refused = call(
id,
&json!({"op": "start_bridged", "toml": config,
"require_static_overlay": static_required})
.to_string(),
);
assert_eq!(refused["ok"], false, "{config}");
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Stopped");
}
// Bridge failure (invalid session limit) rolls the network back.
let config = format!("ipv4 = '10.253.84.11/24'\n{base}");
let failed = call(
id,
&json!({"op": "start_bridged", "toml": config, "max_sessions": 0}).to_string(),
);
assert_eq!(failed["ok"], false);
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Stopped");
let started = call(
id,
&json!({"op": "start_bridged", "toml": config}).to_string(),
);
assert_eq!(started["ok"], true, "{started}");
assert_eq!(started["data"]["mesh_cidrs"], json!(["10.253.84.0/24"]));
assert!(started["data"]["route_generation"].as_u64().unwrap() >= 1);
assert!(std::net::TcpStream::connect(started["data"]["listen"].as_str().unwrap()).is_ok());
let status = call(id, r#"{"op":"status"}"#)["data"].clone();
assert_eq!(status["health"]["mesh_routable"], true);
assert_eq!(
status["platform_network"]["mesh_cidrs"],
json!(["10.253.84.0/24"])
);
assert_eq!(
status["platform_network"]["overlay"]["address"],
"10.253.84.11"
);
let generation = started["data"]["route_generation"].as_u64().unwrap();
let idle = call(
id,
&json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 200})
.to_string(),
);
assert_eq!(idle["data"]["changed"], false, "{idle}");
assert_eq!(idle["data"]["running"], true);
assert_eq!(call(id, r#"{"op":"socks_stop"}"#)["ok"], true);
let status = call(id, r#"{"op":"status"}"#)["data"].clone();
assert_eq!(status["health"]["engine_running"], true);
assert_eq!(status["health"]["mesh_routable"], false);
// A waiter does not hold the context: status still answers, and stop
// wakes it with empty routes well before its timeout.
let waiter = std::thread::spawn(move || {
let at = std::time::Instant::now();
let reply = call(
id,
&json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 20000})
.to_string(),
);
(reply, at.elapsed())
});
std::thread::sleep(Duration::from_millis(200));
assert_eq!(call(id, r#"{"op":"status"}"#)["data"]["state"], "Running");
assert_eq!(call(id, r#"{"op":"stop"}"#)["ok"], true);
let (woken, waited) = waiter.join().unwrap();
assert!(waited < Duration::from_secs(10), "{waited:?}");
assert_eq!(woken["data"]["running"], false, "{woken}");
assert_eq!(woken["data"]["changed"], true);
assert_eq!(woken["data"]["mesh_cidrs"], json!([]));
assert_eq!(
call(id, r#"{"op":"wait_routes","timeout_ms":0}"#)["ok"],
false
);
let info = call(id, r#"{"op":"abi_info"}"#)["data"].clone();
assert_eq!(info["abi"], 1);
assert!(info["revision"].as_u64().unwrap() >= 2);
assert!(
info["operations"]
.as_array()
.unwrap()
.iter()
.any(|o| o == "wait_routes")
);
assert_eq!(
call(id, r#"{"op":"status"}"#)["data"]["health"]["mesh_routable"],
false
);
// Freeing without stop also stops the network and wakes a waiter.
let started = call(
id,
&json!({"op": "start_bridged", "toml": config}).to_string(),
);
assert_eq!(started["ok"], true, "{started}");
let generation = started["data"]["route_generation"].as_u64().unwrap();
let waiter = std::thread::spawn(move || {
let at = std::time::Instant::now();
let reply = call(
id,
&json!({"op": "wait_routes", "after_generation": generation, "timeout_ms": 20000})
.to_string(),
);
(reply, at.elapsed())
});
std::thread::sleep(Duration::from_millis(200));
meshport_context_free(id);
let (woken, waited) = waiter.join().unwrap();
assert!(waited < Duration::from_secs(10), "{waited:?}");
assert_eq!(woken["data"]["running"], false, "{woken}");
}
#[test]
fn socks_control_lifecycle_and_context_cleanup() {
use std::io::{Read, Write};
+8
View File
@@ -4,6 +4,9 @@ mod system_probe;
use anyhow::{Result, ensure};
use meshport_easytier::Engine;
pub use meshport_easytier::parse_config as validate_config;
pub use meshport_easytier::{
MeshRoutes, build_config, check_local_overlap, migrate_config, overlay_projection,
};
pub use meshport_netstack::{TcpListener, TcpStream, UdpSocket};
use std::{
net::SocketAddr,
@@ -27,6 +30,11 @@ impl Network {
pub async fn stop(&self) {
self.engine.stop().await;
}
/// Destinations to route through this network; changes as advertisements
/// are accepted or withdrawn. Use instead of polling `snapshot`.
pub fn watch_mesh_routes(&self) -> tokio::sync::watch::Receiver<MeshRoutes> {
self.engine.watch_mesh_routes()
}
/// Removes this network's secret from diagnostic text before export.
pub fn redact_diagnostic(&self, text: &str) -> String {
self.engine.redact_diagnostic(text)