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.
15 "net/http/internal/ascii"
24 "golang.org/x/net/http/httpguts"
27 // ErrLineTooLong is returned when reading request or response bodies
28 // with malformed chunked encoding.
29 var ErrLineTooLong = internal.ErrLineTooLong
31 type errorReader struct {
35 func (r errorReader) Read(p []byte) (n int, err error) {
39 type byteReader struct {
44 func (br *byteReader) Read(p []byte) (n int, err error) {
56 // transferWriter inspects the fields of a user-supplied Request or Response,
57 // sanitizes them without changing the user object and provides methods for
58 // writing the respective header, body and trailer in wire format.
59 type transferWriter struct {
64 ContentLength int64 // -1 means unknown, 0 means exactly none
66 TransferEncoding []string
70 bodyReadError error // any non-EOF error from reading Body
72 FlushHeaders bool // flush headers to network before body
73 ByteReadCh chan readResult // non-nil if probeRequestBody called
76 func newTransferWriter(r any) (t *transferWriter, err error) {
79 // Extract relevant fields
80 atLeastHTTP11 := false
81 switch rr := r.(type) {
83 if rr.ContentLength != 0 && rr.Body == nil {
84 return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
86 t.Method = valueOrDefault(rr.Method, "GET")
88 t.TransferEncoding = rr.TransferEncoding
90 t.Trailer = rr.Trailer
92 t.BodyCloser = rr.Body
93 t.ContentLength = rr.outgoingLength()
94 if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
95 t.TransferEncoding = []string{"chunked"}
97 // If there's a body, conservatively flush the headers
98 // to any bufio.Writer we're writing to, just in case
99 // the server needs the headers early, before we copy
100 // the body and possibly block. We make an exception
101 // for the common standard library in-memory types,
102 // though, to avoid unnecessary TCP packets on the
103 // wire. (Issue 22088.)
104 if t.ContentLength != 0 && !isKnownInMemoryReader(t.Body) {
105 t.FlushHeaders = true
108 atLeastHTTP11 = true // Transport requests are always 1.1 or 2.0
111 if rr.Request != nil {
112 t.Method = rr.Request.Method
115 t.BodyCloser = rr.Body
116 t.ContentLength = rr.ContentLength
118 t.TransferEncoding = rr.TransferEncoding
120 t.Trailer = rr.Trailer
121 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
122 t.ResponseToHEAD = noResponseBodyExpected(t.Method)
125 // Sanitize Body,ContentLength,TransferEncoding
126 if t.ResponseToHEAD {
128 if chunked(t.TransferEncoding) {
132 if !atLeastHTTP11 || t.Body == nil {
133 t.TransferEncoding = nil
135 if chunked(t.TransferEncoding) {
137 } else if t.Body == nil { // no chunking, no body
143 if !chunked(t.TransferEncoding) {
150 // shouldSendChunkedRequestBody reports whether we should try to send a
151 // chunked request body to the server. In particular, the case we really
152 // want to prevent is sending a GET or other typically-bodyless request to a
153 // server with a chunked body when the body has zero bytes, since GETs with
154 // bodies (while acceptable according to specs), even zero-byte chunked
155 // bodies, are approximately never seen in the wild and confuse most
156 // servers. See Issue 18257, as one example.
158 // The only reason we'd send such a request is if the user set the Body to a
159 // non-nil value (say, io.NopCloser(bytes.NewReader(nil))) and didn't
160 // set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
161 // there's bytes to send.
163 // This code tries to read a byte from the Request.Body in such cases to see
164 // whether the body actually has content (super rare) or is actually just
165 // a non-nil content-less ReadCloser (the more common case). In that more
166 // common case, we act as if their Body were nil instead, and don't send
168 func (t *transferWriter) shouldSendChunkedRequestBody() bool {
169 // Note that t.ContentLength is the corrected content length
170 // from rr.outgoingLength, so 0 actually means zero, not unknown.
171 if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
174 if t.Method == "CONNECT" {
177 if requestMethodUsuallyLacksBody(t.Method) {
178 // Only probe the Request.Body for GET/HEAD/DELETE/etc
179 // requests, because it's only those types of requests
180 // that confuse servers.
181 t.probeRequestBody() // adjusts t.Body, t.ContentLength
184 // For all other request types (PUT, POST, PATCH, or anything
185 // made-up we've never heard of), assume it's normal and the server
186 // can deal with a chunked request body. Maybe we'll adjust this
191 // probeRequestBody reads a byte from t.Body to see whether it's empty
192 // (returns io.EOF right away).
194 // But because we've had problems with this blocking users in the past
195 // (issue 17480) when the body is a pipe (perhaps waiting on the response
196 // headers before the pipe is fed data), we need to be careful and bound how
197 // long we wait for it. This delay will only affect users if all the following
199 // - the request body blocks
200 // - the content length is not set (or set to -1)
201 // - the method doesn't usually have a body (GET, HEAD, DELETE, ...)
202 // - there is no transfer-encoding=chunked already set.
204 // In other words, this delay will not normally affect anybody, and there
205 // are workarounds if it does.
206 func (t *transferWriter) probeRequestBody() {
207 t.ByteReadCh = make(chan readResult, 1)
208 go func(body io.Reader) {
211 rres.n, rres.err = body.Read(buf[:])
218 timer := time.NewTimer(200 * time.Millisecond)
220 case rres := <-t.ByteReadCh:
222 if rres.n == 0 && rres.err == io.EOF {
226 } else if rres.n == 1 {
228 t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
230 t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
232 } else if rres.err != nil {
233 t.Body = errorReader{rres.err}
236 // Too slow. Don't wait. Read it later, and keep
237 // assuming that this is ContentLength == -1
238 // (unknown), which means we'll send a
239 // "Transfer-Encoding: chunked" header.
240 t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
241 // Request that Request.Write flush the headers to the
242 // network before writing the body, since our body may not
243 // become readable until it's seen the response headers.
244 t.FlushHeaders = true
248 func noResponseBodyExpected(requestMethod string) bool {
249 return requestMethod == "HEAD"
252 func (t *transferWriter) shouldSendContentLength() bool {
253 if chunked(t.TransferEncoding) {
256 if t.ContentLength > 0 {
259 if t.ContentLength < 0 {
262 // Many servers expect a Content-Length for these methods
263 if t.Method == "POST" || t.Method == "PUT" || t.Method == "PATCH" {
266 if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
267 if t.Method == "GET" || t.Method == "HEAD" {
276 func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error {
277 if t.Close && !hasToken(t.Header.get("Connection"), "close") {
278 if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
281 if trace != nil && trace.WroteHeaderField != nil {
282 trace.WroteHeaderField("Connection", []string{"close"})
286 // Write Content-Length and/or Transfer-Encoding whose values are a
287 // function of the sanitized field triple (Body, ContentLength,
289 if t.shouldSendContentLength() {
290 if _, err := io.WriteString(w, "Content-Length: "); err != nil {
293 if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
296 if trace != nil && trace.WroteHeaderField != nil {
297 trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
299 } else if chunked(t.TransferEncoding) {
300 if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
303 if trace != nil && trace.WroteHeaderField != nil {
304 trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
308 // Write Trailer header
309 if t.Trailer != nil {
310 keys := make([]string, 0, len(t.Trailer))
311 for k := range t.Trailer {
312 k = CanonicalHeaderKey(k)
314 case "Transfer-Encoding", "Trailer", "Content-Length":
315 return badStringError("invalid Trailer key", k)
317 keys = append(keys, k)
321 // TODO: could do better allocation-wise here, but trailers are rare,
322 // so being lazy for now.
323 if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
326 if trace != nil && trace.WroteHeaderField != nil {
327 trace.WroteHeaderField("Trailer", keys)
335 // always closes t.BodyCloser
336 func (t *transferWriter) writeBody(w io.Writer) (err error) {
340 if closed || t.BodyCloser == nil {
343 if closeErr := t.BodyCloser.Close(); closeErr != nil && err == nil {
348 // Write body. We "unwrap" the body first if it was wrapped in a
349 // nopCloser or readTrackingBody. This is to ensure that we can take advantage of
350 // OS-level optimizations in the event that the body is an
353 var body = t.unwrapBody()
354 if chunked(t.TransferEncoding) {
355 if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
356 w = &internal.FlushAfterChunkWriter{Writer: bw}
358 cw := internal.NewChunkedWriter(w)
359 _, err = t.doBodyCopy(cw, body)
363 } else if t.ContentLength == -1 {
365 if t.Method == "CONNECT" {
366 dst = bufioFlushWriter{dst}
368 ncopy, err = t.doBodyCopy(dst, body)
370 ncopy, err = t.doBodyCopy(w, io.LimitReader(body, t.ContentLength))
375 nextra, err = t.doBodyCopy(io.Discard, body)
382 if t.BodyCloser != nil {
384 if err := t.BodyCloser.Close(); err != nil {
389 if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
390 return fmt.Errorf("http: ContentLength=%d with Body length %d",
391 t.ContentLength, ncopy)
394 if chunked(t.TransferEncoding) {
395 // Write Trailer header
396 if t.Trailer != nil {
397 if err := t.Trailer.Write(w); err != nil {
401 // Last chunk, empty trailer
402 _, err = io.WriteString(w, "\r\n")
407 // doBodyCopy wraps a copy operation, with any resulting error also
408 // being saved in bodyReadError.
410 // This function is only intended for use in writeBody.
411 func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
412 n, err = io.Copy(dst, src)
413 if err != nil && err != io.EOF {
414 t.bodyReadError = err
419 // unwrapBodyReader unwraps the body's inner reader if it's a
420 // nopCloser. This is to ensure that body writes sourced from local
421 // files (*os.File types) are properly optimized.
423 // This function is only intended for use in writeBody.
424 func (t *transferWriter) unwrapBody() io.Reader {
425 if r, ok := unwrapNopCloser(t.Body); ok {
428 if r, ok := t.Body.(*readTrackingBody); ok {
435 type transferReader struct {
450 func (t *transferReader) protoAtLeast(m, n int) bool {
451 return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
454 // bodyAllowedForStatus reports whether a given response status code
455 // permits a body. See RFC 7230, section 3.3.
456 func bodyAllowedForStatus(status int) bool {
458 case status >= 100 && status <= 199:
469 suppressedHeaders304 = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
470 suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
471 excludedHeadersNoBody = map[string]bool{"Content-Length": true, "Transfer-Encoding": true}
474 func suppressedHeaders(status int) []string {
477 // RFC 7232 section 4.1
478 return suppressedHeaders304
479 case !bodyAllowedForStatus(status):
480 return suppressedHeadersNoBody
485 // msg is *Request or *Response.
486 func readTransfer(msg any, r *bufio.Reader) (err error) {
487 t := &transferReader{RequestMethod: "GET"}
491 switch rr := msg.(type) {
494 t.StatusCode = rr.StatusCode
495 t.ProtoMajor = rr.ProtoMajor
496 t.ProtoMinor = rr.ProtoMinor
497 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
499 if rr.Request != nil {
500 t.RequestMethod = rr.Request.Method
504 t.RequestMethod = rr.Method
505 t.ProtoMajor = rr.ProtoMajor
506 t.ProtoMinor = rr.ProtoMinor
507 // Transfer semantics for Requests are exactly like those for
508 // Responses with status code 200, responding to a GET method
512 panic("unexpected type")
515 // Default to HTTP/1.1
516 if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
517 t.ProtoMajor, t.ProtoMinor = 1, 1
520 // Transfer-Encoding: chunked, and overriding Content-Length.
521 if err := t.parseTransferEncoding(); err != nil {
525 realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.Chunked)
529 if isResponse && t.RequestMethod == "HEAD" {
530 if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
536 t.ContentLength = realLength
540 t.Trailer, err = fixTrailer(t.Header, t.Chunked)
545 // If there is no Content-Length or chunked Transfer-Encoding on a *Response
546 // and the status is not 1xx, 204 or 304, then the body is unbounded.
547 // See RFC 7230, section 3.3.
550 if realLength == -1 && !t.Chunked && bodyAllowedForStatus(t.StatusCode) {
556 // Prepare body reader. ContentLength < 0 means chunked encoding
557 // or close connection when finished, since multipart is not supported yet
560 if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
563 t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
565 case realLength == 0:
568 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
570 // realLength < 0, i.e. "Content-Length" not mentioned in header
572 // Close semantics (i.e. HTTP/1.0)
573 t.Body = &body{src: r, closing: t.Close}
575 // Persistent connection (i.e. HTTP/1.1)
581 switch rr := msg.(type) {
584 rr.ContentLength = t.ContentLength
586 rr.TransferEncoding = []string{"chunked"}
589 rr.Trailer = t.Trailer
592 rr.ContentLength = t.ContentLength
594 rr.TransferEncoding = []string{"chunked"}
597 rr.Trailer = t.Trailer
603 // Checks whether chunked is part of the encodings stack
604 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
606 // Checks whether the encoding is explicitly "identity".
607 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
609 // unsupportedTEError reports unsupported transfer-encodings.
610 type unsupportedTEError struct {
614 func (uste *unsupportedTEError) Error() string {
618 // isUnsupportedTEError checks if the error is of type
619 // unsupportedTEError. It is usually invoked with a non-nil err.
620 func isUnsupportedTEError(err error) bool {
621 _, ok := err.(*unsupportedTEError)
625 // parseTransferEncoding sets t.Chunked based on the Transfer-Encoding header.
626 func (t *transferReader) parseTransferEncoding() error {
627 raw, present := t.Header["Transfer-Encoding"]
631 delete(t.Header, "Transfer-Encoding")
633 // Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
634 if !t.protoAtLeast(1, 1) {
638 // Like nginx, we only support a single Transfer-Encoding header field, and
639 // only if set to "chunked". This is one of the most security sensitive
640 // surfaces in HTTP/1.1 due to the risk of request smuggling, so we keep it
641 // strict and simple.
643 return &unsupportedTEError{fmt.Sprintf("too many transfer encodings: %q", raw)}
645 if !ascii.EqualFold(raw[0], "chunked") {
646 return &unsupportedTEError{fmt.Sprintf("unsupported transfer encoding: %q", raw[0])}
649 // RFC 7230 3.3.2 says "A sender MUST NOT send a Content-Length header field
650 // in any message that contains a Transfer-Encoding header field."
652 // but also: "If a message is received with both a Transfer-Encoding and a
653 // Content-Length header field, the Transfer-Encoding overrides the
654 // Content-Length. Such a message might indicate an attempt to perform
655 // request smuggling (Section 9.5) or response splitting (Section 9.4) and
656 // ought to be handled as an error. A sender MUST remove the received
657 // Content-Length field prior to forwarding such a message downstream."
659 // Reportedly, these appear in the wild.
660 delete(t.Header, "Content-Length")
666 // Determine the expected body length, using RFC 7230 Section 3.3. This
667 // function is not a method, because ultimately it should be shared by
668 // ReadResponse and ReadRequest.
669 func fixLength(isResponse bool, status int, requestMethod string, header Header, chunked bool) (int64, error) {
670 isRequest := !isResponse
671 contentLens := header["Content-Length"]
673 // Hardening against HTTP request smuggling
674 if len(contentLens) > 1 {
675 // Per RFC 7230 Section 3.3.2, prevent multiple
676 // Content-Length headers if they differ in value.
677 // If there are dups of the value, remove the dups.
679 first := textproto.TrimString(contentLens[0])
680 for _, ct := range contentLens[1:] {
681 if first != textproto.TrimString(ct) {
682 return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
686 // deduplicate Content-Length
687 header.Del("Content-Length")
688 header.Add("Content-Length", first)
690 contentLens = header["Content-Length"]
693 // Logic based on response type or status
694 if noResponseBodyExpected(requestMethod) {
695 // For HTTP requests, as part of hardening against request
696 // smuggling (RFC 7230), don't allow a Content-Length header for
697 // methods which don't permit bodies. As an exception, allow
698 // exactly one Content-Length header if its value is "0".
699 if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
700 return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
712 // Logic based on Transfer-Encoding
717 // Logic based on Content-Length
719 if len(contentLens) == 1 {
720 cl = textproto.TrimString(contentLens[0])
723 n, err := parseContentLength(cl)
729 header.Del("Content-Length")
732 // RFC 7230 neither explicitly permits nor forbids an
733 // entity-body on a GET request so we permit one if
734 // declared, but we default to 0 here (not -1 below)
735 // if there's no mention of a body.
736 // Likewise, all other request methods are assumed to have
737 // no body if neither Transfer-Encoding chunked nor a
738 // Content-Length are set.
742 // Body-EOF logic based on other methods (like closing, or chunked coding)
746 // Determine whether to hang up after sending a request and body, or
747 // receiving a response and body
748 // 'header' is the request headers
749 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
754 conv := header["Connection"]
755 hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
756 if major == 1 && minor == 0 {
757 return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
760 if hasClose && removeCloseHeader {
761 header.Del("Connection")
767 // Parse the trailer header
768 func fixTrailer(header Header, chunked bool) (Header, error) {
769 vv, ok := header["Trailer"]
774 // Trailer and no chunking:
775 // this is an invalid use case for trailer header.
776 // Nevertheless, no error will be returned and we
777 // let users decide if this is a valid HTTP message.
778 // The Trailer header will be kept in Response.Header
779 // but not populate Response.Trailer.
783 header.Del("Trailer")
785 trailer := make(Header)
787 for _, v := range vv {
788 foreachHeaderElement(v, func(key string) {
789 key = CanonicalHeaderKey(key)
791 case "Transfer-Encoding", "Trailer", "Content-Length":
793 err = badStringError("bad trailer key", key)
803 if len(trailer) == 0 {
809 // body turns a Reader into a ReadCloser.
810 // Close ensures that the body has been fully read
811 // and then reads the trailer if necessary.
814 hdr any // non-nil (Response or Request) value means read trailer
815 r *bufio.Reader // underlying wire-format reader for the trailer
816 closing bool // is the connection to be closed after reading body?
817 doEarlyClose bool // whether Close should stop early
819 mu sync.Mutex // guards following, and calls to Read and Close
822 earlyClose bool // Close called and we didn't read to the end of src
823 onHitEOF func() // if non-nil, func to call when EOF is Read
826 // ErrBodyReadAfterClose is returned when reading a Request or Response
827 // Body after the body has been closed. This typically happens when the body is
828 // read after an HTTP Handler calls WriteHeader or Write on its
830 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
832 func (b *body) Read(p []byte) (n int, err error) {
836 return 0, ErrBodyReadAfterClose
838 return b.readLocked(p)
842 func (b *body) readLocked(p []byte) (n int, err error) {
846 n, err = b.src.Read(p)
850 // Chunked case. Read the trailer.
852 if e := b.readTrailer(); e != nil {
854 // Something went wrong in the trailer, we must not allow any
855 // further reads of any kind to succeed from body, nor any
856 // subsequent requests on the server connection. See
857 // golang.org/issue/12027
863 // If the server declared the Content-Length, our body is a LimitedReader
864 // and we need to check whether this EOF arrived early.
865 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
866 err = io.ErrUnexpectedEOF
871 // If we can return an EOF here along with the read data, do
872 // so. This is optional per the io.Reader contract, but doing
873 // so helps the HTTP transport code recycle its connection
874 // earlier (since it will see this EOF itself), even if the
875 // client doesn't do future reads or Close.
876 if err == nil && n > 0 {
877 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
883 if b.sawEOF && b.onHitEOF != nil {
891 singleCRLF = []byte("\r\n")
892 doubleCRLF = []byte("\r\n\r\n")
895 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
896 for peekSize := 4; ; peekSize++ {
897 // This loop stops when Peek returns an error,
898 // which it does when r's buffer has been filled.
899 buf, err := r.Peek(peekSize)
900 if bytes.HasSuffix(buf, doubleCRLF) {
910 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
912 func (b *body) readTrailer() error {
913 // The common case, since nobody uses trailers.
914 buf, err := b.r.Peek(2)
915 if bytes.Equal(buf, singleCRLF) {
926 // Make sure there's a header terminator coming up, to prevent
927 // a DoS with an unbounded size Trailer. It's not easy to
928 // slip in a LimitReader here, as textproto.NewReader requires
929 // a concrete *bufio.Reader. Also, we can't get all the way
930 // back up to our conn's LimitedReader that *might* be backing
931 // this bufio.Reader. Instead, a hack: we iteratively Peek up
932 // to the bufio.Reader's max size, looking for a double CRLF.
933 // This limits the trailer to the underlying buffer size, typically 4kB.
934 if !seeUpcomingDoubleCRLF(b.r) {
935 return errors.New("http: suspiciously long trailer after chunked body")
938 hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
945 switch rr := b.hdr.(type) {
947 mergeSetHeader(&rr.Trailer, Header(hdr))
949 mergeSetHeader(&rr.Trailer, Header(hdr))
954 func mergeSetHeader(dst *Header, src Header) {
959 for k, vv := range src {
964 // unreadDataSizeLocked returns the number of bytes of unread input.
965 // It returns -1 if unknown.
966 // b.mu must be held.
967 func (b *body) unreadDataSizeLocked() int64 {
968 if lr, ok := b.src.(*io.LimitedReader); ok {
974 func (b *body) Close() error {
983 // Already saw EOF, so no need going to look for it.
984 case b.hdr == nil && b.closing:
985 // no trailer and closing the connection next.
986 // no point in reading to EOF.
988 // Read up to maxPostHandlerReadBytes bytes of the body, looking
989 // for EOF (and trailers), so we can re-use this connection.
990 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
991 // There was a declared Content-Length, and we have more bytes remaining
992 // than our maxPostHandlerReadBytes tolerance. So, give up.
996 // Consume the body, or, which will also lead to us reading
997 // the trailer headers after the body, if present.
998 n, err = io.CopyN(io.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
1002 if n == maxPostHandlerReadBytes {
1007 // Fully consume the body, which will also lead to us reading
1008 // the trailer headers after the body, if present.
1009 _, err = io.Copy(io.Discard, bodyLocked{b})
1015 func (b *body) didEarlyClose() bool {
1021 // bodyRemains reports whether future Read calls might
1023 func (b *body) bodyRemains() bool {
1029 func (b *body) registerOnHitEOF(fn func()) {
1035 // bodyLocked is an io.Reader reading from a *body when its mutex is
1037 type bodyLocked struct {
1041 func (bl bodyLocked) Read(p []byte) (n int, err error) {
1043 return 0, ErrBodyReadAfterClose
1045 return bl.b.readLocked(p)
1048 // parseContentLength trims whitespace from s and returns -1 if no value
1049 // is set, or the value if it's >= 0.
1050 func parseContentLength(cl string) (int64, error) {
1051 cl = textproto.TrimString(cl)
1055 n, err := strconv.ParseUint(cl, 10, 63)
1057 return 0, badStringError("bad Content-Length", cl)
1059 return int64(n), nil
1063 // finishAsyncByteRead finishes reading the 1-byte sniff
1064 // from the ContentLength==0, Body!=nil case.
1065 type finishAsyncByteRead struct {
1069 func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1073 rres := <-fr.tw.ByteReadCh
1074 n, err = rres.n, rres.err
1084 var nopCloserType = reflect.TypeOf(io.NopCloser(nil))
1085 var nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct {
1090 // unwrapNopCloser return the underlying reader and true if r is a NopCloser
1091 // else it return false
1092 func unwrapNopCloser(r io.Reader) (underlyingReader io.Reader, isNopCloser bool) {
1093 switch reflect.TypeOf(r) {
1094 case nopCloserType, nopCloserWriterToType:
1095 return reflect.ValueOf(r).Field(0).Interface().(io.Reader), true
1101 // isKnownInMemoryReader reports whether r is a type known to not
1102 // block on Read. Its caller uses this as an optional optimization to
1103 // send fewer TCP packets.
1104 func isKnownInMemoryReader(r io.Reader) bool {
1106 case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1109 if r, ok := unwrapNopCloser(r); ok {
1110 return isKnownInMemoryReader(r)
1112 if r, ok := r.(*readTrackingBody); ok {
1113 return isKnownInMemoryReader(r.ReadCloser)
1118 // bufioFlushWriter is an io.Writer wrapper that flushes all writes
1119 // on its wrapped writer if it's a *bufio.Writer.
1120 type bufioFlushWriter struct{ w io.Writer }
1122 func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
1123 n, err = fw.w.Write(p)
1124 if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
1126 if ferr != nil && err == nil {