1 // Copyright 2009 The Go Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style
3 // license that can be found in the LICENSE file.
16 "net/http/internal/ascii"
25 "golang.org/x/net/http/httpguts"
28 // ErrLineTooLong is returned when reading request or response bodies
29 // with malformed chunked encoding.
30 var ErrLineTooLong = internal.ErrLineTooLong
32 type errorReader struct {
36 func (r errorReader) Read(p []byte) (n int, err error) {
40 type byteReader struct {
45 func (br *byteReader) Read(p []byte) (n int, err error) {
57 // transferWriter inspects the fields of a user-supplied Request or Response,
58 // sanitizes them without changing the user object and provides methods for
59 // writing the respective header, body and trailer in wire format.
60 type transferWriter struct {
65 ContentLength int64 // -1 means unknown, 0 means exactly none
67 TransferEncoding []string
71 bodyReadError error // any non-EOF error from reading Body
73 FlushHeaders bool // flush headers to network before body
74 ByteReadCh chan readResult // non-nil if probeRequestBody called
77 func newTransferWriter(r any) (t *transferWriter, err error) {
80 // Extract relevant fields
81 atLeastHTTP11 := false
82 switch rr := r.(type) {
84 if rr.ContentLength != 0 && rr.Body == nil {
85 return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
87 t.Method = valueOrDefault(rr.Method, "GET")
89 t.TransferEncoding = rr.TransferEncoding
91 t.Trailer = rr.Trailer
93 t.BodyCloser = rr.Body
94 t.ContentLength = rr.outgoingLength()
95 if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
96 t.TransferEncoding = []string{"chunked"}
98 // If there's a body, conservatively flush the headers
99 // to any bufio.Writer we're writing to, just in case
100 // the server needs the headers early, before we copy
101 // the body and possibly block. We make an exception
102 // for the common standard library in-memory types,
103 // though, to avoid unnecessary TCP packets on the
104 // wire. (Issue 22088.)
105 if t.ContentLength != 0 && !isKnownInMemoryReader(t.Body) {
106 t.FlushHeaders = true
109 atLeastHTTP11 = true // Transport requests are always 1.1 or 2.0
112 if rr.Request != nil {
113 t.Method = rr.Request.Method
116 t.BodyCloser = rr.Body
117 t.ContentLength = rr.ContentLength
119 t.TransferEncoding = rr.TransferEncoding
121 t.Trailer = rr.Trailer
122 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
123 t.ResponseToHEAD = noResponseBodyExpected(t.Method)
126 // Sanitize Body,ContentLength,TransferEncoding
127 if t.ResponseToHEAD {
129 if chunked(t.TransferEncoding) {
133 if !atLeastHTTP11 || t.Body == nil {
134 t.TransferEncoding = nil
136 if chunked(t.TransferEncoding) {
138 } else if t.Body == nil { // no chunking, no body
144 if !chunked(t.TransferEncoding) {
151 // shouldSendChunkedRequestBody reports whether we should try to send a
152 // chunked request body to the server. In particular, the case we really
153 // want to prevent is sending a GET or other typically-bodyless request to a
154 // server with a chunked body when the body has zero bytes, since GETs with
155 // bodies (while acceptable according to specs), even zero-byte chunked
156 // bodies, are approximately never seen in the wild and confuse most
157 // servers. See Issue 18257, as one example.
159 // The only reason we'd send such a request is if the user set the Body to a
160 // non-nil value (say, io.NopCloser(bytes.NewReader(nil))) and didn't
161 // set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
162 // there's bytes to send.
164 // This code tries to read a byte from the Request.Body in such cases to see
165 // whether the body actually has content (super rare) or is actually just
166 // a non-nil content-less ReadCloser (the more common case). In that more
167 // common case, we act as if their Body were nil instead, and don't send
169 func (t *transferWriter) shouldSendChunkedRequestBody() bool {
170 // Note that t.ContentLength is the corrected content length
171 // from rr.outgoingLength, so 0 actually means zero, not unknown.
172 if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
175 if t.Method == "CONNECT" {
178 if requestMethodUsuallyLacksBody(t.Method) {
179 // Only probe the Request.Body for GET/HEAD/DELETE/etc
180 // requests, because it's only those types of requests
181 // that confuse servers.
182 t.probeRequestBody() // adjusts t.Body, t.ContentLength
185 // For all other request types (PUT, POST, PATCH, or anything
186 // made-up we've never heard of), assume it's normal and the server
187 // can deal with a chunked request body. Maybe we'll adjust this
192 // probeRequestBody reads a byte from t.Body to see whether it's empty
193 // (returns io.EOF right away).
195 // But because we've had problems with this blocking users in the past
196 // (issue 17480) when the body is a pipe (perhaps waiting on the response
197 // headers before the pipe is fed data), we need to be careful and bound how
198 // long we wait for it. This delay will only affect users if all the following
200 // - the request body blocks
201 // - the content length is not set (or set to -1)
202 // - the method doesn't usually have a body (GET, HEAD, DELETE, ...)
203 // - there is no transfer-encoding=chunked already set.
205 // In other words, this delay will not normally affect anybody, and there
206 // are workarounds if it does.
207 func (t *transferWriter) probeRequestBody() {
208 t.ByteReadCh = make(chan readResult, 1)
209 go func(body io.Reader) {
212 rres.n, rres.err = body.Read(buf[:])
219 timer := time.NewTimer(200 * time.Millisecond)
221 case rres := <-t.ByteReadCh:
223 if rres.n == 0 && rres.err == io.EOF {
227 } else if rres.n == 1 {
229 t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
231 t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
233 } else if rres.err != nil {
234 t.Body = errorReader{rres.err}
237 // Too slow. Don't wait. Read it later, and keep
238 // assuming that this is ContentLength == -1
239 // (unknown), which means we'll send a
240 // "Transfer-Encoding: chunked" header.
241 t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
242 // Request that Request.Write flush the headers to the
243 // network before writing the body, since our body may not
244 // become readable until it's seen the response headers.
245 t.FlushHeaders = true
249 func noResponseBodyExpected(requestMethod string) bool {
250 return requestMethod == "HEAD"
253 func (t *transferWriter) shouldSendContentLength() bool {
254 if chunked(t.TransferEncoding) {
257 if t.ContentLength > 0 {
260 if t.ContentLength < 0 {
263 // Many servers expect a Content-Length for these methods
264 if t.Method == "POST" || t.Method == "PUT" || t.Method == "PATCH" {
267 if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
268 if t.Method == "GET" || t.Method == "HEAD" {
277 func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error {
278 if t.Close && !hasToken(t.Header.get("Connection"), "close") {
279 if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
282 if trace != nil && trace.WroteHeaderField != nil {
283 trace.WroteHeaderField("Connection", []string{"close"})
287 // Write Content-Length and/or Transfer-Encoding whose values are a
288 // function of the sanitized field triple (Body, ContentLength,
290 if t.shouldSendContentLength() {
291 if _, err := io.WriteString(w, "Content-Length: "); err != nil {
294 if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
297 if trace != nil && trace.WroteHeaderField != nil {
298 trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
300 } else if chunked(t.TransferEncoding) {
301 if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
304 if trace != nil && trace.WroteHeaderField != nil {
305 trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
309 // Write Trailer header
310 if t.Trailer != nil {
311 keys := make([]string, 0, len(t.Trailer))
312 for k := range t.Trailer {
313 k = CanonicalHeaderKey(k)
315 case "Transfer-Encoding", "Trailer", "Content-Length":
316 return badStringError("invalid Trailer key", k)
318 keys = append(keys, k)
322 // TODO: could do better allocation-wise here, but trailers are rare,
323 // so being lazy for now.
324 if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
327 if trace != nil && trace.WroteHeaderField != nil {
328 trace.WroteHeaderField("Trailer", keys)
336 // always closes t.BodyCloser
337 func (t *transferWriter) writeBody(w io.Writer) (err error) {
341 if closed || t.BodyCloser == nil {
344 if closeErr := t.BodyCloser.Close(); closeErr != nil && err == nil {
349 // Write body. We "unwrap" the body first if it was wrapped in a
350 // nopCloser or readTrackingBody. This is to ensure that we can take advantage of
351 // OS-level optimizations in the event that the body is an
354 var body = t.unwrapBody()
355 if chunked(t.TransferEncoding) {
356 if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
357 w = &internal.FlushAfterChunkWriter{Writer: bw}
359 cw := internal.NewChunkedWriter(w)
360 _, err = t.doBodyCopy(cw, body)
364 } else if t.ContentLength == -1 {
366 if t.Method == "CONNECT" {
367 dst = bufioFlushWriter{dst}
369 ncopy, err = t.doBodyCopy(dst, body)
371 ncopy, err = t.doBodyCopy(w, io.LimitReader(body, t.ContentLength))
376 nextra, err = t.doBodyCopy(io.Discard, body)
383 if t.BodyCloser != nil {
385 if err := t.BodyCloser.Close(); err != nil {
390 if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
391 return fmt.Errorf("http: ContentLength=%d with Body length %d",
392 t.ContentLength, ncopy)
395 if chunked(t.TransferEncoding) {
396 // Write Trailer header
397 if t.Trailer != nil {
398 if err := t.Trailer.Write(w); err != nil {
402 // Last chunk, empty trailer
403 _, err = io.WriteString(w, "\r\n")
408 // doBodyCopy wraps a copy operation, with any resulting error also
409 // being saved in bodyReadError.
411 // This function is only intended for use in writeBody.
412 func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
413 bufp := copyBufPool.Get().(*[]byte)
415 defer copyBufPool.Put(bufp)
417 n, err = io.CopyBuffer(dst, src, buf)
418 if err != nil && err != io.EOF {
419 t.bodyReadError = err
424 // unwrapBody unwraps the body's inner reader if it's a
425 // nopCloser. This is to ensure that body writes sourced from local
426 // files (*os.File types) are properly optimized.
428 // This function is only intended for use in writeBody.
429 func (t *transferWriter) unwrapBody() io.Reader {
430 if r, ok := unwrapNopCloser(t.Body); ok {
433 if r, ok := t.Body.(*readTrackingBody); ok {
440 type transferReader struct {
455 func (t *transferReader) protoAtLeast(m, n int) bool {
456 return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
459 // bodyAllowedForStatus reports whether a given response status code
460 // permits a body. See RFC 7230, section 3.3.
461 func bodyAllowedForStatus(status int) bool {
463 case status >= 100 && status <= 199:
474 suppressedHeaders304 = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
475 suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
476 excludedHeadersNoBody = map[string]bool{"Content-Length": true, "Transfer-Encoding": true}
479 func suppressedHeaders(status int) []string {
482 // RFC 7232 section 4.1
483 return suppressedHeaders304
484 case !bodyAllowedForStatus(status):
485 return suppressedHeadersNoBody
490 // msg is *Request or *Response.
491 func readTransfer(msg any, r *bufio.Reader) (err error) {
492 t := &transferReader{RequestMethod: "GET"}
496 switch rr := msg.(type) {
499 t.StatusCode = rr.StatusCode
500 t.ProtoMajor = rr.ProtoMajor
501 t.ProtoMinor = rr.ProtoMinor
502 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
504 if rr.Request != nil {
505 t.RequestMethod = rr.Request.Method
509 t.RequestMethod = rr.Method
510 t.ProtoMajor = rr.ProtoMajor
511 t.ProtoMinor = rr.ProtoMinor
512 // Transfer semantics for Requests are exactly like those for
513 // Responses with status code 200, responding to a GET method
517 panic("unexpected type")
520 // Default to HTTP/1.1
521 if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
522 t.ProtoMajor, t.ProtoMinor = 1, 1
525 // Transfer-Encoding: chunked, and overriding Content-Length.
526 if err := t.parseTransferEncoding(); err != nil {
530 realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.Chunked)
534 if isResponse && t.RequestMethod == "HEAD" {
535 if n, err := parseContentLength(t.Header["Content-Length"]); err != nil {
541 t.ContentLength = realLength
545 t.Trailer, err = fixTrailer(t.Header, t.Chunked)
550 // If there is no Content-Length or chunked Transfer-Encoding on a *Response
551 // and the status is not 1xx, 204 or 304, then the body is unbounded.
552 // See RFC 7230, section 3.3.
555 if realLength == -1 && !t.Chunked && bodyAllowedForStatus(t.StatusCode) {
561 // Prepare body reader. ContentLength < 0 means chunked encoding
562 // or close connection when finished, since multipart is not supported yet
565 if isResponse && (noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode)) {
568 t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
570 case realLength == 0:
573 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
575 // realLength < 0, i.e. "Content-Length" not mentioned in header
577 // Close semantics (i.e. HTTP/1.0)
578 t.Body = &body{src: r, closing: t.Close}
580 // Persistent connection (i.e. HTTP/1.1)
586 switch rr := msg.(type) {
589 rr.ContentLength = t.ContentLength
591 rr.TransferEncoding = []string{"chunked"}
594 rr.Trailer = t.Trailer
597 rr.ContentLength = t.ContentLength
599 rr.TransferEncoding = []string{"chunked"}
602 rr.Trailer = t.Trailer
608 // Checks whether chunked is part of the encodings stack.
609 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
611 // Checks whether the encoding is explicitly "identity".
612 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
614 // unsupportedTEError reports unsupported transfer-encodings.
615 type unsupportedTEError struct {
619 func (uste *unsupportedTEError) Error() string {
623 // isUnsupportedTEError checks if the error is of type
624 // unsupportedTEError. It is usually invoked with a non-nil err.
625 func isUnsupportedTEError(err error) bool {
626 _, ok := err.(*unsupportedTEError)
630 // parseTransferEncoding sets t.Chunked based on the Transfer-Encoding header.
631 func (t *transferReader) parseTransferEncoding() error {
632 raw, present := t.Header["Transfer-Encoding"]
636 delete(t.Header, "Transfer-Encoding")
638 // Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
639 if !t.protoAtLeast(1, 1) {
643 // Like nginx, we only support a single Transfer-Encoding header field, and
644 // only if set to "chunked". This is one of the most security sensitive
645 // surfaces in HTTP/1.1 due to the risk of request smuggling, so we keep it
646 // strict and simple.
648 return &unsupportedTEError{fmt.Sprintf("too many transfer encodings: %q", raw)}
650 if !ascii.EqualFold(raw[0], "chunked") {
651 return &unsupportedTEError{fmt.Sprintf("unsupported transfer encoding: %q", raw[0])}
654 // RFC 7230 3.3.2 says "A sender MUST NOT send a Content-Length header field
655 // in any message that contains a Transfer-Encoding header field."
657 // but also: "If a message is received with both a Transfer-Encoding and a
658 // Content-Length header field, the Transfer-Encoding overrides the
659 // Content-Length. Such a message might indicate an attempt to perform
660 // request smuggling (Section 9.5) or response splitting (Section 9.4) and
661 // ought to be handled as an error. A sender MUST remove the received
662 // Content-Length field prior to forwarding such a message downstream."
664 // Reportedly, these appear in the wild.
665 delete(t.Header, "Content-Length")
671 // Determine the expected body length, using RFC 7230 Section 3.3. This
672 // function is not a method, because ultimately it should be shared by
673 // ReadResponse and ReadRequest.
674 func fixLength(isResponse bool, status int, requestMethod string, header Header, chunked bool) (int64, error) {
675 isRequest := !isResponse
676 contentLens := header["Content-Length"]
678 // Hardening against HTTP request smuggling
679 if len(contentLens) > 1 {
680 // Per RFC 7230 Section 3.3.2, prevent multiple
681 // Content-Length headers if they differ in value.
682 // If there are dups of the value, remove the dups.
684 first := textproto.TrimString(contentLens[0])
685 for _, ct := range contentLens[1:] {
686 if first != textproto.TrimString(ct) {
687 return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
691 // deduplicate Content-Length
692 header.Del("Content-Length")
693 header.Add("Content-Length", first)
695 contentLens = header["Content-Length"]
698 // Logic based on response type or status
699 if isResponse && noResponseBodyExpected(requestMethod) {
710 // Logic based on Transfer-Encoding
715 if len(contentLens) > 0 {
716 // Logic based on Content-Length
717 n, err := parseContentLength(contentLens)
724 header.Del("Content-Length")
727 // RFC 7230 neither explicitly permits nor forbids an
728 // entity-body on a GET request so we permit one if
729 // declared, but we default to 0 here (not -1 below)
730 // if there's no mention of a body.
731 // Likewise, all other request methods are assumed to have
732 // no body if neither Transfer-Encoding chunked nor a
733 // Content-Length are set.
737 // Body-EOF logic based on other methods (like closing, or chunked coding)
741 // Determine whether to hang up after sending a request and body, or
742 // receiving a response and body
743 // 'header' is the request headers.
744 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
749 conv := header["Connection"]
750 hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
751 if major == 1 && minor == 0 {
752 return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
755 if hasClose && removeCloseHeader {
756 header.Del("Connection")
762 // Parse the trailer header.
763 func fixTrailer(header Header, chunked bool) (Header, error) {
764 vv, ok := header["Trailer"]
769 // Trailer and no chunking:
770 // this is an invalid use case for trailer header.
771 // Nevertheless, no error will be returned and we
772 // let users decide if this is a valid HTTP message.
773 // The Trailer header will be kept in Response.Header
774 // but not populate Response.Trailer.
778 header.Del("Trailer")
780 trailer := make(Header)
782 for _, v := range vv {
783 foreachHeaderElement(v, func(key string) {
784 key = CanonicalHeaderKey(key)
786 case "Transfer-Encoding", "Trailer", "Content-Length":
788 err = badStringError("bad trailer key", key)
798 if len(trailer) == 0 {
804 // body turns a Reader into a ReadCloser.
805 // Close ensures that the body has been fully read
806 // and then reads the trailer if necessary.
809 hdr any // non-nil (Response or Request) value means read trailer
810 r *bufio.Reader // underlying wire-format reader for the trailer
811 closing bool // is the connection to be closed after reading body?
812 doEarlyClose bool // whether Close should stop early
814 mu sync.Mutex // guards following, and calls to Read and Close
817 earlyClose bool // Close called and we didn't read to the end of src
818 onHitEOF func() // if non-nil, func to call when EOF is Read
821 // ErrBodyReadAfterClose is returned when reading a Request or Response
822 // Body after the body has been closed. This typically happens when the body is
823 // read after an HTTP Handler calls WriteHeader or Write on its
825 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
827 func (b *body) Read(p []byte) (n int, err error) {
831 return 0, ErrBodyReadAfterClose
833 return b.readLocked(p)
837 func (b *body) readLocked(p []byte) (n int, err error) {
841 n, err = b.src.Read(p)
845 // Chunked case. Read the trailer.
847 if e := b.readTrailer(); e != nil {
849 // Something went wrong in the trailer, we must not allow any
850 // further reads of any kind to succeed from body, nor any
851 // subsequent requests on the server connection. See
852 // golang.org/issue/12027
858 // If the server declared the Content-Length, our body is a LimitedReader
859 // and we need to check whether this EOF arrived early.
860 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
861 err = io.ErrUnexpectedEOF
866 // If we can return an EOF here along with the read data, do
867 // so. This is optional per the io.Reader contract, but doing
868 // so helps the HTTP transport code recycle its connection
869 // earlier (since it will see this EOF itself), even if the
870 // client doesn't do future reads or Close.
871 if err == nil && n > 0 {
872 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
878 if b.sawEOF && b.onHitEOF != nil {
886 singleCRLF = []byte("\r\n")
887 doubleCRLF = []byte("\r\n\r\n")
890 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
891 for peekSize := 4; ; peekSize++ {
892 // This loop stops when Peek returns an error,
893 // which it does when r's buffer has been filled.
894 buf, err := r.Peek(peekSize)
895 if bytes.HasSuffix(buf, doubleCRLF) {
905 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
907 func (b *body) readTrailer() error {
908 // The common case, since nobody uses trailers.
909 buf, err := b.r.Peek(2)
910 if bytes.Equal(buf, singleCRLF) {
921 // Make sure there's a header terminator coming up, to prevent
922 // a DoS with an unbounded size Trailer. It's not easy to
923 // slip in a LimitReader here, as textproto.NewReader requires
924 // a concrete *bufio.Reader. Also, we can't get all the way
925 // back up to our conn's LimitedReader that *might* be backing
926 // this bufio.Reader. Instead, a hack: we iteratively Peek up
927 // to the bufio.Reader's max size, looking for a double CRLF.
928 // This limits the trailer to the underlying buffer size, typically 4kB.
929 if !seeUpcomingDoubleCRLF(b.r) {
930 return errors.New("http: suspiciously long trailer after chunked body")
933 hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
940 switch rr := b.hdr.(type) {
942 mergeSetHeader(&rr.Trailer, Header(hdr))
944 mergeSetHeader(&rr.Trailer, Header(hdr))
949 func mergeSetHeader(dst *Header, src Header) {
954 for k, vv := range src {
959 // unreadDataSizeLocked returns the number of bytes of unread input.
960 // It returns -1 if unknown.
961 // b.mu must be held.
962 func (b *body) unreadDataSizeLocked() int64 {
963 if lr, ok := b.src.(*io.LimitedReader); ok {
969 func (b *body) Close() error {
978 // Already saw EOF, so no need going to look for it.
979 case b.hdr == nil && b.closing:
980 // no trailer and closing the connection next.
981 // no point in reading to EOF.
983 // Read up to maxPostHandlerReadBytes bytes of the body, looking
984 // for EOF (and trailers), so we can re-use this connection.
985 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
986 // There was a declared Content-Length, and we have more bytes remaining
987 // than our maxPostHandlerReadBytes tolerance. So, give up.
991 // Consume the body, or, which will also lead to us reading
992 // the trailer headers after the body, if present.
993 n, err = io.CopyN(io.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
997 if n == maxPostHandlerReadBytes {
1002 // Fully consume the body, which will also lead to us reading
1003 // the trailer headers after the body, if present.
1004 _, err = io.Copy(io.Discard, bodyLocked{b})
1010 func (b *body) didEarlyClose() bool {
1016 // bodyRemains reports whether future Read calls might
1018 func (b *body) bodyRemains() bool {
1024 func (b *body) registerOnHitEOF(fn func()) {
1030 // bodyLocked is an io.Reader reading from a *body when its mutex is
1032 type bodyLocked struct {
1036 func (bl bodyLocked) Read(p []byte) (n int, err error) {
1038 return 0, ErrBodyReadAfterClose
1040 return bl.b.readLocked(p)
1043 var laxContentLength = godebug.New("httplaxcontentlength")
1045 // parseContentLength checks that the header is valid and then trims
1046 // whitespace. It returns -1 if no value is set otherwise the value
1048 func parseContentLength(clHeaders []string) (int64, error) {
1049 if len(clHeaders) == 0 {
1052 cl := textproto.TrimString(clHeaders[0])
1054 // The Content-Length must be a valid numeric value.
1055 // See: https://datatracker.ietf.org/doc/html/rfc2616/#section-14.13
1057 if laxContentLength.Value() == "1" {
1058 laxContentLength.IncNonDefault()
1061 return 0, badStringError("invalid empty Content-Length", cl)
1063 n, err := strconv.ParseUint(cl, 10, 63)
1065 return 0, badStringError("bad Content-Length", cl)
1067 return int64(n), nil
1070 // finishAsyncByteRead finishes reading the 1-byte sniff
1071 // from the ContentLength==0, Body!=nil case.
1072 type finishAsyncByteRead struct {
1076 func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1080 rres := <-fr.tw.ByteReadCh
1081 n, err = rres.n, rres.err
1091 var nopCloserType = reflect.TypeOf(io.NopCloser(nil))
1092 var nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct {
1097 // unwrapNopCloser return the underlying reader and true if r is a NopCloser
1098 // else it return false.
1099 func unwrapNopCloser(r io.Reader) (underlyingReader io.Reader, isNopCloser bool) {
1100 switch reflect.TypeOf(r) {
1101 case nopCloserType, nopCloserWriterToType:
1102 return reflect.ValueOf(r).Field(0).Interface().(io.Reader), true
1108 // isKnownInMemoryReader reports whether r is a type known to not
1109 // block on Read. Its caller uses this as an optional optimization to
1110 // send fewer TCP packets.
1111 func isKnownInMemoryReader(r io.Reader) bool {
1113 case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1116 if r, ok := unwrapNopCloser(r); ok {
1117 return isKnownInMemoryReader(r)
1119 if r, ok := r.(*readTrackingBody); ok {
1120 return isKnownInMemoryReader(r.ReadCloser)
1125 // bufioFlushWriter is an io.Writer wrapper that flushes all writes
1126 // on its wrapped writer if it's a *bufio.Writer.
1127 type bufioFlushWriter struct{ w io.Writer }
1129 func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
1130 n, err = fw.w.Write(p)
1131 if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
1133 if ferr != nil && err == nil {