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

View as plain text