]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/transfer.go
net/http: use copyBufPool in transferWriter.doBodyCopy()
[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         bufp := copyBufPool.Get().(*[]byte)
414         buf := *bufp
415         defer copyBufPool.Put(bufp)
416
417         n, err = io.CopyBuffer(dst, src, buf)
418         if err != nil && err != io.EOF {
419                 t.bodyReadError = err
420         }
421         return
422 }
423
424 // unwrapBody unwraps the body's inner reader if it's a
425 // nopCloser. This is to ensure that body writes sourced from local
426 // files (*os.File types) are properly optimized.
427 //
428 // This function is only intended for use in writeBody.
429 func (t *transferWriter) unwrapBody() io.Reader {
430         if r, ok := unwrapNopCloser(t.Body); ok {
431                 return r
432         }
433         if r, ok := t.Body.(*readTrackingBody); ok {
434                 r.didRead = true
435                 return r.ReadCloser
436         }
437         return t.Body
438 }
439
440 type transferReader struct {
441         // Input
442         Header        Header
443         StatusCode    int
444         RequestMethod string
445         ProtoMajor    int
446         ProtoMinor    int
447         // Output
448         Body          io.ReadCloser
449         ContentLength int64
450         Chunked       bool
451         Close         bool
452         Trailer       Header
453 }
454
455 func (t *transferReader) protoAtLeast(m, n int) bool {
456         return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
457 }
458
459 // bodyAllowedForStatus reports whether a given response status code
460 // permits a body. See RFC 7230, section 3.3.
461 func bodyAllowedForStatus(status int) bool {
462         switch {
463         case status >= 100 && status <= 199:
464                 return false
465         case status == 204:
466                 return false
467         case status == 304:
468                 return false
469         }
470         return true
471 }
472
473 var (
474         suppressedHeaders304    = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
475         suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
476         excludedHeadersNoBody   = map[string]bool{"Content-Length": true, "Transfer-Encoding": true}
477 )
478
479 func suppressedHeaders(status int) []string {
480         switch {
481         case status == 304:
482                 // RFC 7232 section 4.1
483                 return suppressedHeaders304
484         case !bodyAllowedForStatus(status):
485                 return suppressedHeadersNoBody
486         }
487         return nil
488 }
489
490 // msg is *Request or *Response.
491 func readTransfer(msg any, r *bufio.Reader) (err error) {
492         t := &transferReader{RequestMethod: "GET"}
493
494         // Unify input
495         isResponse := false
496         switch rr := msg.(type) {
497         case *Response:
498                 t.Header = rr.Header
499                 t.StatusCode = rr.StatusCode
500                 t.ProtoMajor = rr.ProtoMajor
501                 t.ProtoMinor = rr.ProtoMinor
502                 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
503                 isResponse = true
504                 if rr.Request != nil {
505                         t.RequestMethod = rr.Request.Method
506                 }
507         case *Request:
508                 t.Header = rr.Header
509                 t.RequestMethod = rr.Method
510                 t.ProtoMajor = rr.ProtoMajor
511                 t.ProtoMinor = rr.ProtoMinor
512                 // Transfer semantics for Requests are exactly like those for
513                 // Responses with status code 200, responding to a GET method
514                 t.StatusCode = 200
515                 t.Close = rr.Close
516         default:
517                 panic("unexpected type")
518         }
519
520         // Default to HTTP/1.1
521         if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
522                 t.ProtoMajor, t.ProtoMinor = 1, 1
523         }
524
525         // Transfer-Encoding: chunked, and overriding Content-Length.
526         if err := t.parseTransferEncoding(); err != nil {
527                 return err
528         }
529
530         realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.Chunked)
531         if err != nil {
532                 return err
533         }
534         if isResponse && t.RequestMethod == "HEAD" {
535                 if n, err := parseContentLength(t.Header["Content-Length"]); err != nil {
536                         return err
537                 } else {
538                         t.ContentLength = n
539                 }
540         } else {
541                 t.ContentLength = realLength
542         }
543
544         // Trailer
545         t.Trailer, err = fixTrailer(t.Header, t.Chunked)
546         if err != nil {
547                 return err
548         }
549
550         // If there is no Content-Length or chunked Transfer-Encoding on a *Response
551         // and the status is not 1xx, 204 or 304, then the body is unbounded.
552         // See RFC 7230, section 3.3.
553         switch msg.(type) {
554         case *Response:
555                 if realLength == -1 && !t.Chunked && bodyAllowedForStatus(t.StatusCode) {
556                         // Unbounded body.
557                         t.Close = true
558                 }
559         }
560
561         // Prepare body reader. ContentLength < 0 means chunked encoding
562         // or close connection when finished, since multipart is not supported yet
563         switch {
564         case t.Chunked:
565                 if isResponse && (noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode)) {
566                         t.Body = NoBody
567                 } else {
568                         t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
569                 }
570         case realLength == 0:
571                 t.Body = NoBody
572         case realLength > 0:
573                 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
574         default:
575                 // realLength < 0, i.e. "Content-Length" not mentioned in header
576                 if t.Close {
577                         // Close semantics (i.e. HTTP/1.0)
578                         t.Body = &body{src: r, closing: t.Close}
579                 } else {
580                         // Persistent connection (i.e. HTTP/1.1)
581                         t.Body = NoBody
582                 }
583         }
584
585         // Unify output
586         switch rr := msg.(type) {
587         case *Request:
588                 rr.Body = t.Body
589                 rr.ContentLength = t.ContentLength
590                 if t.Chunked {
591                         rr.TransferEncoding = []string{"chunked"}
592                 }
593                 rr.Close = t.Close
594                 rr.Trailer = t.Trailer
595         case *Response:
596                 rr.Body = t.Body
597                 rr.ContentLength = t.ContentLength
598                 if t.Chunked {
599                         rr.TransferEncoding = []string{"chunked"}
600                 }
601                 rr.Close = t.Close
602                 rr.Trailer = t.Trailer
603         }
604
605         return nil
606 }
607
608 // Checks whether chunked is part of the encodings stack.
609 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
610
611 // Checks whether the encoding is explicitly "identity".
612 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
613
614 // unsupportedTEError reports unsupported transfer-encodings.
615 type unsupportedTEError struct {
616         err string
617 }
618
619 func (uste *unsupportedTEError) Error() string {
620         return uste.err
621 }
622
623 // isUnsupportedTEError checks if the error is of type
624 // unsupportedTEError. It is usually invoked with a non-nil err.
625 func isUnsupportedTEError(err error) bool {
626         _, ok := err.(*unsupportedTEError)
627         return ok
628 }
629
630 // parseTransferEncoding sets t.Chunked based on the Transfer-Encoding header.
631 func (t *transferReader) parseTransferEncoding() error {
632         raw, present := t.Header["Transfer-Encoding"]
633         if !present {
634                 return nil
635         }
636         delete(t.Header, "Transfer-Encoding")
637
638         // Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
639         if !t.protoAtLeast(1, 1) {
640                 return nil
641         }
642
643         // Like nginx, we only support a single Transfer-Encoding header field, and
644         // only if set to "chunked". This is one of the most security sensitive
645         // surfaces in HTTP/1.1 due to the risk of request smuggling, so we keep it
646         // strict and simple.
647         if len(raw) != 1 {
648                 return &unsupportedTEError{fmt.Sprintf("too many transfer encodings: %q", raw)}
649         }
650         if !ascii.EqualFold(raw[0], "chunked") {
651                 return &unsupportedTEError{fmt.Sprintf("unsupported transfer encoding: %q", raw[0])}
652         }
653
654         // RFC 7230 3.3.2 says "A sender MUST NOT send a Content-Length header field
655         // in any message that contains a Transfer-Encoding header field."
656         //
657         // but also: "If a message is received with both a Transfer-Encoding and a
658         // Content-Length header field, the Transfer-Encoding overrides the
659         // Content-Length. Such a message might indicate an attempt to perform
660         // request smuggling (Section 9.5) or response splitting (Section 9.4) and
661         // ought to be handled as an error. A sender MUST remove the received
662         // Content-Length field prior to forwarding such a message downstream."
663         //
664         // Reportedly, these appear in the wild.
665         delete(t.Header, "Content-Length")
666
667         t.Chunked = true
668         return nil
669 }
670
671 // Determine the expected body length, using RFC 7230 Section 3.3. This
672 // function is not a method, because ultimately it should be shared by
673 // ReadResponse and ReadRequest.
674 func fixLength(isResponse bool, status int, requestMethod string, header Header, chunked bool) (int64, error) {
675         isRequest := !isResponse
676         contentLens := header["Content-Length"]
677
678         // Hardening against HTTP request smuggling
679         if len(contentLens) > 1 {
680                 // Per RFC 7230 Section 3.3.2, prevent multiple
681                 // Content-Length headers if they differ in value.
682                 // If there are dups of the value, remove the dups.
683                 // See Issue 16490.
684                 first := textproto.TrimString(contentLens[0])
685                 for _, ct := range contentLens[1:] {
686                         if first != textproto.TrimString(ct) {
687                                 return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
688                         }
689                 }
690
691                 // deduplicate Content-Length
692                 header.Del("Content-Length")
693                 header.Add("Content-Length", first)
694
695                 contentLens = header["Content-Length"]
696         }
697
698         // Logic based on response type or status
699         if isResponse && noResponseBodyExpected(requestMethod) {
700                 return 0, nil
701         }
702         if status/100 == 1 {
703                 return 0, nil
704         }
705         switch status {
706         case 204, 304:
707                 return 0, nil
708         }
709
710         // Logic based on Transfer-Encoding
711         if chunked {
712                 return -1, nil
713         }
714
715         if len(contentLens) > 0 {
716                 // Logic based on Content-Length
717                 n, err := parseContentLength(contentLens)
718                 if err != nil {
719                         return -1, err
720                 }
721                 return n, nil
722         }
723
724         header.Del("Content-Length")
725
726         if isRequest {
727                 // RFC 7230 neither explicitly permits nor forbids an
728                 // entity-body on a GET request so we permit one if
729                 // declared, but we default to 0 here (not -1 below)
730                 // if there's no mention of a body.
731                 // Likewise, all other request methods are assumed to have
732                 // no body if neither Transfer-Encoding chunked nor a
733                 // Content-Length are set.
734                 return 0, nil
735         }
736
737         // Body-EOF logic based on other methods (like closing, or chunked coding)
738         return -1, nil
739 }
740
741 // Determine whether to hang up after sending a request and body, or
742 // receiving a response and body
743 // 'header' is the request headers.
744 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
745         if major < 1 {
746                 return true
747         }
748
749         conv := header["Connection"]
750         hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
751         if major == 1 && minor == 0 {
752                 return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
753         }
754
755         if hasClose && removeCloseHeader {
756                 header.Del("Connection")
757         }
758
759         return hasClose
760 }
761
762 // Parse the trailer header.
763 func fixTrailer(header Header, chunked bool) (Header, error) {
764         vv, ok := header["Trailer"]
765         if !ok {
766                 return nil, nil
767         }
768         if !chunked {
769                 // Trailer and no chunking:
770                 // this is an invalid use case for trailer header.
771                 // Nevertheless, no error will be returned and we
772                 // let users decide if this is a valid HTTP message.
773                 // The Trailer header will be kept in Response.Header
774                 // but not populate Response.Trailer.
775                 // See issue #27197.
776                 return nil, nil
777         }
778         header.Del("Trailer")
779
780         trailer := make(Header)
781         var err error
782         for _, v := range vv {
783                 foreachHeaderElement(v, func(key string) {
784                         key = CanonicalHeaderKey(key)
785                         switch key {
786                         case "Transfer-Encoding", "Trailer", "Content-Length":
787                                 if err == nil {
788                                         err = badStringError("bad trailer key", key)
789                                         return
790                                 }
791                         }
792                         trailer[key] = nil
793                 })
794         }
795         if err != nil {
796                 return nil, err
797         }
798         if len(trailer) == 0 {
799                 return nil, nil
800         }
801         return trailer, nil
802 }
803
804 // body turns a Reader into a ReadCloser.
805 // Close ensures that the body has been fully read
806 // and then reads the trailer if necessary.
807 type body struct {
808         src          io.Reader
809         hdr          any           // non-nil (Response or Request) value means read trailer
810         r            *bufio.Reader // underlying wire-format reader for the trailer
811         closing      bool          // is the connection to be closed after reading body?
812         doEarlyClose bool          // whether Close should stop early
813
814         mu         sync.Mutex // guards following, and calls to Read and Close
815         sawEOF     bool
816         closed     bool
817         earlyClose bool   // Close called and we didn't read to the end of src
818         onHitEOF   func() // if non-nil, func to call when EOF is Read
819 }
820
821 // ErrBodyReadAfterClose is returned when reading a Request or Response
822 // Body after the body has been closed. This typically happens when the body is
823 // read after an HTTP Handler calls WriteHeader or Write on its
824 // ResponseWriter.
825 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
826
827 func (b *body) Read(p []byte) (n int, err error) {
828         b.mu.Lock()
829         defer b.mu.Unlock()
830         if b.closed {
831                 return 0, ErrBodyReadAfterClose
832         }
833         return b.readLocked(p)
834 }
835
836 // Must hold b.mu.
837 func (b *body) readLocked(p []byte) (n int, err error) {
838         if b.sawEOF {
839                 return 0, io.EOF
840         }
841         n, err = b.src.Read(p)
842
843         if err == io.EOF {
844                 b.sawEOF = true
845                 // Chunked case. Read the trailer.
846                 if b.hdr != nil {
847                         if e := b.readTrailer(); e != nil {
848                                 err = e
849                                 // Something went wrong in the trailer, we must not allow any
850                                 // further reads of any kind to succeed from body, nor any
851                                 // subsequent requests on the server connection. See
852                                 // golang.org/issue/12027
853                                 b.sawEOF = false
854                                 b.closed = true
855                         }
856                         b.hdr = nil
857                 } else {
858                         // If the server declared the Content-Length, our body is a LimitedReader
859                         // and we need to check whether this EOF arrived early.
860                         if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
861                                 err = io.ErrUnexpectedEOF
862                         }
863                 }
864         }
865
866         // If we can return an EOF here along with the read data, do
867         // so. This is optional per the io.Reader contract, but doing
868         // so helps the HTTP transport code recycle its connection
869         // earlier (since it will see this EOF itself), even if the
870         // client doesn't do future reads or Close.
871         if err == nil && n > 0 {
872                 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
873                         err = io.EOF
874                         b.sawEOF = true
875                 }
876         }
877
878         if b.sawEOF && b.onHitEOF != nil {
879                 b.onHitEOF()
880         }
881
882         return n, err
883 }
884
885 var (
886         singleCRLF = []byte("\r\n")
887         doubleCRLF = []byte("\r\n\r\n")
888 )
889
890 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
891         for peekSize := 4; ; peekSize++ {
892                 // This loop stops when Peek returns an error,
893                 // which it does when r's buffer has been filled.
894                 buf, err := r.Peek(peekSize)
895                 if bytes.HasSuffix(buf, doubleCRLF) {
896                         return true
897                 }
898                 if err != nil {
899                         break
900                 }
901         }
902         return false
903 }
904
905 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
906
907 func (b *body) readTrailer() error {
908         // The common case, since nobody uses trailers.
909         buf, err := b.r.Peek(2)
910         if bytes.Equal(buf, singleCRLF) {
911                 b.r.Discard(2)
912                 return nil
913         }
914         if len(buf) < 2 {
915                 return errTrailerEOF
916         }
917         if err != nil {
918                 return err
919         }
920
921         // Make sure there's a header terminator coming up, to prevent
922         // a DoS with an unbounded size Trailer. It's not easy to
923         // slip in a LimitReader here, as textproto.NewReader requires
924         // a concrete *bufio.Reader. Also, we can't get all the way
925         // back up to our conn's LimitedReader that *might* be backing
926         // this bufio.Reader. Instead, a hack: we iteratively Peek up
927         // to the bufio.Reader's max size, looking for a double CRLF.
928         // This limits the trailer to the underlying buffer size, typically 4kB.
929         if !seeUpcomingDoubleCRLF(b.r) {
930                 return errors.New("http: suspiciously long trailer after chunked body")
931         }
932
933         hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
934         if err != nil {
935                 if err == io.EOF {
936                         return errTrailerEOF
937                 }
938                 return err
939         }
940         switch rr := b.hdr.(type) {
941         case *Request:
942                 mergeSetHeader(&rr.Trailer, Header(hdr))
943         case *Response:
944                 mergeSetHeader(&rr.Trailer, Header(hdr))
945         }
946         return nil
947 }
948
949 func mergeSetHeader(dst *Header, src Header) {
950         if *dst == nil {
951                 *dst = src
952                 return
953         }
954         for k, vv := range src {
955                 (*dst)[k] = vv
956         }
957 }
958
959 // unreadDataSizeLocked returns the number of bytes of unread input.
960 // It returns -1 if unknown.
961 // b.mu must be held.
962 func (b *body) unreadDataSizeLocked() int64 {
963         if lr, ok := b.src.(*io.LimitedReader); ok {
964                 return lr.N
965         }
966         return -1
967 }
968
969 func (b *body) Close() error {
970         b.mu.Lock()
971         defer b.mu.Unlock()
972         if b.closed {
973                 return nil
974         }
975         var err error
976         switch {
977         case b.sawEOF:
978                 // Already saw EOF, so no need going to look for it.
979         case b.hdr == nil && b.closing:
980                 // no trailer and closing the connection next.
981                 // no point in reading to EOF.
982         case b.doEarlyClose:
983                 // Read up to maxPostHandlerReadBytes bytes of the body, looking
984                 // for EOF (and trailers), so we can re-use this connection.
985                 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
986                         // There was a declared Content-Length, and we have more bytes remaining
987                         // than our maxPostHandlerReadBytes tolerance. So, give up.
988                         b.earlyClose = true
989                 } else {
990                         var n int64
991                         // Consume the body, or, which will also lead to us reading
992                         // the trailer headers after the body, if present.
993                         n, err = io.CopyN(io.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
994                         if err == io.EOF {
995                                 err = nil
996                         }
997                         if n == maxPostHandlerReadBytes {
998                                 b.earlyClose = true
999                         }
1000                 }
1001         default:
1002                 // Fully consume the body, which will also lead to us reading
1003                 // the trailer headers after the body, if present.
1004                 _, err = io.Copy(io.Discard, bodyLocked{b})
1005         }
1006         b.closed = true
1007         return err
1008 }
1009
1010 func (b *body) didEarlyClose() bool {
1011         b.mu.Lock()
1012         defer b.mu.Unlock()
1013         return b.earlyClose
1014 }
1015
1016 // bodyRemains reports whether future Read calls might
1017 // yield data.
1018 func (b *body) bodyRemains() bool {
1019         b.mu.Lock()
1020         defer b.mu.Unlock()
1021         return !b.sawEOF
1022 }
1023
1024 func (b *body) registerOnHitEOF(fn func()) {
1025         b.mu.Lock()
1026         defer b.mu.Unlock()
1027         b.onHitEOF = fn
1028 }
1029
1030 // bodyLocked is an io.Reader reading from a *body when its mutex is
1031 // already held.
1032 type bodyLocked struct {
1033         b *body
1034 }
1035
1036 func (bl bodyLocked) Read(p []byte) (n int, err error) {
1037         if bl.b.closed {
1038                 return 0, ErrBodyReadAfterClose
1039         }
1040         return bl.b.readLocked(p)
1041 }
1042
1043 var laxContentLength = godebug.New("httplaxcontentlength")
1044
1045 // parseContentLength checks that the header is valid and then trims
1046 // whitespace. It returns -1 if no value is set otherwise the value
1047 // if it's >= 0.
1048 func parseContentLength(clHeaders []string) (int64, error) {
1049         if len(clHeaders) == 0 {
1050                 return -1, nil
1051         }
1052         cl := textproto.TrimString(clHeaders[0])
1053
1054         // The Content-Length must be a valid numeric value.
1055         // See: https://datatracker.ietf.org/doc/html/rfc2616/#section-14.13
1056         if cl == "" {
1057                 if laxContentLength.Value() == "1" {
1058                         laxContentLength.IncNonDefault()
1059                         return -1, nil
1060                 }
1061                 return 0, badStringError("invalid empty Content-Length", cl)
1062         }
1063         n, err := strconv.ParseUint(cl, 10, 63)
1064         if err != nil {
1065                 return 0, badStringError("bad Content-Length", cl)
1066         }
1067         return int64(n), nil
1068 }
1069
1070 // finishAsyncByteRead finishes reading the 1-byte sniff
1071 // from the ContentLength==0, Body!=nil case.
1072 type finishAsyncByteRead struct {
1073         tw *transferWriter
1074 }
1075
1076 func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1077         if len(p) == 0 {
1078                 return
1079         }
1080         rres := <-fr.tw.ByteReadCh
1081         n, err = rres.n, rres.err
1082         if n == 1 {
1083                 p[0] = rres.b
1084         }
1085         if err == nil {
1086                 err = io.EOF
1087         }
1088         return
1089 }
1090
1091 var nopCloserType = reflect.TypeOf(io.NopCloser(nil))
1092 var nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct {
1093         io.Reader
1094         io.WriterTo
1095 }{}))
1096
1097 // unwrapNopCloser return the underlying reader and true if r is a NopCloser
1098 // else it return false.
1099 func unwrapNopCloser(r io.Reader) (underlyingReader io.Reader, isNopCloser bool) {
1100         switch reflect.TypeOf(r) {
1101         case nopCloserType, nopCloserWriterToType:
1102                 return reflect.ValueOf(r).Field(0).Interface().(io.Reader), true
1103         default:
1104                 return nil, false
1105         }
1106 }
1107
1108 // isKnownInMemoryReader reports whether r is a type known to not
1109 // block on Read. Its caller uses this as an optional optimization to
1110 // send fewer TCP packets.
1111 func isKnownInMemoryReader(r io.Reader) bool {
1112         switch r.(type) {
1113         case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1114                 return true
1115         }
1116         if r, ok := unwrapNopCloser(r); ok {
1117                 return isKnownInMemoryReader(r)
1118         }
1119         if r, ok := r.(*readTrackingBody); ok {
1120                 return isKnownInMemoryReader(r.ReadCloser)
1121         }
1122         return false
1123 }
1124
1125 // bufioFlushWriter is an io.Writer wrapper that flushes all writes
1126 // on its wrapped writer if it's a *bufio.Writer.
1127 type bufioFlushWriter struct{ w io.Writer }
1128
1129 func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
1130         n, err = fw.w.Write(p)
1131         if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
1132                 ferr := bw.Flush()
1133                 if ferr != nil && err == nil {
1134                         err = ferr
1135                 }
1136         }
1137         return
1138 }