From 5b7523fc4f2831821542b8e43233e091f84a0311 Mon Sep 17 00:00:00 2001 From: shenlei Date: Thu, 15 Oct 2026 13:47:52 +0900 Subject: [PATCH] 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 --- engines/singbox/bridge/diagnostics.go | 15 + engines/singbox/bridge/diagnostics_test.go | 20 ++ engines/singbox/bridge/engine.go | 84 ++++- engines/singbox/bridge/engine_test.go | 33 ++ engines/singbox/bridge/tun_drain_test.go | 338 ++++++++++++++++++ tools/meshport-vpn-helper/src/mac/unified.rs | 4 +- .../src/mac/unified_test.rs | 213 +++++++++++ tools/meshport-vpn-helper/src/main.rs | 3 + 8 files changed, 698 insertions(+), 12 deletions(-) create mode 100644 engines/singbox/bridge/tun_drain_test.go diff --git a/engines/singbox/bridge/diagnostics.go b/engines/singbox/bridge/diagnostics.go index ca3a6bc..21323e0 100644 --- a/engines/singbox/bridge/diagnostics.go +++ b/engines/singbox/bridge/diagnostics.go @@ -37,3 +37,18 @@ func startupFailure(stage string, cause error) error { } return fmt.Errorf("proxy startup failed [stage=%s, code=%s]", stage, code) } + +var errTunAddressInspect = errors.New("desktop TUN address inspection failed") + +// Stop failures use the same fixed-category format as startup failures. The +// raw cause can name interfaces or routes, so it is never returned over ABI. +func cleanupFailure(cause error) error { + code := "engine_close_failed" + switch { + case errors.Is(cause, errTunAddressInspect): + code = "tun_address_inspect_failed" + case strings.Contains(strings.ToLower(cause.Error()), "route"): + code = "route_cleanup_failed" + } + return fmt.Errorf("proxy engine cleanup failed [stage=stop_engine, code=%s]", code) +} diff --git a/engines/singbox/bridge/diagnostics_test.go b/engines/singbox/bridge/diagnostics_test.go index c2da237..4f7d9b8 100644 --- a/engines/singbox/bridge/diagnostics_test.go +++ b/engines/singbox/bridge/diagnostics_test.go @@ -2,6 +2,7 @@ package bridge import ( "errors" + "fmt" "strings" "testing" ) @@ -21,3 +22,22 @@ func TestStartupDiagnosticsDoNotExposeUpstreamCredentials(t *testing.T) { } } } + +func TestCleanupDiagnosticsClassifyStopFailuresWithoutUpstreamText(t *testing.T) { + for _, tc := range []struct { + cause error + code string + }{ + {fmt.Errorf("%w: %v", errTunAddressInspect, errors.New("interface test-secret")), "tun_address_inspect_failed"}, + {errors.New("remove route 10.9.0.0/16 test-secret: not in table"), "route_cleanup_failed"}, + {errors.New("unexpected close test-secret"), "engine_close_failed"}, + } { + result := cleanupFailure(tc.cause).Error() + if !strings.Contains(result, "code="+tc.code) { + t.Fatalf("expected code %s, got %s", tc.code, result) + } + if strings.Contains(result, "test-secret") || strings.Contains(result, "10.9.0.0") { + t.Fatalf("cleanup diagnostic exposed upstream contents: %s", result) + } + } +} diff --git a/engines/singbox/bridge/engine.go b/engines/singbox/bridge/engine.go index 69ac5e2..a0cac98 100644 --- a/engines/singbox/bridge/engine.go +++ b/engines/singbox/bridge/engine.go @@ -13,6 +13,7 @@ import ( "os" "path/filepath" "runtime" + "strconv" "sync" "time" @@ -26,6 +27,7 @@ import ( "github.com/sagernet/sing-box/dns/transport" "github.com/sagernet/sing-box/dns/transport/fakeip" "github.com/sagernet/sing-box/dns/transport/local" + "github.com/sagernet/sing-box/log" "github.com/sagernet/sing-box/option" "github.com/sagernet/sing-box/protocol/direct" "github.com/sagernet/sing-box/protocol/http" @@ -35,6 +37,7 @@ import ( "github.com/sagernet/sing-box/protocol/vless" "github.com/sagernet/sing-box/protocol/vmess" sjson "github.com/sagernet/sing/common/json" + "golang.org/x/sys/unix" ) func registryContext(ctx context.Context) context.Context { @@ -79,6 +82,8 @@ type Engine struct { cancel context.CancelFunc ctx context.Context desktopTun bool + // Set when Stop returned while Darwin still held the retiring utun address. + tunRetained bool } func (e *Engine) Snapshot() Snapshot { @@ -107,12 +112,8 @@ func (e *Engine) Start(parent context.Context, config Config) error { return errors.New("desktop TUN requires macOS privileged helper") } if config.DesktopTun { - attached, err := desktopTunAddressAttached() - if err != nil { - return errors.New("cannot inspect desktop TUN address") - } - if attached { - return errors.New("desktop TUN address already in use") + if err := e.awaitDesktopTunAddress(desktopTunRetainedWait); err != nil { + return err } } data, err := config.managedJSON() @@ -171,10 +172,44 @@ func (e *Engine) Start(parent context.Context, config Config) error { e.state = "Failed" return startupFailure("start_engine", err) } + if config.DesktopTun { + markDesktopTunCloseOnExec() + } e.box, e.cancel, e.ctx, e.state = instance, cancel, ctx, "Running" return nil } +// sing-tun creates its utun control socket without SOCK_CLOEXEC (tun_darwin). +// Any process the host spawns while the engine runs — the unified helper's +// scutil DNS guard or route commands — inherits that socket and pins the utun +// interface past engine stop, so announcement-driven rebuilds cannot reattach +// the desktop address. Mark every utun socket in this process close-on-exec +// as soon as the engine owns it. +func markDesktopTunCloseOnExec() { + if runtime.GOOS != "darwin" { + return + } + directory, err := os.Open("/dev/fd") + if err != nil { + return + } + defer directory.Close() + entries, err := directory.Readdirnames(-1) + if err != nil { + return + } + for _, entry := range entries { + fd, err := strconv.Atoi(entry) + if err != nil || fd <= 2 { + continue + } + if _, err := unix.GetsockoptString(fd, + 2 /* SYSPROTO_CONTROL */, 2 /* UTUN_OPT_IFNAME */); err == nil { + unix.CloseOnExec(fd) + } + } +} + func (e *Engine) Stop() error { e.mu.Lock() defer e.mu.Unlock() @@ -194,14 +229,17 @@ func (e *Engine) Stop() error { for { attached, inspectErr := desktopTunAddressAttached() if inspectErr != nil { - err = inspectErr + err = fmt.Errorf("%w: %v", errTunAddressInspect, inspectErr) break } if !attached { break } if time.Now().After(deadline) { - err = errors.New("desktop TUN address did not detach") + // The engine is already closed, so a retained address only delays reusing + // 172.19.0.1; the next Start waits for it. Warn instead of failing the stop. + e.tunRetained = true + e.runtimeLogs.WriteMessage(log.LevelWarn, "desktop TUN address still retained after stop") break } time.Sleep(20 * time.Millisecond) @@ -212,13 +250,39 @@ func (e *Engine) Stop() error { if e.selfTestTrace { fmt.Fprintf(os.Stderr, "self-test cleanup cause: %v\n", err) } - return errors.New("proxy engine cleanup failed") + return cleanupFailure(err) } e.state = "Stopped" return nil } -func desktopTunAddressAttached() (bool, error) { +// Announcement-driven rebuilds stop and start immediately. If the address +// belongs to this engine's own retiring utun, wait for the kernel to drain it; +// any other owner still fails fast. +func (e *Engine) awaitDesktopTunAddress(wait time.Duration) error { + deadline := time.Now().Add(wait) + for { + attached, err := desktopTunAddressAttached() + if err != nil { + return errors.New("cannot inspect desktop TUN address") + } + if !attached { + e.tunRetained = false + return nil + } + if !e.tunRetained || time.Now().After(deadline) { + return errors.New("desktop TUN address already in use") + } + time.Sleep(50 * time.Millisecond) + } +} + +// Bounded so a utun that never drains still surfaces as a startup failure +// well inside the helper's 30s reply and 60s watchdog limits. +const desktopTunRetainedWait = 10 * time.Second + +// Variable so lifecycle tests can simulate Darwin's delayed address release. +var desktopTunAddressAttached = func() (bool, error) { addresses, err := net.InterfaceAddrs() if err != nil { return false, err diff --git a/engines/singbox/bridge/engine_test.go b/engines/singbox/bridge/engine_test.go index 220fc9e..f0b0f73 100644 --- a/engines/singbox/bridge/engine_test.go +++ b/engines/singbox/bridge/engine_test.go @@ -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") + } +} diff --git a/engines/singbox/bridge/tun_drain_test.go b/engines/singbox/bridge/tun_drain_test.go new file mode 100644 index 0000000..f059259 --- /dev/null +++ b/engines/singbox/bridge/tun_drain_test.go @@ -0,0 +1,338 @@ +package bridge + +import ( + "context" + "encoding/json" + "io" + "net" + "net/http" + "os" + "os/exec" + "runtime" + "strconv" + "strings" + "sync" + "testing" + "time" + + "golang.org/x/sys/unix" +) + +// Root-only diagnostic for announcement-driven rebuilds: measures how long the +// desktop TUN address survives engine Stop and identifies what holds it. +// Run: sudo sh ../../scripts/go-local.sh test ./bridge -run TestDesktopTunAddressDrain -v +func TestDesktopTunAddressDrain(t *testing.T) { + if os.Geteuid() != 0 { + t.Skip("root required") + } + physical := defaultInterface(t) + for _, mode := range []struct { + name string + intet bool + proxy map[string]any + }{ + {"mesh", false, nil}, + {"internet", true, map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": 1}}, + } { + t.Run(mode.name, func(t *testing.T) { + occupied, port := reservePort(t) + occupied.Close() + var engine Engine + config := Config{ + ListenPort: port, + MeshSOCKS: "127.0.0.1:1", + MeshCIDRs: []string{"10.253.88.0/24"}, + ProtectedCIDRs: []string{"10.253.88.0/24"}, + Feature: "combined", + DesktopTun: true, + PhysicalInterface: physical, + DNSProtection: true, + DNS: "1.1.1.1", + ProxyDNS: "https://1.1.1.1/dns-query", + } + if mode.intet { + config.Proxy = mode.proxy + } else { + config.Feature = "mesh" + } + if err := engine.Start(context.Background(), config); err != nil { + t.Fatalf("start: %v", err) + } + if !attachedNow() { + t.Fatal("address not attached while running") + } + if err := engine.Stop(); err != nil { + t.Fatalf("stop: %v", err) + } + drain := waitForDrain(5 * time.Second) + t.Logf("%s mode: address drained after %s (stop returned immediately)", mode.name, drain) + if drain < 0 { + reportHolders(t, "before GC") + for round := 1; round <= 2 && drain < 0; round++ { + runtime.GC() + time.Sleep(300 * time.Millisecond) + drain = waitForDrain(2 * time.Second) + t.Logf("after runtime.GC() round %d: %s", round, drainString(drain)) + } + reportHolders(t, "after GC") + } + // Immediate restart, exactly like the helper's announcement rebuild. + begin := time.Now() + if err := engine.Start(context.Background(), config); err != nil { + t.Fatalf("immediate restart after %s failed: %v", time.Since(begin), err) + } + t.Logf("immediate restart succeeded after %s", time.Since(begin)) + if err := engine.Stop(); err != nil { + t.Fatalf("second stop: %v", err) + } + }) + } + + // Full-fidelity reproduction of the helper: real profile, real proxy node, + // real traffic through the desktop TUN, restart with connections active. + t.Run("real-profile", func(t *testing.T) { + occupied, port := reservePort(t) + occupied.Close() + config, ok := realProfileConfig(t, physical, port) + if !ok { + t.Skip("no proxy profile available") + } + var engine Engine + engine.CacheRoot = "/var/run" // Match the helper's cache directory. + if err := engine.Start(context.Background(), config); err != nil { + t.Fatalf("start: %v", err) + } + if !attachedNow() { + t.Fatal("address not attached while running") + } + stop := make(chan struct{}) + var workers sync.WaitGroup + generateTraffic(stop, &workers) + time.Sleep(4 * time.Second) // Warm up real proxy connections. + if err := engine.Stop(); err != nil { + t.Fatalf("stop with active traffic: %v", err) + } + drain := waitForDrain(8 * time.Second) + t.Logf("real profile: address drained %s after stop returned", drainString(drain)) + if drain < 0 { + reportHolders(t, "before GC") + for round := 1; round <= 2 && drain < 0; round++ { + runtime.GC() + time.Sleep(300 * time.Millisecond) + drain = waitForDrain(2 * time.Second) + t.Logf("real profile after runtime.GC() round %d: %s", round, drainString(drain)) + } + reportHolders(t, "after GC") + } + begin := time.Now() + if err := engine.Start(context.Background(), config); err != nil { + t.Fatalf("immediate restart after %s failed: %v", time.Since(begin), err) + } + t.Logf("immediate restart succeeded after %s", time.Since(begin)) + close(stop) + workers.Wait() + if err := engine.Stop(); err != nil { + t.Fatalf("second stop: %v", err) + } + }) + + // Reproduces the production failure: helper-spawned children (the DNS + // guard's scutil) inherit sing-tun's non-CLOEXEC utun socket and pin the + // interface after engine stop, so announcement rebuilds cannot reattach + // the address. + t.Run("child-guard", func(t *testing.T) { + occupied, port := reservePort(t) + occupied.Close() + config := Config{ + ListenPort: port, + MeshSOCKS: "127.0.0.1:1", + MeshCIDRs: []string{"10.253.88.0/24"}, + ProtectedCIDRs: []string{"10.253.88.0/24"}, + Feature: "combined", + Proxy: map[string]any{"type": "socks", "server": "127.0.0.1", "server_port": 1}, + DesktopTun: true, + PhysicalInterface: physical, + DNSProtection: true, + DNS: "1.1.1.1", + ProxyDNS: "https://1.1.1.1/dns-query", + } + var engine Engine + if err := engine.Start(context.Background(), config); err != nil { + t.Fatalf("start: %v", err) + } + // A long-lived child spawned while the TUN is open, like DnsGuard. + child := exec.Command("/bin/sleep", "60") + if err := child.Start(); err != nil { + engine.Stop() + t.Fatal(err) + } + t.Cleanup(func() { + _ = child.Process.Kill() + _, _ = child.Process.Wait() + }) + if err := engine.Stop(); err != nil { + t.Fatalf("stop: %v", err) + } + drain := waitForDrain(3 * time.Second) + if drain < 0 { + reportHolders(t, "child alive") + t.Errorf("desktop TUN address retained with a helper child alive; announcement rebuild would fail") + } else { + t.Logf("child-guard: address drained after %s despite live child", drain) + } + // The announcement rebuild path must work while the child still lives. + if err := engine.Start(context.Background(), config); err != nil { + t.Fatalf("rebuild with live child failed: %v", err) + } + if err := engine.Stop(); err != nil { + t.Fatalf("second stop: %v", err) + } + }) +} + +// realProfileConfig rebuilds the exact engine configuration the unified +// helper derives from the stored proxy profile, including the real proxy +// node and DNS protection settings. +func realProfileConfig(t *testing.T, physical string, port uint16) (Config, bool) { + path := os.Getenv("MESHPORT_DRAIN_PROFILE") + if path == "" { + path = "/Users/shenlei/Library/Application Support/MeshPort/proxy-profile.json" + } + raw, err := os.ReadFile(path) + if err != nil { + return Config{}, false + } + var profile struct { + ProxyEnabled bool `json:"proxy_enabled"` + Nodes []struct { + ID string `json:"id"` + Options map[string]any `json:"options"` + } `json:"nodes"` + Selected string `json:"selected"` + Runtime json.RawMessage `json:"runtime"` + } + if err := json.Unmarshal(raw, &profile); err != nil || !profile.ProxyEnabled { + return Config{}, false + } + var config Config + if err := json.Unmarshal(profile.Runtime, &config); err != nil { + t.Fatalf("decode profile runtime: %v", err) + } + for _, node := range profile.Nodes { + if node.ID == profile.Selected { + config.Proxy = node.Options + } + } + if config.Proxy == nil { + return Config{}, false + } + config.ListenPort = port + config.MeshSOCKS = "127.0.0.1:1" + config.MeshCIDRs = []string{"10.253.88.0/24"} + config.ProtectedCIDRs = []string{"10.253.88.0/24"} + config.DesktopTun = true + config.PhysicalInterface = physical + return config, true +} + +// generateTraffic drives real connections through the desktop TUN exactly +// like interactive use, so Stop happens with active streams. +func generateTraffic(stop <-chan struct{}, wg *sync.WaitGroup) { + for worker := 0; worker < 3; worker++ { + wg.Add(1) + go func() { + defer wg.Done() + for { + select { + case <-stop: + return + default: + } + ctx, cancel := context.WithTimeout(context.Background(), 3*time.Second) + request, err := http.NewRequestWithContext(ctx, http.MethodGet, + "https://www.gstatic.com/generate_204", nil) + if err == nil { + if response, err := http.DefaultClient.Do(request); err == nil { + _, _ = io.Copy(io.Discard, response.Body) + response.Body.Close() + } + } + cancel() + time.Sleep(100 * time.Millisecond) + } + }() + } +} + +func drainString(d time.Duration) string { + if d < 0 { + return "STILL ATTACHED" + } + return d.String() +} + +func waitForDrain(limit time.Duration) time.Duration { + begin := time.Now() + for { + if !attachedNow() { + return time.Since(begin) + } + if time.Since(begin) > limit { + return -1 + } + time.Sleep(25 * time.Millisecond) + } +} + +func attachedNow() bool { + attached, _ := desktopTunAddressAttached() + return attached +} + +// reportHolders lists this process's open descriptors that are utun sockets. +func reportHolders(t *testing.T, phase string) { + directory, err := os.Open("/dev/fd") + if err != nil { + t.Logf("%s: cannot list fds: %v", phase, err) + return + } + defer directory.Close() + entries, err := directory.Readdirnames(-1) + if err != nil { + t.Logf("%s: cannot list fds: %v", phase, err) + return + } + found := 0 + for _, entry := range entries { + fd, err := strconv.Atoi(entry) + if err != nil { + continue + } + if name, err := unix.GetsockoptString(fd, 2 /* SYSPROTO_CONTROL */, 2 /* UTUN_OPT_IFNAME */); err == nil { + t.Logf("%s: fd %d holds %s", phase, fd, name) + found++ + } + } + if found == 0 { + t.Logf("%s: no open fd holds a utun; retention is kernel-side", phase) + } +} + +func defaultInterface(t *testing.T) string { + out, err := exec.Command("/sbin/route", "-n", "get", "default").Output() + if err != nil { + t.Fatal(err) + } + for _, line := range strings.Split(string(out), "\n") { + if value, ok := strings.CutPrefix(strings.TrimSpace(line), "interface:"); ok { + name := strings.TrimSpace(value) + if name != "" && !strings.HasPrefix(name, "utun") && name != "lo0" { + return name + } + } + } + t.Fatal("no physical default interface") + return "" +} + +var _ = net.IPv4len diff --git a/tools/meshport-vpn-helper/src/mac/unified.rs b/tools/meshport-vpn-helper/src/mac/unified.rs index 48a8150..bc8ca3f 100644 --- a/tools/meshport-vpn-helper/src/mac/unified.rs +++ b/tools/meshport-vpn-helper/src/mac/unified.rs @@ -300,7 +300,7 @@ fn physical_interface(internet: bool) -> Result { } Ok(interface) } -fn prefixes(snapshot: &Value) -> Result> { +pub(super) fn prefixes(snapshot: &Value) -> Result> { let mut result = BTreeSet::new(); let address = snapshot["ipv4"] .as_str() @@ -395,7 +395,7 @@ impl Unified { } result } - fn restart(&mut self, active: BTreeSet) -> Result<()> { + pub(super) fn restart(&mut self, active: BTreeSet) -> Result<()> { let proxy = self.proxy.as_ref().context("proxy unavailable")?; proxy.request(json!({"op":"stop"}))?; self.protected.extend(active.iter().cloned()); diff --git a/tools/meshport-vpn-helper/src/mac/unified_test.rs b/tools/meshport-vpn-helper/src/mac/unified_test.rs index 2a1a133..d665121 100644 --- a/tools/meshport-vpn-helper/src/mac/unified_test.rs +++ b/tools/meshport-vpn-helper/src/mac/unified_test.rs @@ -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 { + 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::() 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(()) +} diff --git a/tools/meshport-vpn-helper/src/main.rs b/tools/meshport-vpn-helper/src/main.rs index b3cb067..343ba4e 100644 --- a/tools/meshport-vpn-helper/src/main.rs +++ b/tools/meshport-vpn-helper/src/main.rs @@ -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();