Source file
src/net/http/transfer.go
1
2
3
4
5 package http
6
7 import (
8 "bufio"
9 "bytes"
10 "errors"
11 "fmt"
12 "internal/godebug"
13 "io"
14 "maps"
15 "math"
16 "net/http/httptrace"
17 "net/http/internal"
18 "net/http/internal/ascii"
19 "net/textproto"
20 "reflect"
21 "slices"
22 "strconv"
23 "strings"
24 "sync"
25 "time"
26
27 "golang.org/x/net/http/httpguts"
28 )
29
30
31
32 var ErrLineTooLong = internal.ErrLineTooLong
33
34 type errorReader struct {
35 err error
36 }
37
38 func (r errorReader) Read(p []byte) (n int, err error) {
39 return 0, r.err
40 }
41
42 type byteReader struct {
43 b byte
44 done bool
45 }
46
47 func (br *byteReader) Read(p []byte) (n int, err error) {
48 if br.done {
49 return 0, io.EOF
50 }
51 if len(p) == 0 {
52 return 0, nil
53 }
54 br.done = true
55 p[0] = br.b
56 return 1, io.EOF
57 }
58
59
60
61
62 type transferWriter struct {
63 Method string
64 Body io.Reader
65 BodyCloser io.Closer
66 ResponseToHEAD bool
67 ContentLength int64
68 Close bool
69 TransferEncoding []string
70 Header Header
71 Trailer Header
72 IsResponse bool
73 bodyReadError error
74
75 FlushHeaders bool
76 ByteReadCh chan readResult
77 }
78
79 func newTransferWriter(r any) (t *transferWriter, err error) {
80 t = &transferWriter{}
81
82
83 atLeastHTTP11 := false
84 switch rr := r.(type) {
85 case *Request:
86 if rr.ContentLength != 0 && rr.Body == nil {
87 return nil, fmt.Errorf("http: Request.ContentLength=%d with nil Body", rr.ContentLength)
88 }
89 t.Method = valueOrDefault(rr.Method, "GET")
90 t.Close = rr.Close
91 t.TransferEncoding = rr.TransferEncoding
92 t.Header = rr.Header
93 t.Trailer = rr.Trailer
94 t.Body = rr.Body
95 t.BodyCloser = rr.Body
96 t.ContentLength = rr.outgoingLength()
97 if t.ContentLength < 0 && len(t.TransferEncoding) == 0 && t.shouldSendChunkedRequestBody() {
98 t.TransferEncoding = []string{"chunked"}
99 }
100
101
102
103
104
105
106
107 if t.ContentLength != 0 && !isKnownInMemoryReader(t.Body) {
108 t.FlushHeaders = true
109 }
110
111 atLeastHTTP11 = true
112 case *Response:
113 t.IsResponse = true
114 if rr.Request != nil {
115 t.Method = rr.Request.Method
116 }
117 t.Body = rr.Body
118 t.BodyCloser = rr.Body
119 t.ContentLength = rr.ContentLength
120 t.Close = rr.Close
121 t.TransferEncoding = rr.TransferEncoding
122 t.Header = rr.Header
123 t.Trailer = rr.Trailer
124 atLeastHTTP11 = rr.ProtoAtLeast(1, 1)
125 t.ResponseToHEAD = noResponseBodyExpected(t.Method)
126 }
127
128
129 if t.ResponseToHEAD {
130 t.Body = nil
131 if chunked(t.TransferEncoding) {
132 t.ContentLength = -1
133 }
134 } else {
135 if !atLeastHTTP11 || t.Body == nil {
136 t.TransferEncoding = nil
137 }
138 if chunked(t.TransferEncoding) {
139 t.ContentLength = -1
140 } else if t.Body == nil {
141 t.ContentLength = 0
142 }
143 }
144
145
146 if !chunked(t.TransferEncoding) {
147 t.Trailer = nil
148 }
149
150
151
152
153 if err := validateTrailers(t.Trailer); err != "" {
154 return nil, fmt.Errorf("net/http: invalid trailer %s", err)
155 }
156
157 return t, nil
158 }
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178 func (t *transferWriter) shouldSendChunkedRequestBody() bool {
179
180
181 if t.ContentLength >= 0 || t.Body == nil {
182 return false
183 }
184 if t.Method == "CONNECT" {
185 return false
186 }
187 if requestMethodUsuallyLacksBody(t.Method) {
188
189
190
191 t.probeRequestBody()
192 return t.Body != nil
193 }
194
195
196
197
198 return true
199 }
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216 func (t *transferWriter) probeRequestBody() {
217 t.ByteReadCh = make(chan readResult, 1)
218 go func(body io.Reader) {
219 var buf [1]byte
220 var rres readResult
221 rres.n, rres.err = body.Read(buf[:])
222 if rres.n == 1 {
223 rres.b = buf[0]
224 }
225 t.ByteReadCh <- rres
226 close(t.ByteReadCh)
227 }(t.Body)
228 timer := time.NewTimer(200 * time.Millisecond)
229 select {
230 case rres := <-t.ByteReadCh:
231 timer.Stop()
232 if rres.n == 0 && rres.err == io.EOF {
233
234 t.Body = nil
235 t.ContentLength = 0
236 } else if rres.n == 1 {
237 if rres.err != nil {
238 t.Body = io.MultiReader(&byteReader{b: rres.b}, errorReader{rres.err})
239 } else {
240 t.Body = io.MultiReader(&byteReader{b: rres.b}, t.Body)
241 }
242 } else if rres.err != nil {
243 t.Body = errorReader{rres.err}
244 }
245 case <-timer.C:
246
247
248
249
250 t.Body = io.MultiReader(finishAsyncByteRead{t}, t.Body)
251
252
253
254 t.FlushHeaders = true
255 }
256 }
257
258 func noResponseBodyExpected(requestMethod string) bool {
259 return requestMethod == "HEAD"
260 }
261
262 func (t *transferWriter) shouldSendContentLength() bool {
263 if chunked(t.TransferEncoding) {
264 return false
265 }
266 if t.ContentLength > 0 {
267 return true
268 }
269 if t.ContentLength < 0 {
270 return false
271 }
272
273 if t.Method == "POST" || t.Method == "PUT" || t.Method == "PATCH" {
274 return true
275 }
276 if t.ContentLength == 0 && isIdentity(t.TransferEncoding) {
277 if t.Method == "GET" || t.Method == "HEAD" {
278 return false
279 }
280 return true
281 }
282
283 return false
284 }
285
286 func (t *transferWriter) writeHeader(w io.Writer, trace *httptrace.ClientTrace) error {
287 if t.Close && !httpguts.HeaderValuesContainsToken(t.Header["Connection"], "close") {
288 if _, err := io.WriteString(w, "Connection: close\r\n"); err != nil {
289 return err
290 }
291 if trace != nil && trace.WroteHeaderField != nil {
292 trace.WroteHeaderField("Connection", []string{"close"})
293 }
294 }
295
296
297
298
299 if t.shouldSendContentLength() {
300 if _, err := io.WriteString(w, "Content-Length: "); err != nil {
301 return err
302 }
303 if _, err := io.WriteString(w, strconv.FormatInt(t.ContentLength, 10)+"\r\n"); err != nil {
304 return err
305 }
306 if trace != nil && trace.WroteHeaderField != nil {
307 trace.WroteHeaderField("Content-Length", []string{strconv.FormatInt(t.ContentLength, 10)})
308 }
309 } else if chunked(t.TransferEncoding) {
310 if _, err := io.WriteString(w, "Transfer-Encoding: chunked\r\n"); err != nil {
311 return err
312 }
313 if trace != nil && trace.WroteHeaderField != nil {
314 trace.WroteHeaderField("Transfer-Encoding", []string{"chunked"})
315 }
316 }
317
318
319 if t.Trailer != nil {
320 keys := make([]string, 0, len(t.Trailer))
321 for k := range t.Trailer {
322 k = CanonicalHeaderKey(k)
323 switch k {
324 case "Transfer-Encoding", "Trailer", "Content-Length":
325 return badStringError("invalid Trailer key", k)
326 }
327 keys = append(keys, k)
328 }
329 if len(keys) > 0 {
330 slices.Sort(keys)
331
332
333 if _, err := io.WriteString(w, "Trailer: "+strings.Join(keys, ",")+"\r\n"); err != nil {
334 return err
335 }
336 if trace != nil && trace.WroteHeaderField != nil {
337 trace.WroteHeaderField("Trailer", keys)
338 }
339 }
340 }
341
342 return nil
343 }
344
345
346 func (t *transferWriter) writeBody(w io.Writer) (err error) {
347 var ncopy int64
348 closed := false
349 defer func() {
350 if closed || t.BodyCloser == nil {
351 return
352 }
353 if closeErr := t.BodyCloser.Close(); closeErr != nil && err == nil {
354 err = closeErr
355 }
356 }()
357
358
359
360
361
362 if !t.ResponseToHEAD && t.Body != nil {
363 var body = t.unwrapBody()
364 if chunked(t.TransferEncoding) {
365 if bw, ok := w.(*bufio.Writer); ok && !t.IsResponse {
366 w = &internal.FlushAfterChunkWriter{Writer: bw}
367 }
368 cw := internal.NewChunkedWriter(w)
369 _, err = t.doBodyCopy(cw, body)
370 if err == nil {
371 err = cw.Close()
372 }
373 } else if t.ContentLength == -1 {
374 dst := w
375 if t.Method == "CONNECT" {
376 dst = bufioFlushWriter{dst}
377 }
378 ncopy, err = t.doBodyCopy(dst, body)
379 } else {
380 ncopy, err = t.doBodyCopy(w, io.LimitReader(body, t.ContentLength))
381 if err != nil {
382 return err
383 }
384 var nextra int64
385 nextra, err = t.doBodyCopy(io.Discard, body)
386 ncopy += nextra
387 }
388 if err != nil {
389 return err
390 }
391 }
392 if t.BodyCloser != nil {
393 closed = true
394 if err := t.BodyCloser.Close(); err != nil {
395 return err
396 }
397 }
398
399 if !t.ResponseToHEAD && t.ContentLength != -1 && t.ContentLength != ncopy {
400 return fmt.Errorf("http: ContentLength=%d with Body length %d",
401 t.ContentLength, ncopy)
402 }
403
404 if !t.ResponseToHEAD && chunked(t.TransferEncoding) {
405
406 if t.Trailer != nil {
407 if err := t.Trailer.Write(w); err != nil {
408 return err
409 }
410 }
411
412 _, err = io.WriteString(w, "\r\n")
413 }
414 return err
415 }
416
417
418
419
420
421 func (t *transferWriter) doBodyCopy(dst io.Writer, src io.Reader) (n int64, err error) {
422 buf := getCopyBuf()
423 defer putCopyBuf(buf)
424
425 n, err = io.CopyBuffer(dst, src, buf)
426 if err != nil && err != io.EOF {
427 t.bodyReadError = err
428 }
429 return
430 }
431
432
433
434
435
436
437 func (t *transferWriter) unwrapBody() io.Reader {
438 if r, ok := unwrapNopCloser(t.Body); ok {
439 return r
440 }
441 if r, ok := t.Body.(*readTrackingBody); ok {
442 r.didRead = true
443 return r.ReadCloser
444 }
445 return t.Body
446 }
447
448 type transferReader struct {
449
450 Header Header
451 StatusCode int
452 RequestMethod string
453 ProtoMajor int
454 ProtoMinor int
455
456 Body io.ReadCloser
457 RealBodyLength int64
458 ContentLength int64
459 Chunked bool
460 Close bool
461 Trailer Header
462 }
463
464 func (t *transferReader) protoAtLeast(m, n int) bool {
465 return t.ProtoMajor > m || (t.ProtoMajor == m && t.ProtoMinor >= n)
466 }
467
468
469
470 func bodyAllowedForStatus(status int) bool {
471 return internal.BodyAllowedForStatus(status)
472 }
473
474 var (
475 suppressedHeaders304 = []string{"Content-Type", "Content-Length", "Transfer-Encoding"}
476 suppressedHeadersNoBody = []string{"Content-Length", "Transfer-Encoding"}
477 excludedHeadersNoBody = map[string]bool{"Content-Length": true, "Transfer-Encoding": true}
478 )
479
480 func suppressedHeaders(status int) []string {
481 switch {
482 case status == 304:
483
484 return suppressedHeaders304
485 case !bodyAllowedForStatus(status):
486 return suppressedHeadersNoBody
487 }
488 return nil
489 }
490
491
492 func readTransfer(msg any, r *bufio.Reader, maxTrailerHeaders int64) (err error) {
493 t := &transferReader{RequestMethod: "GET"}
494
495
496 isResponse := false
497 switch rr := msg.(type) {
498 case *Response:
499 t.Header = rr.Header
500 t.StatusCode = rr.StatusCode
501 t.ProtoMajor = rr.ProtoMajor
502 t.ProtoMinor = rr.ProtoMinor
503 t.Close = shouldClose(t.ProtoMajor, t.ProtoMinor, t.Header, true)
504 isResponse = true
505 if rr.Request != nil {
506 t.RequestMethod = rr.Request.Method
507 }
508 case *Request:
509 t.Header = rr.Header
510 t.RequestMethod = rr.Method
511 t.ProtoMajor = rr.ProtoMajor
512 t.ProtoMinor = rr.ProtoMinor
513
514
515 t.StatusCode = 200
516 t.Close = rr.Close
517 default:
518 panic("unexpected type")
519 }
520
521
522 if t.ProtoMajor == 0 && t.ProtoMinor == 0 {
523 t.ProtoMajor, t.ProtoMinor = 1, 1
524 }
525
526
527 if err := t.determineBodyLength(isResponse); err != nil {
528 return err
529 }
530
531
532 t.Trailer, err = fixTrailer(t.Header, t.Chunked, maxTrailerHeaders)
533 if err != nil {
534 return err
535 }
536
537
538
539 switch {
540 case t.Chunked:
541 if isResponse && (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, maxTrailerHeaders: maxTrailerHeaders}
545 }
546 case t.RealBodyLength == 0:
547 t.Body = NoBody
548 case t.RealBodyLength > 0:
549 t.Body = &body{src: io.LimitReader(r, t.RealBodyLength), closing: t.Close}
550 case t.Close:
551
552 t.Body = &body{src: r, closing: t.Close}
553 default:
554
555 return errors.New("http: unexpected body length (bug)")
556 }
557
558
559 switch rr := msg.(type) {
560 case *Request:
561 rr.Body = t.Body
562 rr.ContentLength = t.ContentLength
563 if t.Chunked {
564 rr.TransferEncoding = []string{"chunked"}
565 }
566 rr.Close = t.Close
567 rr.Trailer = t.Trailer
568 case *Response:
569 rr.Body = t.Body
570 rr.ContentLength = t.ContentLength
571 if t.Chunked {
572 rr.TransferEncoding = []string{"chunked"}
573 }
574 rr.Close = t.Close
575 rr.Trailer = t.Trailer
576 }
577
578 return nil
579 }
580
581
582 func chunked(te []string) bool { return len(te) > 0 && te[0] == "chunked" }
583
584
585 func isIdentity(te []string) bool { return len(te) == 1 && te[0] == "identity" }
586
587
588 type unsupportedTEError struct {
589 err string
590 }
591
592 var (
593 errTooManyTransferEncodings = &unsupportedTEError{"too many transfer encodings"}
594 errUnsupportedTransferEncoding = &unsupportedTEError{"unsupported transfer encoding"}
595
596 errTooManyContentLengths = errors.New("message cannot contain multiple Content-Length headers")
597 )
598
599 func (uste *unsupportedTEError) Error() string {
600 return uste.err
601 }
602
603
604
605 func isUnsupportedTEError(err error) bool {
606 _, ok := err.(*unsupportedTEError)
607 return ok
608 }
609
610
611
612
613 func (t *transferReader) determineBodyLength(isResponse bool) error {
614 isRequest := !isResponse
615 contentLength, hasContentLength := t.Header["Content-Length"]
616 transferEncoding, hasTransferEncoding := t.Header["Transfer-Encoding"]
617 delete(t.Header, "Content-Length")
618 delete(t.Header, "Transfer-Encoding")
619
620
621
622
623
624 if hasTransferEncoding && !t.protoAtLeast(1, 1) {
625
626
627
628
629
630 t.Close = true
631 transferEncoding = nil
632 hasTransferEncoding = false
633 }
634 if hasTransferEncoding {
635
636
637
638
639 if len(transferEncoding) != 1 {
640 return errTooManyTransferEncodings
641 }
642 if !ascii.EqualFold(transferEncoding[0], "chunked") {
643 return errUnsupportedTransferEncoding
644 }
645 }
646
647
648 contentLengthStr, parsedContentLength, err := parseContentLength(contentLength)
649 if err != nil {
650 return err
651 }
652 if parsedContentLength >= 0 {
653 contentLength = contentLength[:1]
654 contentLength[0] = contentLengthStr
655 }
656
657
658
659
660
661
662
663 if isResponse && t.RequestMethod == "HEAD" {
664 t.RealBodyLength = 0
665 if hasTransferEncoding {
666 t.Chunked = true
667 t.ContentLength = -1
668 } else if parsedContentLength >= 0 {
669 t.Header["Content-Length"] = contentLength
670 t.ContentLength = parsedContentLength
671 } else {
672 t.ContentLength = -1
673 }
674 return nil
675 }
676 bodyless := isResponse &&
677 ((t.StatusCode >= 100 && t.StatusCode < 200) ||
678 t.StatusCode == 204 ||
679 t.StatusCode == 304)
680 if bodyless {
681
682
683
684 t.RealBodyLength = 0
685 t.ContentLength = 0
686 if hasTransferEncoding {
687 t.Chunked = true
688 } else if parsedContentLength >= 0 {
689 t.Header["Content-Length"] = contentLength
690 }
691 return nil
692 }
693
694
695
696
697
698
699 if isResponse && t.StatusCode >= 200 && t.StatusCode < 300 && t.RequestMethod == "CONNECT" {
700 t.RealBodyLength = -1
701 t.ContentLength = -1
702 t.Close = true
703 if hasContentLength && parsedContentLength == 0 {
704
705
706
707
708
709 t.RealBodyLength = 0
710 t.ContentLength = 0
711 t.Header["Content-Length"] = contentLength
712 }
713 return nil
714 }
715
716
717
718
719 if hasContentLength && hasTransferEncoding {
720
721
722
723
724
725
726
727 contentLength = nil
728 hasContentLength = false
729 parsedContentLength = -1
730 t.Close = true
731 }
732
733
734
735
736
737
738 if hasTransferEncoding {
739
740 t.Chunked = true
741 t.RealBodyLength = -1
742 t.ContentLength = -1
743 return nil
744 }
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759 if parsedContentLength >= 0 {
760 t.Header["Content-Length"] = contentLength
761 t.RealBodyLength = parsedContentLength
762 t.ContentLength = parsedContentLength
763 return nil
764 }
765
766
767
768
769 if isRequest {
770 t.RealBodyLength = 0
771 t.ContentLength = 0
772 return nil
773 }
774
775
776
777
778
779 t.RealBodyLength = -1
780 t.ContentLength = -1
781 t.Close = true
782 return nil
783 }
784
785
786
787
788 func shouldClose(major, minor int, header Header, removeCloseHeader bool) bool {
789 if major < 1 {
790 return true
791 }
792
793 conv := header["Connection"]
794 hasClose := httpguts.HeaderValuesContainsToken(conv, "close")
795 if major == 1 && minor == 0 {
796 return hasClose || !httpguts.HeaderValuesContainsToken(conv, "keep-alive")
797 }
798
799 if hasClose && removeCloseHeader {
800 header.Del("Connection")
801 }
802
803 return hasClose
804 }
805
806
807 func fixTrailer(header Header, chunked bool, maxHeaders int64) (Header, error) {
808 vv, ok := header["Trailer"]
809 if !ok {
810 return nil, nil
811 }
812 if !chunked {
813
814
815
816
817
818
819
820 return nil, nil
821 }
822 header.Del("Trailer")
823 for _, v := range vv {
824 maxHeaders -= int64(strings.Count(v, ",") + 1)
825 if maxHeaders < 0 {
826 return nil, errTooLarge
827 }
828 }
829
830 trailer := make(Header)
831 var err error
832 for _, v := range vv {
833 foreachHeaderElement(v, func(key string) {
834 key = CanonicalHeaderKey(key)
835 switch key {
836 case "Transfer-Encoding", "Trailer", "Content-Length":
837 if err == nil {
838 err = badStringError("bad trailer key", key)
839 return
840 }
841 }
842 trailer[key] = nil
843 })
844 }
845 if err != nil {
846 return nil, err
847 }
848 if len(trailer) == 0 {
849 return nil, nil
850 }
851 return trailer, nil
852 }
853
854
855
856
857 type body struct {
858 src io.Reader
859 hdr any
860 r *bufio.Reader
861 closing bool
862 doEarlyClose bool
863 maxTrailerHeaders int64
864
865 mu sync.Mutex
866 sawEOF bool
867 closed bool
868 dropTrailer bool
869 onHitEOF func()
870 }
871
872
873
874
875
876 var ErrBodyReadAfterClose = errors.New("http: invalid Read on closed Body")
877
878 func (b *body) Read(p []byte) (n int, err error) {
879 if b == nil {
880 return 0, io.EOF
881 }
882 b.mu.Lock()
883 defer b.mu.Unlock()
884 if b.closed {
885 return 0, ErrBodyReadAfterClose
886 }
887 return b.readLocked(p)
888 }
889
890
891 func (b *body) readLocked(p []byte) (n int, err error) {
892 if b.sawEOF {
893 return 0, io.EOF
894 }
895 n, err = b.src.Read(p)
896
897 if err == io.EOF {
898 b.sawEOF = true
899
900 if b.hdr != nil {
901 if e := b.readTrailer(); e != nil {
902 err = e
903
904
905
906
907 b.sawEOF = false
908 b.closed = true
909 }
910 b.hdr = nil
911 } else {
912
913
914 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > 0 {
915 err = io.ErrUnexpectedEOF
916 }
917 }
918 }
919
920
921
922
923
924
925 if err == nil && n > 0 {
926 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N == 0 {
927 err = io.EOF
928 b.sawEOF = true
929 }
930 }
931
932 if b.sawEOF && b.onHitEOF != nil {
933 b.onHitEOF()
934 }
935
936 return n, err
937 }
938
939 var (
940 singleCRLF = []byte("\r\n")
941 doubleCRLF = []byte("\r\n\r\n")
942 )
943
944 func seeUpcomingDoubleCRLF(r *bufio.Reader) error {
945 containsValidTrailers := func(buf []byte) (valid, complete bool) {
946 if !bytes.HasSuffix(buf, doubleCRLF) {
947 return
948 }
949 complete = true
950 cr := false
951 for _, c := range buf {
952 if cr {
953 switch c {
954 case '\n':
955 cr = false
956 default:
957 return
958 }
959 } else {
960 switch c {
961 case '\r':
962 cr = true
963 case '\n':
964 return
965 }
966 }
967 }
968 if !cr {
969 valid = true
970 }
971 return
972 }
973 for peekSize := 4; ; peekSize++ {
974
975
976 buf, err := r.Peek(peekSize)
977 valid, complete := containsValidTrailers(buf)
978 if complete {
979 if valid {
980 return nil
981 }
982 return errors.New("http: invalid trailer")
983 }
984 if err != nil {
985 break
986 }
987 }
988 return errors.New("http: suspiciously long trailer after chunked body")
989 }
990
991 var errTrailerEOF = errors.New("http: unexpected EOF reading trailer")
992
993 func (b *body) readTrailer() error {
994
995 buf, err := b.r.Peek(2)
996 if bytes.Equal(buf, singleCRLF) {
997 b.r.Discard(2)
998 return nil
999 }
1000 if len(buf) < 2 {
1001 return errTrailerEOF
1002 }
1003 if err != nil {
1004 return err
1005 }
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015 if err := seeUpcomingDoubleCRLF(b.r); err != nil {
1016 return err
1017 }
1018
1019 hdr, err := readMIMEHeader(textproto.NewReader(b.r), math.MaxInt64, b.maxTrailerHeaders)
1020 if err != nil {
1021 if err == io.EOF {
1022 return errTrailerEOF
1023 }
1024 return err
1025 }
1026
1027
1028
1029
1030 if b.dropTrailer {
1031 return nil
1032 }
1033 switch rr := b.hdr.(type) {
1034 case *Request:
1035 mergeSetHeader(&rr.Trailer, Header(hdr))
1036 case *Response:
1037 mergeSetHeader(&rr.Trailer, Header(hdr))
1038 }
1039 return nil
1040 }
1041
1042 func mergeSetHeader(dst *Header, src Header) {
1043 if *dst == nil {
1044 *dst = src
1045 return
1046 }
1047 maps.Copy(*dst, src)
1048 }
1049
1050 func (b *body) discardTrailer() {
1051 b.mu.Lock()
1052 defer b.mu.Unlock()
1053 b.dropTrailer = true
1054 }
1055
1056
1057
1058
1059 func (b *body) unreadDataSizeLocked() int64 {
1060 if lr, ok := b.src.(*io.LimitedReader); ok {
1061 return lr.N
1062 }
1063 return -1
1064 }
1065
1066 func (b *body) Close() error {
1067 if b == nil {
1068 return nil
1069 }
1070 b.mu.Lock()
1071 defer b.mu.Unlock()
1072 if b.closed {
1073 return nil
1074 }
1075 var err error
1076 switch {
1077 case b.sawEOF:
1078
1079 case b.hdr == nil && b.closing:
1080
1081
1082 case b.doEarlyClose:
1083
1084
1085 if lr, ok := b.src.(*io.LimitedReader); ok && lr.N > maxPostHandlerReadBytes {
1086
1087
1088 } else {
1089 var n int64
1090
1091
1092 n, err = io.CopyN(io.Discard, bodyLocked{b}, maxPostHandlerReadBytes+1)
1093 if err == io.EOF && n <= maxPostHandlerReadBytes {
1094 b.sawEOF = true
1095
1096
1097 err = nil
1098 }
1099 }
1100 default:
1101
1102
1103 _, err = io.Copy(io.Discard, bodyLocked{b})
1104 }
1105 b.closed = true
1106 return err
1107 }
1108
1109 func (b *body) consumedEntireBody() bool {
1110 if b == nil {
1111 return true
1112 }
1113 b.mu.Lock()
1114 defer b.mu.Unlock()
1115 return b.sawEOF
1116 }
1117
1118
1119
1120 func (b *body) bodyRemains() bool {
1121 if b == nil {
1122 return false
1123 }
1124 b.mu.Lock()
1125 defer b.mu.Unlock()
1126 return !b.sawEOF
1127 }
1128
1129 func (b *body) registerOnHitEOF(fn func()) {
1130 if b == nil {
1131 return
1132 }
1133 b.mu.Lock()
1134 defer b.mu.Unlock()
1135 b.onHitEOF = fn
1136 }
1137
1138
1139
1140 type bodyLocked struct {
1141 b *body
1142 }
1143
1144 func (bl bodyLocked) Read(p []byte) (n int, err error) {
1145 if bl.b.closed {
1146 return 0, ErrBodyReadAfterClose
1147 }
1148 return bl.b.readLocked(p)
1149 }
1150
1151 var httplaxcontentlength = godebug.New("httplaxcontentlength")
1152
1153
1154
1155
1156
1157 func parseContentLength(contentLength []string) (string, int64, error) {
1158 if len(contentLength) == 0 {
1159 return "", -1, nil
1160 }
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171 cl := textproto.TrimString(contentLength[0])
1172 for _, ct := range contentLength[1:] {
1173 if cl != textproto.TrimString(ct) {
1174 return "", 0, errTooManyContentLengths
1175 }
1176 }
1177
1178
1179
1180 if cl == "" {
1181 if httplaxcontentlength.Value() == "1" {
1182 httplaxcontentlength.IncNonDefault()
1183 return "", -1, nil
1184 }
1185 return "", 0, badStringError("invalid empty Content-Length", cl)
1186 }
1187 n, err := strconv.ParseUint(cl, 10, 63)
1188 if err != nil {
1189 return "", 0, badStringError("bad Content-Length", cl)
1190 }
1191 return cl, int64(n), nil
1192 }
1193
1194
1195
1196 type finishAsyncByteRead struct {
1197 tw *transferWriter
1198 }
1199
1200 func (fr finishAsyncByteRead) Read(p []byte) (n int, err error) {
1201 if len(p) == 0 {
1202 return
1203 }
1204 rres := <-fr.tw.ByteReadCh
1205 n, err = rres.n, rres.err
1206 if n == 1 {
1207 p[0] = rres.b
1208 }
1209 if err == nil {
1210 err = io.EOF
1211 }
1212 return
1213 }
1214
1215 var nopCloserType = reflect.TypeOf(io.NopCloser(nil))
1216 var nopCloserWriterToType = reflect.TypeOf(io.NopCloser(struct {
1217 io.Reader
1218 io.WriterTo
1219 }{}))
1220
1221
1222
1223 func unwrapNopCloser(r io.Reader) (underlyingReader io.Reader, isNopCloser bool) {
1224 switch reflect.TypeOf(r) {
1225 case nopCloserType, nopCloserWriterToType:
1226 return reflect.ValueOf(r).Field(0).Interface().(io.Reader), true
1227 default:
1228 return nil, false
1229 }
1230 }
1231
1232
1233
1234
1235 func isKnownInMemoryReader(r io.Reader) bool {
1236 switch r.(type) {
1237 case *bytes.Reader, *bytes.Buffer, *strings.Reader:
1238 return true
1239 }
1240 if r, ok := unwrapNopCloser(r); ok {
1241 return isKnownInMemoryReader(r)
1242 }
1243 if r, ok := r.(*readTrackingBody); ok {
1244 return isKnownInMemoryReader(r.ReadCloser)
1245 }
1246 return false
1247 }
1248
1249
1250
1251 type bufioFlushWriter struct{ w io.Writer }
1252
1253 func (fw bufioFlushWriter) Write(p []byte) (n int, err error) {
1254 n, err = fw.w.Write(p)
1255 if bw, ok := fw.w.(*bufio.Writer); n > 0 && ok {
1256 ferr := bw.Flush()
1257 if ferr != nil && err == nil {
1258 err = ferr
1259 }
1260 }
1261 return
1262 }
1263
View as plain text