fix: HTTP/1.1 keep-alive connection is reused after read_body_idle timeo

Signed-off-by: wangshun <96341168+xixi-box@users.noreply.github.com>
This commit is contained in:
wangshun 2026-11-10 17:29:15 +00:00
parent f458aa0081
commit bb10d9427a
3 changed files with 57 additions and 2 deletions

View file

@ -23,6 +23,7 @@ import (
"net/http"
"os"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
@ -154,6 +155,11 @@ type IdleTimeoutReader struct {
// HTTP/2) for other protocols or requests without a body.
DrainDeadline bool
// CloseConnection makes a terminal read timeout mark the response as
// non-reusable for HTTP/1. It is false for HTTP/2, where cancellation is
// scoped to the stream.
CloseConnection bool
// ClearBetweenReads makes the reader put back the earliest of
// HardDeadline and the deadline set by the handler (no deadline if
// there is neither) after every successful read, so the idle
@ -172,6 +178,7 @@ type IdleTimeoutReader struct {
installed time.Time // Last deadline successfully installed through Ctrl.
reading bool
finished bool
timedOut atomic.Bool
terminalErr error
handlerDeadline time.Time
@ -254,6 +261,9 @@ func (r *IdleTimeoutReader) Read(p []byte) (int, error) {
r.Deadline.transferred += int64(n)
if err != nil {
r.terminalErr = err
if errors.Is(err, os.ErrDeadlineExceeded) {
r.timedOut.Store(true)
}
if !r.finished {
r.clearDeadlineLocked()
}
@ -265,6 +275,12 @@ func (r *IdleTimeoutReader) Read(p []byte) (int, error) {
return n, err
}
// connectionMustClose reports whether an HTTP/1 response must close the
// connection because the request body reached a terminal read timeout.
func (r *IdleTimeoutReader) connectionMustClose() bool {
return r.CloseConnection && r.timedOut.Load()
}
// HandlerDone prevents later body reads from using the response controller.
// If the body is not finished and DrainDeadline is set, it leaves an idle
// deadline armed for net/http's post-handler drain. Otherwise, it clears a
@ -629,12 +645,47 @@ func (w *IdleTimeoutWriter) FlushError() error {
// readDeadlineWriter routes read deadlines set by handlers through
// http.ResponseController to the IdleTimeoutReader of the request,
// which would otherwise replace them before the next read.
// which would otherwise replace them before the next read. It also marks
// an HTTP/1 response to close the connection if the body reached a
// terminal read timeout, since net/http cancels the connection-level
// context on any body read error and cannot restore it.
type readDeadlineWriter struct {
ResponseWriterWrapper
reader *IdleTimeoutReader
}
// WrapResponseWriter returns w wrapped so that read deadlines set by
// handlers through http.ResponseController reach this reader, and so that
// a terminal HTTP/1 body read timeout marks the response to close the
// connection instead of reusing it with a canceled request context.
func (r *IdleTimeoutReader) WrapResponseWriter(w http.ResponseWriter) http.ResponseWriter {
return &readDeadlineWriter{
ResponseWriterWrapper: ResponseWriterWrapper{ResponseWriter: w},
reader: r,
}
}
func (w *readDeadlineWriter) setConnectionClose() {
if w.reader.connectionMustClose() {
w.Header().Set("Connection", "close")
}
}
func (w *readDeadlineWriter) WriteHeader(status int) {
w.setConnectionClose()
w.ResponseWriterWrapper.WriteHeader(status)
}
func (w *readDeadlineWriter) Write(p []byte) (int, error) {
w.setConnectionClose()
return w.ResponseWriterWrapper.Write(p)
}
func (w *readDeadlineWriter) ReadFrom(r io.Reader) (int64, error) {
w.setConnectionClose()
return w.ResponseWriterWrapper.ReadFrom(r)
}
func (w *readDeadlineWriter) SetReadDeadline(deadline time.Time) error {
return w.reader.SetReadDeadline(deadline)
}
@ -669,6 +720,7 @@ func ContextWithIdleTimeouts(ctx context.Context, reader *IdleTimeoutReader, wri
var (
_ io.ReadCloser = (*IdleTimeoutReader)(nil)
_ http.ResponseWriter = (*readDeadlineWriter)(nil)
_ io.ReaderFrom = (*readDeadlineWriter)(nil)
_ http.ResponseWriter = (*IdleTimeoutWriter)(nil)
_ io.ReaderFrom = (*IdleTimeoutWriter)(nil)
_ interface{ FlushError() error } = (*IdleTimeoutWriter)(nil)

View file

@ -654,11 +654,12 @@ func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) {
},
Logger: s.logger,
DrainDeadline: r.ProtoMajor == 1 && r.ContentLength != 0,
CloseConnection: r.ProtoMajor == 1,
ClearBetweenReads: r.ProtoMajor == 2,
}
defer idleReader.HandlerDone()
r.Body = idleReader
w = &readDeadlineWriter{ResponseWriterWrapper: ResponseWriterWrapper{ResponseWriter: w}, reader: idleReader}
w = idleReader.WrapResponseWriter(w)
}
if s.WriteIdleTimeout > 0 {
idleWriter = &IdleTimeoutWriter{

View file

@ -116,10 +116,12 @@ func (t Timeouts) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht
},
Logger: t.logger,
DrainDeadline: r.ProtoMajor == 1 && r.ContentLength != 0,
CloseConnection: r.ProtoMajor == 1,
ClearBetweenReads: r.ProtoMajor == 2,
}
defer idleReader.HandlerDone()
r.Body = idleReader
w = idleReader.WrapResponseWriter(w)
wrapped = true
}
}