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