github.com/ooni/oohttp@v0.7.2/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/textproto"
    21  	"net/url"
    22  	urlpkg "net/url"
    23  	"strconv"
    24  	"strings"
    25  	"sync"
    26  
    27  	httptrace "github.com/ooni/oohttp/httptrace"
    28  	ascii "github.com/ooni/oohttp/internal/ascii"
    29  	"golang.org/x/net/http/httpguts"
    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 := r.Host
   584  	if host == "" {
   585  		if r.URL == nil {
   586  			return errMissingHost
   587  		}
   588  		host = r.URL.Host
   589  	}
   590  	host, err = httpguts.PunycodeHostPort(host)
   591  	if err != nil {
   592  		return err
   593  	}
   594  	// Validate that the Host header is a valid header in general,
   595  	// but don't validate the host itself. This is sufficient to avoid
   596  	// header or request smuggling via the Host field.
   597  	// The server can (and will, if it's a net/http server) reject
   598  	// the request if it doesn't consider the host valid.
   599  	if !httpguts.ValidHostHeader(host) {
   600  		// Historically, we would truncate the Host header after '/' or ' '.
   601  		// Some users have relied on this truncation to convert a network
   602  		// address such as Unix domain socket path into a valid, ignored
   603  		// Host header (see https://go.dev/issue/61431).
   604  		//
   605  		// We don't preserve the truncation, because sending an altered
   606  		// header field opens a smuggling vector. Instead, zero out the
   607  		// Host header entirely if it isn't valid. (An empty Host is valid;
   608  		// see RFC 9112 Section 3.2.)
   609  		//
   610  		// Return an error if we're sending to a proxy, since the proxy
   611  		// probably can't do anything useful with an empty Host header.
   612  		if !usingProxy {
   613  			host = ""
   614  		} else {
   615  			return errors.New("http: invalid Host header")
   616  		}
   617  	}
   618  
   619  	// According to RFC 6874, an HTTP client, proxy, or other
   620  	// intermediary must remove any IPv6 zone identifier attached
   621  	// to an outgoing URI.
   622  	host = removeZone(host)
   623  
   624  	ruri := r.URL.RequestURI()
   625  	if usingProxy && r.URL.Scheme != "" && r.URL.Opaque == "" {
   626  		ruri = r.URL.Scheme + "://" + host + ruri
   627  	} else if r.Method == "CONNECT" && r.URL.Path == "" {
   628  		// CONNECT requests normally give just the host and port, not a full URL.
   629  		ruri = host
   630  		if r.URL.Opaque != "" {
   631  			ruri = r.URL.Opaque
   632  		}
   633  	}
   634  	if stringContainsCTLByte(ruri) {
   635  		return errors.New("net/http: can't write control character in Request.URL")
   636  	}
   637  	// TODO: validate r.Method too? At least it's less likely to
   638  	// come from an attacker (more likely to be a constant in
   639  	// code).
   640  
   641  	// Wrap the writer in a bufio Writer if it's not already buffered.
   642  	// Don't always call NewWriter, as that forces a bytes.Buffer
   643  	// and other small bufio Writers to have a minimum 4k buffer
   644  	// size.
   645  	var bw *bufio.Writer
   646  	if _, ok := w.(io.ByteWriter); !ok {
   647  		bw = bufio.NewWriter(w)
   648  		w = bw
   649  	}
   650  
   651  	_, err = fmt.Fprintf(w, "%s %s HTTP/1.1\r\n", valueOrDefault(r.Method, "GET"), ruri)
   652  	if err != nil {
   653  		return err
   654  	}
   655  
   656  	// Header lines
   657  	_, err = fmt.Fprintf(w, "Host: %s\r\n", host)
   658  	if err != nil {
   659  		return err
   660  	}
   661  	if trace != nil && trace.WroteHeaderField != nil {
   662  		trace.WroteHeaderField("Host", []string{host})
   663  	}
   664  
   665  	// Use the defaultUserAgent unless the Header contains one, which
   666  	// may be blank to not send the header.
   667  	userAgent := defaultUserAgent
   668  	if r.Header.has("User-Agent") {
   669  		userAgent = r.Header.Get("User-Agent")
   670  	}
   671  	if userAgent != "" {
   672  		_, err = fmt.Fprintf(w, "User-Agent: %s\r\n", userAgent)
   673  		if err != nil {
   674  			return err
   675  		}
   676  		if trace != nil && trace.WroteHeaderField != nil {
   677  			trace.WroteHeaderField("User-Agent", []string{userAgent})
   678  		}
   679  	}
   680  
   681  	// Process Body,ContentLength,Close,Trailer
   682  	tw, err := newTransferWriter(r)
   683  	if err != nil {
   684  		return err
   685  	}
   686  	err = tw.writeHeader(w, trace)
   687  	if err != nil {
   688  		return err
   689  	}
   690  
   691  	err = r.Header.writeSubset(w, reqWriteExcludeHeader, trace)
   692  	if err != nil {
   693  		return err
   694  	}
   695  
   696  	if extraHeaders != nil {
   697  		err = extraHeaders.write(w, trace)
   698  		if err != nil {
   699  			return err
   700  		}
   701  	}
   702  
   703  	_, err = io.WriteString(w, "\r\n")
   704  	if err != nil {
   705  		return err
   706  	}
   707  
   708  	if trace != nil && trace.WroteHeaders != nil {
   709  		trace.WroteHeaders()
   710  	}
   711  
   712  	// Flush and wait for 100-continue if expected.
   713  	if waitForContinue != nil {
   714  		if bw, ok := w.(*bufio.Writer); ok {
   715  			err = bw.Flush()
   716  			if err != nil {
   717  				return err
   718  			}
   719  		}
   720  		if trace != nil && trace.Wait100Continue != nil {
   721  			trace.Wait100Continue()
   722  		}
   723  		if !waitForContinue() {
   724  			closed = true
   725  			r.closeBody()
   726  			return nil
   727  		}
   728  	}
   729  
   730  	if bw, ok := w.(*bufio.Writer); ok && tw.FlushHeaders {
   731  		if err := bw.Flush(); err != nil {
   732  			return err
   733  		}
   734  	}
   735  
   736  	// Write body and trailer
   737  	closed = true
   738  	err = tw.writeBody(w)
   739  	if err != nil {
   740  		if tw.bodyReadError == err {
   741  			err = requestBodyReadError{err}
   742  		}
   743  		return err
   744  	}
   745  
   746  	if bw != nil {
   747  		return bw.Flush()
   748  	}
   749  	return nil
   750  }
   751  
   752  // requestBodyReadError wraps an error from (*Request).write to indicate
   753  // that the error came from a Read call on the Request.Body.
   754  // This error type should not escape the net/http package to users.
   755  type requestBodyReadError struct{ error }
   756  
   757  func idnaASCII(v string) (string, error) {
   758  	// TODO: Consider removing this check after verifying performance is okay.
   759  	// Right now punycode verification, length checks, context checks, and the
   760  	// permissible character tests are all omitted. It also prevents the ToASCII
   761  	// call from salvaging an invalid IDN, when possible. As a result it may be
   762  	// possible to have two IDNs that appear identical to the user where the
   763  	// ASCII-only version causes an error downstream whereas the non-ASCII
   764  	// version does not.
   765  	// Note that for correct ASCII IDNs ToASCII will only do considerably more
   766  	// work, but it will not cause an allocation.
   767  	if ascii.Is(v) {
   768  		return v, nil
   769  	}
   770  	return idna.Lookup.ToASCII(v)
   771  }
   772  
   773  // removeZone removes IPv6 zone identifier from host.
   774  // E.g., "[fe80::1%en0]:8080" to "[fe80::1]:8080"
   775  func removeZone(host string) string {
   776  	if !strings.HasPrefix(host, "[") {
   777  		return host
   778  	}
   779  	i := strings.LastIndex(host, "]")
   780  	if i < 0 {
   781  		return host
   782  	}
   783  	j := strings.LastIndex(host[:i], "%")
   784  	if j < 0 {
   785  		return host
   786  	}
   787  	return host[:j] + host[i:]
   788  }
   789  
   790  // ParseHTTPVersion parses an HTTP version string according to RFC 7230, section 2.6.
   791  // "HTTP/1.0" returns (1, 0, true). Note that strings without
   792  // a minor version, such as "HTTP/2", are not valid.
   793  func ParseHTTPVersion(vers string) (major, minor int, ok bool) {
   794  	switch vers {
   795  	case "HTTP/1.1":
   796  		return 1, 1, true
   797  	case "HTTP/1.0":
   798  		return 1, 0, true
   799  	}
   800  	if !strings.HasPrefix(vers, "HTTP/") {
   801  		return 0, 0, false
   802  	}
   803  	if len(vers) != len("HTTP/X.Y") {
   804  		return 0, 0, false
   805  	}
   806  	if vers[6] != '.' {
   807  		return 0, 0, false
   808  	}
   809  	maj, err := strconv.ParseUint(vers[5:6], 10, 0)
   810  	if err != nil {
   811  		return 0, 0, false
   812  	}
   813  	min, err := strconv.ParseUint(vers[7:8], 10, 0)
   814  	if err != nil {
   815  		return 0, 0, false
   816  	}
   817  	return int(maj), int(min), true
   818  }
   819  
   820  func validMethod(method string) bool {
   821  	/*
   822  	     Method         = "OPTIONS"                ; Section 9.2
   823  	                    | "GET"                    ; Section 9.3
   824  	                    | "HEAD"                   ; Section 9.4
   825  	                    | "POST"                   ; Section 9.5
   826  	                    | "PUT"                    ; Section 9.6
   827  	                    | "DELETE"                 ; Section 9.7
   828  	                    | "TRACE"                  ; Section 9.8
   829  	                    | "CONNECT"                ; Section 9.9
   830  	                    | extension-method
   831  	   extension-method = token
   832  	     token          = 1*<any CHAR except CTLs or separators>
   833  	*/
   834  	return len(method) > 0 && strings.IndexFunc(method, isNotToken) == -1
   835  }
   836  
   837  // NewRequest wraps NewRequestWithContext using context.Background.
   838  func NewRequest(method, url string, body io.Reader) (*Request, error) {
   839  	return NewRequestWithContext(context.Background(), method, url, body)
   840  }
   841  
   842  // NewRequestWithContext returns a new Request given a method, URL, and
   843  // optional body.
   844  //
   845  // If the provided body is also an io.Closer, the returned
   846  // Request.Body is set to body and will be closed by the Client
   847  // methods Do, Post, and PostForm, and Transport.RoundTrip.
   848  //
   849  // NewRequestWithContext returns a Request suitable for use with
   850  // Client.Do or Transport.RoundTrip. To create a request for use with
   851  // testing a Server Handler, either use the NewRequest function in the
   852  // net/http/httptest package, use ReadRequest, or manually update the
   853  // Request fields. For an outgoing client request, the context
   854  // controls the entire lifetime of a request and its response:
   855  // obtaining a connection, sending the request, and reading the
   856  // response headers and body. See the Request type's documentation for
   857  // the difference between inbound and outbound request fields.
   858  //
   859  // If body is of type *bytes.Buffer, *bytes.Reader, or
   860  // *strings.Reader, the returned request's ContentLength is set to its
   861  // exact value (instead of -1), GetBody is populated (so 307 and 308
   862  // redirects can replay the body), and Body is set to NoBody if the
   863  // ContentLength is 0.
   864  func NewRequestWithContext(ctx context.Context, method, url string, body io.Reader) (*Request, error) {
   865  	if method == "" {
   866  		// We document that "" means "GET" for Request.Method, and people have
   867  		// relied on that from NewRequest, so keep that working.
   868  		// We still enforce validMethod for non-empty methods.
   869  		method = "GET"
   870  	}
   871  	if !validMethod(method) {
   872  		return nil, fmt.Errorf("net/http: invalid method %q", method)
   873  	}
   874  	if ctx == nil {
   875  		return nil, errors.New("net/http: nil Context")
   876  	}
   877  	u, err := urlpkg.Parse(url)
   878  	if err != nil {
   879  		return nil, err
   880  	}
   881  	rc, ok := body.(io.ReadCloser)
   882  	if !ok && body != nil {
   883  		rc = io.NopCloser(body)
   884  	}
   885  	// The host's colon:port should be normalized. See Issue 14836.
   886  	u.Host = removeEmptyPort(u.Host)
   887  	req := &Request{
   888  		ctx:        ctx,
   889  		Method:     method,
   890  		URL:        u,
   891  		Proto:      "HTTP/1.1",
   892  		ProtoMajor: 1,
   893  		ProtoMinor: 1,
   894  		Header:     make(Header),
   895  		Body:       rc,
   896  		Host:       u.Host,
   897  	}
   898  	if body != nil {
   899  		switch v := body.(type) {
   900  		case *bytes.Buffer:
   901  			req.ContentLength = int64(v.Len())
   902  			buf := v.Bytes()
   903  			req.GetBody = func() (io.ReadCloser, error) {
   904  				r := bytes.NewReader(buf)
   905  				return io.NopCloser(r), nil
   906  			}
   907  		case *bytes.Reader:
   908  			req.ContentLength = int64(v.Len())
   909  			snapshot := *v
   910  			req.GetBody = func() (io.ReadCloser, error) {
   911  				r := snapshot
   912  				return io.NopCloser(&r), nil
   913  			}
   914  		case *strings.Reader:
   915  			req.ContentLength = int64(v.Len())
   916  			snapshot := *v
   917  			req.GetBody = func() (io.ReadCloser, error) {
   918  				r := snapshot
   919  				return io.NopCloser(&r), nil
   920  			}
   921  		default:
   922  			// This is where we'd set it to -1 (at least
   923  			// if body != NoBody) to mean unknown, but
   924  			// that broke people during the Go 1.8 testing
   925  			// period. People depend on it being 0 I
   926  			// guess. Maybe retry later. See Issue 18117.
   927  		}
   928  		// For client requests, Request.ContentLength of 0
   929  		// means either actually 0, or unknown. The only way
   930  		// to explicitly say that the ContentLength is zero is
   931  		// to set the Body to nil. But turns out too much code
   932  		// depends on NewRequest returning a non-nil Body,
   933  		// so we use a well-known ReadCloser variable instead
   934  		// and have the http package also treat that sentinel
   935  		// variable to mean explicitly zero.
   936  		if req.GetBody != nil && req.ContentLength == 0 {
   937  			req.Body = NoBody
   938  			req.GetBody = func() (io.ReadCloser, error) { return NoBody, nil }
   939  		}
   940  	}
   941  
   942  	return req, nil
   943  }
   944  
   945  // BasicAuth returns the username and password provided in the request's
   946  // Authorization header, if the request uses HTTP Basic Authentication.
   947  // See RFC 2617, Section 2.
   948  func (r *Request) BasicAuth() (username, password string, ok bool) {
   949  	auth := r.Header.Get("Authorization")
   950  	if auth == "" {
   951  		return "", "", false
   952  	}
   953  	return parseBasicAuth(auth)
   954  }
   955  
   956  // parseBasicAuth parses an HTTP Basic Authentication string.
   957  // "Basic QWxhZGRpbjpvcGVuIHNlc2FtZQ==" returns ("Aladdin", "open sesame", true).
   958  func parseBasicAuth(auth string) (username, password string, ok bool) {
   959  	const prefix = "Basic "
   960  	// Case insensitive prefix match. See Issue 22736.
   961  	if len(auth) < len(prefix) || !ascii.EqualFold(auth[:len(prefix)], prefix) {
   962  		return "", "", false
   963  	}
   964  	c, err := base64.StdEncoding.DecodeString(auth[len(prefix):])
   965  	if err != nil {
   966  		return "", "", false
   967  	}
   968  	cs := string(c)
   969  	username, password, ok = strings.Cut(cs, ":")
   970  	if !ok {
   971  		return "", "", false
   972  	}
   973  	return username, password, true
   974  }
   975  
   976  // SetBasicAuth sets the request's Authorization header to use HTTP
   977  // Basic Authentication with the provided username and password.
   978  //
   979  // With HTTP Basic Authentication the provided username and password
   980  // are not encrypted. It should generally only be used in an HTTPS
   981  // request.
   982  //
   983  // The username may not contain a colon. Some protocols may impose
   984  // additional requirements on pre-escaping the username and
   985  // password. For instance, when used with OAuth2, both arguments must
   986  // be URL encoded first with url.QueryEscape.
   987  func (r *Request) SetBasicAuth(username, password string) {
   988  	r.Header.Set("Authorization", "Basic "+basicAuth(username, password))
   989  }
   990  
   991  // parseRequestLine parses "GET /foo HTTP/1.1" into its three parts.
   992  func parseRequestLine(line string) (method, requestURI, proto string, ok bool) {
   993  	method, rest, ok1 := strings.Cut(line, " ")
   994  	requestURI, proto, ok2 := strings.Cut(rest, " ")
   995  	if !ok1 || !ok2 {
   996  		return "", "", "", false
   997  	}
   998  	return method, requestURI, proto, true
   999  }
  1000  
  1001  var textprotoReaderPool sync.Pool
  1002  
  1003  func newTextprotoReader(br *bufio.Reader) *textproto.Reader {
  1004  	if v := textprotoReaderPool.Get(); v != nil {
  1005  		tr := v.(*textproto.Reader)
  1006  		tr.R = br
  1007  		return tr
  1008  	}
  1009  	return textproto.NewReader(br)
  1010  }
  1011  
  1012  func putTextprotoReader(r *textproto.Reader) {
  1013  	r.R = nil
  1014  	textprotoReaderPool.Put(r)
  1015  }
  1016  
  1017  // ReadRequest reads and parses an incoming request from b.
  1018  //
  1019  // ReadRequest is a low-level function and should only be used for
  1020  // specialized applications; most code should use the Server to read
  1021  // requests and handle them via the Handler interface. ReadRequest
  1022  // only supports HTTP/1.x requests. For HTTP/2, use golang.org/x/net/http2.
  1023  func ReadRequest(b *bufio.Reader) (*Request, error) {
  1024  	req, err := readRequest(b)
  1025  	if err != nil {
  1026  		return nil, err
  1027  	}
  1028  
  1029  	delete(req.Header, "Host")
  1030  	return req, err
  1031  }
  1032  
  1033  func readRequest(b *bufio.Reader) (req *Request, err error) {
  1034  	tp := newTextprotoReader(b)
  1035  	defer putTextprotoReader(tp)
  1036  
  1037  	req = new(Request)
  1038  
  1039  	// First line: GET /index.html HTTP/1.0
  1040  	var s string
  1041  	if s, err = tp.ReadLine(); err != nil {
  1042  		return nil, err
  1043  	}
  1044  	defer func() {
  1045  		if err == io.EOF {
  1046  			err = io.ErrUnexpectedEOF
  1047  		}
  1048  	}()
  1049  
  1050  	var ok bool
  1051  	req.Method, req.RequestURI, req.Proto, ok = parseRequestLine(s)
  1052  	if !ok {
  1053  		return nil, badStringError("malformed HTTP request", s)
  1054  	}
  1055  	if !validMethod(req.Method) {
  1056  		return nil, badStringError("invalid method", req.Method)
  1057  	}
  1058  	rawurl := req.RequestURI
  1059  	if req.ProtoMajor, req.ProtoMinor, ok = ParseHTTPVersion(req.Proto); !ok {
  1060  		return nil, badStringError("malformed HTTP version", req.Proto)
  1061  	}
  1062  
  1063  	// CONNECT requests are used two different ways, and neither uses a full URL:
  1064  	// The standard use is to tunnel HTTPS through an HTTP proxy.
  1065  	// It looks like "CONNECT www.google.com:443 HTTP/1.1", and the parameter is
  1066  	// just the authority section of a URL. This information should go in req.URL.Host.
  1067  	//
  1068  	// The net/rpc package also uses CONNECT, but there the parameter is a path
  1069  	// that starts with a slash. It can be parsed with the regular URL parser,
  1070  	// and the path will end up in req.URL.Path, where it needs to be in order for
  1071  	// RPC to work.
  1072  	justAuthority := req.Method == "CONNECT" && !strings.HasPrefix(rawurl, "/")
  1073  	if justAuthority {
  1074  		rawurl = "http://" + rawurl
  1075  	}
  1076  
  1077  	if req.URL, err = url.ParseRequestURI(rawurl); err != nil {
  1078  		return nil, err
  1079  	}
  1080  
  1081  	if justAuthority {
  1082  		// Strip the bogus "http://" back off.
  1083  		req.URL.Scheme = ""
  1084  	}
  1085  
  1086  	// Subsequent lines: Key: value.
  1087  	mimeHeader, err := tp.ReadMIMEHeader()
  1088  	if err != nil {
  1089  		return nil, err
  1090  	}
  1091  	req.Header = Header(mimeHeader)
  1092  	if len(req.Header["Host"]) > 1 {
  1093  		return nil, fmt.Errorf("too many Host headers")
  1094  	}
  1095  
  1096  	// RFC 7230, section 5.3: Must treat
  1097  	//	GET /index.html HTTP/1.1
  1098  	//	Host: www.google.com
  1099  	// and
  1100  	//	GET http://www.google.com/index.html HTTP/1.1
  1101  	//	Host: doesntmatter
  1102  	// the same. In the second case, any Host line is ignored.
  1103  	req.Host = req.URL.Host
  1104  	if req.Host == "" {
  1105  		req.Host = req.Header.get("Host")
  1106  	}
  1107  
  1108  	fixPragmaCacheControl(req.Header)
  1109  
  1110  	req.Close = shouldClose(req.ProtoMajor, req.ProtoMinor, req.Header, false)
  1111  
  1112  	err = readTransfer(req, b)
  1113  	if err != nil {
  1114  		return nil, err
  1115  	}
  1116  
  1117  	if req.isH2Upgrade() {
  1118  		// Because it's neither chunked, nor declared:
  1119  		req.ContentLength = -1
  1120  
  1121  		// We want to give handlers a chance to hijack the
  1122  		// connection, but we need to prevent the Server from
  1123  		// dealing with the connection further if it's not
  1124  		// hijacked. Set Close to ensure that:
  1125  		req.Close = true
  1126  	}
  1127  	return req, nil
  1128  }
  1129  
  1130  // MaxBytesReader is similar to io.LimitReader but is intended for
  1131  // limiting the size of incoming request bodies. In contrast to
  1132  // io.LimitReader, MaxBytesReader's result is a ReadCloser, returns a
  1133  // non-nil error of type *MaxBytesError for a Read beyond the limit,
  1134  // and closes the underlying reader when its Close method is called.
  1135  //
  1136  // MaxBytesReader prevents clients from accidentally or maliciously
  1137  // sending a large request and wasting server resources. If possible,
  1138  // it tells the ResponseWriter to close the connection after the limit
  1139  // has been reached.
  1140  func MaxBytesReader(w ResponseWriter, r io.ReadCloser, n int64) io.ReadCloser {
  1141  	if n < 0 { // Treat negative limits as equivalent to 0.
  1142  		n = 0
  1143  	}
  1144  	return &maxBytesReader{w: w, r: r, i: n, n: n}
  1145  }
  1146  
  1147  // MaxBytesError is returned by MaxBytesReader when its read limit is exceeded.
  1148  type MaxBytesError struct {
  1149  	Limit int64
  1150  }
  1151  
  1152  func (e *MaxBytesError) Error() string {
  1153  	// Due to Hyrum's law, this text cannot be changed.
  1154  	return "http: request body too large"
  1155  }
  1156  
  1157  type maxBytesReader struct {
  1158  	w   ResponseWriter
  1159  	r   io.ReadCloser // underlying reader
  1160  	i   int64         // max bytes initially, for MaxBytesError
  1161  	n   int64         // max bytes remaining
  1162  	err error         // sticky error
  1163  }
  1164  
  1165  func (l *maxBytesReader) Read(p []byte) (n int, err error) {
  1166  	if l.err != nil {
  1167  		return 0, l.err
  1168  	}
  1169  	if len(p) == 0 {
  1170  		return 0, nil
  1171  	}
  1172  	// If they asked for a 32KB byte read but only 5 bytes are
  1173  	// remaining, no need to read 32KB. 6 bytes will answer the
  1174  	// question of the whether we hit the limit or go past it.
  1175  	// 0 < len(p) < 2^63
  1176  	if int64(len(p))-1 > l.n {
  1177  		p = p[:l.n+1]
  1178  	}
  1179  	n, err = l.r.Read(p)
  1180  
  1181  	if int64(n) <= l.n {
  1182  		l.n -= int64(n)
  1183  		l.err = err
  1184  		return n, err
  1185  	}
  1186  
  1187  	n = int(l.n)
  1188  	l.n = 0
  1189  
  1190  	// The server code and client code both use
  1191  	// maxBytesReader. This "requestTooLarge" check is
  1192  	// only used by the server code. To prevent binaries
  1193  	// which only using the HTTP Client code (such as
  1194  	// cmd/go) from also linking in the HTTP server, don't
  1195  	// use a static type assertion to the server
  1196  	// "*response" type. Check this interface instead:
  1197  	type requestTooLarger interface {
  1198  		requestTooLarge()
  1199  	}
  1200  	if res, ok := l.w.(requestTooLarger); ok {
  1201  		res.requestTooLarge()
  1202  	}
  1203  	l.err = &MaxBytesError{l.i}
  1204  	return n, l.err
  1205  }
  1206  
  1207  func (l *maxBytesReader) Close() error {
  1208  	return l.r.Close()
  1209  }
  1210  
  1211  func copyValues(dst, src url.Values) {
  1212  	for k, vs := range src {
  1213  		dst[k] = append(dst[k], vs...)
  1214  	}
  1215  }
  1216  
  1217  func parsePostForm(r *Request) (vs url.Values, err error) {
  1218  	if r.Body == nil {
  1219  		err = errors.New("missing form body")
  1220  		return
  1221  	}
  1222  	ct := r.Header.Get("Content-Type")
  1223  	// RFC 7231, section 3.1.1.5 - empty type
  1224  	//   MAY be treated as application/octet-stream
  1225  	if ct == "" {
  1226  		ct = "application/octet-stream"
  1227  	}
  1228  	ct, _, err = mime.ParseMediaType(ct)
  1229  	switch {
  1230  	case ct == "application/x-www-form-urlencoded":
  1231  		var reader io.Reader = r.Body
  1232  		maxFormSize := int64(1<<63 - 1)
  1233  		if _, ok := r.Body.(*maxBytesReader); !ok {
  1234  			maxFormSize = int64(10 << 20) // 10 MB is a lot of text.
  1235  			reader = io.LimitReader(r.Body, maxFormSize+1)
  1236  		}
  1237  		b, e := io.ReadAll(reader)
  1238  		if e != nil {
  1239  			if err == nil {
  1240  				err = e
  1241  			}
  1242  			break
  1243  		}
  1244  		if int64(len(b)) > maxFormSize {
  1245  			err = errors.New("http: POST too large")
  1246  			return
  1247  		}
  1248  		vs, e = url.ParseQuery(string(b))
  1249  		if err == nil {
  1250  			err = e
  1251  		}
  1252  	case ct == "multipart/form-data":
  1253  		// handled by ParseMultipartForm (which is calling us, or should be)
  1254  		// TODO(bradfitz): there are too many possible
  1255  		// orders to call too many functions here.
  1256  		// Clean this up and write more tests.
  1257  		// request_test.go contains the start of this,
  1258  		// in TestParseMultipartFormOrder and others.
  1259  	}
  1260  	return
  1261  }
  1262  
  1263  // ParseForm populates r.Form and r.PostForm.
  1264  //
  1265  // For all requests, ParseForm parses the raw query from the URL and updates
  1266  // r.Form.
  1267  //
  1268  // For POST, PUT, and PATCH requests, it also reads the request body, parses it
  1269  // as a form and puts the results into both r.PostForm and r.Form. Request body
  1270  // parameters take precedence over URL query string values in r.Form.
  1271  //
  1272  // If the request Body's size has not already been limited by MaxBytesReader,
  1273  // the size is capped at 10MB.
  1274  //
  1275  // For other HTTP methods, or when the Content-Type is not
  1276  // application/x-www-form-urlencoded, the request Body is not read, and
  1277  // r.PostForm is initialized to a non-nil, empty value.
  1278  //
  1279  // ParseMultipartForm calls ParseForm automatically.
  1280  // ParseForm is idempotent.
  1281  func (r *Request) ParseForm() error {
  1282  	var err error
  1283  	if r.PostForm == nil {
  1284  		if r.Method == "POST" || r.Method == "PUT" || r.Method == "PATCH" {
  1285  			r.PostForm, err = parsePostForm(r)
  1286  		}
  1287  		if r.PostForm == nil {
  1288  			r.PostForm = make(url.Values)
  1289  		}
  1290  	}
  1291  	if r.Form == nil {
  1292  		if len(r.PostForm) > 0 {
  1293  			r.Form = make(url.Values)
  1294  			copyValues(r.Form, r.PostForm)
  1295  		}
  1296  		var newValues url.Values
  1297  		if r.URL != nil {
  1298  			var e error
  1299  			newValues, e = url.ParseQuery(r.URL.RawQuery)
  1300  			if err == nil {
  1301  				err = e
  1302  			}
  1303  		}
  1304  		if newValues == nil {
  1305  			newValues = make(url.Values)
  1306  		}
  1307  		if r.Form == nil {
  1308  			r.Form = newValues
  1309  		} else {
  1310  			copyValues(r.Form, newValues)
  1311  		}
  1312  	}
  1313  	return err
  1314  }
  1315  
  1316  // ParseMultipartForm parses a request body as multipart/form-data.
  1317  // The whole request body is parsed and up to a total of maxMemory bytes of
  1318  // its file parts are stored in memory, with the remainder stored on
  1319  // disk in temporary files.
  1320  // ParseMultipartForm calls ParseForm if necessary.
  1321  // If ParseForm returns an error, ParseMultipartForm returns it but also
  1322  // continues parsing the request body.
  1323  // After one call to ParseMultipartForm, subsequent calls have no effect.
  1324  func (r *Request) ParseMultipartForm(maxMemory int64) error {
  1325  	if r.MultipartForm == multipartByReader {
  1326  		return errors.New("http: multipart handled by MultipartReader")
  1327  	}
  1328  	var parseFormErr error
  1329  	if r.Form == nil {
  1330  		// Let errors in ParseForm fall through, and just
  1331  		// return it at the end.
  1332  		parseFormErr = r.ParseForm()
  1333  	}
  1334  	if r.MultipartForm != nil {
  1335  		return nil
  1336  	}
  1337  
  1338  	mr, err := r.multipartReader(false)
  1339  	if err != nil {
  1340  		return err
  1341  	}
  1342  
  1343  	f, err := mr.ReadForm(maxMemory)
  1344  	if err != nil {
  1345  		return err
  1346  	}
  1347  
  1348  	if r.PostForm == nil {
  1349  		r.PostForm = make(url.Values)
  1350  	}
  1351  	for k, v := range f.Value {
  1352  		r.Form[k] = append(r.Form[k], v...)
  1353  		// r.PostForm should also be populated. See Issue 9305.
  1354  		r.PostForm[k] = append(r.PostForm[k], v...)
  1355  	}
  1356  
  1357  	r.MultipartForm = f
  1358  
  1359  	return parseFormErr
  1360  }
  1361  
  1362  // FormValue returns the first value for the named component of the query.
  1363  // POST and PUT body parameters take precedence over URL query string values.
  1364  // FormValue calls ParseMultipartForm and ParseForm if necessary and ignores
  1365  // any errors returned by these functions.
  1366  // If key is not present, FormValue returns the empty string.
  1367  // To access multiple values of the same key, call ParseForm and
  1368  // then inspect Request.Form directly.
  1369  func (r *Request) FormValue(key string) string {
  1370  	if r.Form == nil {
  1371  		r.ParseMultipartForm(defaultMaxMemory)
  1372  	}
  1373  	if vs := r.Form[key]; len(vs) > 0 {
  1374  		return vs[0]
  1375  	}
  1376  	return ""
  1377  }
  1378  
  1379  // PostFormValue returns the first value for the named component of the POST,
  1380  // PATCH, or PUT request body. URL query parameters are ignored.
  1381  // PostFormValue calls ParseMultipartForm and ParseForm if necessary and ignores
  1382  // any errors returned by these functions.
  1383  // If key is not present, PostFormValue returns the empty string.
  1384  func (r *Request) PostFormValue(key string) string {
  1385  	if r.PostForm == nil {
  1386  		r.ParseMultipartForm(defaultMaxMemory)
  1387  	}
  1388  	if vs := r.PostForm[key]; len(vs) > 0 {
  1389  		return vs[0]
  1390  	}
  1391  	return ""
  1392  }
  1393  
  1394  // FormFile returns the first file for the provided form key.
  1395  // FormFile calls ParseMultipartForm and ParseForm if necessary.
  1396  func (r *Request) FormFile(key string) (multipart.File, *multipart.FileHeader, error) {
  1397  	if r.MultipartForm == multipartByReader {
  1398  		return nil, nil, errors.New("http: multipart handled by MultipartReader")
  1399  	}
  1400  	if r.MultipartForm == nil {
  1401  		err := r.ParseMultipartForm(defaultMaxMemory)
  1402  		if err != nil {
  1403  			return nil, nil, err
  1404  		}
  1405  	}
  1406  	if r.MultipartForm != nil && r.MultipartForm.File != nil {
  1407  		if fhs := r.MultipartForm.File[key]; len(fhs) > 0 {
  1408  			f, err := fhs[0].Open()
  1409  			return f, fhs[0], err
  1410  		}
  1411  	}
  1412  	return nil, nil, ErrMissingFile
  1413  }
  1414  
  1415  func (r *Request) expectsContinue() bool {
  1416  	return hasToken(r.Header.get("Expect"), "100-continue")
  1417  }
  1418  
  1419  func (r *Request) wantsHttp10KeepAlive() bool {
  1420  	if r.ProtoMajor != 1 || r.ProtoMinor != 0 {
  1421  		return false
  1422  	}
  1423  	return hasToken(r.Header.get("Connection"), "keep-alive")
  1424  }
  1425  
  1426  func (r *Request) wantsClose() bool {
  1427  	if r.Close {
  1428  		return true
  1429  	}
  1430  	return hasToken(r.Header.get("Connection"), "close")
  1431  }
  1432  
  1433  func (r *Request) closeBody() error {
  1434  	if r.Body == nil {
  1435  		return nil
  1436  	}
  1437  	return r.Body.Close()
  1438  }
  1439  
  1440  func (r *Request) isReplayable() bool {
  1441  	if r.Body == nil || r.Body == NoBody || r.GetBody != nil {
  1442  		switch valueOrDefault(r.Method, "GET") {
  1443  		case "GET", "HEAD", "OPTIONS", "TRACE":
  1444  			return true
  1445  		}
  1446  		// The Idempotency-Key, while non-standard, is widely used to
  1447  		// mean a POST or other request is idempotent. See
  1448  		// https://golang.org/issue/19943#issuecomment-421092421
  1449  		if r.Header.has("Idempotency-Key") || r.Header.has("X-Idempotency-Key") {
  1450  			return true
  1451  		}
  1452  	}
  1453  	return false
  1454  }
  1455  
  1456  // outgoingLength reports the Content-Length of this outgoing (Client) request.
  1457  // It maps 0 into -1 (unknown) when the Body is non-nil.
  1458  func (r *Request) outgoingLength() int64 {
  1459  	if r.Body == nil || r.Body == NoBody {
  1460  		return 0
  1461  	}
  1462  	if r.ContentLength != 0 {
  1463  		return r.ContentLength
  1464  	}
  1465  	return -1
  1466  }
  1467  
  1468  // requestMethodUsuallyLacksBody reports whether the given request
  1469  // method is one that typically does not involve a request body.
  1470  // This is used by the Transport (via
  1471  // transferWriter.shouldSendChunkedRequestBody) to determine whether
  1472  // we try to test-read a byte from a non-nil Request.Body when
  1473  // Request.outgoingLength() returns -1. See the comments in
  1474  // shouldSendChunkedRequestBody.
  1475  func requestMethodUsuallyLacksBody(method string) bool {
  1476  	switch method {
  1477  	case "GET", "HEAD", "DELETE", "OPTIONS", "PROPFIND", "SEARCH":
  1478  		return true
  1479  	}
  1480  	return false
  1481  }
  1482  
  1483  // requiresHTTP1 reports whether this request requires being sent on
  1484  // an HTTP/1 connection.
  1485  func (r *Request) requiresHTTP1() bool {
  1486  	return hasToken(r.Header.Get("Connection"), "upgrade") &&
  1487  		ascii.EqualFold(r.Header.Get("Upgrade"), "websocket")
  1488  }