]> Cypherpunks.ru repositories - gostls13.git/blobdiff - src/net/http/transfer.go
net/http: use copyBufPool in transferWriter.doBodyCopy()
[gostls13.git] / src / net / http / transfer.go
index 480226af824c64564cb0228cb90485043af3b1fa..dffff56b31e94ff8345eedb769948032bf34d9e0 100644 (file)
@@ -9,14 +9,20 @@ import (
        "bytes"
        "errors"
        "fmt"
+       "internal/godebug"
        "io"
-       "io/ioutil"
+       "net/http/httptrace"
        "net/http/internal"
+       "net/http/internal/ascii"
        "net/textproto"
+       "reflect"
        "sort"
        "strconv"
        "strings"
        "sync"
+       "time"
+
+       "golang.org/x/net/http/httpguts"
 )
 
 // ErrLineTooLong is returned when reading request or response bodies
@@ -31,6 +37,23 @@ func (r errorReader) Read(p []byte) (n int, err error) {
        return 0, r.err
 }
 
+type byteReader struct {
+       b    byte
+       done bool
+}
+
+func (br *byteReader) Read(p []byte) (n int, err error) {
+       if br.done {
+               return 0, io.EOF
+       }
+       if len(p) == 0 {
+               return 0, nil
+       }
+       br.done = true
+       p[0] = br.b
+       return 1, io.EOF
+}
+
 // transferWriter inspects the fields of a user-supplied Request or Response,
 // sanitizes them without changing the user object and provides methods for
 // writing the respective header, body and trailer in wire format.
@@ -42,11 +65,16 @@ type transferWriter struct {
        ContentLength    int64 // -1 means unknown, 0 means exactly none
        Close            bool
        TransferEncoding []string
+       Header           Header
        Trailer          Header
        IsResponse       bool
+       bodyReadError    error // any non-EOF error from reading Body
+
+       FlushHeaders bool            // flush headers to network before body
+       ByteReadCh   chan readResult // non-nil if probeRequestBody called
 }
 
