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 := validateTrailers(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 && !httpguts.HeaderValuesContainsToken(t.Header["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  	RealBodyLength int64 // actual size of body (0 for HEAD requests and the like)
   458  	ContentLength  int64 // content-length (may be non-0 for HEAD requests)
   459  	Chunked        bool
   460  	Close          bool
   461  	Trailer        Header
   462  }
   463  
   464  func (t *transferReader) protoAtLeast(m, n int) bool {
   465  	return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
   466  }
   467  
   468  // bodyAllowedForStatus reports whether a given response status code
   469  // permits a body. See RFC 7230, section 3.3.
   470  func bodyAllowedForStatus(status int) bool {
   471  	return internal.BodyAllowedForStatus(status)
   472  }
   473  
   474  var (
   475  	suppressedHeaders304    = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
   476  	suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
   477  	excludedHeadersNoBody   = map[string]bool{"Content-Length": true, "Transfer-Encoding": true}
   478  )
   479  
   480  func suppressedHeaders(status int) []string {
   481  	switch {
   482  	case status == 304:
   483  		// RFC 7232 section 4.1
   484  		return suppressedHeaders304
   485  	case !bodyAllowedForStatus(status):
   486  		return suppressedHeadersNoBody
   487  	}
   488  	return nil
   489  }
   490  
   491  // msg is *Request or *Response.
   492  func readTransfer(msg any, r *bufio.Reader, maxTrailerHeaders int64) (err error) {
   493  	t := &transferReader{RequestMethod: "GET"}
   494  
   495  	// Unify input
   496  	isResponse := false
   497  	switch rr := msg.(type) {
   498  	case *Response:
   499  		t.Header = rr.Header
   500  		t.StatusCode = rr.StatusCode
   501  		t.ProtoMajor = rr.ProtoMajor
   502  		t.ProtoMinor = rr.ProtoMinor
   503  		t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
   504  		isResponse = true
   505  		if rr.Request != nil {
   506  			t.RequestMethod = rr.Request.Method
   507  		}
   508  	case *Request:
   509  		t.Header = rr.Header
   510  		t.RequestMethod = rr.Method
   511  		t.ProtoMajor = rr.ProtoMajor
   512  		t.ProtoMinor = rr.ProtoMinor
   513  		// Transfer semantics for Requests are exactly like those for
   514  		// Responses with status code 200, responding to a GET method
   515  		t.StatusCode = 200
   516  		t.Close = rr.Close
   517  	default:
   518  		panic("unexpected type")
   519  	}
   520  
   521  	// Default to HTTP/1.1
   522  	if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
   523  		t.ProtoMajor, t.ProtoMinor = 1, 1
   524  	}
   525  
   526  	// Content-Length and Transfer-Encoding.
   527  	if err := t.determineBodyLength(isResponse); err != nil {
   528  		return err
   529  	}
   530  
   531  	// Trailer
   532  	t.Trailer, err = fixTrailer(t.Header, t.Chunked, maxTrailerHeaders)
   533  	if err != nil {
   534  		return err
   535  	}
   536  
   537  	// Prepare body reader. Body length < 0 means chunked encoding
   538  	// or close connection when finished, since multipart is not supported yet.
   539  	switch {
   540  	case t.Chunked:
   541  		if isResponse && (noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode)) {
   542  			t.Body = NoBody
   543  		} else {
   544  			t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close, maxTrailerHeaders: maxTrailerHeaders}
   545  		}
   546  	case t.RealBodyLength == 0:
   547  		t.Body = NoBody
   548  	case t.RealBodyLength > 0:
   549  		t.Body = &body{src: io.LimitReader(r, t.RealBodyLength), closing: t.Close}
   550  	case t.Close:
   551  		// Close semantics (no Transfer-Encoding or Content-Length).
   552  		t.Body = &body{src: r, closing: t.Close}
   553  	default:
   554  		// This shouldn't be possible.
   555  		return errors.New("http: unexpected body length (bug)")
   556  	}
   557  
   558  	// Unify output
   559  	switch rr := msg.(type) {
   560  	case *Request:
   561  		rr.Body = t.Body
   562  		rr.ContentLength = t.ContentLength
   563  		if t.Chunked {
   564  			rr.TransferEncoding = []string{"chunked"}
   565  		}
   566  		rr.Close = t.Close
   567  		rr.Trailer = t.Trailer
   568  	case *Response:
   569  		rr.Body = t.Body
   570  		rr.ContentLength = t.ContentLength
   571  		if t.Chunked {
   572  			rr.TransferEncoding = []string{"chunked"}
   573  		}
   574  		rr.Close = t.Close
   575  		rr.Trailer = t.Trailer
   576  	}
   577  
   578  	return nil
   579  }
   580  
   581  // Checks whether chunked is part of the encodings stack.
   582  func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
   583  
   584  // Checks whether the encoding is explicitly "identity".
   585  func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
   586  
   587  // unsupportedTEError reports unsupported transfer-encodings.
   588  type unsupportedTEError struct {
   589  	err string
   590  }
   591  
   592  var (
   593  	errTooManyTransferEncodings    = &unsupportedTEError{"too many transfer encodings"}
   594  	errUnsupportedTransferEncoding = &unsupportedTEError{"unsupported transfer encoding"}
   595  
   596  	errTooManyContentLengths = errors.New("message cannot contain multiple Content-Length headers")
   597  )
   598  
   599  func (uste *unsupportedTEError) Error() string {
   600  	return uste.err
   601  }
   602  
   603  // isUnsupportedTEError checks if the error is of type
   604  // unsupportedTEError. It is usually invoked with a non-nil err.
   605  func isUnsupportedTEError(err error) bool {
   606  	_, ok := err.(*unsupportedTEError)
   607  	return ok
   608  }
   609  
   610  // Determine the expected body length, using RFC 9112 Section 6.3.
   611  //
   612  // Sets t.RealBodyLength, t.ContentLength, t.Chunked, and (sometimes) t.Close.
   613  func (t *transferReader) determineBodyLength(isResponse bool) error {
   614  	isRequest := !isResponse
   615  	contentLength, hasContentLength := t.Header["Content-Length"]
   616  	transferEncoding, hasTransferEncoding := t.Header["Transfer-Encoding"]
   617  	delete(t.Header, "Content-Length")
   618  	delete(t.Header, "Transfer-Encoding")
   619  
   620  	// Early checks of Transfer-Encoding and Content-Length:
   621  	// If these headers are present, we require them to be correct,
   622  	// even if we aren't going to use them.
   623  	// (This is stricter than RFC 9110 requires.)
   624  	if hasTransferEncoding && !t.protoAtLeast(1, 1) {
   625  		// "A server or client that receives an HTTP/1.0 message containing a
   626  		// Transfer-Encoding header field MUST treat the message as if the framing
   627  		// is faulty, even if a Content-Length is present, and close
   628  		// the connection after processing the message."
   629  		// https://datatracker.ietf.org/doc/html/rfc9112#section-6.1-16
   630  		t.Close = true
   631  		transferEncoding = nil
   632  		hasTransferEncoding = false
   633  	}
   634  	if hasTransferEncoding {
   635  		// Like nginx, we only support a single Transfer-Encoding header field, and
   636  		// only if set to "chunked". This is one of the most security sensitive
   637  		// surfaces in HTTP/1.1 due to the risk of request smuggling, so we keep it
   638  		// strict and simple.
   639  		if len(transferEncoding) != 1 {
   640  			return errTooManyTransferEncodings
   641  		}
   642  		if !ascii.EqualFold(transferEncoding[0], "chunked") {
   643  			return errUnsupportedTransferEncoding
   644  		}
   645  	}
   646  	// parsedContentLength >= 0 indicates a valid Content-Length header,
   647  	// parsedContentLength < 0 is either no Content-Length or an empty one we're ignoring.
   648  	contentLengthStr, parsedContentLength, err := parseContentLength(contentLength)
   649  	if err != nil {
   650  		return err
   651  	}
   652  	if parsedContentLength >= 0 {
   653  		contentLength = contentLength[:1]   // Handle duplicate Content-Length headers.
   654  		contentLength[0] = contentLengthStr // Reuse existing slice to avoid extra alloc.
   655  	}
   656  
   657  	// 1. "Any response to a HEAD request and any response with a
   658  	//    1xx (Informational), 204 (No Content), or 304 (Not Modified)
   659  	//    status code is always terminated by the first empty line
   660  	//    after the header fields, regardless of the header fields
   661  	//    present in the message, and thus cannot contain a message
   662  	//    body or trailer section."
   663  	if isResponse && t.RequestMethod == "HEAD" {
   664  		t.RealBodyLength = 0
   665  		if hasTransferEncoding {
   666  			t.Chunked = true
   667  			t.ContentLength = -1
   668  		} else if parsedContentLength >= 0 {
   669  			t.Header["Content-Length"] = contentLength
   670  			t.ContentLength = parsedContentLength
   671  		} else {
   672  			t.ContentLength = -1
   673  		}
   674  		return nil
   675  	}
   676  	bodyless := isResponse &&
   677  		((t.StatusCode >= 100 && t.StatusCode < 200) ||
   678  			t.StatusCode == 204 ||
   679  			t.StatusCode == 304)
   680  	if bodyless {
   681  		// We preserve the Transfer-Encoding and Content-Length headers on
   682  		// these responses, but we don't set the ContentLength field of
   683  		// the Request/Response.
   684  		t.RealBodyLength = 0
   685  		t.ContentLength = 0
   686  		if hasTransferEncoding {
   687  			t.Chunked = true // sets Transfer-Encoding header
   688  		} else if parsedContentLength >= 0 {
   689  			t.Header["Content-Length"] = contentLength
   690  		}
   691  		return nil
   692  	}
   693  
   694  	// 2. "Any 2xx (Successful) response to a CONNECT request
   695  	//    implies that the connection will become a tunnel immediately
   696  	//    after the empty line that concludes the header fields. A
   697  	//    client MUST ignore any Content-Length or Transfer-Encoding
   698  	//    header fields received in such a message."
   699  	if isResponse && t.StatusCode >= 200 && t.StatusCode < 300 && t.RequestMethod == "CONNECT" {
   700  		t.RealBodyLength = -1
   701  		t.ContentLength = -1
   702  		t.Close = true
   703  		if hasContentLength && parsedContentLength == 0 {
   704  			// This is not particularly principled, but avoids breaking some
   705  			// users depending on past behavior. If a 2xx CONNECT response contains
   706  			// a "Content-Length: 0" header, we leave the header in place and
   707  			// set the content length to 0 (so Response.Body is NoBody).
   708  			// We still set t.Close to close the connection.
   709  			t.RealBodyLength = 0
   710  			t.ContentLength = 0
   711  			t.Header["Content-Length"] = contentLength
   712  		}
   713  		return nil
   714  	}
   715  
   716  	// 3. "If a message is received with both a Transfer-Encoding
   717  	//    and a Content-Length header field, the Transfer-Encoding
   718  	//    overrides the Content-Length."
   719  	if hasContentLength && hasTransferEncoding {
   720  		// "A server MAY reject a request that contains
   721  		// both Content-Length and Transfer-Encoding or process
   722  		// such a request in accordance with the Transfer-Encoding
   723  		// alone. Regardless, the server MUST close the
   724  		// connection after responding to such a request to
   725  		// avoid the potential attacks."
   726  		// https://www.rfc-editor.org/rfc/rfc9112.html#section-6.1-15
   727  		contentLength = nil
   728  		hasContentLength = false
   729  		parsedContentLength = -1
   730  		t.Close = true
   731  	}
   732  
   733  	// 4. "If a Transfer-Encoding header field is present and
   734  	//     the chunked transfer coding (Section 7.1) is the final
   735  	//     encoding, the message body length is determined by reading
   736  	//     and decoding the chunked data until the transfer coding
   737  	//     indicates the data is complete."
   738  	if hasTransferEncoding {
   739  		// We verified above that the header contains a single value, "chunked".
   740  		t.Chunked = true
   741  		t.RealBodyLength = -1
   742  		t.ContentLength = -1
   743  		return nil
   744  	}
   745  
   746  	// 5. "If a message is received without Transfer-Encoding
   747  	//     and with an invalid Content-Length header field, then the
   748  	//     message framing is invalid and the recipient MUST treat it
   749  	//     as an unrecoverable error, unless the field value can be
   750  	//     successfully parsed as a comma-separated list (Section 5.6.1
   751  	//     of [HTTP]), all values in the list are valid, and all values
   752  	//     in the list are the same (in which case, the message is
   753  	//     processed with that single value used as the Content-Length
   754  	//     field value)."
   755  	//
   756  	// 6. "If a valid Content-Length header field is present
   757  	//    without Transfer-Encoding, its decimal value defines the
   758  	//    expected message body length in octets."
   759  	if parsedContentLength >= 0 {
   760  		t.Header["Content-Length"] = contentLength
   761  		t.RealBodyLength = parsedContentLength
   762  		t.ContentLength = parsedContentLength
   763  		return nil
   764  	}
   765  
   766  	// 7. "If this is a request message and none of the above
   767  	//    are true, then the message body length is zero (no message
   768  	//    body is present)."
   769  	if isRequest {
   770  		t.RealBodyLength = 0
   771  		t.ContentLength = 0
   772  		return nil
   773  	}
   774  
   775  	// 8. "Otherwise, this is a response message without a
   776  	//    declared message body length, so the message body length
   777  	//    is determined by the number of octets received prior to the
   778  	//    server closing the connection."
   779  	t.RealBodyLength = -1
   780  	t.ContentLength = -1
   781  	t.Close = true
   782  	return nil
   783  }
   784  
   785  // Determine whether to hang up after sending a request and body, or
   786  // receiving a response and body
   787  // 'header' is the request headers.
   788  func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
   789  	if major < 1 {
   790  		return true
   791  	}
   792  
   793  	conv := header["Connection"]
   794  	hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
   795  	if major == 1 && minor == 0 {
   796  		return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
   797  	}
   798  
   799  	if hasClose && removeCloseHeader {
   800  		header.Del("Connection")
   801  	}
   802  
   803  	return hasClose
   804  }
   805  
   806  // Parse the trailer header.
   807  func fixTrailer(header Header, chunked bool, maxHeaders int64) (Header, error) {
   808  	vv, ok := header["Trailer"]
   809  	if !ok {
   810  		return nil, nil
   811  	}
   812  	if !chunked {
   813  		// Trailer and no chunking:
   814  		// this is an invalid use case for trailer header.
   815  		// Nevertheless, no error will be returned and we
   816  		// let users decide if this is a valid HTTP message.
   817  		// The Trailer header will be kept in Response.Header
   818  		// but not populate Response.Trailer.
   819  		// See issue #27197.
   820  		return nil, nil
   821  	}
   822  	header.Del("Trailer")
   823  	for _, v := range vv {
   824  		maxHeaders -= int64(strings.Count(v, ",") + 1)
   825  		if maxHeaders < 0 {
   826  			return nil, errTooLarge
   827  		}
   828  	}
   829  
   830  	trailer := make(Header)
   831  	var err error
   832  	for _, v := range vv {
   833  		foreachHeaderElement(v, func(key string) {
   834  			key = CanonicalHeaderKey(key)
   835  			switch key {
   836  			case "Transfer-Encoding", "Trailer", "Content-Length":
   837  				if err == nil {
   838  					err = badStringError("bad trailer key", key)
   839  					return
   840  				}
   841  			}
   842  			trailer[key] = nil
   843  		})
   844  	}
   845  	if err != nil {
   846  		return nil, err
   847  	}
   848  	if len(trailer) == 0 {
   849  		return nil, nil
   850  	}
   851  	return trailer, nil
   852  }
   853  
   854  // body turns a Reader into a ReadCloser.
   855  // Close ensures that the body has been fully read
   856  // and then reads the trailer if necessary.
   857  type body struct {
   858  	src               io.Reader
   859  	hdr               any           // non-nil (Response or Request) value means read trailer
   860  	r                 *bufio.Reader // underlying wire-format reader for the trailer
   861  	closing           bool          // is the connection to be closed after reading body?
   862  	doEarlyClose      bool          // whether Close should stop early
   863  	maxTrailerHeaders int64         // how many trailer header values are allowed
   864  
   865  	mu          sync.Mutex // guards following, and calls to Read and Close
   866  	sawEOF      bool
   867  	closed      bool
   868  	dropTrailer bool   // if true, do not populate hdr.Trailer
   869  	onHitEOF    func() // if non-nil, func to call when EOF is Read
   870  }
   871  
   872  // ErrBodyReadAfterClose is returned when reading a [Request] or [Response]
   873  // Body after the body has been closed. This typically happens when the body is
   874  // read after an HTTP [Handler] calls WriteHeader or Write on its
   875  // [ResponseWriter].
   876  var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
   877  
   878  func (b *body) Read(p []byte) (n int, err error) {
   879  	if b == nil {
   880  		return 0, io.EOF
   881  	}
   882  	b.mu.Lock()
   883  	defer b.mu.Unlock()
   884  	if b.closed {
   885  		return 0, ErrBodyReadAfterClose
   886  	}
   887  	return b.readLocked(p)
   888  }
   889  
   890  // Must hold b.mu.
   891  func (b *body) readLocked(p []byte) (n int, err error) {
   892  	if b.sawEOF {
   893  		return 0, io.EOF
   894  	}
   895  	n, err = b.src.Read(p)
   896  
   897  	if err == io.EOF {
   898  		b.sawEOF = true
   899  		// Chunked case. Read the trailer.
   900  		if b.hdr != nil {
   901  			if e := b.readTrailer(); e != nil {
   902  				err = e
   903  				// Something went wrong in the trailer, we must not allow any
   904  				// further reads of any kind to succeed from body, nor any
   905  				// subsequent requests on the server connection. See
   906  				// golang.org/issue/12027
   907  				b.sawEOF = false
   908  				b.closed = true
   909  			}
   910  			b.hdr = nil
   911  		} else {
   912  			// If the server declared the Content-Length, our body is a LimitedReader
   913  			// and we need to check whether this EOF arrived early.
   914  			if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
   915  				err = io.ErrUnexpectedEOF
   916  			}
   917  		}
   918  	}
   919  
   920  	// If we can return an EOF here along with the read data, do
   921  	// so. This is optional per the io.Reader contract, but doing
   922  	// so helps the HTTP transport code recycle its connection
   923  	// earlier (since it will see this EOF itself), even if the
   924  	// client doesn't do future reads or Close.
   925  	if err == nil && n > 0 {
   926  		if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
   927  			err = io.EOF
   928  			b.sawEOF = true
   929  		}
   930  	}
   931  
   932  	if b.sawEOF && b.onHitEOF != nil {
   933  		b.onHitEOF()
   934  	}
   935  
   936  	return n, err
   937  }
   938  
   939  var (
   940  	singleCRLF = []byte("\r\n")
   941  	doubleCRLF = []byte("\r\n\r\n")
   942  )
   943  
   944  func seeUpcomingDoubleCRLF(r *bufio.Reader) error {
   945  	containsValidTrailers := func(buf []byte) (valid, complete bool) {
   946  		if !bytes.HasSuffix(buf, doubleCRLF) {
   947  			return
   948  		}
   949  		complete = true
   950  		cr := false
   951  		for _, c := range buf {
   952  			if cr {
   953  				switch c {
   954  				case '\n':
   955  					cr = false
   956  				default:
   957  					return
   958  				}
   959  			} else {
   960  				switch c {
   961  				case '\r':
   962  					cr = true
   963  				case '\n':
   964  					return
   965  				}
   966  			}
   967  		}
   968  		if !cr {
   969  			valid = true
   970  		}
   971  		return
   972  	}
   973  	for peekSize := 4; ; peekSize++ {
   974  		// This loop stops when Peek returns an error,
   975  		// which it does when r's buffer has been filled.
   976  		buf, err := r.Peek(peekSize)
   977  		valid, complete := containsValidTrailers(buf)
   978  		if complete {
   979  			if valid {
   980  				return nil
   981  			}
   982  			return errors.New("http: invalid trailer")
   983  		}
   984  		if err != nil {
   985  			break
   986  		}
   987  	}
   988  	return errors.New("http: suspiciously long trailer after chunked body")
   989  }
   990  
   991  var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
   992  
   993  func (b *body) readTrailer() error {
   994  	// The common case, since nobody uses trailers.
   995  	buf, err := b.r.Peek(2)
   996  	if bytes.Equal(buf, singleCRLF) {
   997  		b.r.Discard(2)
   998  		return nil
   999  	}
  1000  	if len(buf) < 2 {
  1001  		return errTrailerEOF
  1002  	}
  1003  	if err != nil {
  1004  		return err
  1005  	}
  1006  
  1007  	// Make sure there's a header terminator coming up, to prevent
  1008  	// a DoS with an unbounded size Trailer. It's not easy to
  1009  	// slip in a LimitReader here, as textproto.NewReader requires
  1010  	// a concrete *bufio.Reader. Also, we can't get all the way
  1011  	// back up to our conn's LimitedReader that *might* be backing
  1012  	// this bufio.Reader. Instead, a hack: we iteratively Peek up
  1013  	// to the bufio.Reader's max size, looking for a double CRLF.
  1014  	// This limits the trailer to the underlying buffer size, typically 4kB.
  1015  	if err := seeUpcomingDoubleCRLF(b.r); err != nil {
  1016  		return err
  1017  	}
  1018  
  1019  	hdr, err := readMIMEHeader(textproto.NewReader(b.r), math.MaxInt64, b.maxTrailerHeaders)
  1020  	if err != nil {
  1021  		if err == io.EOF {
  1022  			return errTrailerEOF
  1023  		}
  1024  		return err
  1025  	}
  1026  	// When we are automatically draining a response body, let the trailer
  1027  	// still be parsed above (so connection can be reused). However, do not
  1028  	// actually populate b.hdr.Trailer. Doing so is racy as we do not own b.hdr
  1029  	// anymore when automatic draining occurs.
  1030  	if b.dropTrailer {
  1031  		return nil
  1032  	}
  1033  	switch rr := b.hdr.(type) {
  1034  	case *Request:
  1035  		mergeSetHeader(&rr.Trailer, Header(hdr))
  1036  	case *Response:
  1037  		mergeSetHeader(&rr.Trailer, Header(hdr))
  1038  	}
  1039  	return nil
  1040  }
  1041  
  1042  func mergeSetHeader(dst *Header, src Header) {
  1043  	if *dst == nil {
  1044  		*dst = src
  1045  		return
  1046  	}
  1047  	maps.Copy(*dst, src)
  1048  }
  1049  
  1050  func (b *body) discardTrailer() {
  1051  	b.mu.Lock()
  1052  	defer b.mu.Unlock()
  1053  	b.dropTrailer = true
  1054  }
  1055  
  1056  // unreadDataSizeLocked returns the number of bytes of unread input.
  1057  // It returns -1 if unknown.
  1058  // b.mu must be held.
  1059  func (b *body) unreadDataSizeLocked() int64 {
  1060  	if lr, ok := b.src.(*io.LimitedReader); ok {
  1061  		return lr.N
  1062  	}
  1063  	return -1
  1064  }
  1065  
  1066  func (b *body) Close() error {
  1067  	if b == nil {
  1068  		return nil
  1069  	}
  1070  	b.mu.Lock()
  1071  	defer b.mu.Unlock()
  1072  	if b.closed {
  1073  		return nil
  1074  	}
  1075  	var err error
  1076  	switch {
  1077  	case b.sawEOF:
  1078  		// Already saw EOF, so no need going to look for it.
  1079  	case b.hdr == nil && b.closing:
  1080  		// no trailer and closing the connection next.
  1081  		// no point in reading to EOF.
  1082  	case b.doEarlyClose:
  1083  		// Read up to maxPostHandlerReadBytes bytes of the body, looking
  1084  		// for EOF (and trailers), so we can re-use this connection.
  1085  		if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
  1086  			// There was a declared Content-Length, and we have more bytes remaining
  1087  			// than our maxPostHandlerReadBytes tolerance. So, give up.
  1088  		} else {
  1089  			var n int64
  1090  			// Consume the body, or, which will also lead to us reading
  1091  			// the trailer headers after the body, if present.
  1092  			n, err = io.CopyN(io.Discard, bodyLocked{b}, maxPostHandlerReadBytes+1)
  1093  			if err == io.EOF && n <= maxPostHandlerReadBytes {
  1094  				b.sawEOF = true
  1095  				// Reaching the end of the body is the expected
  1096  				// outcome here, not an error to report to the caller.
  1097  				err = nil
  1098  			}
  1099  		}
  1100  	default:
  1101  		// Fully consume the body, which will also lead to us reading
  1102  		// the trailer headers after the body, if present.
  1103  		_, err = io.Copy(io.Discard, bodyLocked{b})
  1104  	}
  1105  	b.closed = true
  1106  	return err
  1107  }
  1108  
  1109  func (b *body) consumedEntireBody() bool {
  1110  	if b == nil {
  1111  		return true
  1112  	}
  1113  	b.mu.Lock()
  1114  	defer b.mu.Unlock()
  1115  	return b.sawEOF
  1116  }
  1117  
  1118  // bodyRemains reports whether future Read calls might
  1119  // yield data.
  1120  func (b *body) bodyRemains() bool {
  1121  	if b == nil {
  1122  		return false
  1123  	}
  1124  	b.mu.Lock()
  1125  	defer b.mu.Unlock()
  1126  	return !b.sawEOF
  1127  }
  1128  
  1129  func (b *body) registerOnHitEOF(fn func()) {
  1130  	if b == nil {
  1131  		return
  1132  	}
  1133  	b.mu.Lock()
  1134  	defer b.mu.Unlock()
  1135  	b.onHitEOF = fn
  1136  }
  1137  
  1138  // bodyLocked is an io.Reader reading from a *body when its mutex is
  1139  // already held.
  1140  type bodyLocked struct {
  1141  	b *body
  1142  }
  1143  
  1144  func (bl bodyLocked) Read(p []byte) (n int, err error) {
  1145  	if bl.b.closed {
  1146  		return 0, ErrBodyReadAfterClose
  1147  	}
  1148  	return bl.b.readLocked(p)
  1149  }
  1150  
  1151  var httplaxcontentlength = godebug.New("httplaxcontentlength")
  1152  
  1153  // parseContentLength checks that the header is valid and then trims whitespace.
  1154  // It returns the parsed header value or an error.
  1155  //
  1156  // When GODEBUG=httplaxcontentlength=1, it returns -1 for an empty Content-Length value.
  1157  func parseContentLength(contentLength []string) (string, int64, error) {
  1158  	if len(contentLength) == 0 {
  1159  		return "", -1, nil
  1160  	}
  1161  
  1162  	// RFC 9112 6.3 item 5: Accept multiple Content-Length header values
  1163  	// if they are all identical.
  1164  	//
  1165  	// To be fully RFC-compliant, we should accept identical,
  1166  	// comma-separated Content-Length values here.
  1167  	//
  1168  	// Not doing so doesn't seem to have been a problem in the ~decade
  1169  	// since the deduplication being added (see #16490) and this comment
  1170  	// being written, so we would need a very good reason to change this now.
  1171  	cl := textproto.TrimString(contentLength[0])
  1172  	for _, ct := range contentLength[1:] {
  1173  		if cl != textproto.TrimString(ct) {
  1174  			return "", 0, errTooManyContentLengths
  1175  		}
  1176  	}
  1177  
  1178  	// The Content-Length must be a valid numeric value.
  1179  	// See: https://www.rfc-editor.org/info/rfc9110/#section-8.6
  1180  	if cl == "" {
  1181  		if httplaxcontentlength.Value() == "1" {
  1182  			httplaxcontentlength.IncNonDefault()
  1183  			return "", -1, nil
  1184  		}
  1185  		return "", 0, badStringError("invalid empty Content-Length", cl)
  1186  	}
  1187  	n, err := strconv.ParseUint(cl, 10, 63)
  1188  	if err != nil {
  1189  		return "", 0, badStringError("bad Content-Length", cl)
  1190  	}
  1191  	return cl, int64(n), nil
  1192  }
  1193  
  1194  // finishAsyncByteRead finishes reading the 1-byte sniff
  1195  // from the ContentLength==0, Body!=nil case.
  1196  type finishAsyncByteRead struct {
  1197  	tw *transferWriter
  1198  }
  1199  
  1200  func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
  1201  	if len(p) == 0 {
  1202  		return
  1203  	}
  1204  	rres := <-fr.tw.ByteReadCh
  1205  	n, err = rres.n, rres.err
  1206  	if n == 1 {
  1207  		p[0] = rres.b
  1208  	}
  1209  	if err == nil {
  1210  		err = io.EOF
  1211  	}
  1212  	return
  1213  }
  1214  
  1215  var nopCloserType = reflect.TypeOf(io.NopCloser(nil))
  1216  var nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct {
  1217  	io.Reader
  1218  	io.WriterTo
  1219  }{}))
  1220  
  1221  // unwrapNopCloser return the underlying reader and true if r is a NopCloser
  1222  // else it return false.
  1223  func unwrapNopCloser(r io.Reader) (underlyingReader io.Reader, isNopCloser bool) {
  1224  	switch reflect.TypeOf(r) {
  1225  	case nopCloserType, nopCloserWriterToType:
  1226  		return reflect.ValueOf(r).Field(0).Interface().(io.Reader), true
  1227  	default:
  1228  		return nil, false
  1229  	}
  1230  }
  1231  
  1232  // isKnownInMemoryReader reports whether r is a type known to not
  1233  // block on Read. Its caller uses this as an optional optimization to
  1234  // send fewer TCP packets.
  1235  func isKnownInMemoryReader(r io.Reader) bool {
  1236  	switch r.(type) {
  1237  	case *bytes.Reader, *bytes.Buffer, *strings.Reader:
  1238  		return true
  1239  	}
  1240  	if r, ok := unwrapNopCloser(r); ok {
  1241  		return isKnownInMemoryReader(r)
  1242  	}
  1243  	if r, ok := r.(*readTrackingBody); ok {
  1244  		return isKnownInMemoryReader(r.ReadCloser)
  1245  	}
  1246  	return false
  1247  }
  1248  
  1249  // bufioFlushWriter is an io.Writer wrapper that flushes all writes
  1250  // on its wrapped writer if it's a *bufio.Writer.
  1251  type bufioFlushWriter struct{ w io.Writer }
  1252  
  1253  func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
  1254  	n, err = fw.w.Write(p)
  1255  	if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
  1256  		ferr := bw.Flush()
  1257  		if ferr != nil && err == nil {
  1258  			err = ferr
  1259  		}
  1260  	}
  1261  	return
  1262  }
  1263  

View as plain text