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