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