]> 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 4583c6b453d08500d42824b55cb8467cb3ba6d7a..dffff56b31e94ff8345eedb769948032bf34d9e0 100644 (file)
@@ -9,6 +9,7 @@ import (
        "bytes"
        "errors"
        "fmt"
+       "internal/godebug"
        "io"
        "net/http/httptrace"
        "net/http/internal"
@@ -409,14 +410,18 @@ 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.
 //
@@ -527,7 +532,7 @@ func readTransfer(msg any, 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
@@ -557,7 +562,7 @@ func readTransfer(msg any, 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}
@@ -600,7 +605,7 @@ func readTransfer(msg any, 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".
@@ -691,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 {
@@ -714,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 {
@@ -745,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
@@ -764,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 {
@@ -1045,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
@@ -1088,7 +1095,7 @@ var nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct {
 }{}))
 
 // unwrapNopCloser return the underlying reader and true if r is a NopCloser
-// else it return false
+// else it return false.
 func unwrapNopCloser(r io.Reader) (underlyingReader io.Reader, isNopCloser bool) {
        switch reflect.TypeOf(r) {
        case nopCloserType, nopCloserWriterToType: