netramesh

Форк
0
/
transfer.go 
1068 строк · 29.0 Кб
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/httptrace"
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
	"github.com/Lookyan/netramesh/pkg/http/internal"
26
)
27

28
// ADDED BUFFER POOL (NOT STD LIB)
29
var bufferPool = sync.Pool{
30
	New: func() interface{} { return make([]byte, 0xffff) },
31
}
32

33
/////////////////////////////////
34

35
// ErrLineTooLong is returned when reading request or response bodies
36
// with malformed chunked encoding.
37
var ErrLineTooLong = internal.ErrLineTooLong
38

39
type errorReader struct {
40
	err error
41
}
42

43
func (r errorReader) Read(p []byte) (n int, err error) {
44
	return 0, r.err
45
}
46

47
type byteReader struct {
48
	b    byte
49
	done bool
50
}
51

52
func (br *byteReader) Read(p []byte) (n int, err error) {
53
	if br.done {
54
		return 0, io.EOF
55
	}
56
	if len(p) == 0 {
57
		return 0, nil
58
	}
59
	br.done = true
60
	p[0] = br.b
61
	return 1, io.EOF
62
}
63

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 }
68

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
73
	}
74
	return
75
}
76

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 {
81
	Method           string
82
	Body             io.Reader
83
	BodyCloser       io.Closer
84
	ResponseToHEAD   bool
85
	ContentLength    int64 // -1 means unknown, 0 means exactly none
86
	Close            bool
87
	TransferEncoding []string
88
	Header           Header
89
	Trailer          Header
90
	IsResponse       bool
91
	bodyReadError    error // any non-EOF error from reading Body
92

93
	FlushHeaders bool            // flush headers to network before body
94
	ByteReadCh   chan readResult // non-nil if probeRequestBody called
95
}
96

97
func newTransferWriter(r interface{}) (t *transferWriter, err error) {
98
	t = &transferWriter{}
99

100
	// Extract relevant fields
101
	atLeastHTTP11 := false
102
	switch rr := r.(type) {
103
	case *Request:
104
		if rr.ContentLength != 0 && rr.Body == nil {
105
			return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
106
		}
107
		t.Method = valueOrDefault(rr.Method, "GET")
108
		t.Close = rr.Close
109
		t.TransferEncoding = rr.TransferEncoding
110
		t.Header = rr.Header
111
		t.Trailer = rr.Trailer
112
		t.Body = rr.Body
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"}
117
		}
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
127
		}
128

129
		atLeastHTTP11 = true // Transport requests are always 1.1 or 2.0
130
	case *Response:
131
		t.IsResponse = true
132
		if rr.Request != nil {
133
			t.Method = rr.Request.Method
134
		}
135
		t.Body = rr.Body
136
		t.BodyCloser = rr.Body
137
		t.ContentLength = rr.ContentLength
138
		t.Close = rr.Close
139
		t.TransferEncoding = rr.TransferEncoding
140
		t.Header = rr.Header
141
		t.Trailer = rr.Trailer
142
		atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
143
		t.ResponseToHEAD = noResponseBodyExpected(t.Method)
144
	}
145

146
	// Sanitize Body,ContentLength,TransferEncoding
147
	if t.ResponseToHEAD {
148
		t.Body = nil
149
		if chunked(t.TransferEncoding) {
150
			t.ContentLength = -1
151
		}
152
	} else {
153
		if !atLeastHTTP11 || t.Body == nil {
154
			t.TransferEncoding = nil
155
		}
156
		if chunked(t.TransferEncoding) {
157
			t.ContentLength = -1
158
		} else if t.Body == nil { // no chunking, no body
159
			t.ContentLength = 0
160
		}
161
	}
162

163
	// Sanitize Trailer
164
	if !chunked(t.TransferEncoding) {
165
		t.Trailer = nil
166
	}
167

168
	return t, nil
169
}
170

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.
178
//
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.
183
//
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
188
// a body.
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
193
		return false
194
	}
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
200
		return t.Body != nil
