]> 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 fbb0c39829d729ca246c5011210b5af245abf355..dffff56b31e94ff8345eedb769948032bf34d9e0 100644 (file)
@@ -9,9 +9,11 @@ import (
        "bytes"
        "errors"
        "fmt"
+       "internal/godebug"
        "io"
        "net/http/httptrace"
        "net/http/internal"
+       "net/http/internal/ascii"
        "net/textproto"
        "reflect"
        "sort"
@@ -72,7 +74,7 @@ type transferWriter struct {
        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
@@ -195,10 +197,11 @@ func (t *transferWriter) shouldSendChunkedRequestBody() bool {
 // 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.
+//   - 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() {
@@ -211,6 +214,7 @@ func (t *transferWriter) probeRequestBody() {
                        rres.b = buf[0]
                }
                t.ByteReadCh <- rres
+               close(t.ByteReadCh)
        }(t.Body)
        timer := time.NewTimer(200 * time.Millisecond)
        select {
@@ -406,21 +410,25 @@ func (t *transferWriter) writeBody(w io.Writer) (err error) {
 //
 // This function is only intended for use in writeBody.
 func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
-       n, err = io.Copy(dst, src)
+       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
 }
 
-// unwrapBodyReader unwraps the body's inner reader if it's a
+// 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 reflect.TypeOf(t.Body) == nopCloserType {
-               return reflect.ValueOf(t.Body).Field(0).Interface().(io.Reader)
+       if r, ok := unwrapNopCloser(t.Body); ok {
+               return r
        }
        if r, ok := t.Body.(*readTrackingBody); ok {
                r.didRead = true
@@ -465,6 +473,7 @@ 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 {
@@ -479,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
@@ -523,7 +532,7 @@ func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
                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
@@ -553,7 +562,7 @@ func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
        // or close connection when finished, since multipart is not supported yet
        switch {
        case t.Chunked:
-               if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
+               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}
@@ -596,7 +605,7 @@ 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".
@@ -638,7 +647,7 @@ func (t *transferReader) parseTransferEncoding() error {
        if len(raw) != 1 {
                return &unsupportedTEError{fmt.Sprintf("too many transfer encodings: %q", raw)}
        }
-       if strings.ToLower(textproto.TrimString(raw[0])) != "chunked" {
+       if !ascii.EqualFold(raw[0], "chunked") {
                return &unsupportedTEError{fmt.Sprintf("unsupported transfer encoding: %q", raw[0])}
        }
 
@@ -687,14 +696,7 @@ func fixLength(isResponse bool, status int, requestMethod string, header Header,
        }
 
        // Logic based on response type or status
-       if noResponseBodyExpected(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)
-               }
+       if isResponse && noResponseBodyExpected(requestMethod) {
                return 0, nil
        }
        if status/100 == 1 {
@@ -710,18 +712,15 @@ func fixLength(isResponse bool, status int, requestMethod string, header Header,
                return -1, nil
        }
 
-       // Logic based on Content-Length
-       var cl string
-       if len(contentLens) == 1 {
-               cl = textproto.TrimString(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
        }
+
        header.Del("Content-Length")
 
        if isRequest {
@@ -741,7 +740,7 @@ 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
@@ -760,7 +759,7 @@ func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
        return hasClose
 }
 
-// Parse the trailer header
+// Parse the trailer header.
 func fixTrailer(header Header, chunked bool) (Header, error) {
        vv, ok := header["Trailer"]
        if !ok {
@@ -807,7 +806,7 @@ func fixTrailer(header Header, chunked bool) (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
@@ -1028,7 +1027,7 @@ func (b *body) registerOnHitEOF(fn func()) {
        b.onHitEOF = fn
 }
 
-// bodyLocked is a io.Reader reading from a *body when its mutex is
+// bodyLocked is an io.Reader reading from a *body when its mutex is
 // already held.
 type bodyLocked struct {
        b *body
@@ -1041,19 +1040,31 @@ 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 = textproto.TrimString(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
        }
+       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
@@ -1071,10 +1082,28 @@ func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
        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
@@ -1084,8 +1113,8 @@ func isKnownInMemoryReader(r io.Reader) bool {
        case *bytes.Reader, *bytes.Buffer, *strings.Reader:
                return true
        }
-       if reflect.TypeOf(r) == nopCloserType {
-               return isKnownInMemoryReader(reflect.ValueOf(r).Field(0).Interface().(io.Reader))
+       if r, ok := unwrapNopCloser(r); ok {
+               return isKnownInMemoryReader(r)
        }
        if r, ok := r.(*readTrackingBody); ok {
                return isKnownInMemoryReader(r.ReadCloser)