Source file src/net/http/request.go

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

View as plain text