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