201
	}
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
205
	// later.
206
	return true
207
}
208

209
// probeRequestBody reads a byte from t.Body to see whether it's empty
210
// (returns io.EOF right away).
211
//
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
216
// are true:
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) {
226
		var buf [1]byte
227
		var rres readResult
228
		rres.n, rres.err = body.Read(buf[:])
229
		if rres.n == 1 {
230
			rres.b = buf[0]
231
		}
232
		t.ByteReadCh <- rres
233
	}(t.Body)
234
	timer := time.NewTimer(200 * time.Millisecond)
235
	select {
236
	case rres := <-t.ByteReadCh:
237
		timer.Stop()
238
		if rres.n == 0 && rres.err == io.EOF {
239
			// It was empty.
240
			t.Body = nil
241
			t.ContentLength = 0
242
		} else if rres.n == 1 {
243
			if rres.err != nil {
244
				t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
245
			} else {
246
				t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
247
			}
248
		} else if rres.err != nil {
249
			t.Body = errorReader{rres.err}
250
		}
251
	case <-timer.C:
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
261
	}
262
}
263

264
func noResponseBodyExpected(requestMethod string) bool {
265
	return requestMethod == "HEAD"
266
}
267

268
func (t *transferWriter) shouldSendContentLength() bool {
269
	if chunked(t.TransferEncoding) {
270
		return false
271
	}
272
	if t.ContentLength > 0 {
273
		return true
274
	}
275
	if t.ContentLength < 0 {
276
		return false
277
	}
278
	// Many servers expect a Content-Length for these methods
279
	if t.Method == "POST" || t.Method == "PUT" {
280
		return true
281
	}
282
	if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
283
		if t.Method == "GET" || t.Method == "HEAD" {
284
			return false
285
		}
286
		return true
287
	}
288

289
	return false
290
}
291

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 {
295
			return err
296
		}
297
		if trace != nil && trace.WroteHeaderField != nil {
298
			trace.WroteHeaderField("Connection", []string{"close"})
299
		}
300
	}
301

302
	// Write Content-Length and/or Transfer-Encoding whose values are a
303
	// function of the sanitized field triple (Body, ContentLength,
304
	// TransferEncoding)
305
	if t.shouldSendContentLength() {
306
		if _, err := io.WriteString(w, "Content-Length: "); err != nil {
307
			return err
308
		}
309
		if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
310
			return err
311
		}
312
		if trace != nil && trace.WroteHeaderField != nil {
313
			trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
314
		}
315
	} else if chunked(t.TransferEncoding) {
316
		if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
317
			return err
318
		}
319
		if trace != nil && trace.WroteHeaderField != nil {
320
			trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
321
		}
322
	}
323

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)
329
			switch k {
330
			case "Transfer-Encoding", "Trailer", "Content-Length":
331
				return &badStringError{"invalid Trailer key", k}
332
			}
333
			keys = append(keys, k)
334
		}
335
		if len(keys) > 0 {
336
			sort.Strings(keys)
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 {
340
				return err
341
			}
342
			if trace != nil && trace.WroteHeaderField != nil {
343
				trace.WroteHeaderField("Trailer", keys)
344
			}
345
		}
346
	}
347

348
	return nil
349
}
350

351
func (t *transferWriter) writeBody(w io.Writer) error {
352
	var err error
353
	var ncopy int64
354

355
	// Write body
356
	if t.Body != nil {
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}
361
			}
362
			cw := internal.NewChunkedWriter(w)
363
			buf := bufferPool.Get().([]byte)
364
			_, err = io.CopyBuffer(cw, body, buf)
365
			bufferPool.Put(buf)
366
			if err == nil {
367
				err = cw.Close()
368
			}
