github.com/ltltlt/go-source-code@v0.0.0-20190830023027-95be009773aa/net/http/request.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 // HTTP Request reading and parsing. 6 7 package http 8 9 import ( 10 "bufio" 11 "bytes" 12 "context" 13 "crypto/tls" 14 "encoding/base64" 15 "errors" 16 "fmt" 17 "io" 18 "io/ioutil" 19 "mime" 20 "mime/multipart" 21 "net" 22 "net/http/httptrace" 23 "net/textproto" 24 "net/url" 25 "strconv" 26 "strings" 27 "sync" 28 29 "golang_org/x/net/idna" 30 ) 31 32 const ( 33 defaultMaxMemory = 32 << 20 // 32 MB 34 ) 35 36 // ErrMissingFile is returned by FormFile when the provided file field name 37 // is either not present in the request or not a file field. 38 var ErrMissingFile = errors.New("http: no such file") 39 40 // ProtocolError represents an HTTP protocol error. 41 // 42 // Deprecated: Not all errors in the http package related to protocol errors 43 // are of type ProtocolError. 44 type ProtocolError struct { 45 ErrorString string 46 } 47 48 func (pe *ProtocolError) Error() string { return pe.ErrorString } 49 50 var ( 51 // ErrNotSupported is returned by the Push method of Pusher 52 // implementations to indicate that HTTP/2 Push support is not 53 // available. 54 ErrNotSupported = &ProtocolError{"feature not supported"} 55 56 // ErrUnexpectedTrailer is returned by the Transport when a server 57 // replies with a Trailer header, but without a chunked reply. 58 ErrUnexpectedTrailer = &ProtocolError{"trailer header without chunked transfer encoding"} 59 60 // ErrMissingBoundary is returned by Request.MultipartReader when the 61 // request's Content-Type does not include a "boundary" parameter. 62 ErrMissingBoundary = &ProtocolError{"no multipart boundary param in Content-Type"} 63 64 // ErrNotMultipart is returned by Request.MultipartReader when the 65 // request's Content-Type is not multipart/form-data. 66 ErrNotMultipart = &ProtocolError{"request Content-Type isn't multipart/form-data"} 67 68 // Deprecated: ErrHeaderTooLong is not used. 69 ErrHeaderTooLong = &ProtocolError{"header too long"} 70 // Deprecated: ErrShortBody is not used. 71 ErrShortBody = &ProtocolError{"entity body too short"} 72 // Deprecated: ErrMissingContentLength is not used. 73 ErrMissingContentLength = &ProtocolError{"missing ContentLength in HEAD response"} 74 ) 75 76 type badStringError struct { 77 what string 78 str string 79 } 80 81 func (e *badStringError) Error() string { return fmt.Sprintf("%s %q", e.what, e.str) } 82 83 // Headers that Request.Write handles itself and should be skipped. 84 var reqWriteExcludeHeader = map[string]bool{ 85 "Host": true, // not in Header map anyway 86 "User-Agent": true, 87 "Content-Length": true, 88 "Transfer-Encoding": true, 89 "Trailer": true, 90 } 91 92 // A Request represents an HTTP request received by a server 93 // or to be sent by a client. 94 // 95 // The field semantics differ slightly between client and server 96 // usage. In addition to the notes on the fields below, see the 97 // documentation for Request.Write and RoundTripper. 98 type Request struct { 99 // Method specifies the HTTP method (GET, POST, PUT, etc.). 100 // For client requests an empty string means GET. 101 // 102 // Go's HTTP client does not support sending a request with 103 // the CONNECT method. See the documentation on Transport for 104 // details. 105 Method string 106 107 // URL specifies either the URI being requested (for server 108 // requests) or the URL to access (for client requests). 109 // 110 // For server requests the URL is parsed from the URI 111 // supplied on the Request-Line as stored in RequestURI. For 112 // most requests, fields other than Path and RawQuery will be 113 // empty. (See RFC 2616, Section 5.1.2) 114 // 115 // For client requests, the URL's Host specifies the server to 116 // connect to, while the Request's Host field optionally 117 // specifies the Host header value to send in the HTTP 118 // request. 119 URL *url.URL 120 121 // The protocol version for incoming server requests. 122 // 123 // For client requests these fields are ignored. The HTTP 124 // client code always uses either HTTP/1.1 or HTTP/2. 125 // See the docs on Transport for details. 126 Proto string // "HTTP/1.0" 127 ProtoMajor int // 1 128 ProtoMinor int // 0 129 130 // Header contains the request header fields either received 131 // by the server or to be sent by the client. 132 // 133 // If a server received a request with header lines, 134 // 135 // Host: example.com 136 // accept-encoding: gzip, deflate 137 // Accept-Language: en-us 138 // fOO: Bar 139 // foo: two 140 // 141 // then 142 // 143 // Header = map[string][]string{ 144 // "Accept-Encoding": {"gzip, deflate"}, 145 // "Accept-Language": {"en-us"}, 146 // "Foo": {"Bar", "two"}, 147 // } 148 // 149 // For incoming requests, the Host header is promoted to the 150 // Request.Host field and removed from the Header map. 151 // 152 // HTTP defines that header names are case-insensitive. The 153 // request parser implements this by using CanonicalHeaderKey, 154 // making the first character and any characters following a 155 // hyphen uppercase and the rest lowercase. 156 // 157 // For client requests, certain headers such as Content-Length 158 // and Connection are automatically written when needed and 159 // values in Header may be ignored. See the documentation 160 // for the Request.Write method. 161 Header Header 162 163 // Body is the request's body. 164 // 165 // For client requests a nil body means the request has no 166 // body, such as a GET request. The HTTP Client's Transport 167 // is responsible for calling the Close method. 168 // 169 // For server requests the Request Body is always non-nil 170 // but will return EOF immediately when no body is present. 171 // The Server will close the request body. The ServeHTTP 172 // Handler does not need to. 173 Body io.ReadCloser 174 175 // GetBody defines an optional func to return a new copy of 176 // Body. It is used for client requests when a redirect requires 177 // reading the body more than once. Use of GetBody still 178 // requires setting Body. 179 // 180 // For server requests it is unused. 181 GetBody func() (io.ReadCloser, error) 182 183 // ContentLength records the length of the associated content. 184 // The value -1 indicates that the length is unknown. 185 // Values >= 0 indicate that the given number of bytes may 186 // be read from Body. 187 // For client requests, a value of 0 with a non-nil Body is 188 // also treated as unknown. 189 ContentLength int64 190 191 // TransferEncoding lists the transfer encodings from outermost to 192 // innermost. An empty list denotes the "identity" encoding. 193 // TransferEncoding can usually be ignored; chunked encoding is 194 // automatically added and removed as necessary when sending and 195 // receiving requests. 196 TransferEncoding []string 197 198 // Close indicates whether to close the connection after 199 // replying to this request (for servers) or after sending this 200 // request and reading its response (for clients). 201 // 202 // For server requests, the HTTP server handles this automatically 203 // and this field is not needed by Handlers. 204 // 205 // For client requests, setting this field prevents re-use of 206 // TCP connections between requests to the same hosts, as if 207 // Transport.DisableKeepAlives were set. 208 Close bool 209 210 // For server requests Host specifies the host on which the 211 // URL is sought. Per RFC 2616, this is either the value of 212 // the "Host" header or the host name given in the URL itself. 213 // It may be of the form "host:port". For international domain 214 // names, Host may be in Punycode or Unicode form. Use 215 // golang.org/x/net/idna to convert it to either format if 216 // needed. 217 // 218 // For client requests Host optionally overrides the Host 219 // header to send. If empty, the Request.Write method uses 220 // the value of URL.Host. Host may contain an international 221 // domain name. 222 Host string 223 224 // Form contains the parsed form data, including both the URL 225 // field's query parameters and the POST or PUT form data. 226 // This field is only available after ParseForm is called. 227 // The HTTP client ignores Form and uses Body instead. 228 Form url.Values 229 230 // PostForm contains the parsed form data from POST, PATCH, 231 // or PUT body parameters. 232 // 233 // This field is only available after ParseForm is called. 234 // The HTTP client ignores PostForm and uses Body instead. 235 PostForm url.Values 236 237 // MultipartForm is the parsed multipart form, including file uploads. 238 // This field is only available after ParseMultipartForm is called. 239 // The HTTP client ignores MultipartForm and uses Body instead. 240 MultipartForm *multipart.Form 241 242 // Trailer specifies additional headers that are sent after the request 243 // body. 244 // 245 // For server requests the Trailer map initially contains only the 246 // trailer keys, with nil values. (The client declares which trailers it 247 // will later send.) While the handler is reading from Body, it must 248 // not reference Trailer. After reading from Body returns EOF, Trailer 249 // can be read again and will contain non-nil values, if they were sent 250 // by the client. 251 // 252 // For client requests Trailer must be initialized to a map containing 253 // the trailer keys to later send. The values may be nil or their final 254 // values. The ContentLength must be 0 or -1, to send a chunked request. 255 // After the HTTP request is sent the map values can be updated while 256 // the request body is read. Once the body returns EOF, the caller must 257 // not mutate Trailer. 258 // 259 // Few HTTP clients, servers, or proxies support HTTP trailers. 260 Trailer Header 261 262 // RemoteAddr allows HTTP servers and other software to record 263 // the network address that sent the request, usually for 264 // logging. This field is not filled in by ReadRequest and 265 // has no defined format. The HTTP server in this package 266 // sets RemoteAddr to an "IP:port" address before invoking a 267 // handler. 268 // This field is ignored by the HTTP client. 269 RemoteAddr string 270 271 // RequestURI is the unmodified Request-URI of the 272 // Request-Line (RFC 2616, Section 5.1) as sent by the client 273 // to a server. Usually the URL field should be used instead. 274 // It is an error to set this field in an HTTP client request. 275 RequestURI string 276 277 // TLS allows HTTP servers and other software to record 278 // information about the TLS connection on which the request 279 // was received. This field is not filled in by ReadRequest. 280 // The HTTP server in this package sets the field for 281 // TLS-enabled connections before invoking a handler; 282 // otherwise it leaves the field nil. 283 // This field is ignored by the HTTP client. 284 TLS *tls.ConnectionState 285 286 // Cancel is an optional channel whose closure indicates that the client 287 // request should be regarded as canceled. Not all implementations of 288 // RoundTripper may support Cancel. 289 // 290 // For server requests, this field is not applicable. 291 // 292 // Deprecated: Use the Context and WithContext methods 293 // instead. If a Request's Cancel field and context are both 294 // set, it is undefined whether Cancel is respected. 295 Cancel <-chan struct{} 296 297 // Response is the redirect response which caused this request 298 // to be created. This field is only populated during client 299 // redirects. 300 Response *Response 301 302 // ctx is either the client or server context. It should only 303 // be modified via copying the whole Request using WithContext. 304 // It is unexported to prevent people from using Context wrong 305 // and mutating the contexts held by callers of the same request. 306 ctx context.Context 307 } 308 309 // Context returns the request's context. To change the context, use 310 // WithContext. 311 // 312 // The returned context is always non-nil; it defaults to the 313 // background context. 314 // 315 // For outgoing client requests, the context controls cancelation. 316 // 317 // For incoming server requests, the context is canceled when the 318 // client's connection closes, the request is canceled (with HTTP/2), 319 // or when the ServeHTTP method returns. 320 func (r *Request) Context() context.Context { 321 if r.ctx != nil { 322 return r.ctx 323 } 324 return context.Background() 325 } 326 327 // WithContext returns a shallow copy of r with its context changed 328 // to ctx. The provided ctx must be non-nil. 329 func (r *Request) WithContext(ctx context.Context) *Request { 330 if ctx == nil { 331 panic("nil context") 332 } 333 r2 := new(Request) 334 *r2 = *r 335 r2.ctx = ctx 336 337 // Deep copy the URL because it isn't 338 // a map and the URL is mutable by users 339 // of WithContext. 340 if r.URL != nil { 341 r2URL := new(url.URL) 342 *r2URL = *r.URL 343 r2.URL = r2URL 344 } 345 346 return r2 347 } 348 349 // ProtoAtLeast reports whether the HTTP protocol used 350 // in the request is at least major.minor. 351 func (r *Request) ProtoAtLeast(major, minor int) bool { 352 return r.ProtoMajor > major || 353 r.ProtoMajor == major && r.ProtoMinor >= minor 354 } 355 356 // UserAgent returns the client's User-Agent, if sent in the request. 357 func (r *Request) UserAgent() string { 358 return r.Header.Get("User-Agent") 359 } 360 361 // Cookies parses and returns the HTTP cookies sent with the request. 362 func (r *Request) Cookies() []*Cookie { 363 return readCookies(r.Header, "") 364 } 365 366 // ErrNoCookie is returned by Request's Cookie method when a cookie is not found. 367 var ErrNoCookie = errors.New("http: named cookie not present") 368 369 // Cookie returns the named cookie provided in the request or 370 // ErrNoCookie if not found. 371 // If multiple cookies match the given name, only one cookie will 372 // be returned. 373 func (r *Request) Cookie(name string) (*Cookie, error) { 374 for _, c := range readCookies(r.Header, name) { 375 return c, nil 376 } 377 return nil, ErrNoCookie 378 } 379 380 // AddCookie adds a cookie to the request. Per RFC 6265 section 5.4, 381 // AddCookie does not attach more than one Cookie header field. That 382 // means all cookies, if any, are written into the same line, 383 // separated by semicolon. 384 func (r *Request) AddCookie(c *Cookie) { 385 s := fmt.Sprintf("%s=%s", sanitizeCookieName(c.Name), sanitizeCookieValue(c.Value)) 386 if c := r.Header.Get("Cookie"); c != "" { 387 r.Header.Set("Cookie", c+"; "+s) 388 } else { 389 r.Header.Set("Cookie", s) 390 } 391 } 392 393 // Referer returns the referring URL, if sent in the request. 394 // 395 // Referer is misspelled as in the request itself, a mistake from the 396 // earliest days of HTTP. This value can also be fetched from the 397 // Header map as Header["Referer"]; the benefit of making it available 398 // as a method is that the compiler can diagnose programs that use the 399 // alternate (correct English) spelling req.Referrer() but cannot 400 // diagnose programs that use Header["Referrer"]. 401 func (r *Request) Referer() string { 402 return r.Header.Get("Referer") 403 } 404 405 // multipartByReader is a sentinel value. 406 // Its presence in Request.MultipartForm indicates that parsing of the request 407 // body has been handed off to a MultipartReader instead of ParseMultipartFrom. 408 var multipartByReader = &multipart.Form{ 409 Value: make(map[string][]string), 410 File: make(map[string][]*multipart.FileHeader), 411 } 412 413 // MultipartReader returns a MIME multipart reader if this is a 414 // multipart/form-data POST request, else returns nil and an error. 415 // Use this function instead of ParseMultipartForm to 416 // process the request body as a stream. 417 func (r *Request) MultipartReader() (*multipart.Reader, error) { 418 if r.MultipartForm == multipartByReader { 419 return nil, errors.New("http: MultipartReader called twice") 420 } 421 if r.MultipartForm != nil { 422 return nil, errors.New("http: multipart handled by ParseMultipartForm") 423 } 424 r.MultipartForm = multipartByReader 425 return r.multipartReader() 426 } 427 428 func (r *Request) multipartReader() (*multipart.Reader, error) { 429 v := r.Header.Get("Content-Type") 430 if v == "" { 431 return nil, ErrNotMultipart 432 } 433 d, params, err := mime.ParseMediaType(v) 434 if err != nil || d != "multipart/form-data" { 435 return nil, ErrNotMultipart 436 } 437 boundary, ok := params["boundary"] 438 if !ok { 439 return nil, ErrMissingBoundary 440 } 441 return multipart.NewReader(r.Body, boundary), nil 442 } 443 444 // isH2Upgrade reports whether r represents the http2 "client preface" 445 // magic string. 446 // In HTTP/2, each endpoint is required to send a connection preface as a final confirmation of the protocol in use and to establish the initial settings for the HTTP/2 connection. … the connection preface starts with the string "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n") 447 func (r *Request) isH2Upgrade() bool { 448 return r.Method == "PRI" && len(r.Header) == 0 && r.URL.Path == "*" && r.Proto == "HTTP/2.0" 449 } 450 451 // Return value if nonempty, def otherwise. 452 func valueOrDefault(value, def string) string { 453 if value != "" { 454 return value 455 } 456 return def 457 } 458 459 // NOTE: This is not intended to reflect the actual Go version being used. 460 // It was changed at the time of Go 1.1 release because the former User-Agent 461 // had ended up on a blacklist for some intrusion detection systems. 462 // See https://codereview.appspot.com/7532043. 463 const defaultUserAgent = "Go-http-client/1.1" 464 465 // Write writes an HTTP/1.1 request, which is the header and body, in wire format. 466 // This method consults the following fields of the request: 467 // Host 468 // URL 469 // Method (defaults to "GET") 470 // Header 471 // ContentLength 472 // TransferEncoding 473 // Body 474 // 475 // If Body is present, Content-Length is <= 0 and TransferEncoding 476 // hasn't been set to "identity", Write adds "Transfer-Encoding: 477 // chunked" to the header. Body is closed after it is sent. 478 func (r *Request) Write(w io.Writer) error { 479 return r.write(w, false, nil, nil) 480 } 481 482 // WriteProxy is like Write but writes the request in the form 483 // expected by an HTTP proxy. In particular, WriteProxy writes the 484 // initial Request-URI line of the request with an absolute URI, per 485 // section 5.1.2 of RFC 2616, including the scheme and host. 486 // In either case, WriteProxy also writes a Host header, using 487 // either r.Host or r.URL.Host. 488 func (r *Request) WriteProxy(w io.Writer) error { 489 return r.write(w, true, nil, nil) 490 } 491 492 // errMissingHost is returned by Write when there is no Host or URL present in 493 // the Request. 494 var errMissingHost = errors.New("http: Request.Write on Request with no Host or URL set") 495 496 // extraHeaders may be nil 497 // waitForContinue may be nil 498 func (r *Request) write(w io.Writer, usingProxy bool, extraHeaders Header, waitForContinue func() bool) (err error) { 499 trace := httptrace.ContextClientTrace(r.Context()) 500 if trace != nil && trace.WroteRequest != nil { 501 defer func() { 502 trace.WroteRequest(httptrace.WroteRequestInfo{ 503 Err: err, 504 }) 505 }() 506 } 507 508 // Find the target host. Prefer the Host: header, but if that 509 // is not given, use the host from the request URL. 510 // 511 // Clean the host, in case it arrives with unexpected stuff in it. 512 host := cleanHost(r.Host) 513 if host == "" { 514 if r.URL == nil { 515 return errMissingHost 516 } 517 host = cleanHost(r.URL.Host) 518 } 519 520 // According to RFC 6874, an HTTP client, proxy, or other 521 // intermediary must remove any IPv6 zone identifier attached 522 // to an outgoing URI. 523 host = removeZone(host) 524 525 ruri := r.URL.RequestURI() 526 if usingProxy && r.URL.Scheme != "" && r.URL.Opaque == "" { 527 ruri = r.URL.Scheme + "://" + host + ruri 528 } else if r.Method == "CONNECT" && r.URL.Path == "" { 529 // CONNECT requests normally give just the host and port, not a full URL. 530 ruri = host 531 } 532 // TODO(bradfitz): escape at least newlines in ruri? 533 534 // Wrap the writer in a bufio Writer if it's not already buffered. 535 // Don't always call NewWriter, as that forces a bytes.Buffer 536 // and other small bufio Writers to have a minimum 4k buffer 537 // size. 538 var bw *bufio.Writer 539 if _, ok := w.(io.ByteWriter); !ok { 540 bw = bufio.NewWriter(w) 541 w = bw 542 } 543 544 _, err = fmt.Fprintf(w, "%s %s HTTP/1.1\r\n", valueOrDefault(r.Method, "GET"), ruri) 545 if err != nil { 546 return err 547 } 548 549 // Header lines 550 _, err = fmt.Fprintf(w, "Host: %s\r\n", host) 551 if err != nil { 552 return err 553 } 554 555 // Use the defaultUserAgent unless the Header contains one, which 556 // may be blank to not send the header. 557 userAgent := defaultUserAgent 558 if _, ok := r.Header["User-Agent"]; ok { 559 userAgent = r.Header.Get("User-Agent") 560 } 561 if userAgent != "" { 562 _, err = fmt.Fprintf(w, "User-Agent: %s\r\n", userAgent) 563 if err != nil { 564 return err 565 } 566 } 567 568 // Process Body,ContentLength,Close,Trailer 569 tw, err := newTransferWriter(r) 570 if err != nil { 571 return err 572 } 573 err = tw.WriteHeader(w) 574 if err != nil { 575 return err 576 } 577 578 err = r.Header.WriteSubset(w, reqWriteExcludeHeader) 579 if err != nil { 580 return err 581 } 582 583 if extraHeaders != nil { 584 err = extraHeaders.Write(w) 585 if err != nil { 586 return err 587 } 588 } 589 590 _, err = io.WriteString(w, "\r\n") 591 if err != nil { 592 return err 593 } 594 595 if trace != nil && trace.WroteHeaders != nil { 596 trace.WroteHeaders() 597 } 598 599 // Flush and wait for 100-continue if expected. 600 if waitForContinue != nil { 601 if bw, ok := w.(*bufio.Writer); ok { 602 err = bw.Flush() 603 if err != nil { 604 return err 605 } 606 } 607 if trace != nil && trace.Wait100Continue != nil { 608 trace.Wait100Continue() 609 } 610 if !waitForContinue() { 611 r.closeBody() 612 return nil 613 } 614 } 615 616 if bw, ok := w.(*bufio.Writer); ok && tw.FlushHeaders { 617 if err := bw.Flush(); err != nil { 618 return err 619 } 620 } 621 622 // Write body and trailer 623 err = tw.WriteBody(w) 624 if err != nil { 625 if tw.bodyReadError == err { 626 err = requestBodyReadError{err} 627 } 628 return err 629 } 630 631 if bw != nil { 632 return bw.Flush() 633 } 634 return nil 635 } 636 637 // requestBodyReadError wraps an error from (*Request).write to indicate 638 // that the error came from a Read call on the Request.Body. 639 // This error type should not escape the net/http package to users. 640 type requestBodyReadError struct{ error } 641 642 func idnaASCII(v string) (string, error) { 643 // TODO: Consider removing this check after verifying performance is okay. 644 // Right now punycode verification, length checks, context checks, and the 645 // permissible character tests are all omitted. It also prevents the ToASCII 646 // call from salvaging an invalid IDN, when possible. As a result it may be 647 // possible to have two IDNs that appear identical to the user where the 648 // ASCII-only version causes an error downstream whereas the non-ASCII 649 // version does not. 650 // Note that for correct ASCII IDNs ToASCII will only do considerably more 651 // work, but it will not cause an allocation. 652 if isASCII(v) { 653 return v, nil 654 } 655 return idna.Lookup.ToASCII(v) 656 } 657 658 // cleanHost cleans up the host sent in request's Host header. 659 // 660 // It both strips anything after '/' or ' ', and puts the value 661 // into Punycode form, if necessary. 662 // 663 // Ideally we'd clean the Host header according to the spec: 664 // https://tools.ietf.org/html/rfc7230#section-5.4 (Host = uri-host [ ":" port ]") 665 // https://tools.ietf.org/html/rfc7230#section-2.7 (uri-host -> rfc3986's host) 666 // https://tools.ietf.org/html/rfc3986#section-3.2.2 (definition of host) 667 // But practically, what we are trying to avoid is the situation in 668 // issue 11206, where a malformed Host header used in the proxy context 669 // would create a bad request. So it is enough to just truncate at the 670 // first offending character. 671 func cleanHost(in string) string { 672 if i := strings.IndexAny(in, " /"); i != -1 { 673 in = in[:i] 674 } 675 host, port, err := net.SplitHostPort(in) 676 if err != nil { // input was just a host 677 a, err := idnaASCII(in) 678 if err != nil { 679 return in // garbage in, garbage out 680 } 681 return a 682 } 683 a, err := idnaASCII(host) 684 if err != nil { 685 return in // garbage in, garbage out 686 } 687 return net.JoinHostPort(a, port) 688 } 689 690 // removeZone removes IPv6 zone identifier from host. 691 // E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080" 692 func removeZone(host string) string { 693 if !strings.HasPrefix(host, "[") { 694 return host 695 } 696 i := strings.LastIndex(host, "]") 697 if i < 0 { 698 return host 699 } 700 j := strings.LastIndex(host[:i], "%") 701 if j < 0 { 702 return host 703 } 704 return host[:j] + host[i:] 705 } 706 707 // ParseHTTPVersion parses a HTTP version string. 708 // "HTTP/1.0" returns (1, 0, true). 709 func ParseHTTPVersion(vers string) (major, minor int, ok bool) { 710 const Big = 1000000 // arbitrary upper bound 711 switch vers { 712 case "HTTP/1.1": 713 return 1, 1, true 714 case "HTTP/1.0": 715 return 1, 0, true 716 } 717 if !strings.HasPrefix(vers, "HTTP/") { 718 return 0, 0, false 719 } 720 dot := strings.Index(vers, ".") 721 if dot < 0 { 722 return 0, 0, false 723 } 724 major, err := strconv.Atoi(vers[5:dot]) 725 if err != nil || major < 0 || major > Big { 726 return 0, 0, false 727 } 728 minor, err = strconv.Atoi(vers[dot+1:]) 729 if err != nil || minor < 0 || minor > Big { 730 return 0, 0, false 731 } 732 return major, minor, true 733 } 734 735 func validMethod(method string) bool { 736 /* 737 Method = "OPTIONS" ; Section 9.2 738 | "GET" ; Section 9.3 739 | "HEAD" ; Section 9.4 740 | "POST" ; Section 9.5 741 | "PUT" ; Section 9.6 742 | "DELETE" ; Section 9.7 743 | "TRACE" ; Section 9.8 744 | "CONNECT" ; Section 9.9 745 | extension-method 746 extension-method = token 747 token = 1*<any CHAR except CTLs or separators> 748 */ 749 return len(method) > 0 && strings.IndexFunc(method, isNotToken) == -1 750 } 751 752 // NewRequest returns a new Request given a method, URL, and optional body. 753 // 754 // If the provided body is also an io.Closer, the returned 755 // Request.Body is set to body and will be closed by the Client 756 // methods Do, Post, and PostForm, and Transport.RoundTrip. 757 // 758 // NewRequest returns a Request suitable for use with Client.Do or 759 // Transport.RoundTrip. To create a request for use with testing a 760 // Server Handler, either use the NewRequest function in the 761 // net/http/httptest package, use ReadRequest, or manually update the 762 // Request fields. See the Request type's documentation for the 763 // difference between inbound and outbound request fields. 764 // 765 // If body is of type *bytes.Buffer, *bytes.Reader, or 766 // *strings.Reader, the returned request's ContentLength is set to its 767 // exact value (instead of -1), GetBody is populated (so 307 and 308 768 // redirects can replay the body), and Body is set to NoBody if the 769 // ContentLength is 0. 770 func NewRequest(method, url string, body io.Reader) (*Request, error) { 771 if method == "" { 772 // We document that "" means "GET" for Request.Method, and people have 773 // relied on that from NewRequest, so keep that working. 774 // We still enforce validMethod for non-empty methods. 775 method = "GET" 776 } 777 if !validMethod(method) { 778 return nil, fmt.Errorf("net/http: invalid method %q", method) 779 } 780 u, err := parseURL(url) // Just url.Parse (url is shadowed for godoc). 781 if err != nil { 782 return nil, err 783 } 784 rc, ok := body.(io.ReadCloser) 785 if !ok && body != nil { 786 rc = ioutil.NopCloser(body) 787 } 788 // The host's colon:port should be normalized. See Issue 14836. 789 u.Host = removeEmptyPort(u.Host) 790 req := &Request{ 791 Method: method, 792 URL: u, 793 Proto: "HTTP/1.1", 794 ProtoMajor: 1, 795 ProtoMinor: 1, 796 Header: make(Header), 797 Body: rc, 798 Host: u.Host, 799 } 800 if body != nil { 801 switch v := body.(type) { 802 case *bytes.Buffer: 803 req.ContentLength = int64(v.Len()) 804 buf := v.Bytes() 805 req.GetBody = func() (io.ReadCloser, error) { 806 r := bytes.NewReader(buf) 807 return ioutil.NopCloser(r), nil 808 } 809 case *bytes.Reader: 810 req.ContentLength = int64(v.Len()) 811 snapshot := *v 812 req.GetBody = func() (io.ReadCloser, error) { 813 r := snapshot 814 return ioutil.NopCloser(&r), nil 815 } 816 case *strings.Reader: 817 req.ContentLength = int64(v.Len()) 818 snapshot := *v 819 req.GetBody = func() (io.ReadCloser, error) { 820 r := snapshot 821 return ioutil.NopCloser(&r), nil 822 } 823 default: 824 // This is where we'd set it to -1 (at least 825 // if body != NoBody) to mean unknown, but 826 // that broke people during the Go 1.8 testing 827 // period. People depend on it being 0 I 828 // guess. Maybe retry later. See Issue 18117. 829 } 830 // For client requests, Request.ContentLength of 0 831 // means either actually 0, or unknown. The only way 832 // to explicitly say that the ContentLength is zero is 833 // to set the Body to nil. But turns out too much code 834 // depends on NewRequest returning a non-nil Body, 835 // so we use a well-known ReadCloser variable instead 836 // and have the http package also treat that sentinel 837 // variable to mean explicitly zero. 838 if req.GetBody != nil && req.ContentLength == 0 { 839 req.Body = NoBody 840 req.GetBody = func() (io.ReadCloser, error) { return NoBody, nil } 841 } 842 } 843 844 return req, nil 845 } 846 847 // BasicAuth returns the username and password provided in the request's 848 // Authorization header, if the request uses HTTP Basic Authentication. 849 // See RFC 2617, Section 2. 850 func (r *Request) BasicAuth() (username, password string, ok bool) { 851 auth := r.Header.Get("Authorization") 852 if auth == "" { 853 return 854 } 855 return parseBasicAuth(auth) 856 } 857 858 // parseBasicAuth parses an HTTP Basic Authentication string. 859 // "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true). 860 func parseBasicAuth(auth string) (username, password string, ok bool) { 861 const prefix = "Basic " 862 if !strings.HasPrefix(auth, prefix) { 863 return 864 } 865 c, err := base64.StdEncoding.DecodeString(auth[len(prefix):]) 866 if err != nil { 867 return 868 } 869 cs := string(c) 870 s := strings.IndexByte(cs, ':') 871 if s < 0 { 872 return 873 } 874 return cs[:s], cs[s+1:], true 875 } 876 877 // SetBasicAuth sets the request's Authorization header to use HTTP 878 // Basic Authentication with the provided username and password. 879 // 880 // With HTTP Basic Authentication the provided username and password 881 // are not encrypted. 882 func (r *Request) SetBasicAuth(username, password string) { 883 r.Header.Set("Authorization", "Basic "+basicAuth(username, password)) 884 } 885 886 // parseRequestLine parses "GET /foo HTTP/1.1" into its three parts. 887 func parseRequestLine(line string) (method, requestURI, proto string, ok bool) { 888 s1 := strings.Index(line, " ") 889 s2 := strings.Index(line[s1+1:], " ") 890 if s1 < 0 || s2 < 0 { 891 return 892 } 893 s2 += s1 + 1 894 return line[:s1], line[s1+1 : s2], line[s2+1:], true 895 } 896 897 var textprotoReaderPool sync.Pool 898 899 func newTextprotoReader(br *bufio.Reader) *textproto.Reader { 900 if v := textprotoReaderPool.Get(); v != nil { 901 tr := v.(*textproto.Reader) 902 tr.R = br 903 return tr 904 } 905 return textproto.NewReader(br) 906 } 907 908 func putTextprotoReader(r *textproto.Reader) { 909 r.R = nil 910 textprotoReaderPool.Put(r) 911 } 912 913 // ReadRequest reads and parses an incoming request from b. 914 func ReadRequest(b *bufio.Reader) (*Request, error) { 915 return readRequest(b, deleteHostHeader) 916 } 917 918 // Constants for readRequest's deleteHostHeader parameter. 919 const ( 920 deleteHostHeader = true 921 keepHostHeader = false 922 ) 923 924 func readRequest(b *bufio.Reader, deleteHostHeader bool) (req *Request, err error) { 925 tp := newTextprotoReader(b) 926 req = new(Request) 927 928 // First line: GET /index.html HTTP/1.0 929 var s string 930 if s, err = tp.ReadLine(); err != nil { 931 return nil, err 932 } 933 defer func() { 934 putTextprotoReader(tp) 935 if err == io.EOF { 936 err = io.ErrUnexpectedEOF 937 } 938 }() 939 940 var ok bool 941 req.Method, req.RequestURI, req.Proto, ok = parseRequestLine(s) 942 if !ok { 943 return nil, &badStringError{"malformed HTTP request", s} 944 } 945 if !validMethod(req.Method) { 946 return nil, &badStringError{"invalid method", req.Method} 947 } 948 rawurl := req.RequestURI 949 if req.ProtoMajor, req.ProtoMinor, ok = ParseHTTPVersion(req.Proto); !ok { 950 return nil, &badStringError{"malformed HTTP version", req.Proto} 951 } 952 953 // CONNECT requests are used two different ways, and neither uses a full URL: 954 // The standard use is to tunnel HTTPS through an HTTP proxy. 955 // It looks like "CONNECT www.google.com:443 HTTP/1.1", and the parameter is 956 // just the authority section of a URL. This information should go in req.URL.Host. 957 // 958 // The net/rpc package also uses CONNECT, but there the parameter is a path 959 // that starts with a slash. It can be parsed with the regular URL parser, 960 // and the path will end up in req.URL.Path, where it needs to be in order for 961 // RPC to work. 962 justAuthority := req.Method == "CONNECT" && !strings.HasPrefix(rawurl, "/") 963 if justAuthority { 964 rawurl = "http://" + rawurl 965 } 966 967 if req.URL, err = url.ParseRequestURI(rawurl); err != nil { 968 return nil, err 969 } 970 971 if justAuthority { 972 // Strip the bogus "http://" back off. 973 req.URL.Scheme = "" 974 } 975 976 // Subsequent lines: Key: value. 977 mimeHeader, err := tp.ReadMIMEHeader() 978 if err != nil { 979 return nil, err 980 } 981 req.Header = Header(mimeHeader) 982 983 // RFC 2616: Must treat 984 // GET /index.html HTTP/1.1 985 // Host: www.google.com 986 // and 987 // GET http://www.google.com/index.html HTTP/1.1 988 // Host: doesntmatter 989 // the same. In the second case, any Host line is ignored. 990 req.Host = req.URL.Host 991 if req.Host == "" { 992 req.Host = req.Header.get("Host") 993 } 994 if deleteHostHeader { 995 delete(req.Header, "Host") 996 } 997 998 fixPragmaCacheControl(req.Header) 999 1000 req.Close = shouldClose(req.ProtoMajor, req.ProtoMinor, req.Header, false) 1001 1002 err = readTransfer(req, b) 1003 if err != nil { 1004 return nil, err 1005 } 1006 1007 if req.isH2Upgrade() { 1008 // Because it's neither chunked, nor declared: 1009 req.ContentLength = -1 1010 1011 // We want to give handlers a chance to hijack the 1012 // connection, but we need to prevent the Server from 1013 // dealing with the connection further if it's not 1014 // hijacked. Set Close to ensure that: 1015 req.Close = true 1016 } 1017 return req, nil 1018 } 1019 1020 // MaxBytesReader is similar to io.LimitReader but is intended for 1021 // limiting the size of incoming request bodies. In contrast to 1022 // io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a 1023 // non-EOF error for a Read beyond the limit, and closes the 1024 // underlying reader when its Close method is called. 1025 // 1026 // MaxBytesReader prevents clients from accidentally or maliciously 1027 // sending a large request and wasting server resources. 1028 func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser { 1029 return &maxBytesReader{w: w, r: r, n: n} 1030 } 1031 1032 type maxBytesReader struct { 1033 w ResponseWriter 1034 r io.ReadCloser // underlying reader 1035 n int64 // max bytes remaining 1036 err error // sticky error 1037 } 1038 1039 func (l *maxBytesReader) Read(p []byte) (n int, err error) { 1040 if l.err != nil { 1041 return 0, l.err 1042 } 1043 if len(p) == 0 { 1044 return 0, nil 1045 } 1046 // If they asked for a 32KB byte read but only 5 bytes are 1047 // remaining, no need to read 32KB. 6 bytes will answer the 1048 // question of the whether we hit the limit or go past it. 1049 if int64(len(p)) > l.n+1 { 1050 p = p[:l.n+1] 1051 } 1052 n, err = l.r.Read(p) 1053 1054 if int64(n) <= l.n { 1055 l.n -= int64(n) 1056 l.err = err 1057 return n, err 1058 } 1059 1060 n = int(l.n) 1061 l.n = 0 1062 1063 // The server code and client code both use 1064 // maxBytesReader. This "requestTooLarge" check is 1065 // only used by the server code. To prevent binaries 1066 // which only using the HTTP Client code (such as 1067 // cmd/go) from also linking in the HTTP server, don't 1068 // use a static type assertion to the server 1069 // "*response" type. Check this interface instead: 1070 type requestTooLarger interface { 1071 requestTooLarge() 1072 } 1073 if res, ok := l.w.(requestTooLarger); ok { 1074 res.requestTooLarge() 1075 } 1076 l.err = errors.New("http: request body too large") 1077 return n, l.err 1078 } 1079 1080 func (l *maxBytesReader) Close() error { 1081 return l.r.Close() 1082 } 1083 1084 func copyValues(dst, src url.Values) { 1085 for k, vs := range src { 1086 for _, value := range vs { 1087 dst.Add(k, value) 1088 } 1089 } 1090 } 1091 1092 func parsePostForm(r *Request) (vs url.Values, err error) { 1093 if r.Body == nil { 1094 err = errors.New("missing form body") 1095 return 1096 } 1097 ct := r.Header.Get("Content-Type") 1098 // RFC 2616, section 7.2.1 - empty type 1099 // SHOULD be treated as application/octet-stream 1100 if ct == "" { 1101 ct = "application/octet-stream" 1102 } 1103 ct, _, err = mime.ParseMediaType(ct) 1104 switch { 1105 case ct == "application/x-www-form-urlencoded": 1106 var reader io.Reader = r.Body 1107 maxFormSize := int64(1<<63 - 1) 1108 if _, ok := r.Body.(*maxBytesReader); !ok { 1109 maxFormSize = int64(10 << 20) // 10 MB is a lot of text. 1110 reader = io.LimitReader(r.Body, maxFormSize+1) 1111 } 1112 b, e := ioutil.ReadAll(reader) 1113 if e != nil { 1114 if err == nil { 1115 err = e 1116 } 1117 break 1118 } 1119 if int64(len(b)) > maxFormSize { 1120 err = errors.New("http: POST too large") 1121 return 1122 } 1123 vs, e = url.ParseQuery(string(b)) 1124 if err == nil { 1125 err = e 1126 } 1127 case ct == "multipart/form-data": 1128 // handled by ParseMultipartForm (which is calling us, or should be) 1129 // TODO(bradfitz): there are too many possible 1130 // orders to call too many functions here. 1131 // Clean this up and write more tests. 1132 // request_test.go contains the start of this, 1133 // in TestParseMultipartFormOrder and others. 1134 } 1135 return 1136 } 1137 1138 // ParseForm populates r.Form and r.PostForm. 1139 // 1140 // For all requests, ParseForm parses the raw query from the URL and updates 1141 // r.Form. 1142 // 1143 // For POST, PUT, and PATCH requests, it also parses the request body as a form 1144 // and puts the results into both r.PostForm and r.Form. Request body parameters 1145 // take precedence over URL query string values in r.Form. 1146 // 1147 // For other HTTP methods, or when the Content-Type is not 1148 // application/x-www-form-urlencoded, the request Body is not read, and 1149 // r.PostForm is initialized to a non-nil, empty value. 1150 // 1151 // If the request Body's size has not already been limited by MaxBytesReader, 1152 // the size is capped at 10MB. 1153 // 1154 // ParseMultipartForm calls ParseForm automatically. 1155 // ParseForm is idempotent. 1156 func (r *Request) ParseForm() error { 1157 var err error 1158 if r.PostForm == nil { 1159 if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" { 1160 r.PostForm, err = parsePostForm(r) 1161 } 1162 if r.PostForm == nil { 1163 r.PostForm = make(url.Values) 1164 } 1165 } 1166 if r.Form == nil { 1167 if len(r.PostForm) > 0 { 1168 r.Form = make(url.Values) 1169 copyValues(r.Form, r.PostForm) 1170 } 1171 var newValues url.Values 1172 if r.URL != nil { 1173 var e error 1174 newValues, e = url.ParseQuery(r.URL.RawQuery) 1175 if err == nil { 1176 err = e 1177 } 1178 } 1179 if newValues == nil { 1180 newValues = make(url.Values) 1181 } 1182 if r.Form == nil { 1183 r.Form = newValues 1184 } else { 1185 copyValues(r.Form, newValues) 1186 } 1187 } 1188 return err 1189 } 1190 1191 // ParseMultipartForm parses a request body as multipart/form-data. 1192 // The whole request body is parsed and up to a total of maxMemory bytes of 1193 // its file parts are stored in memory, with the remainder stored on 1194 // disk in temporary files. 1195 // ParseMultipartForm calls ParseForm if necessary. 1196 // After one call to ParseMultipartForm, subsequent calls have no effect. 1197 func (r *Request) ParseMultipartForm(maxMemory int64) error { 1198 if r.MultipartForm == multipartByReader { 1199 return errors.New("http: multipart handled by MultipartReader") 1200 } 1201 if r.Form == nil { 1202 err := r.ParseForm() 1203 if err != nil { 1204 return err 1205 } 1206 } 1207 if r.MultipartForm != nil { 1208 return nil 1209 } 1210 1211 mr, err := r.multipartReader() 1212 if err != nil { 1213 return err 1214 } 1215 1216 f, err := mr.ReadForm(maxMemory) 1217 if err != nil { 1218 return err 1219 } 1220 1221 if r.PostForm == nil { 1222 r.PostForm = make(url.Values) 1223 } 1224 for k, v := range f.Value { 1225 r.Form[k] = append(r.Form[k], v...) 1226 // r.PostForm should also be populated. See Issue 9305. 1227 r.PostForm[k] = append(r.PostForm[k], v...) 1228 } 1229 1230 r.MultipartForm = f 1231 1232 return nil 1233 } 1234 1235 // FormValue returns the first value for the named component of the query. 1236 // POST and PUT body parameters take precedence over URL query string values. 1237 // FormValue calls ParseMultipartForm and ParseForm if necessary and ignores 1238 // any errors returned by these functions. 1239 // If key is not present, FormValue returns the empty string. 1240 // To access multiple values of the same key, call ParseForm and 1241 // then inspect Request.Form directly. 1242 func (r *Request) FormValue(key string) string { 1243 if r.Form == nil { 1244 r.ParseMultipartForm(defaultMaxMemory) 1245 } 1246 if vs := r.Form[key]; len(vs) > 0 { 1247 return vs[0] 1248 } 1249 return "" 1250 } 1251 1252 // PostFormValue returns the first value for the named component of the POST 1253 // or PUT request body. URL query parameters are ignored. 1254 // PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores 1255 // any errors returned by these functions. 1256 // If key is not present, PostFormValue returns the empty string. 1257 func (r *Request) PostFormValue(key string) string { 1258 if r.PostForm == nil { 1259 r.ParseMultipartForm(defaultMaxMemory) 1260 } 1261 if vs := r.PostForm[key]; len(vs) > 0 { 1262 return vs[0] 1263 } 1264 return "" 1265 } 1266 1267 // FormFile returns the first file for the provided form key. 1268 // FormFile calls ParseMultipartForm and ParseForm if necessary. 1269 func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) { 1270 if r.MultipartForm == multipartByReader { 1271 return nil, nil, errors.New("http: multipart handled by MultipartReader") 1272 } 1273 if r.MultipartForm == nil { 1274 err := r.ParseMultipartForm(defaultMaxMemory) 1275 if err != nil { 1276 return nil, nil, err 1277 } 1278 } 1279 if r.MultipartForm != nil && r.MultipartForm.File != nil { 1280 if fhs := r.MultipartForm.File[key]; len(fhs) > 0 { 1281 f, err := fhs[0].Open() 1282 return f, fhs[0], err 1283 } 1284 } 1285 return nil, nil, ErrMissingFile 1286 } 1287 1288 func (r *Request) expectsContinue() bool { 1289 return hasToken(r.Header.get("Expect"), "100-continue") 1290 } 1291 1292 func (r *Request) wantsHttp10KeepAlive() bool { 1293 if r.ProtoMajor != 1 || r.ProtoMinor != 0 { 1294 return false 1295 } 1296 return hasToken(r.Header.get("Connection"), "keep-alive") 1297 } 1298 1299 func (r *Request) wantsClose() bool { 1300 return hasToken(r.Header.get("Connection"), "close") 1301 } 1302 1303 func (r *Request) closeBody() { 1304 if r.Body != nil { 1305 r.Body.Close() 1306 } 1307 } 1308 1309 func (r *Request) isReplayable() bool { 1310 if r.Body == nil || r.Body == NoBody || r.GetBody != nil { 1311 switch valueOrDefault(r.Method, "GET") { 1312 case "GET", "HEAD", "OPTIONS", "TRACE": 1313 return true 1314 } 1315 } 1316 return false 1317 } 1318 1319 // outgoingLength reports the Content-Length of this outgoing (Client) request. 1320 // It maps 0 into -1 (unknown) when the Body is non-nil. 1321 func (r *Request) outgoingLength() int64 { 1322 if r.Body == nil || r.Body == NoBody { 1323 return 0 1324 } 1325 if r.ContentLength != 0 { 1326 return r.ContentLength 1327 } 1328 return -1 1329 } 1330 1331 // requestMethodUsuallyLacksBody reports whether the given request 1332 // method is one that typically does not involve a request body. 1333 // This is used by the Transport (via 1334 // transferWriter.shouldSendChunkedRequestBody) to determine whether 1335 // we try to test-read a byte from a non-nil Request.Body when 1336 // Request.outgoingLength() returns -1. See the comments in 1337 // shouldSendChunkedRequestBody. 1338 func requestMethodUsuallyLacksBody(method string) bool { 1339 switch method { 1340 case "GET", "HEAD", "DELETE", "OPTIONS", "PROPFIND", "SEARCH": 1341 return true 1342 } 1343 return false 1344 }