Source file src/net/http/transfer.go

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

View as plain text