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>
183 lines
5.7 KiB
Go
183 lines
5.7 KiB
Go
package bridge
|
|
|
|
import (
|
|
"context"
|
|
M "github.com/sagernet/sing/common/metadata"
|
|
"github.com/sagernet/sing/protocol/socks"
|
|
"github.com/sagernet/sing/protocol/socks/socks5"
|
|
"io"
|
|
"net"
|
|
"net/netip"
|
|
"strings"
|
|
"testing"
|
|
"time"
|
|
)
|
|
|
|
func reservePort(t *testing.T) (net.Listener, uint16) {
|
|
t.Helper()
|
|
l, err := net.Listen("tcp4", "127.0.0.1:0")
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
return l, uint16(l.Addr().(*net.TCPAddr).Port)
|
|
}
|
|
|
|
func TestUnconfiguredTargetsAndDomainsAreRejected(t *testing.T) {
|
|
bridgeListener, _ := reservePort(t)
|
|
defer bridgeListener.Close()
|
|
entry, port := reservePort(t)
|
|
entry.Close()
|
|
var engine Engine
|
|
if err := engine.Start(context.Background(), Config{ListenPort: port, MeshSOCKS: bridgeListener.Addr().String(), MeshCIDRs: []string{"10.77.0.0/24"}}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer engine.Stop()
|
|
for _, destination := range []M.Socksaddr{
|
|
M.SocksaddrFrom(netip.MustParseAddr("127.0.0.1"), uint16(bridgeListener.Addr().(*net.TCPAddr).Port)),
|
|
M.SocksaddrFrom(netip.MustParseAddr("10.78.0.1"), 1234),
|
|
M.ParseSocksaddr("must-not-resolve.invalid:1234"),
|
|
} {
|
|
conn, err := net.Dial("tcp4", entry.Addr().String())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
|
_, err = socks.ClientHandshake5(conn, socks5.CommandConnect, destination, "", "")
|
|
conn.Close()
|
|
if err == nil {
|
|
t.Fatal("unconfigured target accepted:", destination)
|
|
}
|
|
if timeout, ok := err.(net.Error); ok && timeout.Timeout() {
|
|
t.Fatal("rejection timed out:", destination)
|
|
}
|
|
}
|
|
bridgeListener.(*net.TCPListener).SetDeadline(time.Now().Add(100 * time.Millisecond))
|
|
if conn, err := bridgeListener.Accept(); err == nil {
|
|
conn.Close()
|
|
t.Fatal("rejected request reached mesh bridge")
|
|
}
|
|
}
|
|
|
|
func TestConfigurationRejectsUnsupportedEndpointsAndPrefixes(t *testing.T) {
|
|
base := Config{ListenPort: 1080, MeshSOCKS: "127.0.0.1:1234", MeshCIDRs: []string{"10.77.0.0/24"}}
|
|
for _, endpoint := range []string{"example.com:1080", "0.0.0.0:1080", "10.0.0.1:1080", "127.0.0.1:0", "[::1]:1080"} {
|
|
c := base
|
|
c.MeshSOCKS = endpoint
|
|
if _, err := c.managedJSON(); err == nil {
|
|
t.Errorf("accepted endpoint %s", endpoint)
|
|
}
|
|
}
|
|
for _, prefix := range []string{"0.0.0.0/0", "10.0.0.0/8", "1.1.1.0/24", "127.0.0.0/24", "fd00::/64", "invalid"} {
|
|
c := base
|
|
c.MeshCIDRs = []string{prefix}
|
|
if _, err := c.managedJSON(); err == nil {
|
|
t.Errorf("accepted prefix %s", prefix)
|
|
}
|
|
}
|
|
c := base
|
|
c.MeshCIDRs = nil
|
|
if _, err := c.managedJSON(); err == nil {
|
|
t.Error("accepted empty projection")
|
|
}
|
|
}
|
|
|
|
func TestEngineLifecycleAndFailedStartRecovery(t *testing.T) {
|
|
occupied, port := reservePort(t)
|
|
defer occupied.Close()
|
|
c := Config{ListenPort: port, MeshSOCKS: "127.0.0.1:1234", MeshCIDRs: []string{"10.77.0.11/24", "10.77.0.0/24"}}
|
|
var engine Engine
|
|
if engine.Snapshot().State != "Stopped" {
|
|
t.Fatal("initial state")
|
|
}
|
|
if err := engine.Start(context.Background(), c); err == nil {
|
|
t.Fatal("started on occupied port")
|
|
} else if !strings.Contains(err.Error(), "listen_port_in_use") {
|
|
t.Fatalf("missing safe occupied-port diagnostic: %v", err)
|
|
}
|
|
if engine.Snapshot().State != "Failed" {
|
|
t.Fatal("failed start state")
|
|
}
|
|
occupied.Close()
|
|
if err := engine.Start(context.Background(), c); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer engine.Stop()
|
|
if engine.Snapshot().State != "Running" {
|
|
t.Fatal("running state")
|
|
}
|
|
if engine.Start(context.Background(), c) == nil {
|
|
t.Fatal("duplicate start accepted")
|
|
}
|
|
conn, err := net.Dial("tcp4", occupied.Addr().String())
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer conn.Close()
|
|
conn.SetDeadline(time.Now().Add(3 * time.Second))
|
|
if _, err := conn.Write([]byte{5, 1, 0}); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
var reply [2]byte
|
|
if _, err := io.ReadFull(conn, reply[:]); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if reply != [2]byte{5, 0} {
|
|
t.Fatal("unexpected negotiation", reply)
|
|
}
|
|
if err := engine.Stop(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if err := engine.Stop(); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if engine.Snapshot().State != "Stopped" {
|
|
t.Fatal("stop state")
|
|
}
|
|
if n, err := conn.Read(reply[:]); n != 0 {
|
|
t.Fatal("active connection retained after stop")
|
|
} else if timeout, ok := err.(net.Error); ok && timeout.Timeout() {
|
|
t.Fatal("active connection only closed by client timeout")
|
|
}
|
|
l, err := net.Listen("tcp4", occupied.Addr().String())
|
|
if err != nil {
|
|
t.Fatal("listener leaked:", err)
|
|
}
|
|
l.Close()
|
|
if err := engine.Start(context.Background(), c); err != nil {
|
|
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")
|
|
}
|
|
}
|