Subject: [PATCH 5/5] Isolate XHTTP data path and Hysteria janitor fixes * XHTTP WaitReadCloser: serialize publishing, reading and closing the response body. Otherwise a late response can race stream shutdown or close the ready channel twice; a body arriving after shutdown must be closed by its producer. * XHTTP closed flag: request goroutines mark a client unusable while Xmux reads that state. Atomic loads/stores avoid a data race when a request fails. * XHTTP HTTP/1.1 uploads: use the ownership map for checkout and return as well. GC can discard an idle sync.Pool entry while the close registry still owns the socket. It then stays open without being available for reuse until Close. * XHTTP HTTP/3: close the packet socket on a failed QUIC DialEarly. The normal close hook is installed only after success; failure otherwise leaks the UDP socket and, with port hopping enabled, its periodic dial worker. * Hysteria janitor: snapshot the clients before taking individual client locks. Otherwise the janitor can hold the manager read lock behind an ongoing handshake and prevent teardown from acquiring it to cancel the dial. * Hysteria manager: initialize the empty registry independently of starting the janitor on the first dial. Otherwise a Stop before the first Hysteria connection starts a permanent, idle cleanup goroutine. --- a/transport/internet/hysteria/dialer.go +++ b/transport/internet/hysteria/dialer.go @@ -318,26 +318,21 @@ ticker := time.NewTicker(idleCleanupInterval) for range ticker.C { m.RLock() + clients := make([]*client, 0, len(m.m)) for _, c := range m.m { + clients = append(clients, c) + } + m.RUnlock() + for _, c := range clients { c.clean() } - m.RUnlock() } } var ( - manager *clientManager + manager = &clientManager{m: make(map[dialerConf]*client)} initmanager sync.Once ) - -func initManager() { - initmanager.Do(func() { - manager = &clientManager{ - m: make(map[dialerConf]*client), - } - go manager.clean() - }) -} // CloseAll retires every pooled QUIC client, including its port hopper. func CloseAll() { closeClients(nil, nil) } @@ -352,7 +347,6 @@ } func closeClients(dest *net.Destination, owner *internet.MemoryStreamConfig) { - initManager() manager.Lock() var clients []*client for key, c := range manager.m { @@ -384,7 +378,9 @@ datagram := DatagramFromContext(ctx) dest.Network = net.Network_UDP - initManager() + initmanager.Do(func() { + go manager.clean() + }) manager.RLock() if streamSettings.PoolRetired.Load() { --- a/transport/internet/splithttp/dialer.go +++ b/transport/internet/splithttp/dialer.go @@ -320,6 +320,7 @@ conn, err := quic.DialEarly(ctx, pktConn, udpAddr, tlsCfg, cfg) if err != nil { + _ = pktConn.Close() return nil, err } context.AfterFunc(conn.Context(), func() { pktConn.Close() }) @@ -372,7 +373,7 @@ Transport: transport, }, httpVersion: httpVersion, - life: life, cancel: cancel, raw: make(map[*H1Conn]struct{}), uploadRawPool: &sync.Pool{}, + life: life, cancel: cancel, raw: make(map[*H1Conn]bool), dialUploadConn: dialContext, } --- a/transport/internet/splithttp/client.go +++ b/transport/internet/splithttp/client.go @@ -8,6 +8,7 @@ "net/http" "net/http/httptrace" "sync" + "sync/atomic" "github.com/apernet/quic-go/http3" "github.com/xtls/xray-core/common" @@ -32,7 +33,7 @@ type DefaultDialerClient struct { transportConfig *Config client *http.Client - closed bool + closed atomic.Bool life context.Context cancel context.CancelFunc closeOnce sync.Once @@ -40,13 +41,12 @@ httpVersion string // pool of net.Conn, created using dialUploadConn rawMu sync.Mutex - raw map[*H1Conn]struct{} // all sockets to close, including checked-out uploads - uploadRawPool *sync.Pool + raw map[*H1Conn]bool // true while available for another packet dialUploadConn func(ctxInner context.Context) (net.Conn, error) } func (c *DefaultDialerClient) IsClosed() bool { - return c.life.Err() != nil || c.closed + return c.closed.Load() } // Keep the original request's routing and accounting values while allowing @@ -91,7 +91,7 @@ resp, err := c.client.Do(req) if err != nil { if !uploadOnly { // stream-down is enough - c.closed = true + c.closed.Store(true) errors.LogInfoInner(ctx, err, "failed to "+method+" "+url) } gotConn.Close() @@ -129,7 +129,7 @@ if c.httpVersion != "1.1" { resp, err := c.client.Do(req) if err != nil { - c.closed = true + c.closed.Store(true) return err } @@ -149,7 +149,7 @@ common.Must(req.Write(requestBuff)) for { - h1UploadConn, _ := c.uploadRawPool.Get().(*H1Conn) + h1UploadConn := c.takeUpload() newConnection := h1UploadConn == nil if newConnection { if ctx.Err() != nil { @@ -166,7 +166,7 @@ _ = newConn.Close() return context.Canceled } - c.raw[h1UploadConn] = struct{}{} + c.raw[h1UploadConn] = false c.rawMu.Unlock() } else { @@ -175,7 +175,7 @@ if h1UploadConn.UnreadedResponsesCount > 0 { resp, err := http.ReadResponse(h1UploadConn.RespBufReader, req) if err != nil { - c.closed = true + c.closed.Store(true) c.releaseUpload(h1UploadConn, false) return fmt.Errorf("error while reading response: %s", err.Error()) } @@ -203,11 +203,23 @@ return nil } +func (c *DefaultDialerClient) takeUpload() *H1Conn { + c.rawMu.Lock() + defer c.rawMu.Unlock() + for conn, idle := range c.raw { + if idle { + c.raw[conn] = false + return conn + } + } + return nil +} + func (c *DefaultDialerClient) releaseUpload(conn *H1Conn, reusable bool) { c.rawMu.Lock() defer c.rawMu.Unlock() if reusable && c.life.Err() == nil { - c.uploadRawPool.Put(conn) + c.raw[conn] = true return } delete(c.raw, conn) @@ -217,6 +229,7 @@ func (c *DefaultDialerClient) Close() error { c.closeOnce.Do(func() { c.cancel() + c.closed.Store(true) c.rawMu.Lock() for conn := range c.raw { _ = conn.Close() @@ -237,42 +250,54 @@ } type WaitReadCloser struct { + Wait chan struct{} + mu sync.Mutex + reader io.ReadCloser + closed bool release func() - Wait chan struct{} - io.ReadCloser } func (w *WaitReadCloser) Set(rc io.ReadCloser) { - w.ReadCloser = rc - defer func() { - if recover() != nil { - rc.Close() - } - }() + w.mu.Lock() + if w.closed { + w.mu.Unlock() + _ = rc.Close() + return + } + w.reader = rc close(w.Wait) + w.mu.Unlock() } func (w *WaitReadCloser) Read(b []byte) (int, error) { - if w.ReadCloser == nil { - if <-w.Wait; w.ReadCloser == nil { - return 0, io.ErrClosedPipe - } - } - return w.ReadCloser.Read(b) + <-w.Wait + w.mu.Lock() + rc := w.reader + w.mu.Unlock() + if rc == nil { + return 0, io.ErrClosedPipe + } + return rc.Read(b) } func (w *WaitReadCloser) Close() error { + w.mu.Lock() + if w.closed { + w.mu.Unlock() + return nil + } + w.closed = true + rc := w.reader + w.reader = nil + if rc == nil { + close(w.Wait) + } + w.mu.Unlock() if w.release != nil { w.release() } - if w.ReadCloser != nil { - return w.ReadCloser.Close() - } - defer func() { - if recover() != nil && w.ReadCloser != nil { - w.ReadCloser.Close() - } - }() - close(w.Wait) + if rc != nil { + return rc.Close() + } return nil }