github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/net/http/transfer.go (about)

     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.
     4  
     5  package http
     6  
     7  import (
     8  	"bufio"
     9  	"bytes"
    10  	"errors"
    11  	"fmt"
    12  	"io"
    13  	"io/ioutil"
    14  	"net/http/internal"
    15  	"net/textproto"
    16  	"sort"
    17  	"strconv"
    18  	"strings"
    19  	"sync"
    20  	"time"
    21  
    22  	"golang_org/x/net/lex/httplex"
    23  )
    24  
    25  // ErrLineTooLong is returned when reading request or response bodies
    26  // with malformed chunked encoding.
    27  var ErrLineTooLong = internal.ErrLineTooLong
    28  
    29  type errorReader struct {
    30  	err error
    31  }
    32  
    33  func (r errorReader) Read(p []byte) (n int, err error) {
    34  	return 0, r.err
    35  }
    36  
    37  type byteReader struct {
    38  	b    byte
    39  	done bool
    40  }
    41  
    42  func (br *byteReader) Read(p []byte) (n int, err error) {
    43  	if br.done {
    44  		return 0, io.EOF
    45  	}
    46  	if len(p) == 0 {
    47  		return 0, nil
    48  	}
    49  	br.done = true
    50  	p[0] = br.b
    51  	return 1, io.EOF
    52  }
    53  
    54  // transferBodyReader is an io.Reader that reads from tw.Body
    55  // and records any non-EOF error in tw.bodyReadError.
    56  // It is exactly 1 pointer wide to avoid allocations into interfaces.
    57  type transferBodyReader struct{ tw *transferWriter }
    58  
    59  func (br transferBodyReader) Read(p []byte) (n int, err error) {
    60  	n, err = br.tw.Body.Read(p)
    61  	if err != nil && err != io.EOF {
    62  		br.tw.bodyReadError = err
    63  	}
    64  	return
    65  }
    66  
    67  // transferWriter inspects the fields of a user-supplied Request or Response,
    68  // sanitizes them without changing the user object and provides methods for
    69  // writing the respective header, body and trailer in wire format.
    70  type transferWriter struct {
    71  	Method           string
    72  	Body             io.Reader
    73  	BodyCloser       io.Closer
    74  	ResponseToHEAD   bool
    75  	ContentLength    int64 // -1 means unknown, 0 means exactly none
    76  	Close            bool
    77  	TransferEncoding []string
    78  	Trailer          Header
    79  	IsResponse       bool
    80  	bodyReadError    error // any non-EOF error from reading Body
    81  
    82  	FlushHeaders bool            // flush headers to network before body
    83  	ByteReadCh   chan readResult // non-nil if probeRequestBody called
    84  }
    85  
    86  func newTransferWriter(r interface{}) (t *transferWriter, err error) {
    87  	t = &transferWriter{}
    88  
    89  	// Extract relevant fields
    90  	atLeastHTTP11 := false
    91  	switch rr := r.(type) {
    92  	case *Request:
    93  		if rr.ContentLength != 0 && rr.Body == nil {
    94  			return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
    95  		}
    96  		t.Method = valueOrDefault(rr.Method, "GET")
    97  		t.Close = rr.Close
    98  		t.TransferEncoding = rr.TransferEncoding
    99  		t.Trailer = rr.Trailer
   100  		atLeastHTTP11 = rr.protoAtLeastOutgoing(1, 1)
   101  		t.Body = rr.Body
   102  		t.BodyCloser = rr.Body
   103  		t.ContentLength = rr.outgoingLength()
   104  		if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && atLeastHTTP11 && t.shouldSendChunkedRequestBody() {
   105  			t.TransferEncoding = []string{"chunked"}
   106  		}
   107  	case *Response:
   108  		t.IsResponse = true
   109  		if rr.Request != nil {
   110  			t.Method = rr.Request.Method
   111  		}
   112  		t.Body = rr.Body
   113  		t.BodyCloser = rr.Body
   114  		t.ContentLength = rr.ContentLength
   115  		t.Close = rr.Close
   116  		t.TransferEncoding = rr.TransferEncoding
   117  		t.Trailer = rr.Trailer
   118  		atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
   119  		t.ResponseToHEAD = noResponseBodyExpected(t.Method)
   120  	}
   121  
   122  	// Sanitize Body,ContentLength,TransferEncoding
   123  	if t.ResponseToHEAD {
   124  		t.Body = nil
   125  		if chunked(t.TransferEncoding) {
   126  			t.ContentLength = -1
   127  		}
   128  	} else {
   129  		if !atLeastHTTP11 || t.Body == nil {
   130  			t.TransferEncoding = nil
   131  		}
   132  		if chunked(t.TransferEncoding) {
   133  			t.ContentLength = -1
   134  		} else if t.Body == nil { // no chunking, no body
   135  			t.ContentLength = 0
   136  		}
   137  	}
   138  
   139  	// Sanitize Trailer
   140  	if !chunked(t.TransferEncoding) {
   141  		t.Trailer = nil
   142  	}
   143  
   144  	return t, nil
   145  }
   146  
   147  // shouldSendChunkedRequestBody reports whether we should try to send a
   148  // chunked request body to the server. In particular, the case we really
   149  // want to prevent is sending a GET or other typically-bodyless request to a
   150  // server with a chunked body when the body has zero bytes, since GETs with
   151  // bodies (while acceptable according to specs), even zero-byte chunked
   152  // bodies, are approximately never seen in the wild and confuse most
   153  // servers. See Issue 18257, as one example.
   154  //
   155  // The only reason we'd send such a request is if the user set the Body to a
   156  // non-nil value (say, ioutil.NopCloser(bytes.NewReader(nil))) and didn't
   157  // set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
   158  // there's bytes to send.
   159  //
   160  // This code tries to read a byte from the Request.Body in such cases to see
   161  // whether the body actually has content (super rare) or is actually just
   162  // a non-nil content-less ReadCloser (the more common case). In that more
   163  // common case, we act as if their Body were nil instead, and don't send
   164  // a body.
   165  func (t *transferWriter) shouldSendChunkedRequestBody() bool {
   166  	// Note that t.ContentLength is the corrected content length
   167  	// from rr.outgoingLength, so 0 actually means zero, not unknown.
   168  	if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
   169  		return false
   170  	}
   171  	if requestMethodUsuallyLacksBody(t.Method) {
   172  		// Only probe the Request.Body for GET/HEAD/DELETE/etc
   173  		// requests, because it's only those types of requests
   174  		// that confuse servers.
   175  		t.probeRequestBody() // adjusts t.Body, t.ContentLength
   176  		return t.Body != nil
   177  	}
   178  	// For all other request types (PUT, POST, PATCH, or anything
   179  	// made-up we've never heard of), assume it's normal and the server
   180  	// can deal with a chunked request body. Maybe we'll adjust this
   181  	// later.
   182  	return true
   183  }
   184  
   185  // probeRequestBody reads a byte from t.Body to see whether it's empty
   186  // (returns io.EOF right away).
   187  //
   188  // But because we've had problems with this blocking users in the past
   189  // (issue 17480) when the body is a pipe (perhaps waiting on the response
   190  // headers before the pipe is fed data), we need to be careful and bound how
   191  // long we wait for it. This delay will only affect users if all the following
   192  // are true:
   193  //   * the request body blocks
   194  //   * the content length is not set (or set to -1)
   195  //   * the method doesn't usually have a body (GET, HEAD, DELETE, ...)
   196  //   * there is no transfer-encoding=chunked already set.
   197  // In other words, this delay will not normally affect anybody, and there
   198  // are workarounds if it does.
   199  func (t *transferWriter) probeRequestBody() {
   200  	t.ByteReadCh = make(chan readResult, 1)
   201  	go func(body io.Reader) {
   202  		var buf [1]byte
   203  		var rres readResult
   204  		rres.n, rres.err = body.Read(buf[:])
   205  		if rres.n == 1 {
   206  			rres.b = buf[0]
   207  		}
   208  		t.ByteReadCh <- rres
   209  	}(t.Body)
   210  	timer := time.NewTimer(200 * time.Millisecond)
   211  	select {
   212  	case rres := <-t.ByteReadCh:
   213  		timer.Stop()
   214  		if rres.n == 0 && rres.err == io.EOF {
   215  			// It was empty.
   216  			t.Body = nil
   217  			t.ContentLength = 0
   218  		} else if rres.n == 1 {
   219  			if rres.err != nil {
   220  				t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
   221  			} else {
   222  				t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
   223  			}
   224  		} else if rres.err != nil {
   225  			t.Body = errorReader{rres.err}
   226  		}
   227  	case <-timer.C:
   228  		// Too slow. Don't wait. Read it later, and keep
   229  		// assuming that this is ContentLength == -1
   230  		// (unknown), which means we'll send a
   231  		// "Transfer-Encoding: chunked" header.
   232  		t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
   233  		// Request that Request.Write flush the headers to the
   234  		// network before writing the body, since our body may not
   235  		// become readable until it's seen the response headers.
   236  		t.FlushHeaders = true
   237  	}
   238  }
   239  
   240  func noResponseBodyExpected(requestMethod string) bool {
   241  	return requestMethod == "HEAD"
   242  }
   243  
   244  func (t *transferWriter) shouldSendContentLength() bool {
   245  	if chunked(t.TransferEncoding) {
   246  		return false
   247  	}
   248  	if t.ContentLength > 0 {
   249  		return true
   250  	}
   251  	if t.ContentLength < 0 {
   252  		return false
   253  	}
   254  	// Many servers expect a Content-Length for these methods
   255  	if t.Method == "POST" || t.Method == "PUT" {
   256  		return true
   257  	}
   258  	if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
   259  		if t.Method == "GET" || t.Method == "HEAD" {
   260  			return false
   261  		}
   262  		return true
   263  	}
   264  
   265  	return false
   266  }
   267  
   268  func (t *transferWriter) WriteHeader(w io.Writer) error {
   269  	if t.Close {
   270  		if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
   271  			return err
   272  		}
   273  	}
   274  
   275  	// Write Content-Length and/or Transfer-Encoding whose values are a
   276  	// function of the sanitized field triple (Body, ContentLength,
   277  	// TransferEncoding)
   278  	if t.shouldSendContentLength() {
   279  		if _, err := io.WriteString(w, "Content-Length: "); err != nil {
   280  			return err
   281  		}
   282  		if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
   283  			return err
   284  		}
   285  	} else if chunked(t.TransferEncoding) {
   286  		if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
   287  			return err
   288  		}
   289  	}
   290  
   291  	// Write Trailer header
   292  	if t.Trailer != nil {
   293  		keys := make([]string, 0, len(t.Trailer))
   294  		for k := range t.Trailer {
   295  			k = CanonicalHeaderKey(k)
   296  			switch k {
   297  			case "Transfer-Encoding", "Trailer", "Content-Length":
   298  				return &badStringError{"invalid Trailer key", k}
   299  			}
   300  			keys = append(keys, k)
   301  		}
   302  		if len(keys) > 0 {
   303  			sort.Strings(keys)
   304  			// TODO: could do better allocation-wise here, but trailers are rare,
   305  			// so being lazy for now.
   306  			if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
   307  				return err
   308  			}
   309  		}
   310  	}
   311  
   312  	return nil
   313  }
   314  
   315  func (t *transferWriter) WriteBody(w io.Writer) error {
   316  	var err error
   317  	var ncopy int64
   318  
   319  	// Write body
   320  	if t.Body != nil {
   321  		var body = transferBodyReader{t}
   322  		if chunked(t.TransferEncoding) {
   323  			if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
   324  				w = &internal.FlushAfterChunkWriter{Writer: bw}
   325  			}
   326  			cw := internal.NewChunkedWriter(w)
   327  			_, err = io.Copy(cw, body)
   328  			if err == nil {
   329  				err = cw.Close()
   330  			}
   331  		} else if t.ContentLength == -1 {
   332  			ncopy, err = io.Copy(w, body)
   333  		} else {
   334  			ncopy, err = io.Copy(w, io.LimitReader(body, t.ContentLength))
   335  			if err != nil {
   336  				return err
   337  			}
   338  			var nextra int64
   339  			nextra, err = io.Copy(ioutil.Discard, body)
   340  			ncopy += nextra
   341  		}
   342  		if err != nil {
   343  			return err
   344  		}
   345  	}
   346  	if t.BodyCloser != nil {
   347  		if err := t.BodyCloser.Close(); err != nil {
   348  			return err
   349  		}
   350  	}
   351  
   352  	if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
   353  		return fmt.Errorf("http: ContentLength=%d with Body length %d",
   354  			t.ContentLength, ncopy)
   355  	}
   356  
   357  	if chunked(t.TransferEncoding) {
   358  		// Write Trailer header
   359  		if t.Trailer != nil {
   360  			if err := t.Trailer.Write(w); err != nil {
   361  				return err
   362  			}
   363  		}
   364  		// Last chunk, empty trailer
   365  		_, err = io.WriteString(w, "\r\n")
   366  	}
   367  	return err
   368  }
   369  
   370  type transferReader struct {
   371  	// Input
   372  	Header        Header
   373  	StatusCode    int
   374  	RequestMethod string
   375  	ProtoMajor    int
   376  	ProtoMinor    int
   377  	// Output
   378  	Body             io.ReadCloser
   379  	ContentLength    int64
   380  	TransferEncoding []string
   381  	Close            bool
   382  	Trailer          Header
   383  }
   384  
   385  func (t *transferReader) protoAtLeast(m, n int) bool {
   386  	return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
   387  }
   388  
   389  // bodyAllowedForStatus reports whether a given response status code
   390  // permits a body. See RFC 2616, section 4.4.
   391  func bodyAllowedForStatus(status int) bool {
   392  	switch {
   393  	case status >= 100 && status <= 199:
   394  		return false
   395  	case status == 204:
   396  		return false
   397  	case status == 304:
   398  		return false
   399  	}
   400  	return true
   401  }
   402  
   403  var (
   404  	suppressedHeaders304    = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
   405  	suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
   406  )
   407  
   408  func suppressedHeaders(status int) []string {
   409  	switch {
   410  	case status == 304:
   411  		// RFC 2616 section 10.3.5: "the response MUST NOT include other entity-headers"
   412  		return suppressedHeaders304
   413  	case !bodyAllowedForStatus(status):
   414  		return suppressedHeadersNoBody
   415  	}
   416  	return nil
   417  }
   418  
   419  // msg is *Request or *Response.
   420  func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
   421  	t := &transferReader{RequestMethod: "GET"}
   422  
   423  	// Unify input
   424  	isResponse := false
   425  	switch rr := msg.(type) {
   426  	case *Response:
   427  		t.Header = rr.Header
   428  		t.StatusCode = rr.StatusCode
   429  		t.ProtoMajor = rr.ProtoMajor
   430  		t.ProtoMinor = rr.ProtoMinor
   431  		t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
   432  		isResponse = true
   433  		if rr.Request != nil {
   434  			t.RequestMethod = rr.Request.Method
   435  		}
   436  	case *Request:
   437  		t.Header = rr.Header
   438  		t.RequestMethod = rr.Method
   439  		t.ProtoMajor = rr.ProtoMajor
   440  		t.ProtoMinor = rr.ProtoMinor
   441  		// Transfer semantics for Requests are exactly like those for
   442  		// Responses with status code 200, responding to a GET method
   443  		t.StatusCode = 200
   444  		t.Close = rr.Close
   445  	default:
   446  		panic("unexpected type")
   447  	}
   448  
   449  	// Default to HTTP/1.1
   450  	if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
   451  		t.ProtoMajor, t.ProtoMinor = 1, 1
   452  	}
   453  
   454  	// Transfer encoding, content length
   455  	err = t.fixTransferEncoding()
   456  	if err != nil {
   457  		return err
   458  	}
   459  
   460  	realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
   461  	if err != nil {
   462  		return err
   463  	}
   464  	if isResponse && t.RequestMethod == "HEAD" {
   465  		if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
   466  			return err
   467  		} else {
   468  			t.ContentLength = n
   469  		}
   470  	} else {
   471  		t.ContentLength = realLength
   472  	}
   473  
   474  	// Trailer
   475  	t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
   476  	if err != nil {
   477  		return err
   478  	}
   479  
   480  	// If there is no Content-Length or chunked Transfer-Encoding on a *Response
   481  	// and the status is not 1xx, 204 or 304, then the body is unbounded.
   482  	// See RFC 2616, section 4.4.
   483  	switch msg.(type) {
   484  	case *Response:
   485  		if realLength == -1 &&
   486  			!chunked(t.TransferEncoding) &&
   487  			bodyAllowedForStatus(t.StatusCode) {
   488  			// Unbounded body.
   489  			t.Close = true
   490  		}
   491  	}
   492  
   493  	// Prepare body reader. ContentLength < 0 means chunked encoding
   494  	// or close connection when finished, since multipart is not supported yet
   495  	switch {
   496  	case chunked(t.TransferEncoding):
   497  		if noResponseBodyExpected(t.RequestMethod) {
   498  			t.Body = NoBody
   499  		} else {
   500  			t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
   501  		}
   502  	case realLength == 0:
   503  		t.Body = NoBody
   504  	case realLength > 0:
   505  		t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
   506  	default:
   507  		// realLength < 0, i.e. "Content-Length" not mentioned in header
   508  		if t.Close {
   509  			// Close semantics (i.e. HTTP/1.0)
   510  			t.Body = &body{src: r, closing: t.Close}
   511  		} else {
   512  			// Persistent connection (i.e. HTTP/1.1)
   513  			t.Body = NoBody
   514  		}
   515  	}
   516  
   517  	// Unify output
   518  	switch rr := msg.(type) {
   519  	case *Request:
   520  		rr.Body = t.Body
   521  		rr.ContentLength = t.ContentLength
   522  		rr.TransferEncoding = t.TransferEncoding
   523  		rr.Close = t.Close
   524  		rr.Trailer = t.Trailer
   525  	case *Response:
   526  		rr.Body = t.Body
   527  		rr.ContentLength = t.ContentLength
   528  		rr.TransferEncoding = t.TransferEncoding
   529  		rr.Close = t.Close
   530  		rr.Trailer = t.Trailer
   531  	}
   532  
   533  	return nil
   534  }
   535  
   536  // Checks whether chunked is part of the encodings stack
   537  func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
   538  
   539  // Checks whether the encoding is explicitly "identity".
   540  func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
   541  
   542  // fixTransferEncoding sanitizes t.TransferEncoding, if needed.
   543  func (t *transferReader) fixTransferEncoding() error {
   544  	raw, present := t.Header["Transfer-Encoding"]
   545  	if !present {
   546  		return nil
   547  	}
   548  	delete(t.Header, "Transfer-Encoding")
   549  
   550  	// Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
   551  	if !t.protoAtLeast(1, 1) {
   552  		return nil
   553  	}
   554  
   555  	encodings := strings.Split(raw[0], ",")
   556  	te := make([]string, 0, len(encodings))
   557  	// TODO: Even though we only support "identity" and "chunked"
   558  	// encodings, the loop below is designed with foresight. One
   559  	// invariant that must be maintained is that, if present,
   560  	// chunked encoding must always come first.
   561  	for _, encoding := range encodings {
   562  		encoding = strings.ToLower(strings.TrimSpace(encoding))
   563  		// "identity" encoding is not recorded
   564  		if encoding == "identity" {
   565  			break
   566  		}
   567  		if encoding != "chunked" {
   568  			return &badStringError{"unsupported transfer encoding", encoding}
   569  		}
   570  		te = te[0 : len(te)+1]
   571  		te[len(te)-1] = encoding
   572  	}
   573  	if len(te) > 1 {
   574  		return &badStringError{"too many transfer encodings", strings.Join(te, ",")}
   575  	}
   576  	if len(te) > 0 {
   577  		// RFC 7230 3.3.2 says "A sender MUST NOT send a
   578  		// Content-Length header field in any message that
   579  		// contains a Transfer-Encoding header field."
   580  		//
   581  		// but also:
   582  		// "If a message is received with both a
   583  		// Transfer-Encoding and a Content-Length header
   584  		// field, the Transfer-Encoding overrides the
   585  		// Content-Length. Such a message might indicate an
   586  		// attempt to perform request smuggling (Section 9.5)
   587  		// or response splitting (Section 9.4) and ought to be
   588  		// handled as an error. A sender MUST remove the
   589  		// received Content-Length field prior to forwarding
   590  		// such a message downstream."
   591  		//
   592  		// Reportedly, these appear in the wild.
   593  		delete(t.Header, "Content-Length")
   594  		t.TransferEncoding = te
   595  		return nil
   596  	}
   597  
   598  	return nil
   599  }
   600  
   601  // Determine the expected body length, using RFC 2616 Section 4.4. This
   602  // function is not a method, because ultimately it should be shared by
   603  // ReadResponse and ReadRequest.
   604  func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
   605  	isRequest := !isResponse
   606  	contentLens := header["Content-Length"]
   607  
   608  	// Hardening against HTTP request smuggling
   609  	if len(contentLens) > 1 {
   610  		// Per RFC 7230 Section 3.3.2, prevent multiple
   611  		// Content-Length headers if they differ in value.
   612  		// If there are dups of the value, remove the dups.
   613  		// See Issue 16490.
   614  		first := strings.TrimSpace(contentLens[0])
   615  		for _, ct := range contentLens[1:] {
   616  			if first != strings.TrimSpace(ct) {
   617  				return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
   618  			}
   619  		}
   620  
   621  		// deduplicate Content-Length
   622  		header.Del("Content-Length")
   623  		header.Add("Content-Length", first)
   624  
   625  		contentLens = header["Content-Length"]
   626  	}
   627  
   628  	// Logic based on response type or status
   629  	if noResponseBodyExpected(requestMethod) {
   630  		// For HTTP requests, as part of hardening against request
   631  		// smuggling (RFC 7230), don't allow a Content-Length header for
   632  		// methods which don't permit bodies. As an exception, allow
   633  		// exactly one Content-Length header if its value is "0".
   634  		if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
   635  			return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
   636  		}
   637  		return 0, nil
   638  	}
   639  	if status/100 == 1 {
   640  		return 0, nil
   641  	}
   642  	switch status {
   643  	case 204, 304:
   644  		return 0, nil
   645  	}
   646  
   647  	// Logic based on Transfer-Encoding
   648  	if chunked(te) {
   649  		return -1, nil
   650  	}
   651  
   652  	// Logic based on Content-Length
   653  	var cl string
   654  	if len(contentLens) == 1 {
   655  		cl = strings.TrimSpace(contentLens[0])
   656  	}
   657  	if cl != "" {
   658  		n, err := parseContentLength(cl)
   659  		if err != nil {
   660  			return -1, err
   661  		}
   662  		return n, nil
   663  	} else {
   664  		header.Del("Content-Length")
   665  	}
   666  
   667  	if isRequest {
   668  		// RFC 2616 neither explicitly permits nor forbids an
   669  		// entity-body on a GET request so we permit one if
   670  		// declared, but we default to 0 here (not -1 below)
   671  		// if there's no mention of a body.
   672  		// Likewise, all other request methods are assumed to have
   673  		// no body if neither Transfer-Encoding chunked nor a
   674  		// Content-Length are set.
   675  		return 0, nil
   676  	}
   677  
   678  	// Body-EOF logic based on other methods (like closing, or chunked coding)
   679  	return -1, nil
   680  }
   681  
   682  // Determine whether to hang up after sending a request and body, or
   683  // receiving a response and body
   684  // 'header' is the request headers
   685  func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
   686  	if major < 1 {
   687  		return true
   688  	}
   689  
   690  	conv := header["Connection"]
   691  	hasClose := httplex.HeaderValuesContainsToken(conv, "close")
   692  	if major == 1 && minor == 0 {
   693  		return hasClose || !httplex.HeaderValuesContainsToken(conv, "keep-alive")
   694  	}
   695  
   696  	if hasClose && removeCloseHeader {
   697  		header.Del("Connection")
   698  	}
   699  
   700  	return hasClose
   701  }
   702  
   703  // Parse the trailer header
   704  func fixTrailer(header Header, te []string) (Header, error) {
   705  	vv, ok := header["Trailer"]
   706  	if !ok {
   707  		return nil, nil
   708  	}
   709  	header.Del("Trailer")
   710  
   711  	trailer := make(Header)
   712  	var err error
   713  	for _, v := range vv {
   714  		foreachHeaderElement(v, func(key string) {
   715  			key = CanonicalHeaderKey(key)
   716  			switch key {
   717  			case "Transfer-Encoding", "Trailer", "Content-Length":
   718  				if err == nil {
   719  					err = &badStringError{"bad trailer key", key}
   720  					return
   721  				}
   722  			}
   723  			trailer[key] = nil
   724  		})
   725  	}
   726  	if err != nil {
   727  		return nil, err
   728  	}
   729  	if len(trailer) == 0 {
   730  		return nil, nil
   731  	}
   732  	if !chunked(te) {
   733  		// Trailer and no chunking
   734  		return nil, ErrUnexpectedTrailer
   735  	}
   736  	return trailer, nil
   737  }
   738  
   739  // body turns a Reader into a ReadCloser.
   740  // Close ensures that the body has been fully read
   741  // and then reads the trailer if necessary.
   742  type body struct {
   743  	src          io.Reader
   744  	hdr          interface{}   // non-nil (Response or Request) value means read trailer
   745  	r            *bufio.Reader // underlying wire-format reader for the trailer
   746  	closing      bool          // is the connection to be closed after reading body?
   747  	doEarlyClose bool          // whether Close should stop early
   748  
   749  	mu         sync.Mutex // guards following, and calls to Read and Close
   750  	sawEOF     bool
   751  	closed     bool
   752  	earlyClose bool   // Close called and we didn't read to the end of src
   753  	onHitEOF   func() // if non-nil, func to call when EOF is Read
   754  }
   755  
   756  // ErrBodyReadAfterClose is returned when reading a Request or Response
   757  // Body after the body has been closed. This typically happens when the body is
   758  // read after an HTTP Handler calls WriteHeader or Write on its
   759  // ResponseWriter.
   760  var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
   761  
   762  func (b *body) Read(p []byte) (n int, err error) {
   763  	b.mu.Lock()
   764  	defer b.mu.Unlock()
   765  	if b.closed {
   766  		return 0, ErrBodyReadAfterClose
   767  	}
   768  	return b.readLocked(p)
   769  }
   770  
   771  // Must hold b.mu.
   772  func (b *body) readLocked(p []byte) (n int, err error) {
   773  	if b.sawEOF {
   774  		return 0, io.EOF
   775  	}
   776  	n, err = b.src.Read(p)
   777  
   778  	if err == io.EOF {
   779  		b.sawEOF = true
   780  		// Chunked case. Read the trailer.
   781  		if b.hdr != nil {
   782  			if e := b.readTrailer(); e != nil {
   783  				err = e
   784  				// Something went wrong in the trailer, we must not allow any
   785  				// further reads of any kind to succeed from body, nor any
   786  				// subsequent requests on the server connection. See
   787  				// golang.org/issue/12027
   788  				b.sawEOF = false
   789  				b.closed = true
   790  			}
   791  			b.hdr = nil
   792  		} else {
   793  			// If the server declared the Content-Length, our body is a LimitedReader
   794  			// and we need to check whether this EOF arrived early.
   795  			if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
   796  				err = io.ErrUnexpectedEOF
   797  			}
   798  		}
   799  	}
   800  
   801  	// If we can return an EOF here along with the read data, do
   802  	// so. This is optional per the io.Reader contract, but doing
   803  	// so helps the HTTP transport code recycle its connection
   804  	// earlier (since it will see this EOF itself), even if the
   805  	// client doesn't do future reads or Close.
   806  	if err == nil && n > 0 {
   807  		if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
   808  			err = io.EOF
   809  			b.sawEOF = true
   810  		}
   811  	}
   812  
   813  	if b.sawEOF && b.onHitEOF != nil {
   814  		b.onHitEOF()
   815  	}
   816  
   817  	return n, err
   818  }
   819  
   820  var (
   821  	singleCRLF = []byte("\r\n")
   822  	doubleCRLF = []byte("\r\n\r\n")
   823  )
   824  
   825  func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
   826  	for peekSize := 4; ; peekSize++ {
   827  		// This loop stops when Peek returns an error,
   828  		// which it does when r's buffer has been filled.
   829  		buf, err := r.Peek(peekSize)
   830  		if bytes.HasSuffix(buf, doubleCRLF) {
   831  			return true
   832  		}
   833  		if err != nil {
   834  			break
   835  		}
   836  	}
   837  	return false
   838  }
   839  
   840  var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
   841  
   842  func (b *body) readTrailer() error {
   843  	// The common case, since nobody uses trailers.
   844  	buf, err := b.r.Peek(2)
   845  	if bytes.Equal(buf, singleCRLF) {
   846  		b.r.Discard(2)
   847  		return nil
   848  	}
   849  	if len(buf) < 2 {
   850  		return errTrailerEOF
   851  	}
   852  	if err != nil {
   853  		return err
   854  	}
   855  
   856  	// Make sure there's a header terminator coming up, to prevent
   857  	// a DoS with an unbounded size Trailer. It's not easy to
   858  	// slip in a LimitReader here, as textproto.NewReader requires
   859  	// a concrete *bufio.Reader. Also, we can't get all the way
   860  	// back up to our conn's LimitedReader that *might* be backing
   861  	// this bufio.Reader. Instead, a hack: we iteratively Peek up
   862  	// to the bufio.Reader's max size, looking for a double CRLF.
   863  	// This limits the trailer to the underlying buffer size, typically 4kB.
   864  	if !seeUpcomingDoubleCRLF(b.r) {
   865  		return errors.New("http: suspiciously long trailer after chunked body")
   866  	}
   867  
   868  	hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
   869  	if err != nil {
   870  		if err == io.EOF {
   871  			return errTrailerEOF
   872  		}
   873  		return err
   874  	}
   875  	switch rr := b.hdr.(type) {
   876  	case *Request:
   877  		mergeSetHeader(&rr.Trailer, Header(hdr))
   878  	case *Response:
   879  		mergeSetHeader(&rr.Trailer, Header(hdr))
   880  	}
   881  	return nil
   882  }
   883  
   884  func mergeSetHeader(dst *Header, src Header) {
   885  	if *dst == nil {
   886  		*dst = src
   887  		return
   888  	}
   889  	for k, vv := range src {
   890  		(*dst)[k] = vv
   891  	}
   892  }
   893  
   894  // unreadDataSizeLocked returns the number of bytes of unread input.
   895  // It returns -1 if unknown.
   896  // b.mu must be held.
   897  func (b *body) unreadDataSizeLocked() int64 {
   898  	if lr, ok := b.src.(*io.LimitedReader); ok {
   899  		return lr.N
   900  	}
   901  	return -1
   902  }
   903  
   904  func (b *body) Close() error {
   905  	b.mu.Lock()
   906  	defer b.mu.Unlock()
   907  	if b.closed {
   908  		return nil
   909  	}
   910  	var err error
   911  	switch {
   912  	case b.sawEOF:
   913  		// Already saw EOF, so no need going to look for it.
   914  	case b.hdr == nil && b.closing:
   915  		// no trailer and closing the connection next.
   916  		// no point in reading to EOF.
   917  	case b.doEarlyClose:
   918  		// Read up to maxPostHandlerReadBytes bytes of the body, looking for
   919  		// for EOF (and trailers), so we can re-use this connection.
   920  		if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
   921  			// There was a declared Content-Length, and we have more bytes remaining
   922  			// than our maxPostHandlerReadBytes tolerance. So, give up.
   923  			b.earlyClose = true
   924  		} else {
   925  			var n int64
   926  			// Consume the body, or, which will also lead to us reading
   927  			// the trailer headers after the body, if present.
   928  			n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
   929  			if err == io.EOF {
   930  				err = nil
   931  			}
   932  			if n == maxPostHandlerReadBytes {
   933  				b.earlyClose = true
   934  			}
   935  		}
   936  	default:
   937  		// Fully consume the body, which will also lead to us reading
   938  		// the trailer headers after the body, if present.
   939  		_, err = io.Copy(ioutil.Discard, bodyLocked{b})
   940  	}
   941  	b.closed = true
   942  	return err
   943  }
   944  
   945  func (b *body) didEarlyClose() bool {
   946  	b.mu.Lock()
   947  	defer b.mu.Unlock()
   948  	return b.earlyClose
   949  }
   950  
   951  // bodyRemains reports whether future Read calls might
   952  // yield data.
   953  func (b *body) bodyRemains() bool {
   954  	b.mu.Lock()
   955  	defer b.mu.Unlock()
   956  	return !b.sawEOF
   957  }
   958  
   959  func (b *body) registerOnHitEOF(fn func()) {
   960  	b.mu.Lock()
   961  	defer b.mu.Unlock()
   962  	b.onHitEOF = fn
   963  }
   964  
   965  // bodyLocked is a io.Reader reading from a *body when its mutex is
   966  // already held.
   967  type bodyLocked struct {
   968  	b *body
   969  }
   970  
   971  func (bl bodyLocked) Read(p []byte) (n int, err error) {
   972  	if bl.b.closed {
   973  		return 0, ErrBodyReadAfterClose
   974  	}
   975  	return bl.b.readLocked(p)
   976  }
   977  
   978  // parseContentLength trims whitespace from s and returns -1 if no value
   979  // is set, or the value if it's >= 0.
   980  func parseContentLength(cl string) (int64, error) {
   981  	cl = strings.TrimSpace(cl)
   982  	if cl == "" {
   983  		return -1, nil
   984  	}
   985  	n, err := strconv.ParseInt(cl, 10, 64)
   986  	if err != nil || n < 0 {
   987  		return 0, &badStringError{"bad Content-Length", cl}
   988  	}
   989  	return n, nil
   990  
   991  }
   992  
   993  // finishAsyncByteRead finishes reading the 1-byte sniff
   994  // from the ContentLength==0, Body!=nil case.
   995  type finishAsyncByteRead struct {
   996  	tw *transferWriter
   997  }
   998  
   999  func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
  1000  	if len(p) == 0 {
  1001  		return
  1002  	}
  1003  	rres := <-fr.tw.ByteReadCh
  1004  	n, err = rres.n, rres.err
  1005  	if n == 1 {
  1006  		p[0] = rres.b
  1007  	}
  1008  	return
  1009  }