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