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() +}