369
		} else if t.ContentLength == -1 {
370
			buf := bufferPool.Get().([]byte)
371
			ncopy, err = io.CopyBuffer(w, body, buf)
372
			bufferPool.Put(buf)
373
		} else {
374
			buf := bufferPool.Get().([]byte)
375
			ncopy, err = io.CopyBuffer(w, io.LimitReader(body, t.ContentLength), buf)
376
			bufferPool.Put(buf)
377
			if err != nil {
378
				return err
379
			}
380
			var nextra int64
381
			buf = bufferPool.Get().([]byte)
382
			nextra, err = io.CopyBuffer(ioutil.Discard, body, buf)
383
			bufferPool.Put(buf)
384
			ncopy += nextra
385
		}
386
		if err != nil {
387
			return err
388
		}
389
	}
390
	if t.BodyCloser != nil {
391
		if err := t.BodyCloser.Close(); err != nil {
392
			return err
393
		}
394
	}
395

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)
399
	}
400

401
	if chunked(t.TransferEncoding) {
402
		// Write Trailer header
403
		if t.Trailer != nil {
404
			if err := t.Trailer.Write(w); err != nil {
405
				return err
406
			}
407
		}
408
		// Last chunk, empty trailer
409
		_, err = io.WriteString(w, "\r\n")
410
	}
411
	return err
412
}
413

414
type transferReader struct {
415
	// Input
416
	Header        Header
417
	StatusCode    int
418
	RequestMethod string
419
	ProtoMajor    int
420
	ProtoMinor    int
421
	// Output
422
	Body             io.ReadCloser
423
	ContentLength    int64
424
	TransferEncoding []string
425
	Close            bool
426
	Trailer          Header
427
}
428

429
func (t *transferReader) protoAtLeast(m, n int) bool {
430
	return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
431
}
432

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 {
436
	switch {
437
	case status >= 100 && status <= 199:
438
		return false
439
	case status == 204:
440
		return false
441
	case status == 304:
442
		return false
443
	}
444
	return true
445
}
446

447
var (
448
	suppressedHeaders304    = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
449
	suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
450
)
451

452
func suppressedHeaders(status int) []string {
453
	switch {
454
	case status == 304:
455
		// RFC 7232 section 4.1
456
		return suppressedHeaders304
457
	case !bodyAllowedForStatus(status):
458
		return suppressedHeadersNoBody
459
	}
460
	return nil
461
}
462

463
// msg is *Request or *Response.
464
func readTransfer(msg interface{}, r *bufio.Reader) (err error) {
465
	t := &transferReader{RequestMethod: "GET"}
466

467
	// Unify input
468
	isResponse := false
469
	switch rr := msg.(type) {
470
	case *Response:
471
		t.Header = rr.Header
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)
476
		isResponse = true
477
		if rr.Request != nil {
478
			t.RequestMethod = rr.Request.Method
479
		}
480
	case *Request:
481
		t.Header = rr.Header
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
487
		t.StatusCode = 200
488
		t.Close = rr.Close
489
	default:
490
		panic("unexpected type")
491
	}
492

493
	// Default to HTTP/1.1
494
	if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
495
		t.ProtoMajor, t.ProtoMinor = 1, 1
496
	}
497

498
	// Transfer encoding, content length
499
	err = t.fixTransferEncoding()
500
	if err != nil {
501
		return err
502
	}
503

504
	realLength, err := fixLength(isResponse, t.StatusCode, t.RequestMethod, t.Header, t.TransferEncoding)
505
	if err != nil {
506
		return err
507
	}
508
	if isResponse && t.RequestMethod == "HEAD" {
509
		if n, err := parseContentLength(t.Header.get("Content-Length")); err != nil {
510
			return err
511
		} else {
512
			t.ContentLength = n
513
		}
514
	} else {
515
		t.ContentLength = realLength
516
	}
517

518
	// Trailer
519
	t.Trailer, err = fixTrailer(t.Header, t.TransferEncoding)
520
	if err != nil {
521
		return err
522
	}
523

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.
527
	switch msg.(type) {
528
	case *Response:
529
		if realLength == -1 &&
530
			!chunked(t.TransferEncoding) &&
531
			bodyAllowedForStatus(t.StatusCode) {
532
			// Unbounded body.
533
			t.Close = true
534
		}
535
	}
