]> Cypherpunks.ru repositories - gostls13.git/blob - src/net/http/transfer.go
[dev.boringcrypto] all: merge master into dev.boringcrypto
[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         "compress/gzip"
11         "errors"
12         "fmt"
13         "io"
14         "io/ioutil"
15         "net/http/httptrace"
16         "net/http/internal"
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 interface{}) (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, ioutil.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 // In other words, this delay will not normally affect anybody, and there
205 // are workarounds if it does.
206 func (t *transferWriter) probeRequestBody() {
207         t.ByteReadCh = make(chan readResult, 1)
208         go func(body io.Reader) {
209                 var buf [1]byte
210                 var rres readResult
211                 rres.n, rres.err = body.Read(buf[:])
212                 if rres.n == 1 {
213                         rres.b = buf[0]
214                 }
215                 t.ByteReadCh <- rres
216         }(t.Body)
217         timer := time.NewTimer(200 * time.Millisecond)
218         select {
219         case rres := <-t.ByteReadCh:
220                 timer.Stop()
221                 if rres.n == 0 && rres.err == io.EOF {
222                         // It was empty.
223                         t.Body = nil
224                         t.ContentLength = 0
225                 } else if rres.n == 1 {
226                         if rres.err != nil {
227                                 t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
228                         } else {
229                                 t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
230                         }
231                 } else if rres.err != nil {
232                         t.Body = errorReader{rres.err}
233                 }
234         case <-timer.C:
235                 // Too slow. Don't wait. Read it later, and keep
236                 // assuming that this is ContentLength == -1
237                 // (unknown), which means we'll send a
238                 // "Transfer-Encoding: chunked" header.
239                 t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
240                 // Request that Request.Write flush the headers to the
241                 // network before writing the body, since our body may not
242                 // become readable until it's seen the response headers.
243                 t.FlushHeaders = true
244         }
245 }
246
247 func noResponseBodyExpected(requestMethod string) bool {
248         return requestMethod == "HEAD"
249 }
250
251 func (t *transferWriter) shouldSendContentLength() bool {
252         if chunked(t.TransferEncoding) {
253                 return false
254         }
255         if t.ContentLength > 0 {
256                 return true
257         }
258         if t.ContentLength < 0 {
259                 return false
260         }
261         // Many servers expect a Content-Length for these methods
262         if t.Method == "POST" || t.Method == "PUT" {
263                 return true
264         }
265         if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
266                 if t.Method == "GET" || t.Method == "HEAD" {
267                         return false
268                 }
269                 return true
270         }
271
272         return false
273 }
274
275 func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error {
276         if t.Close && !hasToken(t.Header.get("Connection"), "close") {
277                 if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
278                         return err
279                 }
280                 if trace != nil && trace.WroteHeaderField != nil {
281                         trace.WroteHeaderField("Connection", []string{"close"})
282                 }
283         }
284
285         // Write Content-Length and/or Transfer-Encoding whose values are a
286         // function of the sanitized field triple (Body, ContentLength,
287         // TransferEncoding)
288         if t.shouldSendContentLength() {
289                 if _, err := io.WriteString(w, "Content-Length: "); err != nil {
290                         return err
291                 }
292                 if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
293                         return err
294                 }
295                 if trace != nil && trace.WroteHeaderField != nil {
296                         trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
297                 }
298         } else if chunked(t.TransferEncoding) {
299                 if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
300                         return err
301                 }
302                 if trace != nil && trace.WroteHeaderField != nil {
303                         trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
304                 }
305         }
306
307         // Write Trailer header
308         if t.Trailer != nil {
309                 keys := make([]string, 0, len(t.Trailer))
310                 for k := range t.Trailer {
311                         k = CanonicalHeaderKey(k)
312                         switch k {
313                         case "Transfer-Encoding", "Trailer", "Content-Length":
314                                 return &badStringError{"invalid Trailer key", k}
315                         }
316                         keys = append(keys, k)
317                 }
318                 if len(keys) > 0 {
319                         sort.Strings(keys)
320                         // TODO: could do better allocation-wise here, but trailers are rare,
321                         // so being lazy for now.
322                         if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
323                                 return err
324                         }
325                         if trace != nil && trace.WroteHeaderField != nil {
326                                 trace.WroteHeaderField("Trailer", keys)
327                         }
328                 }
329         }
330
331         return nil
332 }
333
334 func (t *transferWriter) writeBody(w io.Writer) error {
335         var err error
336         var ncopy int64
337
338         // Write body. We "unwrap" the body first if it was wrapped in a
339         // nopCloser. This is to ensure that we can take advantage of
340         // OS-level optimizations in the event that the body is an
341         // *os.File.
342         if t.Body != nil {
343                 var body = t.unwrapBody()
344                 if chunked(t.TransferEncoding) {
345                         if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
346                                 w = &internal.FlushAfterChunkWriter{Writer: bw}
347                         }
348                         cw := internal.NewChunkedWriter(w)
349                         _, err = t.doBodyCopy(cw, body)
350                         if err == nil {
351                                 err = cw.Close()
352                         }
353                 } else if t.ContentLength == -1 {
354                         dst := w
355                         if t.Method == "CONNECT" {
356                                 dst = bufioFlushWriter{dst}
357                         }
358                         ncopy, err = t.doBodyCopy(dst, body)
359                 } else {
360                         ncopy, err = t.doBodyCopy(w, io.LimitReader(body, t.ContentLength))
361                         if err != nil {
362                                 return err
363                         }
364                         var nextra int64
365                         nextra, err = t.doBodyCopy(ioutil.Discard, body)
366                         ncopy += nextra
367                 }
368                 if err != nil {
369                         return err
370                 }
371         }
372         if t.BodyCloser != nil {
373                 if err := t.BodyCloser.Close(); err != nil {
374                         return err
375                 }
376         }
377
378         if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
379                 return fmt.Errorf("http: ContentLength=%d with Body length %d",
380                         t.ContentLength, ncopy)
381         }
382
383         if chunked(t.TransferEncoding) {
384                 // Write Trailer header
385                 if t.Trailer != nil {
386                         if err := t.Trailer.Write(w); err != nil {
387                                 return err
388                         }
389                 }
390                 // Last chunk, empty trailer
391                 _, err = io.WriteString(w, "\r\n")
392         }
393         return err
394 }
395
396 // doBodyCopy wraps a copy operation, with any resulting error also
397 // being saved in bodyReadError.
398 //
399 // This function is only intended for use in writeBody.
400 func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
401         n, err = io.Copy(dst, src)
402         if err != nil && err != io.EOF {
403                 t.bodyReadError = err
404         }
405         return
406 }
407
408 // unwrapBodyReader unwraps the body's inner reader if it's a
409 // nopCloser. This is to ensure that body writes sourced from local
410 // files (*os.File types) are properly optimized.
411 //
412 // This function is only intended for use in writeBody.
413 func (t *transferWriter) unwrapBody() io.Reader {
414         if reflect.TypeOf(t.Body) == nopCloserType {
415                 return reflect.ValueOf(t.Body).Field(0).Interface().(io.Reader)
416         }
417
418         return t.Body
419 }
420
421 type transferReader struct {
422         // Input
423         Header        Header
424         StatusCode    int
425         RequestMethod string
426         ProtoMajor    int
427         ProtoMinor    int
428         // Output
429         Body             io.ReadCloser
430         ContentLength    int64
431         TransferEncoding []string
432         Close            bool
433         Trailer          Header
434 }
435
436 func (t *transferReader) protoAtLeast(m, n int) bool {
437         return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
438 }
439
440 // bodyAllowedForStatus reports whether a given response status code
441 // permits a body. See RFC 7230, section 3.3.
442 func bodyAllowedForStatus(status int) bool {
443         switch {
444         case status >= 100 && status <= 199:
445                 return false
446         case status == 204:
447                 return false
448         case status == 304:
449                 return false
450         }
451         return true
452 }
453
454 var (
455         suppressedHeaders304    = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
456         suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
457 )
458
459 func suppressedHeaders(status int) []string {
460         switch {
461         case status == 304:
462                 // RFC 7232 section 4.1
463                 return suppressedHeaders304
464         case !bodyAllowedForStatus(status):
465                 return suppressedHeadersNoBody
466         }
467         return nil
468 }
469
470 // proxyingReadCloser is a composite type that accepts and proxies
471 // io.Read and io.Close calls to its respective Reader and Closer.
472 //
473 // It is composed of:
474 // a) a top-level reader e.g. the result of decompression
475 // b) a symbolic Closer e.g. the result of decompression, the
476 //    original body and the connection itself.
477 type proxyingReadCloser struct {
478         io.Reader
479         io.Closer
480 }
481
482 // multiCloser implements io.Closer and allows a bunch of io.Closer values
483 // to all be closed once.
484 // Example usage is with proxyingReadCloser if we are decompressing a response
485 // body on the fly and would like to close both *gzip.Reader and underlying body.
486 type multiCloser []io.Closer
487
488 func (mc multiCloser) Close() error {
489         var err error
490         for _, c := range mc {
491                 if err1 := c.Close(); err1 != nil && err == nil {
492                         err = err1
493                 }
494         }
495         return err
496 }
497
498 // msg is *Request or *Response.
499 func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
500         t := &transferReader{RequestMethod: "GET"}
501
502         // Unify input
503         isResponse := false
504         switch rr := msg.(type) {
505         case *Response:
506                 t.Header = rr.Header
507                 t.StatusCode = rr.StatusCode
508                 t.ProtoMajor = rr.ProtoMajor
509                 t.ProtoMinor = rr.ProtoMinor
510                 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
511                 isResponse = true
512                 if rr.Request != nil {
513                         t.RequestMethod = rr.Request.Method
514                 }
515         case *Request:
516                 t.Header = rr.Header
517                 t.RequestMethod = rr.Method
518                 t.ProtoMajor = rr.ProtoMajor
519                 t.ProtoMinor = rr.ProtoMinor
520                 // Transfer semantics for Requests are exactly like those for
521                 // Responses with status code 200, responding to a GET method
522                 t.StatusCode = 200
523                 t.Close = rr.Close
524         default:
525                 panic("unexpected type")
526         }
527
528         // Default to HTTP/1.1
529         if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
530                 t.ProtoMajor, t.ProtoMinor = 1, 1
531         }
532
533         // Transfer encoding, content length
534         err = t.fixTransferEncoding()
535         if err != nil {
536                 return err
537         }
538
539         realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
540         if err != nil {
541                 return err
542         }
543         if isResponse && t.RequestMethod == "HEAD" {
544                 if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
545                         return err
546                 } else {
547                         t.ContentLength = n
548                 }
549         } else {
550                 t.ContentLength = realLength
551         }
552
553         // Trailer
554         t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
555         if err != nil {
556                 return err
557         }
558
559         // If there is no Content-Length or chunked Transfer-Encoding on a *Response
560         // and the status is not 1xx, 204 or 304, then the body is unbounded.
561         // See RFC 7230, section 3.3.
562         switch msg.(type) {
563         case *Response:
564                 if realLength == -1 &&
565                         !chunked(t.TransferEncoding) &&
566                         bodyAllowedForStatus(t.StatusCode) {
567                         // Unbounded body.
568                         t.Close = true
569                 }
570         }
571
572         // Prepare body reader. ContentLength < 0 means chunked encoding
573         // or close connection when finished, since multipart is not supported yet
574         switch {
575         case chunked(t.TransferEncoding) || implicitlyChunked(t.TransferEncoding):
576                 if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
577                         t.Body = NoBody
578                 } else {
579                         t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
580                 }
581         case realLength == 0:
582                 t.Body = NoBody
583         case realLength > 0:
584                 t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
585         default:
586                 // realLength < 0, i.e. "Content-Length" not mentioned in header
587                 if t.Close {
588                         // Close semantics (i.e. HTTP/1.0)
589                         t.Body = &body{src: r, closing: t.Close}
590                 } else {
591                         // Persistent connection (i.e. HTTP/1.1)
592                         t.Body = NoBody
593                 }
594         }
595
596         // Finally if "gzip" was one of the requested transfer-encodings,
597         // we'll unzip the concatenated body/payload of the request.
598         // TODO: As we support more transfer-encodings, extract
599         // this code and apply the un-codings in reverse.
600         if t.Body != NoBody && gzipped(t.TransferEncoding) {
601                 zr, err := gzip.NewReader(t.Body)
602                 if err != nil {
603                         return fmt.Errorf("http: failed to gunzip body: %v", err)
604                 }
605                 t.Body = &proxyingReadCloser{
606                         Reader: zr,
607                         Closer: multiCloser{zr, t.Body},
608                 }
609         }
610
611         // Unify output
612         switch rr := msg.(type) {
613         case *Request:
614                 rr.Body = t.Body
615                 rr.ContentLength = t.ContentLength
616                 rr.TransferEncoding = t.TransferEncoding
617                 rr.Close = t.Close
618                 rr.Trailer = t.Trailer
619         case *Response:
620                 rr.Body = t.Body
621                 rr.ContentLength = t.ContentLength
622                 rr.TransferEncoding = t.TransferEncoding
623                 rr.Close = t.Close
624                 rr.Trailer = t.Trailer
625         }
626
627         return nil
628 }
629
630 // Checks whether chunked is the last part of the encodings stack
631 func chunked(te []string) bool { return len(te) > 0 && te[len(te)-1] == "chunked" }
632
633 // implicitlyChunked is a helper to check for implicity of chunked, because
634 // RFC 7230 Section 3.3.1 says that the sender MUST apply chunked as the final
635 // payload body to ensure that the message is framed for both the request
636 // and the body. Since "identity" is incompatabile with any other transformational
637 // encoding cannot co-exist, the presence of "identity" will cause implicitlyChunked
638 // to return false.
639 func implicitlyChunked(te []string) bool {
640         if len(te) == 0 { // No transfer-encodings passed in, so not implicity chunked.
641                 return false
642         }
643         for _, tei := range te {
644                 if tei == "identity" {
645                         return false
646                 }
647         }
648         return true
649 }
650
651 func isGzipTransferEncoding(tei string) bool {
652         // RFC 7230 4.2.3 requests that "x-gzip" SHOULD be considered the same as "gzip".
653         return tei == "gzip" || tei == "x-gzip"
654 }
655
656 // Checks where either of "gzip" or "x-gzip" are contained in transfer encodings.
657 func gzipped(te []string) bool {
658         for _, tei := range te {
659                 if isGzipTransferEncoding(tei) {
660                         return true
661                 }
662         }
663         return false
664 }
665
666 // Checks whether the encoding is explicitly "identity".
667 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
668
669 // unsupportedTEError reports unsupported transfer-encodings.
670 type unsupportedTEError struct {
671         err string
672 }
673
674 func (uste *unsupportedTEError) Error() string {
675         return uste.err
676 }
677
678 // isUnsupportedTEError checks if the error is of type
679 // unsupportedTEError. It is usually invoked with a non-nil err.
680 func isUnsupportedTEError(err error) bool {
681         _, ok := err.(*unsupportedTEError)
682         return ok
683 }
684
685 // fixTransferEncoding sanitizes t.TransferEncoding, if needed.
686 func (t *transferReader) fixTransferEncoding() error {
687         raw, present := t.Header["Transfer-Encoding"]
688         if !present {
689                 return nil
690         }
691         delete(t.Header, "Transfer-Encoding")
692
693         // Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
694         if !t.protoAtLeast(1, 1) {
695                 return nil
696         }
697
698         encodings := strings.Split(raw[0], ",")
699         te := make([]string, 0, len(encodings))
700
701         // When adding new encodings, please maintain the invariant:
702         //   if chunked encoding is present, it must always
703         //   come last and it must be applied only once.
704         // See RFC 7230 Section 3.3.1 Transfer-Encoding.
705         for i, encoding := range encodings {
706                 encoding = strings.ToLower(strings.TrimSpace(encoding))
707
708                 if encoding == "identity" {
709                         // "identity" should not be mixed with other transfer-encodings/compressions
710                         // because it means "no compression, no transformation".
711                         if len(encodings) != 1 {
712                                 return &badStringError{`"identity" when present must be the only transfer encoding`, strings.Join(encodings, ",")}
713                         }
714                         // "identity" is not recorded.
715                         break
716                 }
717
718                 switch {
719                 case encoding == "chunked":
720                         // "chunked" MUST ALWAYS be the last
721                         // encoding as per the  loop invariant.
722                         // That is:
723                         //     Invalid: [chunked, gzip]
724                         //     Valid:   [gzip, chunked]
725                         if i+1 != len(encodings) {
726                                 return &badStringError{"chunked must be applied only once, as the last encoding", strings.Join(encodings, ",")}
727                         }
728                         // Supported otherwise.
729
730                 case isGzipTransferEncoding(encoding):
731                         // Supported
732
733                 default:
734                         return &unsupportedTEError{fmt.Sprintf("unsupported transfer encoding: %q", encoding)}
735                 }
736
737                 te = te[0 : len(te)+1]
738                 te[len(te)-1] = encoding
739         }
740
741         if len(te) > 0 {
742                 // RFC 7230 3.3.2 says "A sender MUST NOT send a
743                 // Content-Length header field in any message that
744                 // contains a Transfer-Encoding header field."
745                 //
746                 // but also:
747                 // "If a message is received with both a
748                 // Transfer-Encoding and a Content-Length header
749                 // field, the Transfer-Encoding overrides the
750                 // Content-Length. Such a message might indicate an
751                 // attempt to perform request smuggling (Section 9.5)
752                 // or response splitting (Section 9.4) and ought to be
753                 // handled as an error. A sender MUST remove the
754                 // received Content-Length field prior to forwarding
755                 // such a message downstream."
756                 //
757                 // Reportedly, these appear in the wild.
758                 delete(t.Header, "Content-Length")
759                 t.TransferEncoding = te
760                 return nil
761         }
762
763         return nil
764 }
765
766 // Determine the expected body length, using RFC 7230 Section 3.3. This
767 // function is not a method, because ultimately it should be shared by
768 // ReadResponse and ReadRequest.
769 func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
770         isRequest := !isResponse
771         contentLens := header["Content-Length"]
772
773         // Hardening against HTTP request smuggling
774         if len(contentLens) > 1 {
775                 // Per RFC 7230 Section 3.3.2, prevent multiple
776                 // Content-Length headers if they differ in value.
777                 // If there are dups of the value, remove the dups.
778                 // See Issue 16490.
779                 first := strings.TrimSpace(contentLens[0])
780                 for _, ct := range contentLens[1:] {
781                         if first != strings.TrimSpace(ct) {
782                                 return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
783                         }
784                 }
785
786                 // deduplicate Content-Length
787                 header.Del("Content-Length")
788                 header.Add("Content-Length", first)
789
790                 contentLens = header["Content-Length"]
791         }
792
793         // Logic based on response type or status
794         if noResponseBodyExpected(requestMethod) {
795                 // For HTTP requests, as part of hardening against request
796                 // smuggling (RFC 7230), don't allow a Content-Length header for
797                 // methods which don't permit bodies. As an exception, allow
798                 // exactly one Content-Length header if its value is "0".
799                 if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
800                         return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
801                 }
802                 return 0, nil
803         }
804         if status/100 == 1 {
805                 return 0, nil
806         }
807         switch status {
808         case 204, 304:
809                 return 0, nil
810         }
811
812         // Logic based on Transfer-Encoding
813         if chunked(te) {
814                 return -1, nil
815         }
816
817         // Logic based on Content-Length
818         var cl string
819         if len(contentLens) == 1 {
820                 cl = strings.TrimSpace(contentLens[0])
821         }
822         if cl != "" {
823                 n, err := parseContentLength(cl)
824                 if err != nil {
825                         return -1, err
826                 }
827                 return n, nil
828         }
829         header.Del("Content-Length")
830
831         if isRequest {
832                 // RFC 7230 neither explicitly permits nor forbids an
833                 // entity-body on a GET request so we permit one if
834                 // declared, but we default to 0 here (not -1 below)
835                 // if there's no mention of a body.
836                 // Likewise, all other request methods are assumed to have
837                 // no body if neither Transfer-Encoding chunked nor a
838                 // Content-Length are set.
839                 return 0, nil
840         }
841
842         // Body-EOF logic based on other methods (like closing, or chunked coding)
843         return -1, nil
844 }
845
846 // Determine whether to hang up after sending a request and body, or
847 // receiving a response and body
848 // 'header' is the request headers
849 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
850         if major < 1 {
851                 return true
852         }
853
854         conv := header["Connection"]
855         hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
856         if major == 1 && minor == 0 {
857                 return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
858         }
859
860         if hasClose && removeCloseHeader {
861                 header.Del("Connection")
862         }
863
864         return hasClose
865 }
866
867 // Parse the trailer header
868 func fixTrailer(header Header, te []string) (Header, error) {
869         vv, ok := header["Trailer"]
870         if !ok {
871                 return nil, nil
872         }
873         if !chunked(te) {
874                 // Trailer and no chunking:
875                 // this is an invalid use case for trailer header.
876                 // Nevertheless, no error will be returned and we
877                 // let users decide if this is a valid HTTP message.
878                 // The Trailer header will be kept in Response.Header
879                 // but not populate Response.Trailer.
880                 // See issue #27197.
881                 return nil, nil
882         }
883         header.Del("Trailer")
884
885         trailer := make(Header)
886         var err error
887         for _, v := range vv {
888                 foreachHeaderElement(v, func(key string) {
889                         key = CanonicalHeaderKey(key)
890                         switch key {
891                         case "Transfer-Encoding", "Trailer", "Content-Length":
892                                 if err == nil {
893                                         err = &badStringError{"bad trailer key", key}
894                                         return
895                                 }
896                         }
897                         trailer[key] = nil
898                 })
899         }
900         if err != nil {
901                 return nil, err
902         }
903         if len(trailer) == 0 {
904                 return nil, nil
905         }
906         return trailer, nil
907 }
908
909 // body turns a Reader into a ReadCloser.
910 // Close ensures that the body has been fully read
911 // and then reads the trailer if necessary.
912 type body struct {
913         src          io.Reader
914         hdr          interface{}   // non-nil (Response or Request) value means read trailer
915         r            *bufio.Reader // underlying wire-format reader for the trailer
916         closing      bool          // is the connection to be closed after reading body?
917         doEarlyClose bool          // whether Close should stop early
918
919         mu         sync.Mutex // guards following, and calls to Read and Close
920         sawEOF     bool
921         closed     bool
922         earlyClose bool   // Close called and we didn't read to the end of src
923         onHitEOF   func() // if non-nil, func to call when EOF is Read
924 }
925
926 // ErrBodyReadAfterClose is returned when reading a Request or Response
927 // Body after the body has been closed. This typically happens when the body is
928 // read after an HTTP Handler calls WriteHeader or Write on its
929 // ResponseWriter.
930 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
931
932 func (b *body) Read(p []byte) (n int, err error) {
933         b.mu.Lock()
934         defer b.mu.Unlock()
935         if b.closed {
936                 return 0, ErrBodyReadAfterClose
937         }
938         return b.readLocked(p)
939 }
940
941 // Must hold b.mu.
942 func (b *body) readLocked(p []byte) (n int, err error) {
943         if b.sawEOF {
944                 return 0, io.EOF
945         }
946         n, err = b.src.Read(p)
947
948         if err == io.EOF {
949                 b.sawEOF = true
950                 // Chunked case. Read the trailer.
951                 if b.hdr != nil {
952                         if e := b.readTrailer(); e != nil {
953                                 err = e
954                                 // Something went wrong in the trailer, we must not allow any
955                                 // further reads of any kind to succeed from body, nor any
956                                 // subsequent requests on the server connection. See
957                                 // golang.org/issue/12027
958                                 b.sawEOF = false
959                                 b.closed = true
960                         }
961                         b.hdr = nil
962                 } else {
963                         // If the server declared the Content-Length, our body is a LimitedReader
964                         // and we need to check whether this EOF arrived early.
965                         if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
966                                 err = io.ErrUnexpectedEOF
967                         }
968                 }
969         }
970
971         // If we can return an EOF here along with the read data, do
972         // so. This is optional per the io.Reader contract, but doing
973         // so helps the HTTP transport code recycle its connection
974         // earlier (since it will see this EOF itself), even if the
975         // client doesn't do future reads or Close.
976         if err == nil && n > 0 {
977                 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
978                         err = io.EOF
979                         b.sawEOF = true
980                 }
981         }
982
983         if b.sawEOF && b.onHitEOF != nil {
984                 b.onHitEOF()
985         }
986
987         return n, err
988 }
989
990 var (
991         singleCRLF = []byte("\r\n")
992         doubleCRLF = []byte("\r\n\r\n")
993 )
994
995 func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
996         for peekSize := 4; ; peekSize++ {
997                 // This loop stops when Peek returns an error,
998                 // which it does when r's buffer has been filled.
999                 buf, err := r.Peek(peekSize)
1000                 if bytes.HasSuffix(buf, doubleCRLF) {
1001                         return true
1002                 }
1003                 if err != nil {
1004                         break
1005                 }
1006         }
1007         return false
1008 }
1009
1010 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
1011
1012 func (b *body) readTrailer() error {
1013         // The common case, since nobody uses trailers.
1014         buf, err := b.r.Peek(2)
1015         if bytes.Equal(buf, singleCRLF) {
1016                 b.r.Discard(2)
1017                 return nil
1018         }
1019         if len(buf) < 2 {
1020                 return errTrailerEOF
1021         }
1022         if err != nil {
1023                 return err
1024         }
1025
1026         // Make sure there's a header terminator coming up, to prevent
1027         // a DoS with an unbounded size Trailer. It's not easy to
1028         // slip in a LimitReader here, as textproto.NewReader requires
1029         // a concrete *bufio.Reader. Also, we can't get all the way
1030         // back up to our conn's LimitedReader that *might* be backing
1031         // this bufio.Reader. Instead, a hack: we iteratively Peek up
1032         // to the bufio.Reader's max size, looking for a double CRLF.
1033         // This limits the trailer to the underlying buffer size, typically 4kB.
1034         if !seeUpcomingDoubleCRLF(b.r) {
1035                 return errors.New("http: suspiciously long trailer after chunked body")
1036         }
1037
1038         hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
1039         if err != nil {
1040                 if err == io.EOF {
1041                         return errTrailerEOF
1042                 }
1043                 return err
1044         }
1045         switch rr := b.hdr.(type) {
1046         case *Request:
1047                 mergeSetHeader(&rr.Trailer, Header(hdr))
1048         case *Response:
1049                 mergeSetHeader(&rr.Trailer, Header(hdr))
1050         }
1051         return nil
1052 }
1053
1054 func mergeSetHeader(dst *Header, src Header) {
1055         if *dst == nil {
1056                 *dst = src
1057                 return
1058         }
1059         for k, vv := range src {
1060                 (*dst)[k] = vv
1061         }
1062 }
1063
1064 // unreadDataSizeLocked returns the number of bytes of unread input.
1065 // It returns -1 if unknown.
1066 // b.mu must be held.
1067 func (b *body) unreadDataSizeLocked() int64 {
1068         if lr, ok := b.src.(*io.LimitedReader); ok {
1069                 return lr.N
1070         }
1071         return -1
1072 }
1073
1074 func (b *body) Close() error {
1075         b.mu.Lock()
1076         defer b.mu.Unlock()
1077         if b.closed {
1078                 return nil
1079         }
1080         var err error
1081         switch {
1082         case b.sawEOF:
1083                 // Already saw EOF, so no need going to look for it.
1084         case b.hdr == nil && b.closing:
1085                 // no trailer and closing the connection next.
1086                 // no point in reading to EOF.
1087         case b.doEarlyClose:
1088                 // Read up to maxPostHandlerReadBytes bytes of the body, looking
1089                 // for EOF (and trailers), so we can re-use this connection.
1090                 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
1091                         // There was a declared Content-Length, and we have more bytes remaining
1092                         // than our maxPostHandlerReadBytes tolerance. So, give up.
1093                         b.earlyClose = true
1094                 } else {
1095                         var n int64
1096                         // Consume the body, or, which will also lead to us reading
1097                         // the trailer headers after the body, if present.
1098                         n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
1099                         if err == io.EOF {
1100                                 err = nil
1101                         }
1102                         if n == maxPostHandlerReadBytes {
1103                                 b.earlyClose = true
1104                         }
1105                 }
1106         default:
1107                 // Fully consume the body, which will also lead to us reading
1108                 // the trailer headers after the body, if present.
1109                 _, err = io.Copy(ioutil.Discard, bodyLocked{b})
1110         }
1111         b.closed = true
1112         return err
1113 }
1114
1115 func (b *body) didEarlyClose() bool {
1116         b.mu.Lock()
1117         defer b.mu.Unlock()
1118         return b.earlyClose
1119 }
1120
1121 // bodyRemains reports whether future Read calls might
1122 // yield data.
1123 func (b *body) bodyRemains() bool {
1124         b.mu.Lock()
1125         defer b.mu.Unlock()
1126         return !b.sawEOF
1127 }
1128
1129 func (b *body) registerOnHitEOF(fn func()) {
1130         b.mu.Lock()
1131         defer b.mu.Unlock()
1132         b.onHitEOF = fn
1133 }
1134
1135 // bodyLocked is a io.Reader reading from a *body when its mutex is
1136 // already held.
1137 type bodyLocked struct {
1138         b *body
1139 }
1140
1141 func (bl bodyLocked) Read(p []byte) (n int, err error) {
1142         if bl.b.closed {
1143                 return 0, ErrBodyReadAfterClose
1144         }
1145         return bl.b.readLocked(p)
1146 }
1147
1148 // parseContentLength trims whitespace from s and returns -1 if no value
1149 // is set, or the value if it's >= 0.
1150 func parseContentLength(cl string) (int64, error) {
1151         cl = strings.TrimSpace(cl)
1152         if cl == "" {
1153                 return -1, nil
1154         }
1155         n, err := strconv.ParseInt(cl, 10, 64)
1156         if err != nil || n < 0 {
1157                 return 0, &badStringError{"bad Content-Length", cl}
1158         }
1159         return n, nil
1160
1161 }
1162
1163 // finishAsyncByteRead finishes reading the 1-byte sniff
1164 // from the ContentLength==0, Body!=nil case.
1165 type finishAsyncByteRead struct {
1166         tw *transferWriter
1167 }
1168
1169 func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1170         if len(p) == 0 {
1171                 return
1172         }
1173         rres := <-fr.tw.ByteReadCh
1174         n, err = rres.n, rres.err
1175         if n == 1 {
1176                 p[0] = rres.b
1177         }
1178         return
1179 }
1180
1181 var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))
1182
1183 // isKnownInMemoryReader reports whether r is a type known to not
1184 // block on Read. Its caller uses this as an optional optimization to
1185 // send fewer TCP packets.
1186 func isKnownInMemoryReader(r io.Reader) bool {
1187         switch r.(type) {
1188         case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1189                 return true
1190         }
1191         if reflect.TypeOf(r) == nopCloserType {
1192                 return isKnownInMemoryReader(reflect.ValueOf(r).Field(0).Interface().(io.Reader))
1193         }
1194         return false
1195 }
1196
1197 // bufioFlushWriter is an io.Writer wrapper that flushes all writes
1198 // on its wrapped writer if it's a *bufio.Writer.
1199 type bufioFlushWriter struct{ w io.Writer }
1200
1201 func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
1202         n, err = fw.w.Write(p)
1203         if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
1204                 ferr := bw.Flush()
1205                 if ferr != nil && err == nil {
1206                         err = ferr
1207                 }
1208         }
1209         return
1210 }