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.
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 interface{}) (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, ioutil.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.
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[:])
217 timer := time.NewTimer(200 * time.Millisecond)
219 case rres := <-t.ByteReadCh:
221 if rres.n == 0 && rres.err == io.EOF {
225 } else if rres.n == 1 {
227 t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
229 t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
231 } else if rres.err != nil {
232 t.Body = errorReader{rres.err}
235 // Too slow. Don't wait. Read it later, and keep
236 // assuming that this is ContentLength == -1
237 // (unknown), which means we'll send a
238 // "Transfer-Encoding: chunked" header.
239 t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
240 // Request that Request.Write flush the headers to the
241 // network before writing the body, since our body may not
242 // become readable until it's seen the response headers.
243 t.FlushHeaders = true
247 func noResponseBodyExpected(requestMethod string) bool {
248 return requestMethod == "HEAD"
251 func (t *transferWriter) shouldSendContentLength() bool {
252 if chunked(t.TransferEncoding) {
255 if t.ContentLength > 0 {
258 if t.ContentLength < 0 {
261 // Many servers expect a Content-Length for these methods
262 if t.Method == "POST" || t.Method == "PUT" {
265 if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
266 if t.Method == "GET" || t.Method == "HEAD" {
275 func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error {
276 if t.Close && !hasToken(t.Header.get("Connection"), "close") {
277 if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
280 if trace != nil && trace.WroteHeaderField != nil {
281 trace.WroteHeaderField("Connection", []string{"close"})
285 // Write Content-Length and/or Transfer-Encoding whose values are a
286 // function of the sanitized field triple (Body, ContentLength,
288 if t.shouldSendContentLength() {
289 if _, err := io.WriteString(w, "Content-Length: "); err != nil {
292 if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
295 if trace != nil && trace.WroteHeaderField != nil {
296 trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
298 } else if chunked(t.TransferEncoding) {
299 if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
302 if trace != nil && trace.WroteHeaderField != nil {
303 trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
307 // Write Trailer header
308 if t.Trailer != nil {
309 keys := make([]string, 0, len(t.Trailer))
310 for k := range t.Trailer {
311 k = CanonicalHeaderKey(k)
313 case "Transfer-Encoding", "Trailer", "Content-Length":
314 return &badStringError{"invalid Trailer key", k}
316 keys = append(keys, k)
320 // TODO: could do better allocation-wise here, but trailers are rare,
321 // so being lazy for now.
322 if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
325 if trace != nil && trace.WroteHeaderField != nil {
326 trace.WroteHeaderField("Trailer", keys)
334 func (t *transferWriter) writeBody(w io.Writer) error {
338 // Write body. We "unwrap" the body first if it was wrapped in a
339 // nopCloser. This is to ensure that we can take advantage of
340 // OS-level optimizations in the event that the body is an
343 var body = t.unwrapBody()
344 if chunked(t.TransferEncoding) {
345 if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
346 w = &internal.FlushAfterChunkWriter{Writer: bw}
348 cw := internal.NewChunkedWriter(w)
349 _, err = t.doBodyCopy(cw, body)
353 } else if t.ContentLength == -1 {
355 if t.Method == "CONNECT" {
356 dst = bufioFlushWriter{dst}
358 ncopy, err = t.doBodyCopy(dst, body)
360 ncopy, err = t.doBodyCopy(w, io.LimitReader(body, t.ContentLength))
365 nextra, err = t.doBodyCopy(ioutil.Discard, body)
372 if t.BodyCloser != nil {
373 if err := t.BodyCloser.Close(); err != nil {
378 if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
379 return fmt.Errorf("http: ContentLength=%d with Body length %d",
380 t.ContentLength, ncopy)
383 if chunked(t.TransferEncoding) {
384 // Write Trailer header
385 if t.Trailer != nil {
386 if err := t.Trailer.Write(w); err != nil {
390 // Last chunk, empty trailer
391 _, err = io.WriteString(w, "\r\n")
396 // doBodyCopy wraps a copy operation, with any resulting error also
397 // being saved in bodyReadError.
399 // This function is only intended for use in writeBody.
400 func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
401 n, err = io.Copy(dst, src)
402 if err != nil && err != io.EOF {
403 t.bodyReadError = err
408 // unwrapBodyReader unwraps the body's inner reader if it's a
409 // nopCloser. This is to ensure that body writes sourced from local
410 // files (*os.File types) are properly optimized.
412 // This function is only intended for use in writeBody.
413 func (t *transferWriter) unwrapBody() io.Reader {
414 if reflect.TypeOf(t.Body) == nopCloserType {
415 return reflect.ValueOf(t.Body).Field(0).Interface().(io.Reader)
421 type transferReader struct {
431 TransferEncoding []string
436 func (t *transferReader) protoAtLeast(m, n int) bool {
437 return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
440 // bodyAllowedForStatus reports whether a given response status code
441 // permits a body. See RFC 7230, section 3.3.
442 func bodyAllowedForStatus(status int) bool {
444 case status >= 100 && status <= 199:
455 suppressedHeaders304 = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
456 suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
459 func suppressedHeaders(status int) []string {
462 // RFC 7232 section 4.1
463 return suppressedHeaders304
464 case !bodyAllowedForStatus(status):
465 return suppressedHeadersNoBody
470 // proxyingReadCloser is a composite type that accepts and proxies
471 // io.Read and io.Close calls to its respective Reader and Closer.
473 // It is composed of:
474 // a) a top-level reader e.g. the result of decompression
475 // b) a symbolic Closer e.g. the result of decompression, the
476 // original body and the connection itself.
477 type proxyingReadCloser struct {
482 // multiCloser implements io.Closer and allows a bunch of io.Closer values
483 // to all be closed once.
484 // Example usage is with proxyingReadCloser if we are decompressing a response
485 // body on the fly and would like to close both *gzip.Reader and underlying body.
486 type multiCloser []io.Closer
488 func (mc multiCloser) Close() error {
490 for _, c := range mc {
491 if err1 := c.Close(); err1 != nil && err == nil {
498 // msg is *Request or *Response.
499 func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
500 t := &transferReader{RequestMethod: "GET"}
504 switch rr := msg.(type) {
507 t.StatusCode = rr.StatusCode
508 t.ProtoMajor = rr.ProtoMajor
509 t.ProtoMinor = rr.ProtoMinor
510 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
512 if rr.Request != nil {
513 t.RequestMethod = rr.Request.Method
517 t.RequestMethod = rr.Method
518 t.ProtoMajor = rr.ProtoMajor
519 t.ProtoMinor = rr.ProtoMinor
520 // Transfer semantics for Requests are exactly like those for
521 // Responses with status code 200, responding to a GET method
525 panic("unexpected type")
528 // Default to HTTP/1.1
529 if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
530 t.ProtoMajor, t.ProtoMinor = 1, 1
533 // Transfer encoding, content length
534 err = t.fixTransferEncoding()
539 realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
543 if isResponse && t.RequestMethod == "HEAD" {
544 if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
550 t.ContentLength = realLength
554 t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
559 // If there is no Content-Length or chunked Transfer-Encoding on a *Response
560 // and the status is not 1xx, 204 or 304, then the body is unbounded.
561 // See RFC 7230, section 3.3.
564 if realLength == -1 &&
565 !chunked(t.TransferEncoding) &&
566 bodyAllowedForStatus(t.StatusCode) {
572 // Prepare body reader. ContentLength < 0 means chunked encoding
573 // or close connection when finished, since multipart is not supported yet
575 case chunked(t.TransferEncoding) || implicitlyChunked(t.TransferEncoding):
576 if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
579 t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
581 case realLength == 0:
584 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
586 // realLength < 0, i.e. "Content-Length" not mentioned in header
588 // Close semantics (i.e. HTTP/1.0)
589 t.Body = &body{src: r, closing: t.Close}
591 // Persistent connection (i.e. HTTP/1.1)
596 // Finally if "gzip" was one of the requested transfer-encodings,
597 // we'll unzip the concatenated body/payload of the request.
598 // TODO: As we support more transfer-encodings, extract
599 // this code and apply the un-codings in reverse.
600 if t.Body != NoBody && gzipped(t.TransferEncoding) {
601 zr, err := gzip.NewReader(t.Body)
603 return fmt.Errorf("http: failed to gunzip body: %v", err)
605 t.Body = &proxyingReadCloser{
607 Closer: multiCloser{zr, t.Body},
612 switch rr := msg.(type) {
615 rr.ContentLength = t.ContentLength
616 rr.TransferEncoding = t.TransferEncoding
618 rr.Trailer = t.Trailer
621 rr.ContentLength = t.ContentLength
622 rr.TransferEncoding = t.TransferEncoding
624 rr.Trailer = t.Trailer
630 // Checks whether chunked is the last part of the encodings stack
631 func chunked(te []string) bool { return len(te) > 0 && te[len(te)-1] == "chunked" }
633 // implicitlyChunked is a helper to check for implicity of chunked, because
634 // RFC 7230 Section 3.3.1 says that the sender MUST apply chunked as the final
635 // payload body to ensure that the message is framed for both the request
636 // and the body. Since "identity" is incompatible with any other transformational
637 // encoding cannot co-exist, the presence of "identity" will cause implicitlyChunked
639 func implicitlyChunked(te []string) bool {
640 if len(te) == 0 { // No transfer-encodings passed in, so not implicitly chunked.
643 for _, tei := range te {
644 if tei == "identity" {
651 func isGzipTransferEncoding(tei string) bool {
652 // RFC 7230 4.2.3 requests that "x-gzip" SHOULD be considered the same as "gzip".
653 return tei == "gzip" || tei == "x-gzip"
656 // Checks where either of "gzip" or "x-gzip" are contained in transfer encodings.
657 func gzipped(te []string) bool {
658 for _, tei := range te {
659 if isGzipTransferEncoding(tei) {
666 // Checks whether the encoding is explicitly "identity".
667 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
669 // unsupportedTEError reports unsupported transfer-encodings.
670 type unsupportedTEError struct {
674 func (uste *unsupportedTEError) Error() string {
678 // isUnsupportedTEError checks if the error is of type
679 // unsupportedTEError. It is usually invoked with a non-nil err.
680 func isUnsupportedTEError(err error) bool {
681 _, ok := err.(*unsupportedTEError)
685 // fixTransferEncoding sanitizes t.TransferEncoding, if needed.
686 func (t *transferReader) fixTransferEncoding() error {
687 raw, present := t.Header["Transfer-Encoding"]
691 delete(t.Header, "Transfer-Encoding")
693 // Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
694 if !t.protoAtLeast(1, 1) {
698 encodings := strings.Split(raw[0], ",")
699 te := make([]string, 0, len(encodings))
701 // When adding new encodings, please maintain the invariant:
702 // if chunked encoding is present, it must always
703 // come last and it must be applied only once.
704 // See RFC 7230 Section 3.3.1 Transfer-Encoding.
705 for i, encoding := range encodings {
706 encoding = strings.ToLower(strings.TrimSpace(encoding))
708 if encoding == "identity" {
709 // "identity" should not be mixed with other transfer-encodings/compressions
710 // because it means "no compression, no transformation".
711 if len(encodings) != 1 {
712 return &badStringError{`"identity" when present must be the only transfer encoding`, strings.Join(encodings, ",")}
714 // "identity" is not recorded.
719 case encoding == "chunked":
720 // "chunked" MUST ALWAYS be the last
721 // encoding as per the loop invariant.
723 // Invalid: [chunked, gzip]
724 // Valid: [gzip, chunked]
725 if i+1 != len(encodings) {
726 return &badStringError{"chunked must be applied only once, as the last encoding", strings.Join(encodings, ",")}
728 // Supported otherwise.
730 case isGzipTransferEncoding(encoding):
734 return &unsupportedTEError{fmt.Sprintf("unsupported transfer encoding: %q", encoding)}
737 te = te[0 : len(te)+1]
738 te[len(te)-1] = encoding
742 // RFC 7230 3.3.2 says "A sender MUST NOT send a
743 // Content-Length header field in any message that
744 // contains a Transfer-Encoding header field."
747 // "If a message is received with both a
748 // Transfer-Encoding and a Content-Length header
749 // field, the Transfer-Encoding overrides the
750 // Content-Length. Such a message might indicate an
751 // attempt to perform request smuggling (Section 9.5)
752 // or response splitting (Section 9.4) and ought to be
753 // handled as an error. A sender MUST remove the
754 // received Content-Length field prior to forwarding
755 // such a message downstream."
757 // Reportedly, these appear in the wild.
758 delete(t.Header, "Content-Length")
759 t.TransferEncoding = te
766 // Determine the expected body length, using RFC 7230 Section 3.3. This
767 // function is not a method, because ultimately it should be shared by
768 // ReadResponse and ReadRequest.
769 func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
770 isRequest := !isResponse
771 contentLens := header["Content-Length"]
773 // Hardening against HTTP request smuggling
774 if len(contentLens) > 1 {
775 // Per RFC 7230 Section 3.3.2, prevent multiple
776 // Content-Length headers if they differ in value.
777 // If there are dups of the value, remove the dups.
779 first := strings.TrimSpace(contentLens[0])
780 for _, ct := range contentLens[1:] {
781 if first != strings.TrimSpace(ct) {
782 return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
786 // deduplicate Content-Length
787 header.Del("Content-Length")
788 header.Add("Content-Length", first)
790 contentLens = header["Content-Length"]
793 // Logic based on response type or status
794 if noResponseBodyExpected(requestMethod) {
795 // For HTTP requests, as part of hardening against request
796 // smuggling (RFC 7230), don't allow a Content-Length header for
797 // methods which don't permit bodies. As an exception, allow
798 // exactly one Content-Length header if its value is "0".
799 if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
800 return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
812 // Logic based on Transfer-Encoding
817 // Logic based on Content-Length
819 if len(contentLens) == 1 {
820 cl = strings.TrimSpace(contentLens[0])
823 n, err := parseContentLength(cl)
829 header.Del("Content-Length")
832 // RFC 7230 neither explicitly permits nor forbids an
833 // entity-body on a GET request so we permit one if
834 // declared, but we default to 0 here (not -1 below)
835 // if there's no mention of a body.
836 // Likewise, all other request methods are assumed to have
837 // no body if neither Transfer-Encoding chunked nor a
838 // Content-Length are set.
842 // Body-EOF logic based on other methods (like closing, or chunked coding)
846 // Determine whether to hang up after sending a request and body, or
847 // receiving a response and body
848 // 'header' is the request headers
849 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
854 conv := header["Connection"]
855 hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
856 if major == 1 && minor == 0 {
857 return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
860 if hasClose && removeCloseHeader {
861 header.Del("Connection")
867 // Parse the trailer header
868 func fixTrailer(header Header, te []string) (Header, error) {
869 vv, ok := header["Trailer"]
874 // Trailer and no chunking:
875 // this is an invalid use case for trailer header.
876 // Nevertheless, no error will be returned and we
877 // let users decide if this is a valid HTTP message.
878 // The Trailer header will be kept in Response.Header
879 // but not populate Response.Trailer.
883 header.Del("Trailer")
885 trailer := make(Header)
887 for _, v := range vv {
888 foreachHeaderElement(v, func(key string) {
889 key = CanonicalHeaderKey(key)
891 case "Transfer-Encoding", "Trailer", "Content-Length":
893 err = &badStringError{"bad trailer key", key}
903 if len(trailer) == 0 {
909 // body turns a Reader into a ReadCloser.
910 // Close ensures that the body has been fully read
911 // and then reads the trailer if necessary.
914 hdr interface{} // non-nil (Response or Request) value means read trailer
915 r *bufio.Reader // underlying wire-format reader for the trailer
916 closing bool // is the connection to be closed after reading body?
917 doEarlyClose bool // whether Close should stop early
919 mu sync.Mutex // guards following, and calls to Read and Close
922 earlyClose bool // Close called and we didn't read to the end of src
923 onHitEOF func() // if non-nil, func to call when EOF is Read
926 // ErrBodyReadAfterClose is returned when reading a Request or Response
927 // Body after the body has been closed. This typically happens when the body is
928 // read after an HTTP Handler calls WriteHeader or Write on its
930 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
932 func (b *body) Read(p []byte) (n int, err error) {
936 return 0, ErrBodyReadAfterClose
938 return b.readLocked(p)
942 func (b *body) readLocked(p []byte) (n int, err error) {
946 n, err = b.src.Read(p)
950 // Chunked case. Read the trailer.
952 if e := b.readTrailer(); e != nil {
954 // Something went wrong in the trailer, we must not allow any
955 // further reads of any kind to succeed from body, nor any
956 // subsequent requests on the server connection. See
957 // golang.org/issue/12027
963 // If the server declared the Content-Length, our body is a LimitedReader
964 // and we need to check whether this EOF arrived early.
965 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
966 err = io.ErrUnexpectedEOF
971 // If we can return an EOF here along with the read data, do
972 // so. This is optional per the io.Reader contract, but doing
973 // so helps the HTTP transport code recycle its connection
974 // earlier (since it will see this EOF itself), even if the
975 // client doesn't do future reads or Close.
976 if err == nil && n > 0 {
977 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
983 if b.sawEOF && b.onHitEOF != nil {
991 singleCRLF = []byte("\r\n")
992 doubleCRLF = []byte("\r\n\r\n")
995 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
996 for peekSize := 4; ; peekSize++ {
997 // This loop stops when Peek returns an error,
998 // which it does when r's buffer has been filled.
999 buf, err := r.Peek(peekSize)
1000 if bytes.HasSuffix(buf, doubleCRLF) {
1010 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
1012 func (b *body) readTrailer() error {
1013 // The common case, since nobody uses trailers.
1014 buf, err := b.r.Peek(2)
1015 if bytes.Equal(buf, singleCRLF) {
1020 return errTrailerEOF
1026 // Make sure there's a header terminator coming up, to prevent
1027 // a DoS with an unbounded size Trailer. It's not easy to
1028 // slip in a LimitReader here, as textproto.NewReader requires
1029 // a concrete *bufio.Reader. Also, we can't get all the way
1030 // back up to our conn's LimitedReader that *might* be backing
1031 // this bufio.Reader. Instead, a hack: we iteratively Peek up
1032 // to the bufio.Reader's max size, looking for a double CRLF.
1033 // This limits the trailer to the underlying buffer size, typically 4kB.
1034 if !seeUpcomingDoubleCRLF(b.r) {
1035 return errors.New("http: suspiciously long trailer after chunked body")
1038 hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
1041 return errTrailerEOF
1045 switch rr := b.hdr.(type) {
1047 mergeSetHeader(&rr.Trailer, Header(hdr))
1049 mergeSetHeader(&rr.Trailer, Header(hdr))
1054 func mergeSetHeader(dst *Header, src Header) {
1059 for k, vv := range src {
1064 // unreadDataSizeLocked returns the number of bytes of unread input.
1065 // It returns -1 if unknown.
1066 // b.mu must be held.
1067 func (b *body) unreadDataSizeLocked() int64 {
1068 if lr, ok := b.src.(*io.LimitedReader); ok {
1074 func (b *body) Close() error {
1083 // Already saw EOF, so no need going to look for it.
1084 case b.hdr == nil && b.closing:
1085 // no trailer and closing the connection next.
1086 // no point in reading to EOF.
1087 case b.doEarlyClose:
1088 // Read up to maxPostHandlerReadBytes bytes of the body, looking
1089 // for EOF (and trailers), so we can re-use this connection.
1090 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
1091 // There was a declared Content-Length, and we have more bytes remaining
1092 // than our maxPostHandlerReadBytes tolerance. So, give up.
1096 // Consume the body, or, which will also lead to us reading
1097 // the trailer headers after the body, if present.
1098 n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
1102 if n == maxPostHandlerReadBytes {
1107 // Fully consume the body, which will also lead to us reading
1108 // the trailer headers after the body, if present.
1109 _, err = io.Copy(ioutil.Discard, bodyLocked{b})
1115 func (b *body) didEarlyClose() bool {
1121 // bodyRemains reports whether future Read calls might
1123 func (b *body) bodyRemains() bool {
1129 func (b *body) registerOnHitEOF(fn func()) {
1135 // bodyLocked is a io.Reader reading from a *body when its mutex is
1137 type bodyLocked struct {
1141 func (bl bodyLocked) Read(p []byte) (n int, err error) {
1143 return 0, ErrBodyReadAfterClose
1145 return bl.b.readLocked(p)
1148 // parseContentLength trims whitespace from s and returns -1 if no value
1149 // is set, or the value if it's >= 0.
1150 func parseContentLength(cl string) (int64, error) {
1151 cl = strings.TrimSpace(cl)
1155 n, err := strconv.ParseInt(cl, 10, 64)
1156 if err != nil || n < 0 {
1157 return 0, &badStringError{"bad Content-Length", cl}
1163 // finishAsyncByteRead finishes reading the 1-byte sniff
1164 // from the ContentLength==0, Body!=nil case.
1165 type finishAsyncByteRead struct {
1169 func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1173 rres := <-fr.tw.ByteReadCh
1174 n, err = rres.n, rres.err
1181 var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))
1183 // isKnownInMemoryReader reports whether r is a type known to not
1184 // block on Read. Its caller uses this as an optional optimization to
1185 // send fewer TCP packets.
1186 func isKnownInMemoryReader(r io.Reader) bool {
1188 case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1191 if reflect.TypeOf(r) == nopCloserType {
1192 return isKnownInMemoryReader(reflect.ValueOf(r).Field(0).Interface().(io.Reader))
1197 // bufioFlushWriter is an io.Writer wrapper that flushes all writes
1198 // on its wrapped writer if it's a *bufio.Writer.
1199 type bufioFlushWriter struct{ w io.Writer }
1201 func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
1202 n, err = fw.w.Write(p)
1203 if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
1205 if ferr != nil && err == nil {