536

537
	// Prepare body reader. ContentLength < 0 means chunked encoding
538
	// or close connection when finished, since multipart is not supported yet
539
	switch {
540
	case chunked(t.TransferEncoding):
541
		if noResponseBodyExpected(t.RequestMethod) || !bodyAllowedForStatus(t.StatusCode) {
542
			t.Body = NoBody
543
		} else {
544
			t.Body = &body{src: internal.NewChunkedReader(r), hdr: msg, r: r, closing: t.Close}
545
		}
546
	case realLength == 0:
547
		t.Body = NoBody
548
	case realLength > 0:
549
		t.Body = &body{src: io.LimitReader(r, realLength), closing: t.Close}
550
	default:
551
		// realLength < 0, i.e. "Content-Length" not mentioned in header
552
		if t.Close {
553
			// Close semantics (i.e. HTTP/1.0)
554
			t.Body = &body{src: r, closing: t.Close}
555
		} else {
556
			// Persistent connection (i.e. HTTP/1.1)
557
			t.Body = NoBody
558
		}
559
	}
560

561
	// Unify output
562
	switch rr := msg.(type) {
563
	case *Request:
564
		rr.Body = t.Body
565
		rr.ContentLength = t.ContentLength
566
		rr.TransferEncoding = t.TransferEncoding
567
		rr.Close = t.Close
568
		rr.Trailer = t.Trailer
569
	case *Response:
570
		rr.Body = t.Body
571
		rr.ContentLength = t.ContentLength
572
		rr.TransferEncoding = t.TransferEncoding
573
		rr.Close = t.Close
574
		rr.Trailer = t.Trailer
575
	}
576

577
	return nil
578
}
579

580
// Checks whether chunked is part of the encodings stack
581
func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
582

583
// Checks whether the encoding is explicitly "identity".
584
func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
585

586
// fixTransferEncoding sanitizes t.TransferEncoding, if needed.
587
func (t *transferReader) fixTransferEncoding() error {
588
	raw, present := t.Header["Transfer-Encoding"]
589
	if !present {
590
		return nil
591
	}
592
	delete(t.Header, "Transfer-Encoding")
593

594
	// Issue 12785; ignore Transfer-Encoding on HTTP/1.0 requests.
595
	if !t.protoAtLeast(1, 1) {
596
		return nil
597
	}
598

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" {
609
			break
610
		}
611
		if encoding != "chunked" {
612
			return &badStringError{"unsupported transfer encoding", encoding}
613
		}
614
		te = te[0 : len(te)+1]
615
		te[len(te)-1] = encoding
616
	}
617
	if len(te) > 1 {
618
		return &badStringError{"too many transfer encodings", strings.Join(te, ",")}
619
	}
620
	if len(te) > 0 {
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."
624
		//
625
		// but also:
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."
635
		//
636
		// Reportedly, these appear in the wild.
637
		delete(t.Header, "Content-Length")
638
		t.TransferEncoding = te
639
		return nil
640
	}
641

642
	return nil
643
}
644

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"]
651

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.
657
		// See Issue 16490.
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)
662
			}
663
		}
664

665
		// deduplicate Content-Length
666
		header.Del("Content-Length")
667
		header.Add("Content-Length", first)
668

669
		contentLens = header["Content-Length"]
670
	}
671

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)
680
		}
681
		return 0, nil
682
	}
683
	if status/100 == 1 {
684
		return 0, nil
685
	}
686
	switch status {
687
	case 204, 304:
688
		return 0, nil
689
	}
690

691
	// Logic based on Transfer-Encoding
692
	if chunked(te) {
693
		return -1, nil
694
	}
695

696
	// Logic based on Content-Length
697
	var cl string
698
	if len(contentLens) == 1 {
699
		cl = strings.TrimSpace(contentLens[0])
700
	}
701
	if cl != "" {
702
		n, err := parseContentLength(cl)
703
		if err != nil {
704
			return -1, err
705
		}
706
		return n, nil
707
	}
