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:
co-authored by
Claude Opus 5.5
parent
29d236f3fe
commit
dc1bfc99d2
@@ -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();
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -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(
|
||||
|
||||
Reference in New Issue
Block a user