Files
shater/transport/v2rayhttpupgrade/client_leak_lx_test.go
T
omarandClaude Opus 5 0a6689b29e fix(quic,v2ray): close the sockets quic-go was never going to close
DialEarly with a packet conn the caller made sets a flag that means quic-go does
not own it: closing the transport only stops reading from the socket. Neither DNS
transport closed it. On the QUIC one it was closed on a failed handshake and
never on success, so every redial — idle timeout, retry error, engine reload —
left a UDP socket for the life of the process. On the HTTP/3 one the library
drives its own reconnects, so the leak compounds without anything in our code
looking wrong.

That is the same shape as v2rayquic's, where offerNew overwrote the raw conn on
every reconnect without closing the previous one. Both are now owned by a watcher
tied to the connection's own context, so the socket lives exactly as long as the
connection does.

This matters more than it did last week: the shipped resolvers are DoH, and DNS
is intercepted by default now, so the whole network's query stream rides this
path on a router with 512 MB.

The same upstream commit fixes both halves. We had taken the v2ray half and not
the DNS one — the third time this session a paired fix arrived half-applied, and
the first of those cost a day of debugging. These two files are now byte-identical
to upstream so a rebase cannot reopen it.

Also from that family: websocket and httpupgrade leaked their conn on failed
handshakes, and a QUIC stream's Close did not release a blocked write.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
2026-07-26 15:39:59 +03:00

125 lines
3.3 KiB
Go

package v2rayhttpupgrade
import (
"context"
"net"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/sagernet/sing-box/option"
M "github.com/sagernet/sing/common/metadata"
"github.com/stretchr/testify/require"
)
// A failed http-upgrade handshake used to return the error while leaving the
// dialed TCP connection open: nothing in the caller chain owns a conn that was
// never returned. On a router that keeps ~380 nodes under a health checker, one
// leaked descriptor per failed handshake is a slow death. Upstream 0f1763877.
type trackedConn struct {
net.Conn
closed atomic.Bool
}
func (c *trackedConn) Close() error {
c.closed.Store(true)
return c.Conn.Close()
}
// dialRecorder dials the real (test) listener and remembers every conn handed
// out, so the test can assert on the exact conn the client was given.
type dialRecorder struct {
access sync.Mutex
conns []*trackedConn
}
func (d *dialRecorder) DialContext(ctx context.Context, network string, destination M.Socksaddr) (net.Conn, error) {
conn, err := new(net.Dialer).DialContext(ctx, network, destination.String())
if err != nil {
return nil, err
}
tracked := &trackedConn{Conn: conn}
d.access.Lock()
d.conns = append(d.conns, tracked)
d.access.Unlock()
return tracked, nil
}
func (d *dialRecorder) ListenPacket(ctx context.Context, destination M.Socksaddr) (net.PacketConn, error) {
return nil, net.ErrClosed
}
func (d *dialRecorder) only(t *testing.T) *trackedConn {
t.Helper()
d.access.Lock()
defer d.access.Unlock()
require.Len(t, d.conns, 1, "client must have dialed exactly once")
return d.conns[0]
}
// serveOnce accepts one connection, drains the request and writes raw response
// bytes back.
func serveOnce(t *testing.T, response string) net.Listener {
t.Helper()
listener, err := net.Listen("tcp", "127.0.0.1:0")
require.NoError(t, err)
t.Cleanup(func() { listener.Close() })
go func() {
conn, acceptErr := listener.Accept()
if acceptErr != nil {
return
}
defer conn.Close()
buffer := make([]byte, 4096)
conn.SetReadDeadline(time.Now().Add(5 * time.Second))
conn.Read(buffer)
if response != "" {
conn.Write([]byte(response))
}
}()
return listener
}
func newTestClient(t *testing.T, dialer *dialRecorder, listener net.Listener) *Client {
t.Helper()
client, err := NewClient(
context.Background(),
dialer,
M.ParseSocksaddr(listener.Addr().String()),
option.V2RayHTTPUpgradeOptions{Path: "/"},
nil,
)
require.NoError(t, err)
return client
}
func TestClientClosesConnOnUnexpectedStatus(t *testing.T) {
t.Parallel()
listener := serveOnce(t, "HTTP/1.1 403 Forbidden\r\nContent-Length: 0\r\n\r\n")
dialer := &dialRecorder{}
client := newTestClient(t, dialer, listener)
conn, err := client.DialContext(context.Background())
require.Error(t, err)
require.Nil(t, conn)
require.True(t, dialer.only(t).closed.Load(),
"the dialed conn must be closed when the upgrade is refused")
}
func TestClientClosesConnOnResponseFailure(t *testing.T) {
t.Parallel()
// The server hangs up without answering: http.ReadResponse fails.
listener := serveOnce(t, "")
dialer := &dialRecorder{}
client := newTestClient(t, dialer, listener)
conn, err := client.DialContext(context.Background())
require.Error(t, err)
require.Nil(t, conn)
require.True(t, dialer.only(t).closed.Load(),
"the dialed conn must be closed when the response cannot be read")
}