From 1daa21f553deb5abdbfdec6c97fc7254b44a7782 Mon Sep 17 00:00:00 2001 From: Dean Chen <862469039@qq.com> Date: Fri, 20 Nov 2026 12:14:23 +0500 Subject: [PATCH] wgengine/magicsock: close old UDP sockets when TS_DEBUG_ALWAYS_USE_DERP is set bindSocket's TS_DEBUG_ALWAYS_USE_DERP branch swapped in an empty socket group without closing the existing one. If the knob was turned on after the Conn was bound, a Rebind left the old socket open with no reference to it, so its port stayed bound even after Conn.Close. Close the current sockets first, as the normal bind path does. Fixes #22524 Signed-off-by: Dean Chen <862469039@qq.com> --- wgengine/magicsock/magicsock.go | 3 +++ wgengine/magicsock/magicsock_test.go | 20 ++++++++++++++++++++ 2 files changed, 23 insertions(+) diff --git a/wgengine/magicsock/magicsock.go b/wgengine/magicsock/magicsock.go index 68eb1c3fd..791e53c1a 100644 --- a/wgengine/magicsock/magicsock.go +++ b/wgengine/magicsock/magicsock.go @@ -4028,6 +4028,9 @@ func (c *Conn) bindSocket(ruc *RebindingUDPConn, network string, curPortFate cur if debugAlwaysDERP() { c.logf("disabled %v per TS_DEBUG_ALWAYS_USE_DERP", network) + if err := ruc.closeLocked(); err != nil { + c.logf("magicsock: bindSocket %v close failed: %v", network, err) + } ruc.setConnLocked(nil, c.udpSockets, "", c.controlKnobs) return nil } diff --git a/wgengine/magicsock/magicsock_test.go b/wgengine/magicsock/magicsock_test.go index 677e1da07..67dd3a726 100644 --- a/wgengine/magicsock/magicsock_test.go +++ b/wgengine/magicsock/magicsock_test.go @@ -5465,3 +5465,23 @@ func TestSetNetworkMapAndFilterAfterClose(t *testing.T) { t.Error("relay client enabled on a closed Conn") } } + +func TestBindSocketAlwaysDERPClosesOldSocket(t *testing.T) { + c, _ := newTestConnAndRegistry(t) + port := c.LocalPort() + if port == 0 { + t.Fatal("conn not bound to a UDP port") + } + + envknob.SetenvForTest(t, "TS_DEBUG_ALWAYS_USE_DERP", "true") + c.Rebind() + + if got := c.LocalPort(); got != 0 { + t.Fatalf("LocalPort after rebind = %d, want 0", got) + } + pc, err := net.ListenUDP("udp4", &net.UDPAddr{Port: int(port)}) + if err != nil { + t.Fatalf("old port %d still in use after rebind: %v", port, err) + } + pc.Close() +}