Skip to content

net/http: fix request canceler leak on connection close #61745

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 1 commit into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/net/http/transport.go
Original file line number Diff line number Diff line change
Expand Up @@ -2267,6 +2267,7 @@ func (pc *persistConn) readLoop() {
pc.t.cancelRequest(rc.cancelKey, rc.req.Context().Err())
case <-pc.closech:
alive = false
pc.t.setReqCanceler(rc.cancelKey, nil)
}

testHookReadLoopBeforeNextRead()
Expand Down
52 changes: 52 additions & 0 deletions src/net/http/transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6810,3 +6810,55 @@ func testRequestSanitization(t *testing.T, mode testMode) {
resp.Body.Close()
}
}

// Issue 61708
func TestTransportAndServerSharedBodyReqCancelerCleanupOnConnectionClose(t *testing.T) {
run(t, testTransportAndServerSharedBodyReqCancelerCleanupOnConnectionClose, []testMode{http1Mode})
}
func testTransportAndServerSharedBodyReqCancelerCleanupOnConnectionClose(t *testing.T, mode testMode) {
const bodySize = 1 << 20

backend := newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {
io.Copy(rw, req.Body)
}))
t.Logf("Backend address: %s", backend.ts.Listener.Addr().String())

var proxy *clientServerTest
proxy = newClientServerTest(t, mode, HandlerFunc(func(rw ResponseWriter, req *Request) {
breq, _ := NewRequest("POST", backend.ts.URL, req.Body)

bresp, err := backend.c.Do(breq)
if err != nil {
t.Fatalf("Unexpected proxy outbound request error: %v", err)
}
defer bresp.Body.Close()

_, err = io.Copy(rw, bresp.Body)
if err == nil {
t.Fatalf("Expected proxy copy error")
}
t.Logf("Proxy copy error: %v", err)
}))
t.Logf("Proxy address: %s", proxy.ts.Listener.Addr().String())

req, _ := NewRequest("POST", proxy.ts.URL, io.LimitReader(neverEnding('a'), bodySize))
res, err := proxy.c.Do(req)
if err != nil {
t.Fatalf("Original request: %v", err)
}
// Close body without reading to trigger proxy copy error
res.Body.Close()

// Verify no outstanding requests after readLoop/writeLoop
// goroutines shut down.
waitCondition(t, 10*time.Millisecond, func(d time.Duration) bool {
n := backend.tr.NumPendingRequestsForTesting()
if n > 0 {
if d > 0 {
t.Logf("pending requests = %d after %v (want 0)", n, d)
}
return false
}
return true
})
}