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