github.com/c12o16h1/go/src@v0.0.0-20200114212001-5a151c0f00ed/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  	"compress/gzip"
    11  	"errors"
    12  	"fmt"
    13  	"io"
    14  	"io/ioutil"
    15  	"net/http/httptrace"
    16  	"net/textproto"
    17  	"reflect"
    18  	"sort"
    19  	"strconv"
    20  	"strings"
    21  	"sync"
    22  	"time"
    23  
    24  	"github.com/c12o16h1/go/src/net/http/internal"
    25  
    26  	"golang.org/x/net/http/httpguts"
    27  )
    28  
    29  // ErrLineTooLong is returned when reading request or response bodies
    30  // with malformed chunked encoding.
    31  var ErrLineTooLong = internal.ErrLineTooLong
    32  
    33  type errorReader struct {
    34  	err error
    35  }
    36  
    37  func (r errorReader) Read(p []byte) (n int, err error) {
    38  	return 0, r.err
    39  }
    40  
    41  type byteReader struct {
    42  	b    byte
    43  	done bool
    44  }
    45  
    46  func (br *byteReader) Read(p []byte) (n int, err error) {
    47  	if br.done {
    48  		return 0, io.EOF
    49  	}
    50  	if len(p) == 0 {
    51  		return 0, nil
    52  	}
    53  	br.done = true
    54  	p[0] = br.b
    55  	return 1, io.EOF
    56  }
    57  
    58  // transferWriter inspects the fields of a user-supplied Request or Response,
    59  // sanitizes them without changing the user object and provides methods for
    60  // writing the respective header, body and trailer in wire format.
    61  type transferWriter struct {
    62  	Method           string
    63  	Body             io.Reader
    64  	BodyCloser       io.Closer
    65  	ResponseToHEAD   bool
    66  	ContentLength    int64 // -1 means unknown, 0 means exactly none
    67  	Close            bool
    68  	TransferEncoding []string
    69  	Header           Header
    70  	Trailer          Header
    71  	IsResponse       bool
    72  	bodyReadError    error // any non-EOF error from reading Body
    73  
    74  	FlushHeaders bool            // flush headers to network before body
    75  	ByteReadCh   chan readResult // non-nil if probeRequestBody called
    76  }
    77  
    78  func newTransferWriter(r interface{}) (t *transferWriter, err error) {
    79  	t = &transferWriter{}
    80  
    81  	// Extract relevant fields
    82  	atLeastHTTP11 := false
    83  	switch rr := r.(type) {
    84  	case *Request:
    85  		if rr.ContentLength != 0 && rr.Body == nil {
    86  			return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
    87  		}
    88  		t.Method = valueOrDefault(rr.Method, "GET")
    89  		t.Close = rr.Close
    90  		t.TransferEncoding = rr.TransferEncoding
    91  		t.Header = rr.Header
    92  		t.Trailer = rr.Trailer
    93  		t.Body = rr.Body
    94  		t.BodyCloser = rr.Body
    95  		t.ContentLength = rr.outgoingLength()
    96  		if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
    97  			t.TransferEncoding = []string{"chunked"}
    98  		}
    99  		// If there's a body, conservatively flush the headers
   100  		// to any bufio.Writer we're writing to, just in case
   101  		// the server needs the headers early, before we copy
   102  		// the body and possibly block. We make an exception
   103  		// for the common standard library in-memory types,
   104  		// though, to avoid unnecessary TCP packets on the
   105  		// wire. (Issue 22088.)
   106  		if t.ContentLength != 0 && !isKnownInMemoryReader(t.Body) {
   107  			t.FlushHeaders = true
   108  		}
   109  
   110  		atLeastHTTP11 = true // Transport requests are always 1.1 or 2.0
   111  	case *Response:
   112  		t.IsResponse = true
   113  		if rr.Request != nil {
   114  			t.Method = rr.Request.Method
   115  		}
   116  		t.Body = rr.Body
   117  		t.BodyCloser = rr.Body
   118  		t.ContentLength = rr.ContentLength
   119  		t.Close = rr.Close
   120  		t.TransferEncoding = rr.TransferEncoding
   121  		t.Header = rr.Header
   122  		t.Trailer = rr.Trailer
   123  		atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
   124  		t.ResponseToHEAD = noResponseBodyExpected(t.Method)
   125  	}
   126  
   127  	// Sanitize Body,ContentLength,TransferEncoding
   128  	if t.ResponseToHEAD {
   129  		t.Body = nil
   130  		if chunked(t.TransferEncoding) {
   131  			t.ContentLength = -1
   132  		}
   133  	} else {
   134  		if !atLeastHTTP11 || t.Body == nil {
   135  			t.TransferEncoding = nil
   136  		}
   137  		if chunked(t.TransferEncoding) {
   138  			t.ContentLength = -1
   139  		} else if t.Body == nil { // no chunking, no body
   140  			t.ContentLength = 0
   141  		}
   142  	}
   143  
   144  	// Sanitize Trailer
   145  	if !chunked(t.TransferEncoding) {
   146  		t.Trailer = nil
   147  	}
   148  
   149  	return t, nil
   150  }
   151  
   152  // shouldSendChunkedRequestBody reports whether we should try to send a
   153  // chunked request body to the server. In particular, the case we really
   154  // want to prevent is sending a GET or other typically-bodyless request to a
   155  // server with a chunked body when the body has zero bytes, since GETs with
   156  // bodies (while acceptable according to specs), even zero-byte chunked
   157  // bodies, are approximately never seen in the wild and confuse most
   158  // servers. See Issue 18257, as one example.
   159  //
   160  // The only reason we'd send such a request is if the user set the Body to a
   161  // non-nil value (say, ioutil.NopCloser(bytes.NewReader(nil))) and didn't
   162  // set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
   163  // there's bytes to send.
   164  //
   165  // This code tries to read a byte from the Request.Body in such cases to see
   166  // whether the body actually has content (super rare) or is actually just
   167  // a non-nil content-less ReadCloser (the more common case). In that more
   168  // common case, we act as if their Body were nil instead, and don't send
   169  // a body.
   170  func (t *transferWriter) shouldSendChunkedRequestBody() bool {
   171  	// Note that t.ContentLength is the corrected content length
   172  	// from rr.outgoingLength, so 0 actually means zero, not unknown.
   173  	if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
   174  		return false
   175  	}
   176  	if t.Method == "CONNECT" {
   177  		return false
   178  	}
   179  	if requestMethodUsuallyLacksBody(t.Method) {
   180  		// Only probe the Request.Body for GET/HEAD/DELETE/etc
   181  		// requests, because it's only those types of requests
   182  		// that confuse servers.
   183  		t.probeRequestBody() // adjusts t.Body, t.ContentLength
   184  		return t.Body != nil
   185  	}
   186  	// For all other request types (PUT, POST, PATCH, or anything
   187  	// made-up we've never heard of), assume it's normal and the server
   188  	// can deal with a chunked request body. Maybe we'll adjust this
   189  	// later.
   190  	return true
   191  }
   192  
   193  // probeRequestBody reads a byte from t.Body to see whether it's empty
   194  // (returns io.EOF right away).
   195  //
   196  // But because we've had problems with this blocking users in the past
   197  // (issue 17480) when the body is a pipe (perhaps waiting on the response
   198  // headers before the pipe is fed data), we need to be careful and bound how
   199  // long we wait for it. This delay will only affect users if all the following
   200  // are true:
   201  //   * the request body blocks
   202  //   * the content length is not set (or set to -1)
   203  //   * the method doesn't usually have a body (GET, HEAD, DELETE, ...)
   204  //   * there is no transfer-encoding=chunked already set.
   205  // In other words, this delay will not normally affect anybody, and there
   206  // are workarounds if it does.
   207  func (t *transferWriter) probeRequestBody() {
   208  	t.ByteReadCh = make(chan readResult, 1)
   209  	go func(body io.Reader) {
   210  		var buf [1]byte
   211  		var rres readResult
   212  		rres.n, rres.err = body.Read(buf[:])
   213  		if rres.n == 1 {
   214  			rres.b = buf[0]
   215  		}
   216  		t.ByteReadCh <- rres
   217  	}(t.Body)
   218  	timer := time.NewTimer(200 * time.Millisecond)
   219  	select {
   220  	case rres := <-t.ByteReadCh:
   221  		timer.Stop()
   222  		if rres.n == 0 && rres.err == io.EOF {
   223  			// It was empty.
   224  			t.Body = nil
   225  			t.ContentLength = 0
   226  		} else if rres.n == 1 {
   227  			if rres.err != nil {
   228  				t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
   229  			} else {
   230  				t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
   231  			}
   232  		} else if rres.err != nil {
   233  			t.Body = errorReader{rres.err}
   234  		}
   235  	case <-timer.C:
   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
   245  	}
   246  }
   247  
   248  func noResponseBodyExpected(requestMethod string) bool {
   249  	return requestMethod == "HEAD"
   250  }
   251  
   252  func (t *transferWriter) shouldSendContentLength() bool {
   253  	if chunked(t.TransferEncoding) {
   254  		return false
   255  	}
   256  	if t.ContentLength > 0 {
   257  		return true
   258  	}
   259  	if t.ContentLength < 0 {
   260  		return false
   261  	}
   262  	// Many servers expect a Content-Length for these methods
   263  	if t.Method == "POST" || t.Method == "PUT" {
   264  		return true
   265  	}
   266  	if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
   267  		if t.Method == "GET" || t.Method == "HEAD" {
   268  			return false
   269  		}
   270  		return true
   271  	}
   272  
   273  	return false
   274  }
   275  
   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 {
   279  			return err
   280  		}
   281  		if trace != nil && trace.WroteHeaderField != nil {
   282  			trace.WroteHeaderField("Connection", []string{"close"})
   283  		}
   284  	}
   285  
   286  	// Write Content-Length and/or Transfer-Encoding whose values are a
   287  	// function of the sanitized field triple (Body, ContentLength,
   288  	// TransferEncoding)
   289  	if t.shouldSendContentLength() {
   290  		if _, err := io.WriteString(w, "Content-Length: "); err != nil {
   291  			return err
   292  		}
   293  		if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
   294  			return err
   295  		}
   296  		if trace != nil && trace.WroteHeaderField != nil {
   297  			trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
   298  		}
   299  	} else if chunked(t.TransferEncoding) {
   300  		if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
   301  			return err
   302  		}
   303  		if trace != nil && trace.WroteHeaderField != nil {
   304  			trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
   305  		}
   306  	}
   307  
   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)
   313  			switch k {
   314  			case "Transfer-Encoding", "Trailer", "Content-Length":
   315  				return &badStringError{"invalid Trailer key", k}
   316  			}
   317  			keys = append(keys, k)
   318  		}
   319  		if len(keys) > 0 {
   320  			sort.Strings(keys)
   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 {
   324  				return err
   325  			}
   326  			if trace != nil && trace.WroteHeaderField != nil {
   327  				trace.WroteHeaderField("Trailer", keys)
   328  			}
   329  		}
   330  	}
   331  
   332  	return nil
   333  }
   334  
   335  func (t *transferWriter) writeBody(w io.Writer) error {
   336  	var err error
   337  	var ncopy int64
   338  
   339  	// Write body. We "unwrap" the body first if it was wrapped in a
   340  	// nopCloser. This is to ensure that we can take advantage of
   341  	// OS-level optimizations in the event that the body is an
   342  	// *os.File.
   343  	if t.Body != nil {
   344  		var body = t.unwrapBody()
   345  		if chunked(t.TransferEncoding) {
   346  			if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
   347  				w = &internal.FlushAfterChunkWriter{Writer: bw}
   348  			}
   349  			cw := internal.NewChunkedWriter(w)
   350  			_, err = t.doBodyCopy(cw, body)
   351  			if err == nil {
   352  				err = cw.Close()
   353  			}
   354  		} else if t.ContentLength == -1 {
   355  			dst := w
   356  			if t.Method == "CONNECT" {
   357  				dst = bufioFlushWriter{dst}
   358  			}
   359  			ncopy, err = t.doBodyCopy(dst, body)
   360  		} else {
   361  			ncopy, err = t.doBodyCopy(w, io.LimitReader(body, t.ContentLength))
   362  			if err != nil {
   363  				return err
   364  			}
   365  			var nextra int64
   366  			nextra, err = t.doBodyCopy(ioutil.Discard, body)
   367  			ncopy += nextra
   368  		}
   369  		if err != nil {
   370  			return err
   371  		}
   372  	}
   373  	if t.BodyCloser != nil {
   374  		if err := t.BodyCloser.Close(); err != nil {
   375  			return err
   376  		}
   377  	}
   378  
   379  	if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
   380  		return fmt.Errorf("http: ContentLength=%d with Body length %d",
   381  			t.ContentLength, ncopy)
   382  	}
   383  
   384  	if chunked(t.TransferEncoding) {
   385  		// Write Trailer header
   386  		if t.Trailer != nil {
   387  			if err := t.Trailer.Write(w); err != nil {
   388  				return err
   389  			}
   390  		}
   391  		// Last chunk, empty trailer
   392  		_, err = io.WriteString(w, "\r\n")
   393  	}
   394  	return err
   395  }
   396  
   397  // doBodyCopy wraps a copy operation, with any resulting error also
   398  // being saved in bodyReadError.
   399  //
   400  // This function is only intended for use in writeBody.
   401  func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
   402  	n, err = io.Copy(dst, src)
   403  	if err != nil && err != io.EOF {
   404  		t.bodyReadError = err
   405  	}
   406  	return
   407  }
   408  
   409  // unwrapBodyReader unwraps the body's inner reader if it's a
   410  // nopCloser. This is to ensure that body writes sourced from local
   411  // files (*os.File types) are properly optimized.
   412  //
   413  // This function is only intended for use in writeBody.
   414  func (t *transferWriter) unwrapBody() io.Reader {
   415  	if reflect.TypeOf(t.Body) == nopCloserType {
   416  		return reflect.ValueOf(t.Body).Field(0).Interface().(io.Reader)
   417  	}
   418  
   419  	return t.Body
   420  }
   421  
   422  type transferReader struct {
   423  	// Input
   424  	Header        Header
   425  	StatusCode    int
   426  	RequestMethod string
   427  	ProtoMajor    int
   428  	ProtoMinor    int
   429  	// Output
   430  	Body             io.ReadCloser
   431  	ContentLength    int64
   432  	TransferEncoding []string
   433  	Close            bool
   434  	Trailer          Header
   435  }
   436  
   437  func (t *transferReader) protoAtLeast(m, n int) bool {
   438  	return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
   439  }
   440  
   441  // bodyAllowedForStatus reports whether a given response status code
   442  // permits a body. See RFC 7230, section 3.3.
   443  func bodyAllowedForStatus(status int) bool {
   444  	switch {
   445  	case status >= 100 && status <= 199:
   446  		return false
   447  	case status == 204:
   448  		return false
   449  	case status == 304:
   450  		return false
   451  	}
   452  	return true
   453  }
   454  
   455  var (
   456  	suppressedHeaders304    = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
   457  	suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
   458  )
   459  
   460  func suppressedHeaders(status int) []string {
   461  	switch {
   462  	case status == 304:
   463  		// RFC 7232 section 4.1
   464  		return suppressedHeaders304
   465  	case !bodyAllowedForStatus(status):
   466  		return suppressedHeadersNoBody
   467  	}
   468  	return nil
   469  }
   470  
   471  // proxyingReadCloser is a composite type that accepts and proxies
   472  // io.Read and io.Close calls to its respective Reader and Closer.
   473  //
   474  // It is composed of:
   475  // a) a top-level reader e.g. the result of decompression
   476  // b) a symbolic Closer e.g. the result of decompression, the
   477  //    original body and the connection itself.
   478  type proxyingReadCloser struct {
   479  	io.Reader
   480  	io.Closer
   481  }
   482  
   483  // multiCloser implements io.Closer and allows a bunch of io.Closer values
   484  // to all be closed once.
   485  // Example usage is with proxyingReadCloser if we are decompressing a response
   486  // body on the fly and would like to close both *gzip.Reader and underlying body.
   487  type multiCloser []io.Closer
   488  
   489  func (mc multiCloser) Close() error {
   490  	var err error
   491  	for _, c := range mc {
   492  		if err1 := c.Close(); err1 != nil && err == nil {
   493  			err = err1
   494  		}
   495  	}
   496  	return err
   497  }
   498  
   499  // msg is *Request or *Response.
   500  func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
   501  	t := &transferReader{RequestMethod: "GET"}
   502  
   503  	// Unify input
   504  	isResponse := false
   505  	switch rr := msg.(type) {
   506  	case *Response:
   507  		t.Header = rr.Header
   508  		t.StatusCode = rr.StatusCode
   509  		t.ProtoMajor = rr.ProtoMajor
   510  		t.ProtoMinor = rr.ProtoMinor
   511  		t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
   512  		isResponse = true
   513  		if rr.Request != nil {
   514  			t.RequestMethod = rr.Request.Method
   515  		}
   516  	case *Request:
   517  		t.Header = rr.Header
   518  		t.RequestMethod = rr.Method
   519  		t.ProtoMajor = rr.ProtoMajor
   520  		t.ProtoMinor = rr.ProtoMinor
   521  		// Transfer semantics for Requests are exactly like those for
   522  		// Responses with status code 200, responding to a GET method
   523  		t.StatusCode = 200
   524  		t.Close = rr.Close
   525  	default:
   526  		panic("unexpected type")
   527  	}
   528  
   529  	// Default to HTTP/1.1
   530  	if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
   531  		t.ProtoMajor, t.ProtoMinor = 1, 1
   532  	}
   533  
   534  	// Transfer encoding, content length
   535  	err = t.fixTransferEncoding()
   536  	if err != nil {
   537  		return err
   538  	}
   539  
   540  	realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
   541  	if err != nil {
   542  		return err
   543  	}
   544  	if isResponse && t.RequestMethod == "HEAD" {
   545  		if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
   546  			return err
   547  		} else {
   548  			t.ContentLength = n
   549  		}
   550  	} else {
   551  		t.ContentLength = realLength
   552  	}
   553  
   554  	// Trailer
   555  	t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
   556  	if err != nil {
   557  		return err
   558  	}
   559  
   560  	// If there is no Content-Length or chunked Transfer-Encoding on a *Response
   561  	// and the status is not 1xx, 204 or 304, then the body is unbounded.
   562  	// See RFC 7230, section 3.3.
   563  	switch msg.(type) {
   564  	case *Response:
   565  		if realLength == -1 &&
   566  			!chunked(t.TransferEncoding) &&
   567  			bodyAllowedForStatus(t.StatusCode) {
   568  			// Unbounded body.
   569  			t.Close = true
   570  		}
   571  	}
   572  
   573  	// Prepare body reader. ContentLength < 0 means chunked encoding
   574  	// or close connection when finished, since multipart is not supported yet
   575  	switch {
   576  	case chunked(t.TransferEncoding) || implicitlyChunked(t.TransferEncoding):
   577  		if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
   578  			t.Body = NoBody
   579  		} else {
   580  			t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
   581  		}
   582  	case realLength == 0:
   583  		t.Body = NoBody
   584  	case realLength > 0:
   585  		t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
   586  	default:
   587  		// realLength < 0, i.e. "Content-Length" not mentioned in header
   588  		if t.Close {
   589  			// Close semantics (i.e. HTTP/1.0)
   590  			t.Body = &body{src: r, closing: t.Close}
   591  		} else {
   592  			// Persistent connection (i.e. HTTP/1.1)
   593  			t.Body = NoBody
   594  		}
   595  	}
   596  
   597  	// Finally if "gzip" was one of the requested transfer-encodings,
   598  	// we'll unzip the concatenated body/payload of the request.
   599  	// TODO: As we support more transfer-encodings, extract
   600  	// this code and apply the un-codings in reverse.
   601  	if t.Body != NoBody && gzipped(t.TransferEncoding) {
   602  		zr, err := gzip.NewReader(t.Body)
   603  		if err != nil {
   604  			return fmt.Errorf("http: failed to gunzip body: %v", err)
   605  		}
   606  		t.Body = &proxyingReadCloser{
   607  			Reader: zr,
   608  			Closer: multiCloser{zr, t.Body},
   609  		}
   610  	}
   611  
   612  	// Unify output
   613  	switch rr := msg.(type) {
   614  	case *Request:
   615  		rr.Body = t.Body
   616  		rr.ContentLength = t.ContentLength
   617  		rr.TransferEncoding = t.TransferEncoding
   618  		rr.Close = t.Close
   619  		rr.Trailer = t.Trailer
   620  	case *Response:
   621  		rr.Body = t.Body
   622  		rr.ContentLength = t.ContentLength
   623  		rr.TransferEncoding = t.TransferEncoding
   624  		rr.Close = t.Close
   625  		rr.Trailer = t.Trailer
   626  	}
   627  
   628  	return nil
   629  }
   630  
   631  // Checks whether chunked is the last part of the encodings stack
   632  func chunked(te []string) bool { return len(te) > 0 && te[len(te)-1] == "chunked" }
   633  
   634  // implicitlyChunked is a helper to check for implicity of chunked, because
   635  // RFC 7230 Section 3.3.1 says that the sender MUST apply chunked as the final
   636  // payload body to ensure that the message is framed for both the request
   637  // and the body. Since "identity" is incompatible with any other transformational
   638  // encoding cannot co-exist, the presence of "identity" will cause implicitlyChunked
   639  // to return false.
   640  func implicitlyChunked(te []string) bool {
   641  	if len(te) == 0 { // No transfer-encodings passed in, so not implicitly chunked.
   642  		return false
   643  	}
   644  	for _, tei := range te {
   645  		if tei == "identity" {
   646  			return false
   647  		}
   648  	}
   649  	return true
   650  }
   651  
   652  func isGzipTransferEncoding(tei string) bool {
   653  	// RFC 7230 4.2.3 requests that "x-gzip" SHOULD be considered the same as "gzip".
   654  	return tei == "gzip" || tei == "x-gzip"
   655  }
   656  
   657  // Checks where either of "gzip" or "x-gzip" are contained in transfer encodings.
   658  func gzipped(te []string) bool {
   659  	for _, tei := range te {
   660  		if isGzipTransferEncoding(tei) {
   661  			return true
   662  		}
   663  	}
   664  	return false
   665  }
   666  
   667  // Checks whether the encoding is explicitly "identity".
   668  func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
   669  
   670  // unsupportedTEError reports unsupported transfer-encodings.
   671  type unsupportedTEError struct {
   672  	err string
   673  }
   674  
   675  func (uste *unsupportedTEError) Error() string {
   676  	return uste.err
   677  }
   678  
   679  // isUnsupportedTEError checks if the error is of type
   680  // unsupportedTEError. It is usually invoked with a non-nil err.
   681  func isUnsupportedTEError(err error) bool {
   682  	_, ok := err.(*unsupportedTEError)
   683  	return ok
   684  }
   685  
   686  // fixTransferEncoding sanitizes t.TransferEncoding, if needed.
   687  func (t *transferReader) fixTransferEncoding() error {
   688  	raw, present := t.Header["Transfer-Encoding"]
   689  	if !present {
   690  		return nil
   691  	}
   692  	delete(t.Header, "Transfer-Encoding")
   693  
   694  	// Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
   695  	if !t.protoAtLeast(1, 1) {
   696  		return nil
   697  	}
   698  
   699  	encodings := strings.Split(raw[0], ",")
   700  	te := make([]string, 0, len(encodings))
   701  
   702  	// When adding new encodings, please maintain the invariant:
   703  	//   if chunked encoding is present, it must always
   704  	//   come last and it must be applied only once.
   705  	// See RFC 7230 Section 3.3.1 Transfer-Encoding.
   706  	for i, encoding := range encodings {
   707  		encoding = strings.ToLower(strings.TrimSpace(encoding))
   708  
   709  		if encoding == "identity" {
   710  			// "identity" should not be mixed with other transfer-encodings/compressions
   711  			// because it means "no compression, no transformation".
   712  			if len(encodings) != 1 {
   713  				return &badStringError{`"identity" when present must be the only transfer encoding`, strings.Join(encodings, ",")}
   714  			}
   715  			// "identity" is not recorded.
   716  			break
   717  		}
   718  
   719  		switch {
   720  		case encoding == "chunked":
   721  			// "chunked" MUST ALWAYS be the last
   722  			// encoding as per the  loop invariant.
   723  			// That is:
   724  			//     Invalid: [chunked, gzip]
   725  			//     Valid:   [gzip, chunked]
   726  			if i+1 != len(encodings) {
   727  				return &badStringError{"chunked must be applied only once, as the last encoding", strings.Join(encodings, ",")}
   728  			}
   729  			// Supported otherwise.
   730  
   731  		case isGzipTransferEncoding(encoding):
   732  			// Supported
   733  
   734  		default:
   735  			return &unsupportedTEError{fmt.Sprintf("unsupported transfer encoding: %q", encoding)}
   736  		}
   737  
   738  		te = te[0 : len(te)+1]
   739  		te[len(te)-1] = encoding
   740  	}
   741  
   742  	if len(te) > 0 {
   743  		// RFC 7230 3.3.2 says "A sender MUST NOT send a
   744  		// Content-Length header field in any message that
   745  		// contains a Transfer-Encoding header field."
   746  		//
   747  		// but also:
   748  		// "If a message is received with both a
   749  		// Transfer-Encoding and a Content-Length header
   750  		// field, the Transfer-Encoding overrides the
   751  		// Content-Length. Such a message might indicate an
   752  		// attempt to perform request smuggling (Section 9.5)
   753  		// or response splitting (Section 9.4) and ought to be
   754  		// handled as an error. A sender MUST remove the
   755  		// received Content-Length field prior to forwarding
   756  		// such a message downstream."
   757  		//
   758  		// Reportedly, these appear in the wild.
   759  		delete(t.Header, "Content-Length")
   760  		t.TransferEncoding = te
   761  		return nil
   762  	}
   763  
   764  	return nil
   765  }
   766  
   767  // Determine the expected body length, using RFC 7230 Section 3.3. This
   768  // function is not a method, because ultimately it should be shared by
   769  // ReadResponse and ReadRequest.
   770  func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
   771  	isRequest := !isResponse
   772  	contentLens := header["Content-Length"]
   773  
   774  	// Hardening against HTTP request smuggling
   775  	if len(contentLens) > 1 {
   776  		// Per RFC 7230 Section 3.3.2, prevent multiple
   777  		// Content-Length headers if they differ in value.
   778  		// If there are dups of the value, remove the dups.
   779  		// See Issue 16490.
   780  		first := strings.TrimSpace(contentLens[0])
   781  		for _, ct := range contentLens[1:] {
   782  			if first != strings.TrimSpace(ct) {
   783  				return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
   784  			}
   785  		}
   786  
   787  		// deduplicate Content-Length
   788  		header.Del("Content-Length")
   789  		header.Add("Content-Length", first)
   790  
   791  		contentLens = header["Content-Length"]
   792  	}
   793  
   794  	// Logic based on response type or status
   795  	if noResponseBodyExpected(requestMethod) {
   796  		// For HTTP requests, as part of hardening against request
   797  		// smuggling (RFC 7230), don't allow a Content-Length header for
   798  		// methods which don't permit bodies. As an exception, allow
   799  		// exactly one Content-Length header if its value is "0".
   800  		if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
   801  			return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
   802  		}
   803  		return 0, nil
   804  	}
   805  	if status/100 == 1 {
   806  		return 0, nil
   807  	}
   808  	switch status {
   809  	case 204, 304:
   810  		return 0, nil
   811  	}
   812  
   813  	// Logic based on Transfer-Encoding
   814  	if chunked(te) {
   815  		return -1, nil
   816  	}
   817  
   818  	// Logic based on Content-Length
   819  	var cl string
   820  	if len(contentLens) == 1 {
   821  		cl = strings.TrimSpace(contentLens[0])
   822  	}
   823  	if cl != "" {
   824  		n, err := parseContentLength(cl)
   825  		if err != nil {
   826  			return -1, err
   827  		}
   828  		return n, nil
   829  	}
   830  	header.Del("Content-Length")
   831  
   832  	if isRequest {
   833  		// RFC 7230 neither explicitly permits nor forbids an
   834  		// entity-body on a GET request so we permit one if
   835  		// declared, but we default to 0 here (not -1 below)
   836  		// if there's no mention of a body.
   837  		// Likewise, all other request methods are assumed to have
   838  		// no body if neither Transfer-Encoding chunked nor a
   839  		// Content-Length are set.
   840  		return 0, nil
   841  	}
   842  
   843  	// Body-EOF logic based on other methods (like closing, or chunked coding)
   844  	return -1, nil
   845  }
   846  
   847  // Determine whether to hang up after sending a request and body, or
   848  // receiving a response and body
   849  // 'header' is the request headers
   850  func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
   851  	if major < 1 {
   852  		return true
   853  	}
   854  
   855  	conv := header["Connection"]
   856  	hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
   857  	if major == 1 && minor == 0 {
   858  		return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
   859  	}
   860  
   861  	if hasClose && removeCloseHeader {
   862  		header.Del("Connection")
   863  	}
   864  
   865  	return hasClose
   866  }
   867  
   868  // Parse the trailer header
   869  func fixTrailer(header Header, te []string) (Header, error) {
   870  	vv, ok := header["Trailer"]
   871  	if !ok {
   872  		return nil, nil
   873  	}
   874  	if !chunked(te) {
   875  		// Trailer and no chunking:
   876  		// this is an invalid use case for trailer header.
   877  		// Nevertheless, no error will be returned and we
   878  		// let users decide if this is a valid HTTP message.
   879  		// The Trailer header will be kept in Response.Header
   880  		// but not populate Response.Trailer.
   881  		// See issue #27197.
   882  		return nil, nil
   883  	}
   884  	header.Del("Trailer")
   885  
   886  	trailer := make(Header)
   887  	var err error
   888  	for _, v := range vv {
   889  		foreachHeaderElement(v, func(key string) {
   890  			key = CanonicalHeaderKey(key)
   891  			switch key {
   892  			case "Transfer-Encoding", "Trailer", "Content-Length":
   893  				if err == nil {
   894  					err = &badStringError{"bad trailer key", key}
   895  					return
   896  				}
   897  			}
   898  			trailer[key] = nil
   899  		})
   900  	}
   901  	if err != nil {
   902  		return nil, err
   903  	}
   904  	if len(trailer) == 0 {
   905  		return nil, nil
   906  	}
   907  	return trailer, nil
   908  }
   909  
   910  // body turns a Reader into a ReadCloser.
   911  // Close ensures that the body has been fully read
   912  // and then reads the trailer if necessary.
   913  type body struct {
   914  	src          io.Reader
   915  	hdr          interface{}   // non-nil (Response or Request) value means read trailer
   916  	r            *bufio.Reader // underlying wire-format reader for the trailer
   917  	closing      bool          // is the connection to be closed after reading body?
   918  	doEarlyClose bool          // whether Close should stop early
   919  
   920  	mu         sync.Mutex // guards following, and calls to Read and Close
   921  	sawEOF     bool
   922  	closed     bool
   923  	earlyClose bool   // Close called and we didn't read to the end of src
   924  	onHitEOF   func() // if non-nil, func to call when EOF is Read
   925  }
   926  
   927  // ErrBodyReadAfterClose is returned when reading a Request or Response
   928  // Body after the body has been closed. This typically happens when the body is
   929  // read after an HTTP Handler calls WriteHeader or Write on its
   930  // ResponseWriter.
   931  var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
   932  
   933  func (b *body) Read(p []byte) (n int, err error) {
   934  	b.mu.Lock()
   935  	defer b.mu.Unlock()
   936  	if b.closed {
   937  		return 0, ErrBodyReadAfterClose
   938  	}
   939  	return b.readLocked(p)
   940  }
   941  
   942  // Must hold b.mu.
   943  func (b *body) readLocked(p []byte) (n int, err error) {
   944  	if b.sawEOF {
   945  		return 0, io.EOF
   946  	}
   947  	n, err = b.src.Read(p)
   948  
   949  	if err == io.EOF {
   950  		b.sawEOF = true
   951  		// Chunked case. Read the trailer.
   952  		if b.hdr != nil {
   953  			if e := b.readTrailer(); e != nil {
   954  				err = e
   955  				// Something went wrong in the trailer, we must not allow any
   956  				// further reads of any kind to succeed from body, nor any
   957  				// subsequent requests on the server connection. See
   958  				// golang.org/issue/12027
   959  				b.sawEOF = false
   960  				b.closed = true
   961  			}
   962  			b.hdr = nil
   963  		} else {
   964  			// If the server declared the Content-Length, our body is a LimitedReader
   965  			// and we need to check whether this EOF arrived early.
   966  			if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
   967  				err = io.ErrUnexpectedEOF
   968  			}
   969  		}
   970  	}
   971  
   972  	// If we can return an EOF here along with the read data, do
   973  	// so. This is optional per the io.Reader contract, but doing
   974  	// so helps the HTTP transport code recycle its connection
   975  	// earlier (since it will see this EOF itself), even if the
   976  	// client doesn't do future reads or Close.
   977  	if err == nil && n > 0 {
   978  		if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
   979  			err = io.EOF
   980  			b.sawEOF = true
   981  		}
   982  	}
   983  
   984  	if b.sawEOF && b.onHitEOF != nil {
   985  		b.onHitEOF()
   986  	}
   987  
   988  	return n, err
   989  }
   990  
   991  var (
   992  	singleCRLF = []byte("\r\n")
   993  	doubleCRLF = []byte("\r\n\r\n")
   994  )
   995  
   996  func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
   997  	for peekSize := 4; ; peekSize++ {
   998  		// This loop stops when Peek returns an error,
   999  		// which it does when r's buffer has been filled.
  1000  		buf, err := r.Peek(peekSize)
  1001  		if bytes.HasSuffix(buf, doubleCRLF) {
  1002  			return true
  1003  		}
  1004  		if err != nil {
  1005  			break
  1006  		}
  1007  	}
  1008  	return false
  1009  }
  1010  
  1011  var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
  1012  
  1013  func (b *body) readTrailer() error {
  1014  	// The common case, since nobody uses trailers.
  1015  	buf, err := b.r.Peek(2)
  1016  	if bytes.Equal(buf, singleCRLF) {
  1017  		b.r.Discard(2)
  1018  		return nil
  1019  	}
  1020  	if len(buf) < 2 {
  1021  		return errTrailerEOF
  1022  	}
  1023  	if err != nil {
  1024  		return err
  1025  	}
  1026  
  1027  	// Make sure there's a header terminator coming up, to prevent
  1028  	// a DoS with an unbounded size Trailer. It's not easy to
  1029  	// slip in a LimitReader here, as textproto.NewReader requires
  1030  	// a concrete *bufio.Reader. Also, we can't get all the way
  1031  	// back up to our conn's LimitedReader that *might* be backing
  1032  	// this bufio.Reader. Instead, a hack: we iteratively Peek up
  1033  	// to the bufio.Reader's max size, looking for a double CRLF.
  1034  	// This limits the trailer to the underlying buffer size, typically 4kB.
  1035  	if !seeUpcomingDoubleCRLF(b.r) {
  1036  		return errors.New("http: suspiciously long trailer after chunked body")
  1037  	}
  1038  
  1039  	hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
  1040  	if err != nil {
  1041  		if err == io.EOF {
  1042  			return errTrailerEOF
  1043  		}
  1044  		return err
  1045  	}
  1046  	switch rr := b.hdr.(type) {
  1047  	case *Request:
  1048  		mergeSetHeader(&rr.Trailer, Header(hdr))
  1049  	case *Response:
  1050  		mergeSetHeader(&rr.Trailer, Header(hdr))
  1051  	}
  1052  	return nil
  1053  }
  1054  
  1055  func mergeSetHeader(dst *Header, src Header) {
  1056  	if *dst == nil {
  1057  		*dst = src
  1058  		return
  1059  	}
  1060  	for k, vv := range src {
  1061  		(*dst)[k] = vv
  1062  	}
  1063  }
  1064  
  1065  // unreadDataSizeLocked returns the number of bytes of unread input.
  1066  // It returns -1 if unknown.
  1067  // b.mu must be held.
  1068  func (b *body) unreadDataSizeLocked() int64 {
  1069  	if lr, ok := b.src.(*io.LimitedReader); ok {
  1070  		return lr.N
  1071  	}
  1072  	return -1
  1073  }
  1074  
  1075  func (b *body) Close() error {
  1076  	b.mu.Lock()
  1077  	defer b.mu.Unlock()
  1078  	if b.closed {
  1079  		return nil
  1080  	}
  1081  	var err error
  1082  	switch {
  1083  	case b.sawEOF:
  1084  		// Already saw EOF, so no need going to look for it.
  1085  	case b.hdr == nil && b.closing:
  1086  		// no trailer and closing the connection next.
  1087  		// no point in reading to EOF.
  1088  	case b.doEarlyClose:
  1089  		// Read up to maxPostHandlerReadBytes bytes of the body, looking
  1090  		// for EOF (and trailers), so we can re-use this connection.
  1091  		if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
  1092  			// There was a declared Content-Length, and we have more bytes remaining
  1093  			// than our maxPostHandlerReadBytes tolerance. So, give up.
  1094  			b.earlyClose = true
  1095  		} else {
  1096  			var n int64
  1097  			// Consume the body, or, which will also lead to us reading
  1098  			// the trailer headers after the body, if present.
  1099  			n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
  1100  			if err == io.EOF {
  1101  				err = nil
  1102  			}
  1103  			if n == maxPostHandlerReadBytes {
  1104  				b.earlyClose = true
  1105  			}
  1106  		}
  1107  	default:
  1108  		// Fully consume the body, which will also lead to us reading
  1109  		// the trailer headers after the body, if present.
  1110  		_, err = io.Copy(ioutil.Discard, bodyLocked{b})
  1111  	}
  1112  	b.closed = true
  1113  	return err
  1114  }
  1115  
  1116  func (b *body) didEarlyClose() bool {
  1117  	b.mu.Lock()
  1118  	defer b.mu.Unlock()
  1119  	return b.earlyClose
  1120  }
  1121  
  1122  // bodyRemains reports whether future Read calls might
  1123  // yield data.
  1124  func (b *body) bodyRemains() bool {
  1125  	b.mu.Lock()
  1126  	defer b.mu.Unlock()
  1127  	return !b.sawEOF
  1128  }
  1129  
  1130  func (b *body) registerOnHitEOF(fn func()) {
  1131  	b.mu.Lock()
  1132  	defer b.mu.Unlock()
  1133  	b.onHitEOF = fn
  1134  }
  1135  
  1136  // bodyLocked is a io.Reader reading from a *body when its mutex is
  1137  // already held.
  1138  type bodyLocked struct {
  1139  	b *body
  1140  }
  1141  
  1142  func (bl bodyLocked) Read(p []byte) (n int, err error) {
  1143  	if bl.b.closed {
  1144  		return 0, ErrBodyReadAfterClose
  1145  	}
  1146  	return bl.b.readLocked(p)
  1147  }
  1148  
  1149  // parseContentLength trims whitespace from s and returns -1 if no value
  1150  // is set, or the value if it's >= 0.
  1151  func parseContentLength(cl string) (int64, error) {
  1152  	cl = strings.TrimSpace(cl)
  1153  	if cl == "" {
  1154  		return -1, nil
  1155  	}
  1156  	n, err := strconv.ParseInt(cl, 10, 64)
  1157  	if err != nil || n < 0 {
  1158  		return 0, &badStringError{"bad Content-Length", cl}
  1159  	}
  1160  	return n, nil
  1161  
  1162  }
  1163  
  1164  // finishAsyncByteRead finishes reading the 1-byte sniff
  1165  // from the ContentLength==0, Body!=nil case.
  1166  type finishAsyncByteRead struct {
  1167  	tw *transferWriter
  1168  }
  1169  
  1170  func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
  1171  	if len(p) == 0 {
  1172  		return
  1173  	}
  1174  	rres := <-fr.tw.ByteReadCh
  1175  	n, err = rres.n, rres.err
  1176  	if n == 1 {
  1177  		p[0] = rres.b
  1178  	}
  1179  	return
  1180  }
  1181  
  1182  var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))
  1183  
  1184  // isKnownInMemoryReader reports whether r is a type known to not
  1185  // block on Read. Its caller uses this as an optional optimization to
  1186  // send fewer TCP packets.
  1187  func isKnownInMemoryReader(r io.Reader) bool {
  1188  	switch r.(type) {
  1189  	case *bytes.Reader, *bytes.Buffer, *strings.Reader:
  1190  		return true
  1191  	}
  1192  	if reflect.TypeOf(r) == nopCloserType {
  1193  		return isKnownInMemoryReader(reflect.ValueOf(r).Field(0).Interface().(io.Reader))
  1194  	}
  1195  	return false
  1196  }
  1197  
  1198  // bufioFlushWriter is an io.Writer wrapper that flushes all writes
  1199  // on its wrapped writer if it's a *bufio.Writer.
  1200  type bufioFlushWriter struct{ w io.Writer }
  1201  
  1202  func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
  1203  	n, err = fw.w.Write(p)
  1204  	if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
  1205  		ferr := bw.Flush()
  1206  		if ferr != nil && err == nil {
  1207  			err = ferr
  1208  		}
  1209  	}
  1210  	return
  1211  }