Files
MeshPort/tools/meshport-vpn-helper/src/mac/unified.rs
T
shenandshen c7cc2aa865 Fix VPN internet connectivity and simplify client setup
Initialize Android physical interfaces and preserve macOS scoped routes. Add redacted diagnostics, default DNS, ordered auto-save, simplified controls, scanner rotation settings, and native regression coverage. Restore vendored build sources and document validation and stability checks.
2026-10-12 06:51:25 -07:00

478 lines
18 KiB
Rust

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,
}
// Darwin IP_BOUND_IF sockets need an interface-scoped default when the TUN's
// more-specific split defaults become the global route. Own only our new route.
struct PhysicalRouteGuard {
interface: String,
gateway: std::net::Ipv4Addr,
owned: bool,
}
fn route_field<'a>(text: &'a str, field: &str) -> Option<&'a str> {
text.lines()
.find_map(|line| line.trim().strip_prefix(field).map(str::trim))
}
fn scoped_route_matches(text: &str, interface: &str, gateway: std::net::Ipv4Addr) -> bool {
route_field(text, "interface:") == Some(interface)
&& route_field(text, "gateway:").and_then(|value| value.parse().ok()) == Some(gateway)
&& route_field(text, "flags:").is_some_and(|flags| flags.contains("IFSCOPE"))
}
impl PhysicalRouteGuard {
fn install(interface: &str) -> Result<Self> {
let before = Command::new("/sbin/route")
.args(["-n", "get", "-ifscope", interface, "default"])
.output()?;
ensure!(before.status.success(), "physical IPv4 gateway unavailable");
let text = String::from_utf8(before.stdout)?;
ensure!(
route_field(&text, "interface:") == Some(interface),
"physical gateway interface changed"
);
let gateway: std::net::Ipv4Addr = route_field(&text, "gateway:")
.context("physical IPv4 gateway missing")?
.parse()?;
let mut guard = Self {
interface: interface.into(),
gateway,
owned: false,
};
if scoped_route_matches(&text, interface, gateway) {
return Ok(guard);
}
let installed = Command::new("/sbin/route")
.args([
"-n",
"add",
"-inet",
"-ifscope",
interface,
"default",
&gateway.to_string(),
])
.output()?;
if !installed.status.success() {
// Another owner may have installed it meanwhile. Reuse, never remove.
let existing = Command::new("/sbin/route")
.args(["-n", "get", "-ifscope", interface, "default"])
.output()?;
ensure!(
existing.status.success()
&& scoped_route_matches(
&String::from_utf8_lossy(&existing.stdout),
interface,
gateway
),
"cannot protect physical IPv4 default route"
);
return Ok(guard);
}
guard.owned = true;
let verified = Command::new("/sbin/route")
.args(["-n", "get", "-ifscope", interface, "default"])
.output()?;
ensure!(
verified.status.success()
&& scoped_route_matches(
&String::from_utf8_lossy(&verified.stdout),
interface,
gateway
),
"physical scoped route verification failed"
);
Ok(guard)
}
}
impl Drop for PhysicalRouteGuard {
fn drop(&mut self) {
if !self.owned {
return;
}
if let Ok(current) = Command::new("/sbin/route")
.args(["-n", "get", "-ifscope", &self.interface, "default"])
.output()
{
if current.status.success()
&& scoped_route_matches(
&String::from_utf8_lossy(&current.stdout),
&self.interface,
self.gateway,
)
{
let _ = Command::new("/sbin/route")
.args([
"-n",
"delete",
"-inet",
"-ifscope",
&self.interface,
"default",
&self.gateway.to_string(),
])
.output();
}
}
}
}
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 {
physical_route: Option<PhysicalRouteGuard>,
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";
let physical_route = if self.profile["feature"] != "mesh" {
Some(PhysicalRouteGuard::install(&self.physical)?)
} else {
None
};
self.proxy = Some(Proxy::open()?);
self.physical_route = physical_route;
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.physical_route.take();
self.protected.clear();
self.active.clear();
if let Some(error) = proxy_error {
return Err(error);
}
network?;
Ok(())
}
}
#[cfg(test)]
mod route_guard_tests {
use super::scoped_route_matches;
#[test]
fn only_matching_scoped_route_is_owned() {
let gateway = "192.168.21.1".parse().unwrap();
let original = "gateway: 192.168.21.1\ninterface: en0\nflags: <UP,GATEWAY,GLOBAL>";
assert!(!scoped_route_matches(original, "en0", gateway));
let scoped = original.replace("GLOBAL", "IFSCOPE");
assert!(scoped_route_matches(&scoped, "en0", gateway));
assert!(!scoped_route_matches(&scoped, "en1", gateway));
assert!(!scoped_route_matches(
&scoped,
"en0",
"192.168.21.2".parse().unwrap()
));
}
}