Skip to content

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

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
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 @@ -2277,6 +2277,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
62 changes: 62 additions & 0 deletions src/net/http/transport_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6969,3 +6969,65 @@ func testProxyAuthHeader(t *testing.T, mode testMode) {
}
resp.Body.Close()
}

// Issue 61708
func TestTransportReqCancelerCleanupOnRequestBodyWriteError(t *testing.T) {
ln := newLocalListener(t)
addr := ln.Addr().String()

done := make(chan struct{})
go func() {
conn, err := ln.Accept()
if err != nil {
t.Errorf("ln.Accept: %v", err)
return
}
// Start reading request before sending response to avoid
// "Unsolicited response received on idle HTTP channel" RoundTrip error.
if _, err := io.ReadFull(conn, make([]byte, 1)); err != nil {
t.Errorf("conn.Read: %v", err)
return
}
io.WriteString(conn, "HTTP/1.1 200\r\nContent-Length: 3\r\n\r\nfoo")
<-done
conn.Close()
}()

didRead := make(chan bool)
SetReadLoopBeforeNextReadHook(func() { didRead <- true })
defer SetReadLoopBeforeNextReadHook(nil)

tr := &Transport{}

// Send a request with a body guaranteed to fail on write.
req, err := NewRequest("POST", "http://"+addr, io.LimitReader(neverEnding('x'), 1<<30))
if err != nil {
t.Fatalf("NewRequest: %v", err)
}

resp, err := tr.RoundTrip(req)
if err != nil {
t.Fatalf("tr.RoundTrip: %v", err)
}

close(done)

// Before closing response body wait for readLoopDone goroutine
// to complete due to closed connection by writeLoop.
<-didRead

resp.Body.Close()

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