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.
23
"golang.org/x/net/http/httpguts"
25
"github.com/Lookyan/netramesh/pkg/http/internal"
28
// ADDED BUFFER POOL (NOT STD LIB)
29
var bufferPool = sync.Pool{
30
New: func() interface{} { return make([]byte, 0xffff) },
33
/////////////////////////////////
35
// ErrLineTooLong is returned when reading request or response bodies
36
// with malformed chunked encoding.
37
var ErrLineTooLong = internal.ErrLineTooLong
39
type errorReader struct {
43
func (r errorReader) Read(p []byte) (n int, err error) {
47
type byteReader struct {
52
func (br *byteReader) Read(p []byte) (n int, err error) {
64
// transferBodyReader is an io.Reader that reads from tw.Body
65
// and records any non-EOF error in tw.bodyReadError.
66
// It is exactly 1 pointer wide to avoid allocations into interfaces.
67
type transferBodyReader struct{ tw *transferWriter }
69
func (br transferBodyReader) Read(p []byte) (n int, err error) {
70
n, err = br.tw.Body.Read(p)
71
if err != nil && err != io.EOF {
72
br.tw.bodyReadError = err
77
// transferWriter inspects the fields of a user-supplied Request or Response,
78
// sanitizes them without changing the user object and provides methods for
79
// writing the respective header, body and trailer in wire format.
80
type transferWriter struct {
85
ContentLength int64 // -1 means unknown, 0 means exactly none
87
TransferEncoding []string
91
bodyReadError error // any non-EOF error from reading Body
93
FlushHeaders bool // flush headers to network before body
94
ByteReadCh chan readResult // non-nil if probeRequestBody called
97
func newTransferWriter(r interface{}) (t *transferWriter, err error) {
100
// Extract relevant fields
101
atLeastHTTP11 := false
102
switch rr := r.(type) {
104
if rr.ContentLength != 0 && rr.Body == nil {
105
return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
107
t.Method = valueOrDefault(rr.Method, "GET")
109
t.TransferEncoding = rr.TransferEncoding
111
t.Trailer = rr.Trailer
113
t.BodyCloser = rr.Body
114
t.ContentLength = rr.outgoingLength()
115
if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
116
t.TransferEncoding = []string{"chunked"}
118
// If there's a body, conservatively flush the headers
119
// to any bufio.Writer we're writing to, just in case
120
// the server needs the headers early, before we copy
121
// the body and possibly block. We make an exception
122
// for the common standard library in-memory types,
123
// though, to avoid unnecessary TCP packets on the
124
// wire. (Issue 22088.)
125
if t.ContentLength != 0 && !isKnownInMemoryReader(t.Body) {
126
t.FlushHeaders = true
129
atLeastHTTP11 = true // Transport requests are always 1.1 or 2.0
132
if rr.Request != nil {
133
t.Method = rr.Request.Method
136
t.BodyCloser = rr.Body
137
t.ContentLength = rr.ContentLength
139
t.TransferEncoding = rr.TransferEncoding
141
t.Trailer = rr.Trailer
142
atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
143
t.ResponseToHEAD = noResponseBodyExpected(t.Method)
146
// Sanitize Body,ContentLength,TransferEncoding
147
if t.ResponseToHEAD {
149
if chunked(t.TransferEncoding) {
153
if !atLeastHTTP11 || t.Body == nil {
154
t.TransferEncoding = nil
156
if chunked(t.TransferEncoding) {
158
} else if t.Body == nil { // no chunking, no body
164
if !chunked(t.TransferEncoding) {
171
// shouldSendChunkedRequestBody reports whether we should try to send a
172
// chunked request body to the server. In particular, the case we really
173
// want to prevent is sending a GET or other typically-bodyless request to a
174
// server with a chunked body when the body has zero bytes, since GETs with
175
// bodies (while acceptable according to specs), even zero-byte chunked
176
// bodies, are approximately never seen in the wild and confuse most
177
// servers. See Issue 18257, as one example.
179
// The only reason we'd send such a request is if the user set the Body to a
180
// non-nil value (say, ioutil.NopCloser(bytes.NewReader(nil))) and didn't
181
// set ContentLength, or NewRequest set it to -1 (unknown), so then we assume
182
// there's bytes to send.
184
// This code tries to read a byte from the Request.Body in such cases to see
185
// whether the body actually has content (super rare) or is actually just
186
// a non-nil content-less ReadCloser (the more common case). In that more
187
// common case, we act as if their Body were nil instead, and don't send
189
func (t *transferWriter) shouldSendChunkedRequestBody() bool {
190
// Note that t.ContentLength is the corrected content length
191
// from rr.outgoingLength, so 0 actually means zero, not unknown.
192
if t.ContentLength >= 0 || t.Body == nil { // redundant checks; caller did them
195
if requestMethodUsuallyLacksBody(t.Method) {
196
// Only probe the Request.Body for GET/HEAD/DELETE/etc
197
// requests, because it's only those types of requests
198
// that confuse servers.
199
t.probeRequestBody() // adjusts t.Body, t.ContentLength
202
// For all other request types (PUT, POST, PATCH, or anything
203
// made-up we've never heard of), assume it's normal and the server
204
// can deal with a chunked request body. Maybe we'll adjust this
209
// probeRequestBody reads a byte from t.Body to see whether it's empty
210
// (returns io.EOF right away).
212
// But because we've had problems with this blocking users in the past
213
// (issue 17480) when the body is a pipe (perhaps waiting on the response
214
// headers before the pipe is fed data), we need to be careful and bound how
215
// long we wait for it. This delay will only affect users if all the following
217
// * the request body blocks
218
// * the content length is not set (or set to -1)
219
// * the method doesn't usually have a body (GET, HEAD, DELETE, ...)
220
// * there is no transfer-encoding=chunked already set.
221
// In other words, this delay will not normally affect anybody, and there
222
// are workarounds if it does.
223
func (t *transferWriter) probeRequestBody() {
224
t.ByteReadCh = make(chan readResult, 1)
225
go func(body io.Reader) {
228
rres.n, rres.err = body.Read(buf[:])
234
timer := time.NewTimer(200 * time.Millisecond)
236
case rres := <-t.ByteReadCh:
238
if rres.n == 0 && rres.err == io.EOF {
242
} else if rres.n == 1 {
244
t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
246
t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
248
} else if rres.err != nil {
249
t.Body = errorReader{rres.err}
252
// Too slow. Don't wait. Read it later, and keep
253
// assuming that this is ContentLength == -1
254
// (unknown), which means we'll send a
255
// "Transfer-Encoding: chunked" header.
256
t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
257
// Request that Request.Write flush the headers to the
258
// network before writing the body, since our body may not
259
// become readable until it's seen the response headers.
260
t.FlushHeaders = true
264
func noResponseBodyExpected(requestMethod string) bool {
265
return requestMethod == "HEAD"
268
func (t *transferWriter) shouldSendContentLength() bool {
269
if chunked(t.TransferEncoding) {
272
if t.ContentLength > 0 {
275
if t.ContentLength < 0 {
278
// Many servers expect a Content-Length for these methods
279
if t.Method == "POST" || t.Method == "PUT" {
282
if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
283
if t.Method == "GET" || t.Method == "HEAD" {
292
func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error {
293
if t.Close && !hasToken(t.Header.get("Connection"), "close") {
294
if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
297
if trace != nil && trace.WroteHeaderField != nil {
298
trace.WroteHeaderField("Connection", []string{"close"})
302
// Write Content-Length and/or Transfer-Encoding whose values are a
303
// function of the sanitized field triple (Body, ContentLength,
305
if t.shouldSendContentLength() {
306
if _, err := io.WriteString(w, "Content-Length: "); err != nil {
309
if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
312
if trace != nil && trace.WroteHeaderField != nil {
313
trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
315
} else if chunked(t.TransferEncoding) {
316
if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
319
if trace != nil && trace.WroteHeaderField != nil {
320
trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
324
// Write Trailer header
325
if t.Trailer != nil {
326
keys := make([]string, 0, len(t.Trailer))
327
for k := range t.Trailer {
328
k = CanonicalHeaderKey(k)
330
case "Transfer-Encoding", "Trailer", "Content-Length":
331
return &badStringError{"invalid Trailer key", k}
333
keys = append(keys, k)
337
// TODO: could do better allocation-wise here, but trailers are rare,
338
// so being lazy for now.
339
if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
342
if trace != nil && trace.WroteHeaderField != nil {
343
trace.WroteHeaderField("Trailer", keys)
351
func (t *transferWriter) writeBody(w io.Writer) error {
357
var body = transferBodyReader{t}
358
if chunked(t.TransferEncoding) {
359
if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
360
w = &internal.FlushAfterChunkWriter{Writer: bw}
362
cw := internal.NewChunkedWriter(w)
363
buf := bufferPool.Get().([]byte)
364
_, err = io.CopyBuffer(cw, body, buf)
369
} else if t.ContentLength == -1 {
370
buf := bufferPool.Get().([]byte)
371
ncopy, err = io.CopyBuffer(w, body, buf)
374
buf := bufferPool.Get().([]byte)
375
ncopy, err = io.CopyBuffer(w, io.LimitReader(body, t.ContentLength), buf)
381
buf = bufferPool.Get().([]byte)
382
nextra, err = io.CopyBuffer(ioutil.Discard, body, buf)
390
if t.BodyCloser != nil {
391
if err := t.BodyCloser.Close(); err != nil {
396
if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
397
return fmt.Errorf("http: ContentLength=%d with Body length %d",
398
t.ContentLength, ncopy)
401
if chunked(t.TransferEncoding) {
402
// Write Trailer header
403
if t.Trailer != nil {
404
if err := t.Trailer.Write(w); err != nil {
408
// Last chunk, empty trailer
409
_, err = io.WriteString(w, "\r\n")
414
type transferReader struct {
424
TransferEncoding []string
429
func (t *transferReader) protoAtLeast(m, n int) bool {
430
return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
433
// bodyAllowedForStatus reports whether a given response status code
434
// permits a body. See RFC 7230, section 3.3.
435
func bodyAllowedForStatus(status int) bool {
437
case status >= 100 && status <= 199:
448
suppressedHeaders304 = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
449
suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
452
func suppressedHeaders(status int) []string {
455
// RFC 7232 section 4.1
456
return suppressedHeaders304
457
case !bodyAllowedForStatus(status):
458
return suppressedHeadersNoBody
463
// msg is *Request or *Response.
464
func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
465
t := &transferReader{RequestMethod: "GET"}
469
switch rr := msg.(type) {
472
t.StatusCode = rr.StatusCode
473
t.ProtoMajor = rr.ProtoMajor
474
t.ProtoMinor = rr.ProtoMinor
475
t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
477
if rr.Request != nil {
478
t.RequestMethod = rr.Request.Method
482
t.RequestMethod = rr.Method
483
t.ProtoMajor = rr.ProtoMajor
484
t.ProtoMinor = rr.ProtoMinor
485
// Transfer semantics for Requests are exactly like those for
486
// Responses with status code 200, responding to a GET method
490
panic("unexpected type")
493
// Default to HTTP/1.1
494
if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
495
t.ProtoMajor, t.ProtoMinor = 1, 1
498
// Transfer encoding, content length
499
err = t.fixTransferEncoding()
504
realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
508
if isResponse && t.RequestMethod == "HEAD" {
509
if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
515
t.ContentLength = realLength
519
t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
524
// If there is no Content-Length or chunked Transfer-Encoding on a *Response
525
// and the status is not 1xx, 204 or 304, then the body is unbounded.
526
// See RFC 7230, section 3.3.
529
if realLength == -1 &&
530
!chunked(t.TransferEncoding) &&
531
bodyAllowedForStatus(t.StatusCode) {
537
// Prepare body reader. ContentLength < 0 means chunked encoding
538
// or close connection when finished, since multipart is not supported yet
540
case chunked(t.TransferEncoding):
541
if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
544
t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
546
case realLength == 0:
549
t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
551
// realLength < 0, i.e. "Content-Length" not mentioned in header
553
// Close semantics (i.e. HTTP/1.0)
554
t.Body = &body{src: r, closing: t.Close}
556
// Persistent connection (i.e. HTTP/1.1)
562
switch rr := msg.(type) {
565
rr.ContentLength = t.ContentLength
566
rr.TransferEncoding = t.TransferEncoding
568
rr.Trailer = t.Trailer
571
rr.ContentLength = t.ContentLength
572
rr.TransferEncoding = t.TransferEncoding
574
rr.Trailer = t.Trailer
580
// Checks whether chunked is part of the encodings stack
581
func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
583
// Checks whether the encoding is explicitly "identity".
584
func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
586
// fixTransferEncoding sanitizes t.TransferEncoding, if needed.
587
func (t *transferReader) fixTransferEncoding() error {
588
raw, present := t.Header["Transfer-Encoding"]
592
delete(t.Header, "Transfer-Encoding")
594
// Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
595
if !t.protoAtLeast(1, 1) {
599
encodings := strings.Split(raw[0], ",")
600
te := make([]string, 0, len(encodings))
601
// TODO: Even though we only support "identity" and "chunked"
602
// encodings, the loop below is designed with foresight. One
603
// invariant that must be maintained is that, if present,
604
// chunked encoding must always come first.
605
for _, encoding := range encodings {
606
encoding = strings.ToLower(strings.TrimSpace(encoding))
607
// "identity" encoding is not recorded
608
if encoding == "identity" {
611
if encoding != "chunked" {
612
return &badStringError{"unsupported transfer encoding", encoding}
614
te = te[0 : len(te)+1]
615
te[len(te)-1] = encoding
618
return &badStringError{"too many transfer encodings", strings.Join(te, ",")}
621
// RFC 7230 3.3.2 says "A sender MUST NOT send a
622
// Content-Length header field in any message that
623
// contains a Transfer-Encoding header field."
626
// "If a message is received with both a
627
// Transfer-Encoding and a Content-Length header
628
// field, the Transfer-Encoding overrides the
629
// Content-Length. Such a message might indicate an
630
// attempt to perform request smuggling (Section 9.5)
631
// or response splitting (Section 9.4) and ought to be
632
// handled as an error. A sender MUST remove the
633
// received Content-Length field prior to forwarding
634
// such a message downstream."
636
// Reportedly, these appear in the wild.
637
delete(t.Header, "Content-Length")
638
t.TransferEncoding = te
645
// Determine the expected body length, using RFC 7230 Section 3.3. This
646
// function is not a method, because ultimately it should be shared by
647
// ReadResponse and ReadRequest.
648
func fixLength(isResponse bool, status int, requestMethod string, header Header, te []string) (int64, error) {
649
isRequest := !isResponse
650
contentLens := header["Content-Length"]
652
// Hardening against HTTP request smuggling
653
if len(contentLens) > 1 {
654
// Per RFC 7230 Section 3.3.2, prevent multiple
655
// Content-Length headers if they differ in value.
656
// If there are dups of the value, remove the dups.
658
first := strings.TrimSpace(contentLens[0])
659
for _, ct := range contentLens[1:] {
660
if first != strings.TrimSpace(ct) {
661
return 0, fmt.Errorf("http: message cannot contain multiple Content-Length headers; got %q", contentLens)
665
// deduplicate Content-Length
666
header.Del("Content-Length")
667
header.Add("Content-Length", first)
669
contentLens = header["Content-Length"]
672
// Logic based on response type or status
673
if noResponseBodyExpected(requestMethod) {
674
// For HTTP requests, as part of hardening against request
675
// smuggling (RFC 7230), don't allow a Content-Length header for
676
// methods which don't permit bodies. As an exception, allow
677
// exactly one Content-Length header if its value is "0".
678
if isRequest && len(contentLens) > 0 && !(len(contentLens) == 1 && contentLens[0] == "0") {
679
return 0, fmt.Errorf("http: method cannot contain a Content-Length; got %q", contentLens)
691
// Logic based on Transfer-Encoding
696
// Logic based on Content-Length
698
if len(contentLens) == 1 {
699
cl = strings.TrimSpace(contentLens[0])
702
n, err := parseContentLength(cl)
708
header.Del("Content-Length")
711
// RFC 7230 neither explicitly permits nor forbids an
712
// entity-body on a GET request so we permit one if
713
// declared, but we default to 0 here (not -1 below)
714
// if there's no mention of a body.
715
// Likewise, all other request methods are assumed to have
716
// no body if neither Transfer-Encoding chunked nor a
717
// Content-Length are set.
721
// Body-EOF logic based on other methods (like closing, or chunked coding)
725
// Determine whether to hang up after sending a request and body, or
726
// receiving a response and body
727
// 'header' is the request headers
728
func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
733
conv := header["Connection"]
734
hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
735
if major == 1 && minor == 0 {
736
return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
739
if hasClose && removeCloseHeader {
740
header.Del("Connection")
746
// Parse the trailer header
747
func fixTrailer(header Header, te []string) (Header, error) {
748
vv, ok := header["Trailer"]
752
header.Del("Trailer")
754
trailer := make(Header)
756
for _, v := range vv {
757
foreachHeaderElement(v, func(key string) {
758
key = CanonicalHeaderKey(key)
760
case "Transfer-Encoding", "Trailer", "Content-Length":
762
err = &badStringError{"bad trailer key", key}
772
if len(trailer) == 0 {
776
// Trailer and no chunking
777
return nil, ErrUnexpectedTrailer
782
// body turns a Reader into a ReadCloser.
783
// Close ensures that the body has been fully read
784
// and then reads the trailer if necessary.
787
hdr interface{} // non-nil (Response or Request) value means read trailer
788
r *bufio.Reader // underlying wire-format reader for the trailer
789
closing bool // is the connection to be closed after reading body?
790
doEarlyClose bool // whether Close should stop early
792
mu sync.Mutex // guards following, and calls to Read and Close
795
earlyClose bool // Close called and we didn't read to the end of src
796
onHitEOF func() // if non-nil, func to call when EOF is Read
799
// ErrBodyReadAfterClose is returned when reading a Request or Response
800
// Body after the body has been closed. This typically happens when the body is
801
// read after an HTTP Handler calls WriteHeader or Write on its
803
var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
805
func (b *body) Read(p []byte) (n int, err error) {
809
return 0, ErrBodyReadAfterClose
811
return b.readLocked(p)
815
func (b *body) readLocked(p []byte) (n int, err error) {
819
n, err = b.src.Read(p)
823
// Chunked case. Read the trailer.
825
if e := b.readTrailer(); e != nil {
827
// Something went wrong in the trailer, we must not allow any
828
// further reads of any kind to succeed from body, nor any
829
// subsequent requests on the server connection. See
830
// golang.org/issue/12027
836
// If the server declared the Content-Length, our body is a LimitedReader
837
// and we need to check whether this EOF arrived early.
838
if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
839
err = io.ErrUnexpectedEOF
844
// If we can return an EOF here along with the read data, do
845
// so. This is optional per the io.Reader contract, but doing
846
// so helps the HTTP transport code recycle its connection
847
// earlier (since it will see this EOF itself), even if the
848
// client doesn't do future reads or Close.
849
if err == nil && n > 0 {
850
if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
856
if b.sawEOF && b.onHitEOF != nil {
864
singleCRLF = []byte("\r\n")
865
doubleCRLF = []byte("\r\n\r\n")
868
func seeUpcomingDoubleCRLF(r *bufio.Reader) bool {
869
for peekSize := 4; ; peekSize++ {
870
// This loop stops when Peek returns an error,
871
// which it does when r's buffer has been filled.
872
buf, err := r.Peek(peekSize)
873
if bytes.HasSuffix(buf, doubleCRLF) {
883
var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
885
func (b *body) readTrailer() error {
886
// The common case, since nobody uses trailers.
887
buf, err := b.r.Peek(2)
888
if bytes.Equal(buf, singleCRLF) {
899
// Make sure there's a header terminator coming up, to prevent
900
// a DoS with an unbounded size Trailer. It's not easy to
901
// slip in a LimitReader here, as textproto.NewReader requires
902
// a concrete *bufio.Reader. Also, we can't get all the way
903
// back up to our conn's LimitedReader that *might* be backing
904
// this bufio.Reader. Instead, a hack: we iteratively Peek up
905
// to the bufio.Reader's max size, looking for a double CRLF.
906
// This limits the trailer to the underlying buffer size, typically 4kB.
907
if !seeUpcomingDoubleCRLF(b.r) {
908
return errors.New("http: suspiciously long trailer after chunked body")
911
hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
918
switch rr := b.hdr.(type) {
920
mergeSetHeader(&rr.Trailer, Header(hdr))
922
mergeSetHeader(&rr.Trailer, Header(hdr))
927
func mergeSetHeader(dst *Header, src Header) {
932
for k, vv := range src {
937
// unreadDataSizeLocked returns the number of bytes of unread input.
938
// It returns -1 if unknown.
940
func (b *body) unreadDataSizeLocked() int64 {
941
if lr, ok := b.src.(*io.LimitedReader); ok {
947
func (b *body) Close() error {
956
// Already saw EOF, so no need going to look for it.
957
case b.hdr == nil && b.closing:
958
// no trailer and closing the connection next.
959
// no point in reading to EOF.
961
// Read up to maxPostHandlerReadBytes bytes of the body, looking for
962
// for EOF (and trailers), so we can re-use this connection.
963
if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
964
// There was a declared Content-Length, and we have more bytes remaining
965
// than our maxPostHandlerReadBytes tolerance. So, give up.
969
// Consume the body, or, which will also lead to us reading
970
// the trailer headers after the body, if present.
971
n, err = io.CopyN(ioutil.Discard, bodyLocked{b}, maxPostHandlerReadBytes)
975
if n == maxPostHandlerReadBytes {
980
// Fully consume the body, which will also lead to us reading
981
// the trailer headers after the body, if present.
982
_, err = io.Copy(ioutil.Discard, bodyLocked{b})
988
func (b *body) didEarlyClose() bool {
994
// bodyRemains reports whether future Read calls might
996
func (b *body) bodyRemains() bool {
1002
func (b *body) registerOnHitEOF(fn func()) {
1008
// bodyLocked is a io.Reader reading from a *body when its mutex is
1010
type bodyLocked struct {
1014
func (bl bodyLocked) Read(p []byte) (n int, err error) {
1016
return 0, ErrBodyReadAfterClose
1018
return bl.b.readLocked(p)
1021
// parseContentLength trims whitespace from s and returns -1 if no value
1022
// is set, or the value if it's >= 0.
1023
func parseContentLength(cl string) (int64, error) {
1024
cl = strings.TrimSpace(cl)
1028
n, err := strconv.ParseInt(cl, 10, 64)
1029
if err != nil || n < 0 {
1030
return 0, &badStringError{"bad Content-Length", cl}
1036
// finishAsyncByteRead finishes reading the 1-byte sniff
1037
// from the ContentLength==0, Body!=nil case.
1038
type finishAsyncByteRead struct {
1042
func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1046
rres := <-fr.tw.ByteReadCh
1047
n, err = rres.n, rres.err
1054
var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))
1056
// isKnownInMemoryReader reports whether r is a type known to not
1057
// block on Read. Its caller uses this as an optional optimization to
1058
// send fewer TCP packets.
1059
func isKnownInMemoryReader(r io.Reader) bool {
1061
case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1064
if reflect.TypeOf(r) == nopCloserType {
1065
return isKnownInMemoryReader(reflect.ValueOf(r).Field(0).Interface().(io.Reader))