Fix desktop TUN address leak that broke VPN rebuilds
sing-tun creates its utun control socket without SOCK_CLOEXEC (tun_darwin.go), so any child the unified helper spawns while the engine runs - the DnsGuard scutil process, route commands - inherits that socket and pins the utun interface past engine stop. The announcement-driven rebuild then fails with "desktop TUN address already in use" and tears down the whole VPN session. Mark every utun socket in the process close-on-exec as soon as the engine starts. Stop now only warns when Darwin still holds the retiring address (classified via cleanupFailure), and Start waits bounded for an address this engine itself retained while failing fast on any other owner. Adds a root-only drain diagnostic with a real-profile pass, a child-guard regression test that reproduced the production failure before the fix, and a --self-test-unified-rebuild helper self-test that forces stop/start cycles in combined mode end to end. Co-Authored-By: Claude Code <noreply@anthropic.com>
This commit is contained in:
@@ -300,7 +300,7 @@ fn physical_interface(internet: bool) -> Result<String> {
|
||||
}
|
||||
Ok(interface)
|
||||
}
|
||||
fn prefixes(snapshot: &Value) -> Result<BTreeSet<String>> {
|
||||
pub(super) fn prefixes(snapshot: &Value) -> Result<BTreeSet<String>> {
|
||||
let mut result = BTreeSet::new();
|
||||
let address = snapshot["ipv4"]
|
||||
.as_str()
|
||||
@@ -395,7 +395,7 @@ impl Unified {
|
||||
}
|
||||
result
|
||||
}
|
||||
fn restart(&mut self, active: BTreeSet<String>) -> Result<()> {
|
||||
pub(super) 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());
|
||||
|
||||
@@ -190,3 +190,216 @@ pub fn run() -> Result<()> {
|
||||
);
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn desktop_tun_attached() -> bool {
|
||||
let mut head: *mut libc::ifaddrs = std::ptr::null_mut();
|
||||
if unsafe { libc::getifaddrs(&mut head) } != 0 {
|
||||
return false;
|
||||
}
|
||||
let mut attached = false;
|
||||
let mut cursor = head;
|
||||
while !cursor.is_null() {
|
||||
let row = unsafe { &*cursor };
|
||||
if !row.ifa_addr.is_null()
|
||||
&& unsafe { (*row.ifa_addr).sa_family as i32 } == libc::AF_INET
|
||||
{
|
||||
let address = unsafe { &*(row.ifa_addr as *const libc::sockaddr_in) };
|
||||
let parsed = std::net::Ipv4Addr::from(u32::from_be(address.sin_addr.s_addr));
|
||||
if parsed == std::net::Ipv4Addr::new(172, 19, 0, 1) {
|
||||
attached = true;
|
||||
break;
|
||||
}
|
||||
}
|
||||
cursor = row.ifa_next;
|
||||
}
|
||||
unsafe { libc::freeifaddrs(head) };
|
||||
attached
|
||||
}
|
||||
|
||||
fn fd_utun_name(fd: i32) -> Option<String> {
|
||||
let mut buffer = [0u8; 64];
|
||||
let mut length: libc::socklen_t = buffer.len() as u32;
|
||||
let status = unsafe {
|
||||
libc::getsockopt(
|
||||
fd,
|
||||
2, /* SYSPROTO_CONTROL */
|
||||
2, /* UTUN_OPT_IFNAME */
|
||||
buffer.as_mut_ptr() as *mut libc::c_void,
|
||||
&mut length,
|
||||
)
|
||||
};
|
||||
if status == 0 && length > 0 {
|
||||
Some(
|
||||
String::from_utf8_lossy(&buffer[..length as usize])
|
||||
.trim_matches('\0')
|
||||
.to_string(),
|
||||
)
|
||||
} else {
|
||||
None
|
||||
}
|
||||
}
|
||||
|
||||
// Names every live holder of the desktop TUN address: the helper's own
|
||||
// descriptors plus any spawned child that inherited a utun socket.
|
||||
fn report_desktop_tun_holders(tag: &str) {
|
||||
println!(
|
||||
"diagnostics[{tag}]: desktop TUN address attached = {}",
|
||||
desktop_tun_attached()
|
||||
);
|
||||
match std::fs::read_dir("/dev/fd") {
|
||||
Ok(entries) => {
|
||||
let mut holders = 0;
|
||||
for entry in entries.flatten() {
|
||||
let Ok(fd) = entry.file_name().to_string_lossy().parse::<i32>() else {
|
||||
continue;
|
||||
};
|
||||
if let Some(name) = fd_utun_name(fd) {
|
||||
println!("diagnostics[{tag}]: own fd {fd} holds {name}");
|
||||
holders += 1;
|
||||
}
|
||||
}
|
||||
if holders == 0 {
|
||||
println!("diagnostics[{tag}]: no own fd holds a utun");
|
||||
}
|
||||
}
|
||||
Err(error) => println!("diagnostics[{tag}]: cannot list /dev/fd: {error}"),
|
||||
}
|
||||
let self_pid = std::process::id().to_string();
|
||||
if let Ok(output) = Command::new("/usr/bin/pgrep")
|
||||
.args(["-P", &self_pid])
|
||||
.output()
|
||||
{
|
||||
let children = String::from_utf8_lossy(&output.stdout).to_string();
|
||||
println!("diagnostics[{tag}]: children = {children}");
|
||||
for pid in children.split_whitespace() {
|
||||
let Ok(report) = Command::new("/usr/sbin/lsof")
|
||||
.args(["-p", pid])
|
||||
.output()
|
||||
else {
|
||||
continue;
|
||||
};
|
||||
for line in String::from_utf8_lossy(&report.stdout).lines() {
|
||||
if line.contains("utun") || line.contains("SYSTEM") {
|
||||
println!("diagnostics[{tag}]: child {pid}: {line}");
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Announcement-driven rebuild under the combined feature: the proxy engine
|
||||
// must survive stop -> immediate start while DnsGuard and the physical route
|
||||
// guard are installed. This is the exact path that fails interactively.
|
||||
pub fn run_rebuild() -> Result<()> {
|
||||
let runtime = tokio::runtime::Runtime::new()?;
|
||||
let port = UdpSocket::bind("127.0.0.1:0")?.local_addr()?.port();
|
||||
let identity =
|
||||
"[network_identity]\nnetwork_name='unified-tun-self-test'\nnetwork_secret='test-only'\n";
|
||||
let server_config = easytier::common::config::TomlConfigLoader::new_from_str(&format!(
|
||||
"ipv4='10.253.88.2/25'\nlisteners=['udp://127.0.0.1:{port}']\nstun_servers=[]\nstun_servers_v6=[]\n[[proxy_network]]\ncidr='127.0.0.0/25'\nmapped_cidr='10.253.88.128/25'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
))?;
|
||||
let server = {
|
||||
let _entered = runtime.enter();
|
||||
easytier::instance::factory::create_native_instance(server_config)?
|
||||
};
|
||||
runtime.block_on(server.start())?;
|
||||
let id = super::ContextHandle(meshport_ffi::meshport_context_new());
|
||||
let mut unified = super::unified::Unified::default();
|
||||
let before = Command::new("/sbin/route")
|
||||
.args(["-n", "get", "default"])
|
||||
.output()?
|
||||
.stdout;
|
||||
let profile = json!({
|
||||
"feature": "combined",
|
||||
// No bypass_cn here: its remote rule sets cannot download through the
|
||||
// synthetic dead SOCKS node; the rebuild path under test is identical.
|
||||
"default_action": "proxy",
|
||||
"rules": [],
|
||||
"dns_protection": true,
|
||||
"dns_server": "1.1.1.1",
|
||||
"proxy_dns_server": "https://1.1.1.1/dns-query",
|
||||
"rule_sets": [],
|
||||
"mesh_dns": [],
|
||||
"fakeip": false,
|
||||
"proxy": {"type": "socks", "server": "127.0.0.1", "server_port": 1},
|
||||
});
|
||||
let config = format!(
|
||||
"ipv4='10.253.88.11/25'\nlisteners=[]\nstun_servers=[]\nstun_servers_v6=[]\n[[peer]]\nuri='udp://127.0.0.1:{port}'\n{identity}[flags]\nno_tun=true\nuse_smoltcp=true"
|
||||
);
|
||||
let result = (|| -> Result<()> {
|
||||
unified
|
||||
.start(id.0, &json!({"toml": config, "unified_profile": profile}))
|
||||
.context("unified combined startup")?;
|
||||
let deadline = Instant::now();
|
||||
loop {
|
||||
let snapshot = unified
|
||||
.status(id.0)
|
||||
.context("status poll during convergence")?;
|
||||
if snapshot["data"]["platform_network"]["installed_subnet_routes"]
|
||||
.as_array()
|
||||
.is_some_and(|v| v.iter().any(|r| r == "10.253.88.128/25"))
|
||||
{
|
||||
break;
|
||||
}
|
||||
ensure!(
|
||||
deadline.elapsed() < Duration::from_secs(12),
|
||||
"peer discovery timeout"
|
||||
);
|
||||
std::thread::sleep(Duration::from_millis(200));
|
||||
}
|
||||
ensure!(
|
||||
desktop_tun_attached(),
|
||||
"combined mode did not attach the desktop TUN address"
|
||||
);
|
||||
println!("PASS: announcement rebuild converged in combined mode");
|
||||
// Hammer the announcement path directly: even identical prefix sets
|
||||
// stop and immediately start the proxy engine.
|
||||
for round in 1..=3 {
|
||||
let snapshot = unified.status(id.0).context("status before rebuild")?;
|
||||
let active = super::unified::prefixes(&snapshot["data"])?;
|
||||
if let Err(error) = unified.restart(active) {
|
||||
report_desktop_tun_holders("rebuild failure");
|
||||
return Err(error).context(format!("forced rebuild {round} failed"));
|
||||
}
|
||||
ensure!(
|
||||
desktop_tun_attached(),
|
||||
"desktop TUN address missing after rebuild {round}"
|
||||
);
|
||||
println!("PASS: forced rebuild {round} completed");
|
||||
std::thread::sleep(Duration::from_millis(300));
|
||||
}
|
||||
Ok(())
|
||||
})();
|
||||
if let Err(error) = &result {
|
||||
eprintln!("rebuild self-test failure: {error:#}");
|
||||
}
|
||||
let stopped = unified.stop(id.0);
|
||||
runtime.block_on(server.stop());
|
||||
let mut drained = false;
|
||||
for _ in 0..80 {
|
||||
if !desktop_tun_attached() {
|
||||
drained = true;
|
||||
break;
|
||||
}
|
||||
std::thread::sleep(Duration::from_millis(250));
|
||||
}
|
||||
if !drained {
|
||||
report_desktop_tun_holders("after stop");
|
||||
}
|
||||
if let Err(error) = &stopped {
|
||||
eprintln!("self-test cleanup failure: {error:#}");
|
||||
}
|
||||
ensure!(
|
||||
Command::new("/sbin/route")
|
||||
.args(["-n", "get", "default"])
|
||||
.output()?
|
||||
.stdout
|
||||
== before,
|
||||
"default route changed"
|
||||
);
|
||||
result?;
|
||||
stopped?;
|
||||
ensure!(drained, "desktop TUN address retained 20s after unified stop");
|
||||
println!("PASS: combined feature survives announcement rebuilds and stops cleanly");
|
||||
Ok(())
|
||||
}
|
||||
|
||||
@@ -198,6 +198,9 @@ mod mac {
|
||||
if args == ["--self-test-unified"] {
|
||||
return unified_test::run();
|
||||
}
|
||||
if args == ["--self-test-unified-rebuild"] {
|
||||
return unified_test::run_rebuild();
|
||||
}
|
||||
if args == ["--self-test"] {
|
||||
*BUSY_SINCE.lock().unwrap() = None;
|
||||
return self_test::run();
|
||||
|
||||
Reference in New Issue
Block a user