fix(tuic): keep a UDP association when the peer stops one response stream

In stream mode every UDP response travels on its own unidirectional stream.
A client that reads the packet by its declared size and then drops the
stream sends STOP_SENDING. When that arrived before the server's Close, or
while a large response was still being written, the write path returned an
error, the response reader exited and the whole association was released:
later packets on it were answered on the wrong transport or not at all.

A stop from the peer now ends that one packet only. Close reports it as an
untyped error, so the stream's own cancel cause is what is checked.

This is also the flake that turned main's CI red three times, in
TestAudit3UDPAssociationMustRecoverAfterBridgeReadFailure/stream and
TestAudit3FirstTransportReturnsPositiveEchoAfterOppositeModePacket/stream-first:
their helper cancels the read after each packet, and a loaded runner lost the
race between Write and Close. Sleeping 50 ms between the two reproduces both
failures on the old code every run and none with this change.

The recovery test also matched its log line by a tag reused across runs, so
any -count above 1 passed its wait on the previous run's line; the tag is
now unique.
This commit is contained in:
Sanaei
2026-11-25 11:02:24 +03:30
parent 6aefb14569
commit de7ef54739
3 changed files with 48 additions and 9 deletions
+27 -3
View File
@@ -4,6 +4,7 @@ import (
"bytes"
"context"
"encoding/binary"
"fmt"
"io"
"net"
"runtime"
@@ -61,7 +62,7 @@ func audit3RestartableSOCKS(t *testing.T) (string, *net.UDPConn, *net.UDPAddr) {
func audit3StartUDPEcho(u *net.UDPConn, arrived chan<- struct{}) {
go func() {
buf := make([]byte, 2048)
buf := make([]byte, maxSocksUdpDatagramSize)
for {
n, src, err := u.ReadFromUDP(buf)
if err != nil {
@@ -151,14 +152,16 @@ func TestAudit3UDPAssociationMustRecoverAfterBridgeReadFailure(t *testing.T) {
t.Fatalf("initial echo %q %v", p, err)
}
s.UpdateRuntimeSettings("recovery-"+name, "bbr", "warn")
// The log buffer outlives a run: a tag from an earlier -count pass must not match.
tag := fmt.Sprintf("recovery-%s-%d", name, time.Now().UnixNano())
s.UpdateRuntimeSettings(tag, "bbr", "warn")
_ = u.Close()
audit3SendPacket(t, c, mode, 42131, 2, "while-down")
deadline := time.Now().Add(2 * time.Second)
for {
found := false
for _, line := range logger.GetLogs(10000, "DEBUG") {
if strings.Contains(line, "recovery-"+name) && strings.Contains(line, "UDP relay receive failed") {
if strings.Contains(line, tag) && strings.Contains(line, "UDP relay receive failed") {
found = true
break
}
@@ -220,6 +223,27 @@ func TestAudit3FirstTransportReturnsPositiveEchoAfterOppositeModePacket(t *testi
}
}
func TestPeerStoppingOneResponseStreamKeepsItsUDPAssociation(t *testing.T) {
relayAddr, u, _ := audit3RestartableSOCKS(t)
audit3StartUDPEcho(u, nil)
// A stream window far below the response holds the server in Write until the stop arrives.
_, c, _, _ := startLifecycleTestServerWithClient(t, &SocksRelay{Addr: relayAddr, Password: "lifecycle-socks-password"},
"stopped-stream@x", &clientquic.Config{EnableDatagrams: true, InitialStreamReceiveWindow: 16, MaxStreamReceiveWindow: 16})
audit3SendPacket(t, c, packetTransportStream, 43301, 1, strings.Repeat("x", 1500))
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
response, err := c.AcceptUniStream(ctx)
if err != nil {
t.Fatalf("no response stream for the first packet: %v", err)
}
response.CancelRead(0)
audit3SendPacket(t, c, packetTransportDatagram, 43301, 2, "next")
if _, p, err := audit3ReceivePacket(c, packetTransportStream, 2*time.Second); err != nil || string(p) != "next" {
t.Fatalf("stopping one response stream ended its whole association: %q %v", p, err)
}
}
func TestUDPReaderCleanupCannotDeleteReplacementAssociation(t *testing.T) {
registry := newUdpAssociationRegistry(1500)
header := &PacketHeader{AssocID: 7, FragTotal: 1, Size: 1, Addr: &Address{Type: AddrTypeIPv4, IP: net.IPv4(1, 1, 1, 1), Port: 53}}
+15 -4
View File
@@ -1041,11 +1041,15 @@ func (s *Server) sendUDPPacketFragments(
if err != nil {
return err
}
if _, err := stream.Write(frame.Bytes()); err != nil {
stream.CancelWrite(0)
return err
_, err = stream.Write(frame.Bytes())
if err == nil {
err = stream.Close()
}
if err := stream.Close(); err != nil {
if err != nil {
if peerStoppedStream(stream) {
return nil
}
stream.CancelWrite(0)
return err
}
continue
@@ -1057,6 +1061,13 @@ func (s *Server) sendUDPPacketFragments(
return nil
}
// peerStoppedStream reports a STOP_SENDING: the peer dropped that one packet, while its
// association lives on. Close reports it untyped, so the stream's own cause is read.
func peerStoppedStream(stream *quic.SendStream) bool {
var stopped *quic.StreamError
return errors.As(context.Cause(stream.Context()), &stopped) && stopped.Remote
}
// Close gracefully stops the server and releases all network resources.
func (s *Server) Close() error {
if s.closed.Swap(true) {
+6 -2
View File
@@ -20,6 +20,11 @@ func startLifecycleTestServer(t *testing.T, relayAddr, email string) (*Server, *
}
func startLifecycleTestServerWithRelay(t *testing.T, relay *SocksRelay, email string) (*Server, *clientquic.Conn, uuid.UUID, string) {
t.Helper()
return startLifecycleTestServerWithClient(t, relay, email, &clientquic.Config{EnableDatagrams: true})
}
func startLifecycleTestServerWithClient(t *testing.T, relay *SocksRelay, email string, clientConfig *clientquic.Config) (*Server, *clientquic.Conn, uuid.UUID, string) {
t.Helper()
cert, key := generateTestCert(t)
clientID := uuid.New()
@@ -41,8 +46,7 @@ func startLifecycleTestServerWithRelay(t *testing.T, relay *SocksRelay, email st
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
client, err := clientquic.DialAddr(ctx, server.packetConn.LocalAddr().String(),
&tls.Config{InsecureSkipVerify: true, NextProtos: []string{"h3"}},
&clientquic.Config{EnableDatagrams: true})
&tls.Config{InsecureSkipVerify: true, NextProtos: []string{"h3"}}, clientConfig)
if err != nil {
t.Fatalf("dial TUIC server: %v", err)
}