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.
22 // ErrLineTooLong is returned when reading request or response bodies
23 // with malformed chunked encoding.
24 var ErrLineTooLong = internal.ErrLineTooLong
26 type errorReader struct {
30 func (r errorReader) Read(p []byte) (n int, err error) {
34 // transferWriter inspects the fields of a user-supplied Request or Response,
35 // sanitizes them without changing the user object and provides methods for
36 // writing the respective header, body and trailer in wire format.
37 type transferWriter struct {
42 ContentLength int64 // -1 means unknown, 0 means exactly none
44 TransferEncoding []string
49 func newTransferWriter(r interface{}) (t *transferWriter, err error) {
52 // Extract relevant fields
53 atLeastHTTP11 := false
54 switch rr := r.(type) {
56 if rr.ContentLength != 0 && rr.Body == nil {
57 return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
59 t.Method = valueOrDefault(rr.Method, "GET")
61 t.BodyCloser = rr.Body
62 t.ContentLength = rr.ContentLength
64 t.TransferEncoding = rr.TransferEncoding
65 t.Trailer = rr.Trailer
66 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
67 if t.Body != nil && len(t.TransferEncoding) == 0 && atLeastHTTP11 {
68 if t.ContentLength == 0 {
69 // Test to see if it's actually zero or just unset.
71 n, rerr := io.ReadFull(t.Body, buf[:])
72 if rerr != nil && rerr != io.EOF {
74 t.Body = errorReader{rerr}
76 // Oh, guess there is data in this Body Reader after all.
77 // The ContentLength field just wasn't set.
78 // Stich the Body back together again, re-attaching our
81 t.Body = io.MultiReader(bytes.NewReader(buf[:]), t.Body)
83 // Body is actually empty.
88 if t.ContentLength < 0 {
89 t.TransferEncoding = []string{"chunked"}
94 if rr.Request != nil {
95 t.Method = rr.Request.Method
98 t.BodyCloser = rr.Body
99 t.ContentLength = rr.ContentLength
101 t.TransferEncoding = rr.TransferEncoding
102 t.Trailer = rr.Trailer
103 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
104 t.ResponseToHEAD = noBodyExpected(t.Method)
107 // Sanitize Body,ContentLength,TransferEncoding
108 if t.ResponseToHEAD {
110 if chunked(t.TransferEncoding) {
114 if !atLeastHTTP11 || t.Body == nil {
115 t.TransferEncoding = nil
117 if chunked(t.TransferEncoding) {
119 } else if t.Body == nil { // no chunking, no body
125 if !chunked(t.TransferEncoding) {
132 func noBodyExpected(requestMethod string) bool {
133 return requestMethod == "HEAD"
136 func (t *transferWriter) shouldSendContentLength() bool {
137 if chunked(t.TransferEncoding) {
140 if t.ContentLength > 0 {
143 if t.ContentLength < 0 {
146 // Many servers expect a Content-Length for these methods
147 if t.Method == "POST" || t.Method == "PUT" {
150 if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
151 if t.Method == "GET" || t.Method == "HEAD" {
160 func (t *transferWriter) WriteHeader(w io.Writer) error {
162 if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
167 // Write Content-Length and/or Transfer-Encoding whose values are a
168 // function of the sanitized field triple (Body, ContentLength,
170 if t.shouldSendContentLength() {
171 if _, err := io.WriteString(w, "Content-Length: "); err != nil {
174 if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
177 } else if chunked(t.TransferEncoding) {
178 if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
183 // Write Trailer header
184 if t.Trailer != nil {
185 keys := make([]string, 0, len(t.Trailer))
186 for k := range t.Trailer {
187 k = CanonicalHeaderKey(k)
189 case "Transfer-Encoding", "Trailer", "Content-Length":
190 return &badStringError{"invalid Trailer key", k}
192 keys = append(keys, k)
196 // TODO: could do better allocation-wise here, but trailers are rare,
197 // so being lazy for now.
198 if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
207 func (t *transferWriter) WriteBody(w io.Writer) error {
213 if chunked(t.TransferEncoding) {
214 if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
215 w = &internal.FlushAfterChunkWriter{bw}
217 cw := internal.NewChunkedWriter(w)
218 _, err = io.Copy(cw, t.Body)
222 } else if t.ContentLength == -1 {
223 ncopy, err = io.Copy(w, t.Body)
225 ncopy, err = io.Copy(w, io.LimitReader(t.Body, t.ContentLength))
230 nextra, err = io.Copy(ioutil.Discard, t.Body)
236 if err = t.BodyCloser.Close(); err != nil {
241 if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
242 return fmt.Errorf("http: ContentLength=%d with Body length %d",
243 t.ContentLength, ncopy)
246 if chunked(t.TransferEncoding) {
247 // Write Trailer header
248 if t.Trailer != nil {
249 if err := t.Trailer.Write(w); err != nil {
253 // Last chunk, empty trailer
254 _, err = io.WriteString(w, "\r\n")
259 type transferReader struct {
269 TransferEncoding []string
274 func (t *transferReader) protoAtLeast(m, n int) bool {
275 return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
278 // bodyAllowedForStatus reports whether a given response status code
279 // permits a body. See RFC2616, section 4.4.
280 func bodyAllowedForStatus(status int) bool {
282 case status >= 100 && status <= 199:
293 suppressedHeaders304 = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
294 suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
297 func suppressedHeaders(status int) []string {
300 // RFC 2616 section 10.3.5: "the response MUST NOT include other entity-headers"
301 return suppressedHeaders304
302 case !bodyAllowedForStatus(status):
303 return suppressedHeadersNoBody
308 // msg is *Request or *Response.
309 func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
310 t := &transferReader{RequestMethod: "GET"}
314 switch rr := msg.(type) {
317 t.StatusCode = rr.StatusCode
318 t.ProtoMajor = rr.ProtoMajor
319 t.ProtoMinor = rr.ProtoMinor
320 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
322 if rr.Request != nil {
323 t.RequestMethod = rr.Request.Method
327 t.RequestMethod = rr.Method
328 t.ProtoMajor = rr.ProtoMajor
329 t.ProtoMinor = rr.ProtoMinor
330 // Transfer semantics for Requests are exactly like those for
331 // Responses with status code 200, responding to a GET method
335 panic("unexpected type")
338 // Default to HTTP/1.1
339 if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
340 t.ProtoMajor, t.ProtoMinor = 1, 1
343 // Transfer encoding, content length
344 err = t.fixTransferEncoding()
349 realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
353 if isResponse && t.RequestMethod == "HEAD" {
354 if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
360 t.ContentLength = realLength
364 t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
369 // If there is no Content-Length or chunked Transfer-Encoding on a *Response
370 // and the status is not 1xx, 204 or 304, then the body is unbounded.
371 // See RFC2616, section 4.4.
374 if realLength == -1 &&
375 !chunked(t.TransferEncoding) &&
376 bodyAllowedForStatus(t.StatusCode) {
382 // Prepare body reader. ContentLength < 0 means chunked encoding
383 // or close connection when finished, since multipart is not supported yet
385 case chunked(t.TransferEncoding):
386 if noBodyExpected(t.RequestMethod) {
389 t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
391 case realLength == 0:
394 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
396 // realLength < 0, i.e. "Content-Length" not mentioned in header
398 // Close semantics (i.e. HTTP/1.0)
399 t.Body = &body{src: r, closing: t.Close}
401 // Persistent connection (i.e. HTTP/1.1)
407 switch rr := msg.(type) {
410 rr.ContentLength = t.ContentLength
411 rr.TransferEncoding = t.TransferEncoding
413 rr.Trailer = t.Trailer
416 rr.ContentLength = t.ContentLength
417 rr.TransferEncoding = t.TransferEncoding
419 rr.Trailer = t.Trailer
425 // Checks whether chunked is part of the encodings stack
426 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
428 // Checks whether the encoding is explicitly "identity".
429 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
431 // fixTransferEncoding sanitizes t.TransferEncoding, if needed.
432 func (t *transferReader) fixTransferEncoding() error {
433 raw, present := t.Header["Transfer-Encoding"]
437 delete(t.Header, "Transfer-Encoding")
439 // Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
440 if !t.protoAtLeast(1, 1) {
444 encodings := strings.Split(raw[0], ",")
445 te := make([]string, 0, len(encodings))
446 // TODO: Even though we only support "identity" and "chunked"
447 // encodings, the loop below is designed with foresight. One
448 // invariant that must be maintained is that, if present,
449 // chunked encoding must always come first.
450 for _, encoding := range encodings {
451 encoding = strings.ToLower(strings.TrimSpace(encoding))
452 // "identity" encoding is not recorded
453 if encoding == "identity" {
456 if encoding != "chunked" {
457 return &badStringError{"unsupported transfer encoding", encoding}
459 te = te[0 : len(te)+1]
460 te[len(te)-1] = encoding
463 return &badStringError{"too many transfer encodings", strings.Join(te, ",")}
466 // RFC 7230 3.3.2 says "A sender MUST NOT send a
467 // Content-Length header field in any message that
468 // contains a Transfer-Encoding header field."
471 // "If a message is received with both a
472 // Transfer-Encoding and a Content-Length header
473 // field, the Transfer-Encoding overrides the
474 // Content-Length. Such a message might indicate an
475 // attempt to perform request smuggling (Section 9.5)
476 // or response splitting (Section 9.4) and ought to be
477 // handled as an error. A sender MUST remove the
478 // received Content-Length field prior to forwarding
479 // such a message downstream."
481 // Reportedly, these appear in the wild.
482 delete(t.Header, "Content-Length")
483 t.TransferEncoding = te
490 // Determine the expected body length, using RFC 2616 Section 4.4. This
491 // function is not a method, because ultimately it should be shared by
492 // ReadResponse and ReadRequest.
493 func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
494 contentLens := header["Content-Length"]
495 isRequest := !isResponse
496 // Logic based on response type or status
497 if noBodyExpected(requestMethod) {
498 // For HTTP requests, as part of hardening against request
499 // smuggling (RFC 7230), don't allow a Content-Length header for
500 // methods which don't permit bodies. As an exception, allow
501 // exactly one Content-Length header if its value is "0".
502 if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
503 return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
515 if len(contentLens) > 1 {
516 // harden against HTTP request smuggling. See RFC 7230.
517 return 0, errors.New("http: message cannot contain multiple Content-Length headers")
520 // Logic based on Transfer-Encoding
525 // Logic based on Content-Length
527 if len(contentLens) == 1 {
528 cl = strings.TrimSpace(contentLens[0])
531 n, err := parseContentLength(cl)
537 header.Del("Content-Length")
541 // RFC 2616 neither explicitly permits nor forbids an
542 // entity-body on a GET request so we permit one if
543 // declared, but we default to 0 here (not -1 below)
544 // if there's no mention of a body.
545 // Likewise, all other request methods are assumed to have
546 // no body if neither Transfer-Encoding chunked nor a
547 // Content-Length are set.
551 // Body-EOF logic based on other methods (like closing, or chunked coding)
555 // Determine whether to hang up after sending a request and body, or
556 // receiving a response and body
557 // 'header' is the request headers
558 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
563 conv := header["Connection"]
564 hasClose := headerValuesContainsToken(conv, "close")
565 if major == 1 && minor == 0 {
566 return hasClose || !headerValuesContainsToken(conv, "keep-alive")
569 if hasClose && removeCloseHeader {
570 header.Del("Connection")
576 // Parse the trailer header
577 func fixTrailer(header Header, te []string) (Header, error) {
578 vv, ok := header["Trailer"]
582 header.Del("Trailer")
584 trailer := make(Header)
586 for _, v := range vv {
587 foreachHeaderElement(v, func(key string) {
588 key = CanonicalHeaderKey(key)
590 case "Transfer-Encoding", "Trailer", "Content-Length":
592 err = &badStringError{"bad trailer key", key}
602 if len(trailer) == 0 {
606 // Trailer and no chunking
607 return nil, ErrUnexpectedTrailer
612 // body turns a Reader into a ReadCloser.
613 // Close ensures that the body has been fully read
614 // and then reads the trailer if necessary.
617 hdr interface{} // non-nil (Response or Request) value means read trailer
618 r *bufio.Reader // underlying wire-format reader for the trailer
619 closing bool // is the connection to be closed after reading body?
620 doEarlyClose bool // whether Close should stop early
622 mu sync.Mutex // guards following, and calls to Read and Close
625 earlyClose bool // Close called and we didn't read to the end of src
626 onHitEOF func() // if non-nil, func to call when EOF is Read
629 // ErrBodyReadAfterClose is returned when reading a Request or Response
630 // Body after the body has been closed. This typically happens when the body is
631 // read after an HTTP Handler calls WriteHeader or Write on its
633 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
635 func (b *body) Read(p []byte) (n int, err error) {
639 return 0, ErrBodyReadAfterClose
641 return b.readLocked(p)
645 func (b *body) readLocked(p []byte) (n int, err error) {
649 n, err = b.src.Read(p)
653 // Chunked case. Read the trailer.
655 if e := b.readTrailer(); e != nil {
657 // Something went wrong in the trailer, we must not allow any
658 // further reads of any kind to succeed from body, nor any
659 // subsequent requests on the server connection. See
660 // golang.org/issue/12027
666 // If the server declared the Content-Length, our body is a LimitedReader
667 // and we need to check whether this EOF arrived early.
668 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
669 err = io.ErrUnexpectedEOF
674 // If we can return an EOF here along with the read data, do
675 // so. This is optional per the io.Reader contract, but doing
676 // so helps the HTTP transport code recycle its connection
677 // earlier (since it will see this EOF itself), even if the
678 // client doesn't do future reads or Close.
679 if err == nil && n > 0 {
680 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
686 if b.sawEOF && b.onHitEOF != nil {
694 singleCRLF = []byte("\r\n")
695 doubleCRLF = []byte("\r\n\r\n")
698 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
699 for peekSize := 4; ; peekSize++ {
700 // This loop stops when Peek returns an error,
701 // which it does when r's buffer has been filled.
702 buf, err := r.Peek(peekSize)
703 if bytes.HasSuffix(buf, doubleCRLF) {
713 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
715 func (b *body) readTrailer() error {
716 // The common case, since nobody uses trailers.
717 buf, err := b.r.Peek(2)
718 if bytes.Equal(buf, singleCRLF) {
729 // Make sure there's a header terminator coming up, to prevent
730 // a DoS with an unbounded size Trailer. It's not easy to
731 // slip in a LimitReader here, as textproto.NewReader requires
732 // a concrete *bufio.Reader. Also, we can't get all the way
733 // back up to our conn's LimitedReader that *might* be backing
734 // this bufio.Reader. Instead, a hack: we iteratively Peek up
735 // to the bufio.Reader's max size, looking for a double CRLF.
736 // This limits the trailer to the underlying buffer size, typically 4kB.
737 if !seeUpcomingDoubleCRLF(b.r) {
738 return errors.New("http: suspiciously long trailer after chunked body")
741 hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
748 switch rr := b.hdr.(type) {
750 mergeSetHeader(&rr.Trailer, Header(hdr))
752 mergeSetHeader(&rr.Trailer, Header(hdr))
757 func mergeSetHeader(dst *Header, src Header) {
762 for k, vv := range src {
767 // unreadDataSizeLocked returns the number of bytes of unread input.
768 // It returns -1 if unknown.
769 // b.mu must be held.
770 func (b *body) unreadDataSizeLocked() int64 {
771 if lr, ok := b.src.(*io.LimitedReader); ok {
777 func (b *body) Close() error {
786 // Already saw EOF, so no need going to look for it.
787 case b.hdr == nil && b.closing:
788 // no trailer and closing the connection next.
789 // no point in reading to EOF.
791 // Read up to maxPostHandlerReadBytes bytes of the body, looking for
792 // for EOF (and trailers), so we can re-use this connection.
793 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
794 // There was a declared Content-Length, and we have more bytes remaining
795 // than our maxPostHandlerReadBytes tolerance. So, give up.
799 // Consume the body, or, which will also lead to us reading
800 // the trailer headers after the body, if present.
801 n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
805 if n == maxPostHandlerReadBytes {
810 // Fully consume the body, which will also lead to us reading
811 // the trailer headers after the body, if present.
812 _, err = io.Copy(ioutil.Discard, bodyLocked{b})
818 func (b *body) didEarlyClose() bool {
824 // bodyRemains reports whether future Read calls might
826 func (b *body) bodyRemains() bool {
832 func (b *body) registerOnHitEOF(fn func()) {
838 // bodyLocked is a io.Reader reading from a *body when its mutex is
840 type bodyLocked struct {
844 func (bl bodyLocked) Read(p []byte) (n int, err error) {
846 return 0, ErrBodyReadAfterClose
848 return bl.b.readLocked(p)
851 // parseContentLength trims whitespace from s and returns -1 if no value
852 // is set, or the value if it's >= 0.
853 func parseContentLength(cl string) (int64, error) {
854 cl = strings.TrimSpace(cl)
858 n, err := strconv.ParseInt(cl, 10, 64)
859 if err != nil || n < 0 {
860 return 0, &badStringError{"bad Content-Length", cl}