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