mirror of
https://github.com/soypat/lneto.git
synced 2026-09-10 16:49:37 +00:00
fix(xnet): allocate ephemeral ports sequentially, not randomly (#180)
Ephemeral ports were drawn at random from the 16384-port dynamic range on every dial. Under connection-per-request churn the birthday paradox reuses a recently-released port after only a few dozen dials (~1% per dial at 200 outstanding-in-teardown), and a reused 4-tuple lands on whatever state the previous conversation left along the path, such as the peer's TIME-WAIT socket or a NAT's flow-table entry, which silently swallows the new SYN. Measured end to end: an HTTP client with keep-alives off against a macOS peer hit a dead dial after ~286 connections and stayed dark for ~30 seconds, exactly one 2MSL TIME-WAIT expiry. Allocate sequentially from a per-stack random starting offset instead: a port is only revisited after the full 16384-port cycle, and the random start keeps a rebooted node off the ports its previous life just used. TestEphemeralPortSequence pins the full-cycle-no-reuse property. Co-authored-by: Derek den Haas <d.haas@directcode.com>
This commit is contained in:
@@ -1196,3 +1196,39 @@ func TestEgressIP_TCPMSSAdvertisesMTU(t *testing.T) {
|
||||
t.Errorf("advertised MSS = %d, want %d (MTU %d - 40)", gotMSS, wantMSS, mtu)
|
||||
}
|
||||
}
|
||||
|
||||
// TestEphemeralPortSequence checks no ephemeral port is reused before the whole
|
||||
// 16384-port dynamic range has cycled, which is what keeps a redial off the
|
||||
// teardown state (TIME-WAIT, NAT flow entries) of the conversation before it.
|
||||
func TestEphemeralPortSequence(t *testing.T) {
|
||||
s := new(StackAsync)
|
||||
err := s.Reset(StackConfig{
|
||||
Hostname: "eph",
|
||||
RandSeed: 42,
|
||||
StaticAddress4: [4]byte{10, 0, 0, 50},
|
||||
MaxActiveTCPPorts: 1,
|
||||
HardwareAddress: [6]byte{0xbe, 0xef, 0, 0, 0, 50},
|
||||
MTU: ethernet.MaxMTU,
|
||||
ICMPQueueLimit: 2,
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
const cycle = 16384
|
||||
var seen [cycle]bool
|
||||
for i := 0; i < cycle; i++ {
|
||||
port := s.ephemeralPort()
|
||||
if port < 49152 {
|
||||
t.Fatalf("port %d below dynamic range (RFC 6335)", port)
|
||||
}
|
||||
idx := port - 49152
|
||||
if seen[idx] {
|
||||
t.Fatalf("port %d reused after only %d allocations (want full %d cycle)", port, i, cycle)
|
||||
}
|
||||
seen[idx] = true
|
||||
}
|
||||
// The cycle is exhausted: the next allocation may legitimately reuse.
|
||||
if got := s.ephemeralPort(); got < 49152 {
|
||||
t.Fatalf("post-cycle port %d below dynamic range", got)
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user