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