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:
shenlei
2026-10-15 13:47:52 +09:00
co-authored by Claude Code
parent 50cfbb6867
commit 5b7523fc4f
8 changed files with 698 additions and 12 deletions
+33
View File
@@ -147,3 +147,36 @@ func TestEngineLifecycleAndFailedStartRecovery(t *testing.T) {
t.Fatal("restart:", err)
}
}
func TestDesktopTunStartWaitsOnlyForOwnRetainedAddress(t *testing.T) {
original := desktopTunAddressAttached
defer func() { desktopTunAddressAttached = original }()
releaseAt := time.Now().Add(150 * time.Millisecond)
desktopTunAddressAttached = func() (bool, error) { return time.Now().Before(releaseAt), nil }
// Another owner holds the address: fail immediately, never wait.
var foreign Engine
began := time.Now()
if err := foreign.awaitDesktopTunAddress(time.Second); err == nil || !strings.Contains(err.Error(), "already in use") {
t.Fatalf("foreign address accepted: %v", err)
}
if time.Since(began) > 50*time.Millisecond {
t.Fatal("foreign address delayed the startup failure")
}
// Our own retiring utun: a rebuild waits for Darwin to drain it.
retiring := Engine{tunRetained: true}
if err := retiring.awaitDesktopTunAddress(time.Second); err != nil {
t.Fatalf("rebuild failed while own address drained: %v", err)
}
if retiring.tunRetained {
t.Fatal("retained marker survived a successful start")
}
// An address that never drains still fails after the bound.
desktopTunAddressAttached = func() (bool, error) { return true, nil }
stuck := Engine{tunRetained: true}
if err := stuck.awaitDesktopTunAddress(100 * time.Millisecond); err == nil {
t.Fatal("never-released address accepted")
}
}