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

55 lines
1.9 KiB
Go

package bridge
import (
"context"
"errors"
"fmt"
"net"
"os"
"strings"
"syscall"
)
// Return fixed diagnostic categories, never upstream messages containing node
// credentials, subscription URLs, or the generated configuration.
func startupFailure(stage string, cause error) error {
code := "engine_failure"
var dnsError *net.DNSError
var networkError net.Error
message := strings.ToLower(cause.Error())
switch {
case errors.Is(cause, syscall.EADDRINUSE):
code = "listen_port_in_use"
case errors.Is(cause, os.ErrPermission):
code = "permission_denied"
case errors.Is(cause, context.DeadlineExceeded) || errors.As(cause, &networkError) && networkError.Timeout():
code = "network_timeout"
case errors.As(cause, &dnsError):
code = "dns_resolution_failed"
case strings.Contains(message, "certificate") || strings.Contains(message, "x509"):
code = "tls_certificate_failed"
case strings.Contains(message, "rule-set") || strings.Contains(message, "rule set"):
code = "rule_set_failed"
case strings.Contains(message, "connection refused"):
code = "connection_refused"
case strings.Contains(message, "unsupported") || strings.Contains(message, "unknown") || strings.Contains(message, "invalid"):
code = "invalid_engine_options"
}
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)
}