-func newTransferWriter(r interface{}) (t *transferWriter, err error) {
+func newTransferWriter(r any) (t *transferWriter, err error) {
        t = &transferWriter{}
 
        // Extract relevant fields
@@ -57,38 +85,28 @@ func newTransferWriter(r interface{}) (t *transferWriter, err error) {
                        return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
                }
                t.Method = valueOrDefault(rr.Method, "GET")
-               t.Body = rr.Body
-               t.BodyCloser = rr.Body
-               t.ContentLength = rr.ContentLength
                t.Close = rr.Close
                t.TransferEncoding = rr.TransferEncoding
+               t.Header = rr.Header
                t.Trailer = rr.Trailer
-               atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
-               if t.Body != nil && len(t.TransferEncoding) == 0 && atLeastHTTP11 {
-                       if t.ContentLength == 0 {
-                               // Test to see if it's actually zero or just unset.
-                               var buf [1]byte
-                               n, rerr := io.ReadFull(t.Body, buf[:])
-                               if rerr != nil && rerr != io.EOF {
-                                       t.ContentLength = -1
-                                       t.Body = errorReader{rerr}
-                               } else if n == 1 {
-                                       // Oh, guess there is data in this Body Reader after all.
-                                       // The ContentLength field just wasn't set.
-                                       // Stich the Body back together again, re-attaching our
-                                       // consumed byte.
-                                       t.ContentLength = -1
-                                       t.Body = io.MultiReader(bytes.NewReader(buf[:]), t.Body)
-                               } else {
-                                       // Body is actually empty.
-                                       t.Body = nil
-                                       t.BodyCloser = nil
-                               }
-                       }
-                       if t.ContentLength < 0 {
-                               t.TransferEncoding = []string{"chunked"}
-                       }
+               t.Body = rr.Body
+               t.BodyCloser = rr.Body
+               t.ContentLength = rr.outgoingLength()
+               if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
+                       t.TransferEncoding = []string{"chunked"}
+               }
+               // If there's a body, conservatively flush the headers
+               // to any bufio.Writer we're writing to, just in case
+               // the server needs the headers early, before we copy
+               // the body and possibly block. We make an exception
+               // for the common standard library in-memory types,
+               // though, to avoid unnecessary TCP packets on the
+               // wire. (Issue 22088.)
+               if t.ContentLength != 0 && !isKnownInMemoryReader(t.Body) {
+                       t.FlushHeaders = true
                }
+
+               atLeastHTTP11 = true // Transport requests are always 1.1 or 2.0
        case *Response:
                t.IsResponse = true
                if rr.Request != nil {
@@ -99,9 +117,10 @@ func newTransferWriter(r interface{}) (t *transferWriter, err error) {
                t.ContentLength = rr.ContentLength
                t.Close = rr.Close
                t.TransferEncoding = rr.TransferEncoding
+               t.Header = rr.Header
                t.Trailer = rr.Trailer
                atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
-               t.ResponseToHEAD = noBodyExpected(t.Method)
+               t.ResponseToHEAD = noResponseBodyExpected(t.Method)
        }
 
        // Sanitize Body,ContentLength,TransferEncoding
@@ -129,7 +148,105 @@ func newTransferWriter(r interface{}) (t *transferWriter, err error) {
        return t, nil
 }
 
-func noBodyExpected(requestMethod string) bool {
+// shouldSendChunkedRequestBody reports whether we should try to send a
+// chunked request body to the server. In particular, the case we really
+// want to prevent is sending a GET or other typically-bodyless request to a
+// server with a chunked body when the body has zero bytes, since GETs with
+// bodies (while acceptable according to specs), even zero-byte chunked
+// bodies, are approximately never seen in the wild and confuse most
+// servers. See Issue 18257, as one example.
+//
+// The only reason we'd send such a request is if the user set the Body to a
+// non-nil value (say, io.NopCloser(bytes.NewReader(nil))) and didn't
+// set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
+// there's bytes to send.
+//
+// This code tries to read a byte from the Request.Body in such cases to see
+// whether the body actually has content (super rare) or is actually just
+// a non-nil content-less ReadCloser (the more common case). In that more
+// common case, we act as if their Body were nil instead, and don't send
+// a body.
+func (t *transferWriter) shouldSendChunkedRequestBody() bool {
+       // Note that t.ContentLength is the corrected content length
+       // from rr.outgoingLength, so 0 actually means zero, not unknown.
+       if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
+               return false
+       }
+       if t.Method == "CONNECT" {
+               return false
+       }
+       if requestMethodUsuallyLacksBody(t.Method) {
+               // Only probe the Request.Body for GET/HEAD/DELETE/etc
+               // requests, because it's only those types of requests
+               // that confuse servers.
+               t.probeRequestBody() // adjusts t.Body, t.ContentLength
+               return t.Body != nil
+       }
+       // For all other request types (PUT, POST, PATCH, or anything
+       // made-up we've never heard of), assume it's normal and the server
+       // can deal with a chunked request body. Maybe we'll adjust this
+       // later.
+       return true
+}
+
+// probeRequestBody reads a byte from t.Body to see whether it's empty
+// (returns io.EOF right away).
+//
+// But because we've had problems with this blocking users in the past
+// (issue 17480) when the body is a pipe (perhaps waiting on the response
+// headers before the pipe is fed data), we need to be careful and bound how
+// long we wait for it. This delay will only affect users if all the following
+// are true:
+//   - the request body blocks
+//   - the content length is not set (or set to -1)
+//   - the method doesn't usually have a body (GET, HEAD, DELETE, ...)
+//   - there is no transfer-encoding=chunked already set.
+//
+// In other words, this delay will not normally affect anybody, and there
+// are workarounds if it does.
+func (t *transferWriter) probeRequestBody() {
+       t.ByteReadCh = make(chan readResult, 1)
+       go func(body io.Reader) {
+               var buf [1]byte
+               var rres readResult
+               rres.n, rres.err = body.Read(buf[:])
+               if rres.n == 1 {
+                       rres.b = buf[0]
+               }
+               t.ByteReadCh <- rres
+               close(t.ByteReadCh)
+       }(t.Body)
+       timer := time.NewTimer(200 * time.Millisecond)
+       select {
+       case rres := <-t.ByteReadCh:
+               timer.Stop()
+               if rres.n == 0 && rres.err == io.EOF {
+                       // It was empty.
+                       t.Body = nil
+                       t.ContentLength = 0
+               } else if rres.n == 1 {
+                       if rres.err != nil {
+                               t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
+                       } else {
+                               t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
+                       }
+               } else if rres.err != nil {
+                       t.Body = errorReader{rres.err}
+               }
+       case <-timer.C:
+               // Too slow. Don't wait. Read it later, and keep
+               // assuming that this is ContentLength == -1
+               // (unknown), which means we'll send a
+               // "Transfer-Encoding: chunked" header.
+               t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
+               // Request that Request.Write flush the headers to the
+               // network before writing the body, since our body may not
+               // become readable until it's seen the response headers.
+               t.FlushHeaders = true
+       }
+}
+
+func noResponseBodyExpected(requestMethod string) bool {
        return requestMethod == "HEAD"
 }
 
@@ -144,7 +261,7 @@ func (t *transferWriter) shouldSendContentLength() bool {
                return false
        }
        // Many servers expect a Content-Length for these methods
-       if t.Method == "POST" || t.Method == "PUT" {
+       if t.Method == "POST" || t.Method == "PUT" || t.Method == "PATCH" {
                return true
        }
        if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
@@ -157,11 +274,14 @@ func (t *transferWriter) shouldSendContentLength() bool {
        return false
 }
 
-func (t *transferWriter) WriteHeader(w io.Writer) error {
-       if t.Close {
+func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error {
+       if t.Close && !hasToken(t.Header.get("Connection"), "close") {
                if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
                        return err
                }
+               if trace != nil && trace.WroteHeaderField != nil {
+                       trace.WroteHeaderField("Connection", []string{"close"})
+               }
        }
 
        // Write Content-Length and/or Transfer-Encoding whose values are a
@@ -174,10 +294,16 @@ func (t *transferWriter) WriteHeader(w io.Writer) error {
                if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
                        return err
                }
+               if trace != nil && trace.WroteHeaderField != nil {
+                       trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
+               }
        } else if chunked(t.TransferEncoding) {
                if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
                        return err
                }
+               if trace != nil && trace.WroteHeaderField != nil {
+                       trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
+               }
        }
 
        // Write Trailer header
@@ -187,7 +313,7 @@ func (t *transferWriter) WriteHeader(w io.Writer) error {
                        k = CanonicalHeaderKey(k)
                        switch k {
                        case "Transfer-Encoding", "Trailer", "Content-Length":
-                               return &badStringError{"invalid Trailer key", k}
+                               return badStringError("invalid Trailer key", k)
                        }
                        keys = append(keys, k)
                }
@@ -198,42 +324,65 @@ func (t *transferWriter) WriteHeader(w io.Writer) error {
                        if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
                                return err
                        }
+                       if trace != nil && trace.WroteHeaderField != nil {
+                               trace.WroteHeaderField("Trailer", keys)
+                       }
                }
        }
 
        return nil
 }
 
-func (t *transferWriter) WriteBody(w io.Writer) error {
-       var err error
+// always closes t.BodyCloser
+func (t *transferWriter) writeBody(w io.Writer) (err error) {
        var ncopy int64
+       closed := false
+       defer func() {
+               if closed || t.BodyCloser == nil {
+                       return
+               }
+               if closeErr := t.BodyCloser.Close(); closeErr != nil && err == nil {
+                       err = closeErr
+               }
+       }()
 
-       // Write body
+       // Write body. We "unwrap" the body first if it was wrapped in a
+       // nopCloser or readTrackingBody. This is to ensure that we can take advantage of
+       // OS-level optimizations in the event that the body is an
+       // *os.File.
        if t.Body != nil {
+               var body = t.unwrapBody()
                if chunked(t.TransferEncoding) {
                        if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
-                               w = &internal.FlushAfterChunkWriter{bw}
+                               w = &internal.FlushAfterChunkWriter{Writer: bw}
                        }
                        cw := internal.NewChunkedWriter(w)
-                       _, err = io.Copy(cw, t.Body)
+                       _, err = t.doBodyCopy(cw, body)
                        if err == nil {
                                err = cw.Close()
                        }
                } else if t.ContentLength == -1 {
-                       ncopy, err = io.Copy(w, t.Body)
+                       dst := w
+                       if t.Method == "CONNECT" {
+                               dst = bufioFlushWriter{dst}
+                       }
+                       ncopy, err = t.doBodyCopy(dst, body)
                } else {
-                       ncopy, err = io.Copy(w, io.LimitReader(t.Body, t.ContentLength))
+                       ncopy, err = t.doBodyCopy(w, io.LimitReader(body, t.ContentLength))
                        if err != nil {
                                return err
                        }
                        var nextra int64
-                       nextra, err = io.Copy(ioutil.Discard, t.Body)
+                       nextra, err = t.doBodyCopy(io.Discard, body)
                        ncopy += nextra
                }
                if err != nil {
                        return err
                }
-               if err = t.BodyCloser.Close(); err != nil {
+       }
+       if t.BodyCloser != nil {
+               closed = true
+               if err := t.BodyCloser.Close(); err != nil {
                        return err
                }
        }
@@ -256,6 +405,38 @@ func (t *transferWriter) WriteBody(w io.Writer) error {
        return err
 }
 
+// doBodyCopy wraps a copy operation, with any resulting error also
+// being saved in bodyReadError.
+//
+// This function is only intended for use in writeBody.
+func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
+       bufp := copyBufPool.Get().(*[]byte)
+       buf := *bufp
+       defer copyBufPool.Put(bufp)
+
+       n, err = io.CopyBuffer(dst, src, buf)
+       if err != nil && err != io.EOF {
+               t.bodyReadError = err
+       }
+       return
+}
+
+// unwrapBody unwraps the body's inner reader if it's a
+// nopCloser. This is to ensure that body writes sourced from local
+// files (*os.File types) are properly optimized.
+//
+// This function is only intended for use in writeBody.
+func (t *transferWriter) unwrapBody() io.Reader {
+       if r, ok := unwrapNopCloser(t.Body); ok {
+               return r
+       }
+       if r, ok := t.Body.(*readTrackingBody); ok {
+               r.didRead = true
+               return r.ReadCloser
+       }
+       return t.Body
+}
+
 type transferReader struct {
        // Input
        Header        Header
@@ -264,11 +445,11 @@ type transferReader struct {
        ProtoMajor    int
        ProtoMinor    int
        // Output
-       Body             io.ReadCloser
-       ContentLength    int64
-       TransferEncoding []string
-       Close            bool
-       Trailer          Header
+       Body          io.ReadCloser
+       ContentLength int64
+       Chunked       bool
+       Close         bool
+       Trailer       Header
 }
 
 func (t *transferReader) protoAtLeast(m, n int) bool {
@@ -276,7 +457,7 @@ func (t *transferReader) protoAtLeast(m, n int) bool {
 }
 
 // bodyAllowedForStatus reports whether a given response status code
-// permits a body.  See RFC2616, section 4.4.
+// permits a body. See RFC 7230, section 3.3.
 func bodyAllowedForStatus(status int) bool {
        switch {
        case status >= 100 && status <= 199:
@@ -292,12 +473,13 @@ func bodyAllowedForStatus(status int) bool {
 var (
        suppressedHeaders304    = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
        suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
+       excludedHeadersNoBody   = map[string]bool{"Content-Length": true, "Transfer-Encoding": true}
 )
 
 func suppressedHeaders(status int) []string {
        switch {
        case status == 304:
-               // RFC 2616 section 10.3.5: "the response MUST NOT include other entity-headers"
+               // RFC 7232 section 4.1
                return suppressedHeaders304
        case !bodyAllowedForStatus(status):
                return suppressedHeadersNoBody
@@ -306,7 +488,7 @@ func suppressedHeaders(status int) []string {
 }
 
 // msg is *Request or *Response.
-func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
+func readTransfer(msg any, r *bufio.Reader) (err error) {
        t := &transferReader{RequestMethod: "GET"}
 
        // Unify input
@@ -340,18 +522,17 @@ func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
                t.ProtoMajor, t.ProtoMinor = 1, 1
        }
 
-       // Transfer encoding, content length
-       err = t.fixTransferEncoding()
-       if err != nil {
+       // Transfer-Encoding: chunked, and overriding Content-Length.
+       if err := t.parseTransferEncoding(); err != nil {
                return err
        }
 
-       realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
+       realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.Chunked)
        if err != nil {
                return err
        }
        if isResponse && t.RequestMethod == "HEAD" {
-               if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
+               if n, err := parseContentLength(t.Header["Content-Length"]); err != nil {
                        return err
                } else {
                        t.ContentLength = n
@@ -361,35 +542,33 @@ func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
        }
 
        // Trailer
-       t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
+       t.Trailer, err = fixTrailer(t.Header, t.Chunked)
        if err != nil {
                return err
        }
 
        // If there is no Content-Length or chunked Transfer-Encoding on a *Response
        // and the status is not 1xx, 204 or 304, then the body is unbounded.
-       // See RFC2616, section 4.4.
+       // See RFC 7230, section 3.3.
        switch msg.(type) {
        case *Response:
-               if realLength == -1 &&
-                       !chunked(t.TransferEncoding) &&
-                       bodyAllowedForStatus(t.StatusCode) {
+               if realLength == -1 && !t.Chunked && bodyAllowedForStatus(t.StatusCode) {
                        // Unbounded body.
                        t.Close = true
                }
        }
 
-       // Prepare body reader.  ContentLength < 0 means chunked encoding
+       // Prepare body reader. ContentLength < 0 means chunked encoding
        // or close connection when finished, since multipart is not supported yet
        switch {
-       case chunked(t.TransferEncoding):
-               if noBodyExpected(t.RequestMethod) {
-                       t.Body = eofReader
+       case t.Chunked:
+               if isResponse && (noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode)) {
+                       t.Body = NoBody
                } else {
                        t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
                }
        case realLength == 0:
-               t.Body = eofReader
+               t.Body = NoBody
        case realLength > 0:
                t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
        default:
@@ -399,7 +578,7 @@ func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
                        t.Body = &body{src: r, closing: t.Close}
                } else {
                        // Persistent connection (i.e. HTTP/1.1)
-                       t.Body = eofReader
+                       t.Body = NoBody
                }
        }
 
@@ -408,13 +587,17 @@ func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
        case *Request:
                rr.Body = t.Body
                rr.ContentLength = t.ContentLength
-               rr.TransferEncoding = t.TransferEncoding
+               if t.Chunked {
+                       rr.TransferEncoding = []string{"chunked"}
+               }
                rr.Close = t.Close
                rr.Trailer = t.Trailer
        case *Response:
                rr.Body = t.Body
                rr.ContentLength = t.ContentLength
-               rr.TransferEncoding = t.TransferEncoding
+               if t.Chunked {
+                       rr.TransferEncoding = []string{"chunked"}
+               }
                rr.Close = t.Close
                rr.Trailer = t.Trailer
        }
@@ -422,14 +605,30 @@ func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
        return nil
 }
 
-// Checks whether chunked is part of the encodings stack
+// Checks whether chunked is part of the encodings stack.
 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
 
 // Checks whether the encoding is explicitly "identity".
 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
 
-// fixTransferEncoding sanitizes t.TransferEncoding, if needed.
-func (t *transferReader) fixTransferEncoding() error {
+// unsupportedTEError reports unsupported transfer-encodings.
+type unsupportedTEError struct {
+       err string
+}
+
+func (uste *unsupportedTEError) Error() string {
+       return uste.err
+}
+
+// isUnsupportedTEError checks if the error is of type
+// unsupportedTEError. It is usually invoked with a non-nil err.
+func isUnsupportedTEError(err error) bool {
+       _, ok := err.(*unsupportedTEError)
+       return ok
+}
+
+// parseTransferEncoding sets t.Chunked based on the Transfer-Encoding header.
+func (t *transferReader) parseTransferEncoding() error {
        raw, present := t.Header["Transfer-Encoding"]
        if !present {
                return nil
@@ -441,67 +640,63 @@ func (t *transferReader) fixTransferEncoding() error {
                return nil
        }
 
-       encodings := strings.Split(raw[0], ",")
-       te := make([]string, 0, len(encodings))
-       // TODO: Even though we only support "identity" and "chunked"
-       // encodings, the loop below is designed with foresight. One
-       // invariant that must be maintained is that, if present,
-       // chunked encoding must always come first.
-       for _, encoding := range encodings {
-               encoding = strings.ToLower(strings.TrimSpace(encoding))
-               // "identity" encoding is not recorded
-               if encoding == "identity" {
-                       break
-               }
-               if encoding != "chunked" {
-                       return &badStringError{"unsupported transfer encoding", encoding}
-               }
-               te = te[0 : len(te)+1]
-               te[len(te)-1] = encoding
-       }
-       if len(te) > 1 {
-               return &badStringError{"too many transfer encodings", strings.Join(te, ",")}
-       }
-       if len(te) > 0 {
-               // RFC 7230 3.3.2 says "A sender MUST NOT send a
-               // Content-Length header field in any message that
-               // contains a Transfer-Encoding header field."
-               //
-               // but also:
-               // "If a message is received with both a
-               // Transfer-Encoding and a Content-Length header
-               // field, the Transfer-Encoding overrides the
-               // Content-Length. Such a message might indicate an
-               // attempt to perform request smuggling (Section 9.5)
-               // or response splitting (Section 9.4) and ought to be
-               // handled as an error. A sender MUST remove the
-               // received Content-Length field prior to forwarding
-               // such a message downstream."
-               //
-               // Reportedly, these appear in the wild.
-               delete(t.Header, "Content-Length")
-               t.TransferEncoding = te
-               return nil
+       // Like nginx, we only support a single Transfer-Encoding header field, and
+       // only if set to "chunked". This is one of the most security sensitive
+       // surfaces in HTTP/1.1 due to the risk of request smuggling, so we keep it
+       // strict and simple.
+       if len(raw) != 1 {
+               return &unsupportedTEError{fmt.Sprintf("too many transfer encodings: %q", raw)}
+       }
+       if !ascii.EqualFold(raw[0], "chunked") {
+               return &unsupportedTEError{fmt.Sprintf("unsupported transfer encoding: %q", raw[0])}
        }
 
+       // RFC 7230 3.3.2 says "A sender MUST NOT send a Content-Length header field
+       // in any message that contains a Transfer-Encoding header field."
+       //
+       // but also: "If a message is received with both a Transfer-Encoding and a
+       // Content-Length header field, the Transfer-Encoding overrides the
+       // Content-Length. Such a message might indicate an attempt to perform
+       // request smuggling (Section 9.5) or response splitting (Section 9.4) and
+       // ought to be handled as an error. A sender MUST remove the received
+       // Content-Length field prior to forwarding such a message downstream."
+       //
+       // Reportedly, these appear in the wild.
+       delete(t.Header, "Content-Length")
+
+       t.Chunked = true
        return nil
 }
 
-// Determine the expected body length, using RFC 2616 Section 4.4. This
+// Determine the expected body length, using RFC 7230 Section 3.3. This
 // function is not a method, because ultimately it should be shared by
 // ReadResponse and ReadRequest.
-func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
-       contentLens := header["Content-Length"]
+func fixLength(isResponse bool, status int, requestMethod string, header Header, chunked bool) (int64, error) {
        isRequest := !isResponse
-       // Logic based on response type or status
-       if noBodyExpected(requestMethod) {
-               // For HTTP requests, as part of hardening against request
-               // smuggling (RFC 7230), don't allow a Content-Length header for
-               // methods which don't permit bodies. As an exception, allow
-               // exactly one Content-Length header if its value is "0".
-               if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
-                       return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
+       contentLens := header["Content-Length"]
+
+       // Hardening against HTTP request smuggling
+       if len(contentLens) > 1 {
+               // Per RFC 7230 Section 3.3.2, prevent multiple
+               // Content-Length headers if they differ in value.
+               // If there are dups of the value, remove the dups.
+               // See Issue 16490.
+               first := textproto.TrimString(contentLens[0])
+               for _, ct := range contentLens[1:] {
+                       if first != textproto.TrimString(ct) {
+                               return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
+                       }
                }
+
+               // deduplicate Content-Length
+               header.Del("Content-Length")
+               header.Add("Content-Length", first)
+
+               contentLens = header["Content-Length"]
+       }
+
+       // Logic based on response type or status
+       if isResponse && noResponseBodyExpected(requestMethod) {
                return 0, nil
        }
        if status/100 == 1 {
@@ -512,33 +707,24 @@ func fixLength(isResponse bool, status int, requestMethod string, header Header,
                return 0, nil
        }
 
-       if len(contentLens) > 1 {
-               // harden against HTTP request smuggling. See RFC 7230.
-               return 0, errors.New("http: message cannot contain multiple Content-Length headers")
-       }
-
        // Logic based on Transfer-Encoding
-       if chunked(te) {
+       if chunked {
                return -1, nil
        }
 
-       // Logic based on Content-Length
-       var cl string
-       if len(contentLens) == 1 {
-               cl = strings.TrimSpace(contentLens[0])
-       }
-       if cl != "" {
-               n, err := parseContentLength(cl)
+       if len(contentLens) > 0 {
+               // Logic based on Content-Length
+               n, err := parseContentLength(contentLens)
                if err != nil {
                        return -1, err
                }
                return n, nil
-       } else {
-               header.Del("Content-Length")
        }
 
-       if !isResponse {
-               // RFC 2616 neither explicitly permits nor forbids an
+       header.Del("Content-Length")
+
+       if isRequest {
+               // RFC 7230 neither explicitly permits nor forbids an
                // entity-body on a GET request so we permit one if
                // declared, but we default to 0 here (not -1 below)
                // if there's no mention of a body.
@@ -554,33 +740,41 @@ func fixLength(isResponse bool, status int, requestMethod string, header Header,
 
 // Determine whether to hang up after sending a request and body, or
 // receiving a response and body
-// 'header' is the request headers
+// 'header' is the request headers.
 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
        if major < 1 {
                return true
-       } else if major == 1 && minor == 0 {
-               vv := header["Connection"]
-               if headerValuesContainsToken(vv, "close") || !headerValuesContainsToken(vv, "keep-alive") {
-                       return true
-               }
-               return false
-       } else {
-               if headerValuesContainsToken(header["Connection"], "close") {
-                       if removeCloseHeader {
-                               header.Del("Connection")
-                       }
-                       return true
-               }
        }
-       return false
+
+       conv := header["Connection"]
+       hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
+       if major == 1 && minor == 0 {
+               return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
+       }
+
+       if hasClose && removeCloseHeader {
+               header.Del("Connection")
+       }
+
+       return hasClose
 }
 
-// Parse the trailer header
-func fixTrailer(header Header, te []string) (Header, error) {
+// Parse the trailer header.
+func fixTrailer(header Header, chunked bool) (Header, error) {
        vv, ok := header["Trailer"]
        if !ok {
                return nil, nil
        }
+       if !chunked {
+               // Trailer and no chunking:
+               // this is an invalid use case for trailer header.
+               // Nevertheless, no error will be returned and we
+               // let users decide if this is a valid HTTP message.
+               // The Trailer header will be kept in Response.Header
+               // but not populate Response.Trailer.
+               // See issue #27197.
+               return nil, nil
+       }
        header.Del("Trailer")
 
        trailer := make(Header)
@@ -591,7 +785,7 @@ func fixTrailer(header Header, te []string) (Header, error) {
                        switch key {
                        case "Transfer-Encoding", "Trailer", "Content-Length":
                                if err == nil {
-                                       err = &badStringError{"bad trailer key", key}
+                                       err = badStringError("bad trailer key", key)
                                        return
                                }
                        }
@@ -604,10 +798,6 @@ func fixTrailer(header Header, te []string) (Header, error) {
        if len(trailer) == 0 {
                return nil, nil
        }
-       if !chunked(te) {
-               // Trailer and no chunking
-               return nil, ErrUnexpectedTrailer
-       }
        return trailer, nil
 }
 
@@ -616,15 +806,16 @@ func fixTrailer(header Header, te []string) (Header, error) {
 // and then reads the trailer if necessary.
 type body struct {
        src          io.Reader
-       hdr          interface{}   // non-nil (Response or Request) value means read trailer
+       hdr          any           // non-nil (Response or Request) value means read trailer
        r            *bufio.Reader // underlying wire-format reader for the trailer
        closing      bool          // is the connection to be closed after reading body?
        doEarlyClose bool          // whether Close should stop early
 
-       mu         sync.Mutex // guards closed, and calls to Read and Close
+       mu         sync.Mutex // guards following, and calls to Read and Close
        sawEOF     bool
        closed     bool
-       earlyClose bool // Close called and we didn't read to the end of src
+       earlyClose bool   // Close called and we didn't read to the end of src
+       onHitEOF   func() // if non-nil, func to call when EOF is Read
 }
 
 // ErrBodyReadAfterClose is returned when reading a Request or Response
@@ -684,6 +875,10 @@ func (b *body) readLocked(p []byte) (n int, err error) {
                }
        }
 
+       if b.sawEOF && b.onHitEOF != nil {
+               b.onHitEOF()
+       }
+
        return n, err
 }
 
@@ -724,11 +919,11 @@ func (b *body) readTrailer() error {
        }
 
        // Make sure there's a header terminator coming up, to prevent
-       // a DoS with an unbounded size Trailer.  It's not easy to
+       // a DoS with an unbounded size Trailer. It's not easy to
        // slip in a LimitReader here, as textproto.NewReader requires
-       // a concrete *bufio.Reader.  Also, we can't get all the way
+       // a concrete *bufio.Reader. Also, we can't get all the way
        // back up to our conn's LimitedReader that *might* be backing
-       // this bufio.Reader.  Instead, a hack: we iteratively Peek up
+       // this bufio.Reader. Instead, a hack: we iteratively Peek up
        // to the bufio.Reader's max size, looking for a double CRLF.
        // This limits the trailer to the underlying buffer size, typically 4kB.
        if !seeUpcomingDoubleCRLF(b.r) {
@@ -785,7 +980,7 @@ func (b *body) Close() error {
                // no trailer and closing the connection next.
                // no point in reading to EOF.
        case b.doEarlyClose:
-               // Read up to maxPostHandlerReadBytes bytes of the body, looking for
+               // Read up to maxPostHandlerReadBytes bytes of the body, looking
                // for EOF (and trailers), so we can re-use this connection.
                if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
                        // There was a declared Content-Length, and we have more bytes remaining
@@ -795,7 +990,7 @@ func (b *body) Close() error {
                        var n int64
                        // Consume the body, or, which will also lead to us reading
                        // the trailer headers after the body, if present.
-                       n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
+                       n, err = io.CopyN(io.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
                        if err == io.EOF {
                                err = nil
                        }
@@ -806,7 +1001,7 @@ func (b *body) Close() error {
        default:
                // Fully consume the body, which will also lead to us reading
                // the trailer headers after the body, if present.
-               _, err = io.Copy(ioutil.Discard, bodyLocked{b})
+               _, err = io.Copy(io.Discard, bodyLocked{b})
        }
        b.closed = true
        return err
@@ -818,7 +1013,21 @@ func (b *body) didEarlyClose() bool {
        return b.earlyClose
 }
 
-// bodyLocked is a io.Reader reading from a *body when its mutex is
+// bodyRemains reports whether future Read calls might
+// yield data.
+func (b *body) bodyRemains() bool {
+       b.mu.Lock()
+       defer b.mu.Unlock()
+       return !b.sawEOF
+}
+
+func (b *body) registerOnHitEOF(fn func()) {
+       b.mu.Lock()
+       defer b.mu.Unlock()
+       b.onHitEOF = fn
+}
+
+// bodyLocked is an io.Reader reading from a *body when its mutex is
 // already held.
 type bodyLocked struct {
        b *body
@@ -831,17 +1040,99 @@ func (bl bodyLocked) Read(p []byte) (n int, err error) {
        return bl.b.readLocked(p)
 }
 
-// parseContentLength trims whitespace from s and returns -1 if no value
-// is set, or the value if it's >= 0.
-func parseContentLength(cl string) (int64, error) {
-       cl = strings.TrimSpace(cl)
-       if cl == "" {
+var laxContentLength = godebug.New("httplaxcontentlength")
+
+// parseContentLength checks that the header is valid and then trims
+// whitespace. It returns -1 if no value is set otherwise the value
+// if it's >= 0.
+func parseContentLength(clHeaders []string) (int64, error) {
+       if len(clHeaders) == 0 {
                return -1, nil
        }
-       n, err := strconv.ParseInt(cl, 10, 64)
-       if err != nil || n < 0 {
-               return 0, &badStringError{"bad Content-Length", cl}
+       cl := textproto.TrimString(clHeaders[0])
+
+       // The Content-Length must be a valid numeric value.
+       // See: https://datatracker.ietf.org/doc/html/rfc2616/#section-14.13
+       if cl == "" {
+               if laxContentLength.Value() == "1" {
+                       laxContentLength.IncNonDefault()
+                       return -1, nil
+               }
+               return 0, badStringError("invalid empty Content-Length", cl)
+       }
+       n, err := strconv.ParseUint(cl, 10, 63)
+       if err != nil {
+               return 0, badStringError("bad Content-Length", cl)
+       }
+       return int64(n), nil
+}
+
+// finishAsyncByteRead finishes reading the 1-byte sniff
+// from the ContentLength==0, Body!=nil case.
+type finishAsyncByteRead struct {
+       tw *transferWriter
+}
+
+func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
+       if len(p) == 0 {
+               return
+       }
+       rres := <-fr.tw.ByteReadCh
+       n, err = rres.n, rres.err
+       if n == 1 {
+               p[0] = rres.b
+       }
+       if err == nil {
+               err = io.EOF
+       }
+       return
+}
+
+var nopCloserType = reflect.TypeOf(io.NopCloser(nil))
+var nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct {
+       io.Reader
+       io.WriterTo
+}{}))
+
+// unwrapNopCloser return the underlying reader and true if r is a NopCloser
+// else it return false.
+func unwrapNopCloser(r io.Reader) (underlyingReader io.Reader, isNopCloser bool) {
+       switch reflect.TypeOf(r) {
+       case nopCloserType, nopCloserWriterToType:
+               return reflect.ValueOf(r).Field(0).Interface().(io.Reader), true
+       default:
+               return nil, false
+       }
+}
+
+// isKnownInMemoryReader reports whether r is a type known to not
+// block on Read. Its caller uses this as an optional optimization to
+// send fewer TCP packets.
+func isKnownInMemoryReader(r io.Reader) bool {
+       switch r.(type) {
+       case *bytes.Reader, *bytes.Buffer, *strings.Reader:
+               return true
+       }
+       if r, ok := unwrapNopCloser(r); ok {
+               return isKnownInMemoryReader(r)
        }
-       return n, nil
+       if r, ok := r.(*readTrackingBody); ok {
+               return isKnownInMemoryReader(r.ReadCloser)
+       }
+       return false
+}
+
+// bufioFlushWriter is an io.Writer wrapper that flushes all writes
+// on its wrapped writer if it's a *bufio.Writer.
+type bufioFlushWriter struct{ w io.Writer }
 
+func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
+       n, err = fw.w.Write(p)
+       if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
+               ferr := bw.Flush()
+               if ferr != nil && err == nil {
+                       err = ferr
+               }
+       }
+       return
 }