Files
shenleiandClaude Code 5b7523fc4f 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>
2026-10-15 13:47:52 +09:00

339 lines
9.8 KiB
Go

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