708
	header.Del("Content-Length")
709

710
	if isRequest {
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.
718
		return 0, nil
719
	}
720

721
	// Body-EOF logic based on other methods (like closing, or chunked coding)
722
	return -1, nil
723
}
724

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 {
729
	if major < 1 {
730
		return true
731
	}
732

733
	conv := header["Connection"]
734
	hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
735
	if major == 1 && minor == 0 {
736
		return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
737
	}
738

739
	if hasClose && removeCloseHeader {
740
		header.Del("Connection")
741
	}
742

743
	return hasClose
744
}
745

746
// Parse the trailer header
747
func fixTrailer(header Header, te []string) (Header, error) {
748
	vv, ok := header["Trailer"]
749
	if !ok {
750
		return nil, nil
751
	}
752
	header.Del("Trailer")
753

754
	trailer := make(Header)
755
	var err error
756
	for _, v := range vv {
757
		foreachHeaderElement(v, func(key string) {
758
			key = CanonicalHeaderKey(key)
759
			switch key {
760
			case "Transfer-Encoding", "Trailer", "Content-Length":
761
				if err == nil {
762
					err = &badStringError{"bad trailer key", key}
763
					return
764
				}
765
			}
766
			trailer[key] = nil
767
		})
768
	}
769
	if err != nil {
770
		return nil, err
771
	}
772
	if len(trailer) == 0 {
773
		return nil, nil
774
	}
775
	if !chunked(te) {
776
		// Trailer and no chunking
777
		return nil, ErrUnexpectedTrailer
778
	}
779
	return trailer, nil
780
}
781

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.
785
type body struct {
786
	src          io.Reader
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
791

792
	mu         sync.Mutex // guards following, and calls to Read and Close
793
	sawEOF     bool
794
	closed     bool
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
797
}
798

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
802
// ResponseWriter.
803
var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
804

805
func (b *body) Read(p []byte) (n int, err error) {
806
	b.mu.Lock()
807
	defer b.mu.Unlock()
808
	if b.closed {
809
		return 0, ErrBodyReadAfterClose
810
	}
811
	return b.readLocked(p)
812
}
813

814
// Must hold b.mu.
815
func (b *body) readLocked(p []byte) (n int, err error) {
816
	if b.sawEOF {
817
		return 0, io.EOF
818
	}
819
	n, err = b.src.Read(p)
820

821
	if err == io.EOF {
822
		b.sawEOF = true
823
		// Chunked case. Read the trailer.
824
		if b.hdr != nil {
825
			if e := b.readTrailer(); e != nil {
826
				err = e
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
831
				b.sawEOF = false
832
				b.closed = true
833
			}
834
			b.hdr = nil
835
		} else {
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
840
			}
841
		}
842
	}
843

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 {
851
			err = io.EOF
852
			b.sawEOF = true
853
		}
854
	}
855

856
	if b.sawEOF && b.onHitEOF != nil {
857
		b.onHitEOF()
858
	}
859

860
	return n, err
861
}
862

863
var (
864
	singleCRLF = []byte("\r\n")
865
	doubleCRLF = []byte("\r\n\r\n")
866
)
867

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) {
874
			return true
875
		}
876
		if err != nil {
877
			break
878
		}
879
	}
880
	return false
881
}
882

883
var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
884

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) {
889
		b.r.Discard(2)
890
		return nil
891
	}
892
	if len(buf) < 2 {
893
		return errTrailerEOF
894
	}
895
	if err != nil {
896
		return err
897
	}
898

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")
909
	}
910

911
	hdr, err := textproto.NewReader(b.r).ReadMIMEHeader()
912
	if err != nil {
913
		if err == io.EOF {
914
			return errTrailerEOF
915
		}
916
		return err
917
	}
918
	switch rr := b.hdr.(type) {
919
	case *Request:
920
		mergeSetHeader(&rr.Trailer, Header(hdr))
921
	case *Response:
922
		mergeSetHeader(&rr.Trailer, Header(hdr))
923
	}
