diff --git a/modules/caddyhttp/idletimeout.go b/modules/caddyhttp/idletimeout.go index c3967940f..d6c8230a5 100644 --- a/modules/caddyhttp/idletimeout.go +++ b/modules/caddyhttp/idletimeout.go @@ -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) diff --git a/modules/caddyhttp/server.go b/modules/caddyhttp/server.go index ab0977911..4ec3927c6 100644 --- a/modules/caddyhttp/server.go +++ b/modules/caddyhttp/server.go @@ -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{ diff --git a/modules/caddyhttp/timeouts/timeouts.go b/modules/caddyhttp/timeouts/timeouts.go index b3bdda4f5..9d5ad0e89 100644 --- a/modules/caddyhttp/timeouts/timeouts.go +++ b/modules/caddyhttp/timeouts/timeouts.go @@ -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 } }