924
	return nil
925
}
926

927
func mergeSetHeader(dst *Header, src Header) {
928
	if *dst == nil {
929
		*dst = src
930
		return
931
	}
932
	for k, vv := range src {
933
		(*dst)[k] = vv
934
	}
935
}
936

937
// unreadDataSizeLocked returns the number of bytes of unread input.
938
// It returns -1 if unknown.
939
// b.mu must be held.
940
func (b *body) unreadDataSizeLocked() int64 {
941
	if lr, ok := b.src.(*io.LimitedReader); ok {
942
		return lr.N
943
	}
944
	return -1
945
}
946

947
func (b *body) Close() error {
948
	b.mu.Lock()
949
	defer b.mu.Unlock()
950
	if b.closed {
951
		return nil
952
	}
953
	var err error
954
	switch {
955
	case b.sawEOF:
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.
960
	case b.doEarlyClose:
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.
966
			b.earlyClose = true
967
		} else {
968
			var n int64
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)
972
			if err == io.EOF {
973
				err = nil
974
			}
975
			if n == maxPostHandlerReadBytes {
976
				b.earlyClose = true
977
			}
978
		}
979
	default:
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})
983
	}
984
	b.closed = true
985
	return err
986
}
987

988
func (b *body) didEarlyClose() bool {
989
	b.mu.Lock()
990
	defer b.mu.Unlock()
991
	return b.earlyClose
992
}
993

994
// bodyRemains reports whether future Read calls might
995
// yield data.
996
func (b *body) bodyRemains() bool {
997
	b.mu.Lock()
998
	defer b.mu.Unlock()
999
	return !b.sawEOF
1000
}
1001

1002
func (b *body) registerOnHitEOF(fn func()) {
1003
	b.mu.Lock()
1004
	defer b.mu.Unlock()
1005
	b.onHitEOF = fn
1006
}
1007

1008
// bodyLocked is a io.Reader reading from a *body when its mutex is
1009
// already held.
1010
type bodyLocked struct {
1011
	b *body
1012
}
1013

1014
func (bl bodyLocked) Read(p []byte) (n int, err error) {
1015
	if bl.b.closed {
1016
		return 0, ErrBodyReadAfterClose
1017
	}
1018
	return bl.b.readLocked(p)
1019
}
1020

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)
1025
	if cl == "" {
1026
		return -1, nil
1027
	}
1028
	n, err := strconv.ParseInt(cl, 10, 64)
1029
	if err != nil || n < 0 {
1030
		return 0, &badStringError{"bad Content-Length", cl}
1031
	}
1032
	return n, nil
1033

1034
}
1035

1036
// finishAsyncByteRead finishes reading the 1-byte sniff
1037
// from the ContentLength==0, Body!=nil case.
1038
type finishAsyncByteRead struct {
1039
	tw *transferWriter
1040
}
1041

1042
func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1043
	if len(p) == 0 {
1044
		return
1045
	}
1046
	rres := <-fr.tw.ByteReadCh
1047
	n, err = rres.n, rres.err
1048
	if n == 1 {
1049
		p[0] = rres.b
1050
	}
1051
	return
1052
}
1053

1054
var nopCloserType = reflect.TypeOf(ioutil.NopCloser(nil))
1055

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 {
1060
	switch r.(type) {
1061
	case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1062
		return true
1063
	}
1064
	if reflect.TypeOf(r) == nopCloserType {
1065
		return isKnownInMemoryReader(reflect.ValueOf(r).Field(0).Interface().(io.Reader))
1066
	}
1067
	return false
1068
}
1069

Использование cookies

Мы используем файлы cookie в соответствии с Политикой конфиденциальности и Политикой использования cookies.

Нажимая кнопку «Принимаю», Вы даете АО «СберТех» согласие на обработку Ваших персональных данных в целях совершенствования нашего веб-сайта и Сервиса GitVerse, а также повышения удобства их использования.

Запретить использование cookies Вы можете самостоятельно в настройках Вашего браузера.