...

Source file src/net/http/server.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 server. See RFC 7230 through 7235.
     6	
     7	package http
     8	
     9	import (
    10		"bufio"
    11		"bytes"
    12		"context"
    13		"crypto/tls"
    14		"errors"
    15		"fmt"
    16		"io"
    17		"io/ioutil"
    18		"log"
    19		"net"
    20		"net/textproto"
    21		"net/url"
    22		"os"
    23		"path"
    24		"runtime"
    25		"sort"
    26		"strconv"
    27		"strings"
    28		"sync"
    29		"sync/atomic"
    30		"time"
    31	
    32		"golang.org/x/net/http/httpguts"
    33	)
    34	
    35	// Errors used by the HTTP server.
    36	var (
    37		// ErrBodyNotAllowed is returned by ResponseWriter.Write calls
    38		// when the HTTP method or response code does not permit a
    39		// body.
    40		ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body")
    41	
    42		// ErrHijacked is returned by ResponseWriter.Write calls when
    43		// the underlying connection has been hijacked using the
    44		// Hijacker interface. A zero-byte write on a hijacked
    45		// connection will return ErrHijacked without any other side
    46		// effects.
    47		ErrHijacked = errors.New("http: connection has been hijacked")
    48	
    49		// ErrContentLength is returned by ResponseWriter.Write calls
    50		// when a Handler set a Content-Length response header with a
    51		// declared size and then attempted to write more bytes than
    52		// declared.
    53		ErrContentLength = errors.New("http: wrote more than the declared Content-Length")
    54	
    55		// Deprecated: ErrWriteAfterFlush is no longer returned by
    56		// anything in the net/http package. Callers should not
    57		// compare errors against this variable.
    58		ErrWriteAfterFlush = errors.New("unused")
    59	)
    60	
    61	// A Handler responds to an HTTP request.
    62	//
    63	// ServeHTTP should write reply headers and data to the ResponseWriter
    64	// and then return. Returning signals that the request is finished; it
    65	// is not valid to use the ResponseWriter or read from the
    66	// Request.Body after or concurrently with the completion of the
    67	// ServeHTTP call.
    68	//
    69	// Depending on the HTTP client software, HTTP protocol version, and
    70	// any intermediaries between the client and the Go server, it may not
    71	// be possible to read from the Request.Body after writing to the
    72	// ResponseWriter. Cautious handlers should read the Request.Body
    73	// first, and then reply.
    74	//
    75	// Except for reading the body, handlers should not modify the
    76	// provided Request.
    77	//
    78	// If ServeHTTP panics, the server (the caller of ServeHTTP) assumes
    79	// that the effect of the panic was isolated to the active request.
    80	// It recovers the panic, logs a stack trace to the server error log,
    81	// and either closes the network connection or sends an HTTP/2
    82	// RST_STREAM, depending on the HTTP protocol. To abort a handler so
    83	// the client sees an interrupted response but the server doesn't log
    84	// an error, panic with the value ErrAbortHandler.
    85	type Handler interface {
    86		ServeHTTP(ResponseWriter, *Request)
    87	}
    88	
    89	// A ResponseWriter interface is used by an HTTP handler to
    90	// construct an HTTP response.
    91	//
    92	// A ResponseWriter may not be used after the Handler.ServeHTTP method
    93	// has returned.
    94	type ResponseWriter interface {
    95		// Header returns the header map that will be sent by
    96		// WriteHeader. The Header map also is the mechanism with which
    97		// Handlers can set HTTP trailers.
    98		//
    99		// Changing the header map after a call to WriteHeader (or
   100		// Write) has no effect unless the modified headers are
   101		// trailers.
   102		//
   103		// There are two ways to set Trailers. The preferred way is to
   104		// predeclare in the headers which trailers you will later
   105		// send by setting the "Trailer" header to the names of the
   106		// trailer keys which will come later. In this case, those
   107		// keys of the Header map are treated as if they were
   108		// trailers. See the example. The second way, for trailer
   109		// keys not known to the Handler until after the first Write,
   110		// is to prefix the Header map keys with the TrailerPrefix
   111		// constant value. See TrailerPrefix.
   112		//
   113		// To suppress automatic response headers (such as "Date"), set
   114		// their value to nil.
   115		Header() Header
   116	
   117		// Write writes the data to the connection as part of an HTTP reply.
   118		//
   119		// If WriteHeader has not yet been called, Write calls
   120		// WriteHeader(http.StatusOK) before writing the data. If the Header
   121		// does not contain a Content-Type line, Write adds a Content-Type set
   122		// to the result of passing the initial 512 bytes of written data to
   123		// DetectContentType. Additionally, if the total size of all written
   124		// data is under a few KB and there are no Flush calls, the
   125		// Content-Length header is added automatically.
   126		//
   127		// Depending on the HTTP protocol version and the client, calling
   128		// Write or WriteHeader may prevent future reads on the
   129		// Request.Body. For HTTP/1.x requests, handlers should read any
   130		// needed request body data before writing the response. Once the
   131		// headers have been flushed (due to either an explicit Flusher.Flush
   132		// call or writing enough data to trigger a flush), the request body
   133		// may be unavailable. For HTTP/2 requests, the Go HTTP server permits
   134		// handlers to continue to read the request body while concurrently
   135		// writing the response. However, such behavior may not be supported
   136		// by all HTTP/2 clients. Handlers should read before writing if
   137		// possible to maximize compatibility.
   138		Write([]byte) (int, error)
   139	
   140		// WriteHeader sends an HTTP response header with the provided
   141		// status code.
   142		//
   143		// If WriteHeader is not called explicitly, the first call to Write
   144		// will trigger an implicit WriteHeader(http.StatusOK).
   145		// Thus explicit calls to WriteHeader are mainly used to
   146		// send error codes.
   147		//
   148		// The provided code must be a valid HTTP 1xx-5xx status code.
   149		// Only one header may be written. Go does not currently
   150		// support sending user-defined 1xx informational headers,
   151		// with the exception of 100-continue response header that the
   152		// Server sends automatically when the Request.Body is read.
   153		WriteHeader(statusCode int)
   154	}
   155	
   156	// The Flusher interface is implemented by ResponseWriters that allow
   157	// an HTTP handler to flush buffered data to the client.
   158	//
   159	// The default HTTP/1.x and HTTP/2 ResponseWriter implementations
   160	// support Flusher, but ResponseWriter wrappers may not. Handlers
   161	// should always test for this ability at runtime.
   162	//
   163	// Note that even for ResponseWriters that support Flush,
   164	// if the client is connected through an HTTP proxy,
   165	// the buffered data may not reach the client until the response
   166	// completes.
   167	type Flusher interface {
   168		// Flush sends any buffered data to the client.
   169		Flush()
   170	}
   171	
   172	// The Hijacker interface is implemented by ResponseWriters that allow
   173	// an HTTP handler to take over the connection.
   174	//
   175	// The default ResponseWriter for HTTP/1.x connections supports
   176	// Hijacker, but HTTP/2 connections intentionally do not.
   177	// ResponseWriter wrappers may also not support Hijacker. Handlers
   178	// should always test for this ability at runtime.
   179	type Hijacker interface {
   180		// Hijack lets the caller take over the connection.
   181		// After a call to Hijack the HTTP server library
   182		// will not do anything else with the connection.
   183		//
   184		// It becomes the caller's responsibility to manage
   185		// and close the connection.
   186		//
   187		// The returned net.Conn may have read or write deadlines
   188		// already set, depending on the configuration of the
   189		// Server. It is the caller's responsibility to set
   190		// or clear those deadlines as needed.
   191		//
   192		// The returned bufio.Reader may contain unprocessed buffered
   193		// data from the client.
   194		//
   195		// After a call to Hijack, the original Request.Body must not
   196		// be used. The original Request's Context remains valid and
   197		// is not canceled until the Request's ServeHTTP method
   198		// returns.
   199		Hijack() (net.Conn, *bufio.ReadWriter, error)
   200	}
   201	
   202	// The CloseNotifier interface is implemented by ResponseWriters which
   203	// allow detecting when the underlying connection has gone away.
   204	//
   205	// This mechanism can be used to cancel long operations on the server
   206	// if the client has disconnected before the response is ready.
   207	//
   208	// Deprecated: the CloseNotifier interface predates Go's context package.
   209	// New code should use Request.Context instead.
   210	type CloseNotifier interface {
   211		// CloseNotify returns a channel that receives at most a
   212		// single value (true) when the client connection has gone
   213		// away.
   214		//
   215		// CloseNotify may wait to notify until Request.Body has been
   216		// fully read.
   217		//
   218		// After the Handler has returned, there is no guarantee
   219		// that the channel receives a value.
   220		//
   221		// If the protocol is HTTP/1.1 and CloseNotify is called while
   222		// processing an idempotent request (such a GET) while
   223		// HTTP/1.1 pipelining is in use, the arrival of a subsequent
   224		// pipelined request may cause a value to be sent on the
   225		// returned channel. In practice HTTP/1.1 pipelining is not
   226		// enabled in browsers and not seen often in the wild. If this
   227		// is a problem, use HTTP/2 or only use CloseNotify on methods
   228		// such as POST.
   229		CloseNotify() <-chan bool
   230	}
   231	
   232	var (
   233		// ServerContextKey is a context key. It can be used in HTTP
   234		// handlers with Context.Value to access the server that
   235		// started the handler. The associated value will be of
   236		// type *Server.
   237		ServerContextKey = &contextKey{"http-server"}
   238	
   239		// LocalAddrContextKey is a context key. It can be used in
   240		// HTTP handlers with Context.Value to access the local
   241		// address the connection arrived on.
   242		// The associated value will be of type net.Addr.
   243		LocalAddrContextKey = &contextKey{"local-addr"}
   244	)
   245	
   246	// A conn represents the server side of an HTTP connection.
   247	type conn struct {
   248		// server is the server on which the connection arrived.
   249		// Immutable; never nil.
   250		server *Server
   251	
   252		// cancelCtx cancels the connection-level context.
   253		cancelCtx context.CancelFunc
   254	
   255		// rwc is the underlying network connection.
   256		// This is never wrapped by other types and is the value given out
   257		// to CloseNotifier callers. It is usually of type *net.TCPConn or
   258		// *tls.Conn.
   259		rwc net.Conn
   260	
   261		// remoteAddr is rwc.RemoteAddr().String(). It is not populated synchronously
   262		// inside the Listener's Accept goroutine, as some implementations block.
   263		// It is populated immediately inside the (*conn).serve goroutine.
   264		// This is the value of a Handler's (*Request).RemoteAddr.
   265		remoteAddr string
   266	
   267		// tlsState is the TLS connection state when using TLS.
   268		// nil means not TLS.
   269		tlsState *tls.ConnectionState
   270	
   271		// werr is set to the first write error to rwc.
   272		// It is set via checkConnErrorWriter{w}, where bufw writes.
   273		werr error
   274	
   275		// r is bufr's read source. It's a wrapper around rwc that provides
   276		// io.LimitedReader-style limiting (while reading request headers)
   277		// and functionality to support CloseNotifier. See *connReader docs.
   278		r *connReader
   279	
   280		// bufr reads from r.
   281		bufr *bufio.Reader
   282	
   283		// bufw writes to checkConnErrorWriter{c}, which populates werr on error.
   284		bufw *bufio.Writer
   285	
   286		// lastMethod is the method of the most recent request
   287		// on this connection, if any.
   288		lastMethod string
   289	
   290		curReq atomic.Value // of *response (which has a Request in it)
   291	
   292		curState struct{ atomic uint64 } // packed (unixtime<<8|uint8(ConnState))
   293	
   294		// mu guards hijackedv
   295		mu sync.Mutex
   296	
   297		// hijackedv is whether this connection has been hijacked
   298		// by a Handler with the Hijacker interface.
   299		// It is guarded by mu.
   300		hijackedv bool
   301	}
   302	
   303	func (c *conn) hijacked() bool {
   304		c.mu.Lock()
   305		defer c.mu.Unlock()
   306		return c.hijackedv
   307	}
   308	
   309	// c.mu must be held.
   310	func (c *conn) hijackLocked() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
   311		if c.hijackedv {
   312			return nil, nil, ErrHijacked
   313		}
   314		c.r.abortPendingRead()
   315	
   316		c.hijackedv = true
   317		rwc = c.rwc
   318		rwc.SetDeadline(time.Time{})
   319	
   320		buf = bufio.NewReadWriter(c.bufr, bufio.NewWriter(rwc))
   321		if c.r.hasByte {
   322			if _, err := c.bufr.Peek(c.bufr.Buffered() + 1); err != nil {
   323				return nil, nil, fmt.Errorf("unexpected Peek failure reading buffered byte: %v", err)
   324			}
   325		}
   326		c.setState(rwc, StateHijacked)
   327		return
   328	}
   329	
   330	// This should be >= 512 bytes for DetectContentType,
   331	// but otherwise it's somewhat arbitrary.
   332	const bufferBeforeChunkingSize = 2048
   333	
   334	// chunkWriter writes to a response's conn buffer, and is the writer
   335	// wrapped by the response.bufw buffered writer.
   336	//
   337	// chunkWriter also is responsible for finalizing the Header, including
   338	// conditionally setting the Content-Type and setting a Content-Length
   339	// in cases where the handler's final output is smaller than the buffer
   340	// size. It also conditionally adds chunk headers, when in chunking mode.
   341	//
   342	// See the comment above (*response).Write for the entire write flow.
   343	type chunkWriter struct {
   344		res *response
   345	
   346		// header is either nil or a deep clone of res.handlerHeader
   347		// at the time of res.writeHeader, if res.writeHeader is
   348		// called and extra buffering is being done to calculate
   349		// Content-Type and/or Content-Length.
   350		header Header
   351	
   352		// wroteHeader tells whether the header's been written to "the
   353		// wire" (or rather: w.conn.buf). this is unlike
   354		// (*response).wroteHeader, which tells only whether it was
   355		// logically written.
   356		wroteHeader bool
   357	
   358		// set by the writeHeader method:
   359		chunking bool // using chunked transfer encoding for reply body
   360	}
   361	
   362	var (
   363		crlf       = []byte("\r\n")
   364		colonSpace = []byte(": ")
   365	)
   366	
   367	func (cw *chunkWriter) Write(p []byte) (n int, err error) {
   368		if !cw.wroteHeader {
   369			cw.writeHeader(p)
   370		}
   371		if cw.res.req.Method == "HEAD" {
   372			// Eat writes.
   373			return len(p), nil
   374		}
   375		if cw.chunking {
   376			_, err = fmt.Fprintf(cw.res.conn.bufw, "%x\r\n", len(p))
   377			if err != nil {
   378				cw.res.conn.rwc.Close()
   379				return
   380			}
   381		}
   382		n, err = cw.res.conn.bufw.Write(p)
   383		if cw.chunking && err == nil {
   384			_, err = cw.res.conn.bufw.Write(crlf)
   385		}
   386		if err != nil {
   387			cw.res.conn.rwc.Close()
   388		}
   389		return
   390	}
   391	
   392	func (cw *chunkWriter) flush() {
   393		if !cw.wroteHeader {
   394			cw.writeHeader(nil)
   395		}
   396		cw.res.conn.bufw.Flush()
   397	}
   398	
   399	func (cw *chunkWriter) close() {
   400		if !cw.wroteHeader {
   401			cw.writeHeader(nil)
   402		}
   403		if cw.chunking {
   404			bw := cw.res.conn.bufw // conn's bufio writer
   405			// zero chunk to mark EOF
   406			bw.WriteString("0\r\n")
   407			if trailers := cw.res.finalTrailers(); trailers != nil {
   408				trailers.Write(bw) // the writer handles noting errors
   409			}
   410			// final blank line after the trailers (whether
   411			// present or not)
   412			bw.WriteString("\r\n")
   413		}
   414	}
   415	
   416	// A response represents the server side of an HTTP response.
   417	type response struct {
   418		conn             *conn
   419		req              *Request // request for this response
   420		reqBody          io.ReadCloser
   421		cancelCtx        context.CancelFunc // when ServeHTTP exits
   422		wroteHeader      bool               // reply header has been (logically) written
   423		wroteContinue    bool               // 100 Continue response was written
   424		wants10KeepAlive bool               // HTTP/1.0 w/ Connection "keep-alive"
   425		wantsClose       bool               // HTTP request has Connection "close"
   426	
   427		w  *bufio.Writer // buffers output in chunks to chunkWriter
   428		cw chunkWriter
   429	
   430		// handlerHeader is the Header that Handlers get access to,
   431		// which may be retained and mutated even after WriteHeader.
   432		// handlerHeader is copied into cw.header at WriteHeader
   433		// time, and privately mutated thereafter.
   434		handlerHeader Header
   435		calledHeader  bool // handler accessed handlerHeader via Header
   436	
   437		written       int64 // number of bytes written in body
   438		contentLength int64 // explicitly-declared Content-Length; or -1
   439		status        int   // status code passed to WriteHeader
   440	
   441		// close connection after this reply.  set on request and
   442		// updated after response from handler if there's a
   443		// "Connection: keep-alive" response header and a
   444		// Content-Length.
   445		closeAfterReply bool
   446	
   447		// requestBodyLimitHit is set by requestTooLarge when
   448		// maxBytesReader hits its max size. It is checked in
   449		// WriteHeader, to make sure we don't consume the
   450		// remaining request body to try to advance to the next HTTP
   451		// request. Instead, when this is set, we stop reading
   452		// subsequent requests on this connection and stop reading
   453		// input from it.
   454		requestBodyLimitHit bool
   455	
   456		// trailers are the headers to be sent after the handler
   457		// finishes writing the body. This field is initialized from
   458		// the Trailer response header when the response header is
   459		// written.
   460		trailers []string
   461	
   462		handlerDone atomicBool // set true when the handler exits
   463	
   464		// Buffers for Date, Content-Length, and status code
   465		dateBuf   [len(TimeFormat)]byte
   466		clenBuf   [10]byte
   467		statusBuf [3]byte
   468	
   469		// closeNotifyCh is the channel returned by CloseNotify.
   470		// TODO(bradfitz): this is currently (for Go 1.8) always
   471		// non-nil. Make this lazily-created again as it used to be?
   472		closeNotifyCh  chan bool
   473		didCloseNotify int32 // atomic (only 0->1 winner should send)
   474	}
   475	
   476	// TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
   477	// that, if present, signals that the map entry is actually for
   478	// the response trailers, and not the response headers. The prefix
   479	// is stripped after the ServeHTTP call finishes and the values are
   480	// sent in the trailers.
   481	//
   482	// This mechanism is intended only for trailers that are not known
   483	// prior to the headers being written. If the set of trailers is fixed
   484	// or known before the header is written, the normal Go trailers mechanism
   485	// is preferred:
   486	//    https://golang.org/pkg/net/http/#ResponseWriter
   487	//    https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
   488	const TrailerPrefix = "Trailer:"
   489	
   490	// finalTrailers is called after the Handler exits and returns a non-nil
   491	// value if the Handler set any trailers.
   492	func (w *response) finalTrailers() Header {
   493		var t Header
   494		for k, vv := range w.handlerHeader {
   495			if strings.HasPrefix(k, TrailerPrefix) {
   496				if t == nil {
   497					t = make(Header)
   498				}
   499				t[strings.TrimPrefix(k, TrailerPrefix)] = vv
   500			}
   501		}
   502		for _, k := range w.trailers {
   503			if t == nil {
   504				t = make(Header)
   505			}
   506			for _, v := range w.handlerHeader[k] {
   507				t.Add(k, v)
   508			}
   509		}
   510		return t
   511	}
   512	
   513	type atomicBool int32
   514	
   515	func (b *atomicBool) isSet() bool { return atomic.LoadInt32((*int32)(b)) != 0 }
   516	func (b *atomicBool) setTrue()    { atomic.StoreInt32((*int32)(b), 1) }
   517	
   518	// declareTrailer is called for each Trailer header when the
   519	// response header is written. It notes that a header will need to be
   520	// written in the trailers at the end of the response.
   521	func (w *response) declareTrailer(k string) {
   522		k = CanonicalHeaderKey(k)
   523		if !httpguts.ValidTrailerHeader(k) {
   524			// Forbidden by RFC 7230, section 4.1.2
   525			return
   526		}
   527		w.trailers = append(w.trailers, k)
   528	}
   529	
   530	// requestTooLarge is called by maxBytesReader when too much input has
   531	// been read from the client.
   532	func (w *response) requestTooLarge() {
   533		w.closeAfterReply = true
   534		w.requestBodyLimitHit = true
   535		if !w.wroteHeader {
   536			w.Header().Set("Connection", "close")
   537		}
   538	}
   539	
   540	// needsSniff reports whether a Content-Type still needs to be sniffed.
   541	func (w *response) needsSniff() bool {
   542		_, haveType := w.handlerHeader["Content-Type"]
   543		return !w.cw.wroteHeader && !haveType && w.written < sniffLen
   544	}
   545	
   546	// writerOnly hides an io.Writer value's optional ReadFrom method
   547	// from io.Copy.
   548	type writerOnly struct {
   549		io.Writer
   550	}
   551	
   552	func srcIsRegularFile(src io.Reader) (isRegular bool, err error) {
   553		switch v := src.(type) {
   554		case *os.File:
   555			fi, err := v.Stat()
   556			if err != nil {
   557				return false, err
   558			}
   559			return fi.Mode().IsRegular(), nil
   560		case *io.LimitedReader:
   561			return srcIsRegularFile(v.R)
   562		default:
   563			return
   564		}
   565	}
   566	
   567	// ReadFrom is here to optimize copying from an *os.File regular file
   568	// to a *net.TCPConn with sendfile.
   569	func (w *response) ReadFrom(src io.Reader) (n int64, err error) {
   570		// Our underlying w.conn.rwc is usually a *TCPConn (with its
   571		// own ReadFrom method). If not, or if our src isn't a regular
   572		// file, just fall back to the normal copy method.
   573		rf, ok := w.conn.rwc.(io.ReaderFrom)
   574		regFile, err := srcIsRegularFile(src)
   575		if err != nil {
   576			return 0, err
   577		}
   578		if !ok || !regFile {
   579			bufp := copyBufPool.Get().(*[]byte)
   580			defer copyBufPool.Put(bufp)
   581			return io.CopyBuffer(writerOnly{w}, src, *bufp)
   582		}
   583	
   584		// sendfile path:
   585	
   586		if !w.wroteHeader {
   587			w.WriteHeader(StatusOK)
   588		}
   589	
   590		if w.needsSniff() {
   591			n0, err := io.Copy(writerOnly{w}, io.LimitReader(src, sniffLen))
   592			n += n0
   593			if err != nil {
   594				return n, err
   595			}
   596		}
   597	
   598		w.w.Flush()  // get rid of any previous writes
   599		w.cw.flush() // make sure Header is written; flush data to rwc
   600	
   601		// Now that cw has been flushed, its chunking field is guaranteed initialized.
   602		if !w.cw.chunking && w.bodyAllowed() {
   603			n0, err := rf.ReadFrom(src)
   604			n += n0
   605			w.written += n0
   606			return n, err
   607		}
   608	
   609		n0, err := io.Copy(writerOnly{w}, src)
   610		n += n0
   611		return n, err
   612	}
   613	
   614	// debugServerConnections controls whether all server connections are wrapped
   615	// with a verbose logging wrapper.
   616	const debugServerConnections = false
   617	
   618	// Create new connection from rwc.
   619	func (srv *Server) newConn(rwc net.Conn) *conn {
   620		c := &conn{
   621			server: srv,
   622			rwc:    rwc,
   623		}
   624		if debugServerConnections {
   625			c.rwc = newLoggingConn("server", c.rwc)
   626		}
   627		return c
   628	}
   629	
   630	type readResult struct {
   631		n   int
   632		err error
   633		b   byte // byte read, if n == 1
   634	}
   635	
   636	// connReader is the io.Reader wrapper used by *conn. It combines a
   637	// selectively-activated io.LimitedReader (to bound request header
   638	// read sizes) with support for selectively keeping an io.Reader.Read
   639	// call blocked in a background goroutine to wait for activity and
   640	// trigger a CloseNotifier channel.
   641	type connReader struct {
   642		conn *conn
   643	
   644		mu      sync.Mutex // guards following
   645		hasByte bool
   646		byteBuf [1]byte
   647		cond    *sync.Cond
   648		inRead  bool
   649		aborted bool  // set true before conn.rwc deadline is set to past
   650		remain  int64 // bytes remaining
   651	}
   652	
   653	func (cr *connReader) lock() {
   654		cr.mu.Lock()
   655		if cr.cond == nil {
   656			cr.cond = sync.NewCond(&cr.mu)
   657		}
   658	}
   659	
   660	func (cr *connReader) unlock() { cr.mu.Unlock() }
   661	
   662	func (cr *connReader) startBackgroundRead() {
   663		cr.lock()
   664		defer cr.unlock()
   665		if cr.inRead {
   666			panic("invalid concurrent Body.Read call")
   667		}
   668		if cr.hasByte {
   669			return
   670		}
   671		cr.inRead = true
   672		cr.conn.rwc.SetReadDeadline(time.Time{})
   673		go cr.backgroundRead()
   674	}
   675	
   676	func (cr *connReader) backgroundRead() {
   677		n, err := cr.conn.rwc.Read(cr.byteBuf[:])
   678		cr.lock()
   679		if n == 1 {
   680			cr.hasByte = true
   681			// We were past the end of the previous request's body already
   682			// (since we wouldn't be in a background read otherwise), so
   683			// this is a pipelined HTTP request. Prior to Go 1.11 we used to
   684			// send on the CloseNotify channel and cancel the context here,
   685			// but the behavior was documented as only "may", and we only
   686			// did that because that's how CloseNotify accidentally behaved
   687			// in very early Go releases prior to context support. Once we
   688			// added context support, people used a Handler's
   689			// Request.Context() and passed it along. Having that context
   690			// cancel on pipelined HTTP requests caused problems.
   691			// Fortunately, almost nothing uses HTTP/1.x pipelining.
   692			// Unfortunately, apt-get does, or sometimes does.
   693			// New Go 1.11 behavior: don't fire CloseNotify or cancel
   694			// contexts on pipelined requests. Shouldn't affect people, but
   695			// fixes cases like Issue 23921. This does mean that a client
   696			// closing their TCP connection after sending a pipelined
   697			// request won't cancel the context, but we'll catch that on any
   698			// write failure (in checkConnErrorWriter.Write).
   699			// If the server never writes, yes, there are still contrived
   700			// server & client behaviors where this fails to ever cancel the
   701			// context, but that's kinda why HTTP/1.x pipelining died
   702			// anyway.
   703		}
   704		if ne, ok := err.(net.Error); ok && cr.aborted && ne.Timeout() {
   705			// Ignore this error. It's the expected error from
   706			// another goroutine calling abortPendingRead.
   707		} else if err != nil {
   708			cr.handleReadError(err)
   709		}
   710		cr.aborted = false
   711		cr.inRead = false
   712		cr.unlock()
   713		cr.cond.Broadcast()
   714	}
   715	
   716	func (cr *connReader) abortPendingRead() {
   717		cr.lock()
   718		defer cr.unlock()
   719		if !cr.inRead {
   720			return
   721		}
   722		cr.aborted = true
   723		cr.conn.rwc.SetReadDeadline(aLongTimeAgo)
   724		for cr.inRead {
   725			cr.cond.Wait()
   726		}
   727		cr.conn.rwc.SetReadDeadline(time.Time{})
   728	}
   729	
   730	func (cr *connReader) setReadLimit(remain int64) { cr.remain = remain }
   731	func (cr *connReader) setInfiniteReadLimit()     { cr.remain = maxInt64 }
   732	func (cr *connReader) hitReadLimit() bool        { return cr.remain <= 0 }
   733	
   734	// handleReadError is called whenever a Read from the client returns a
   735	// non-nil error.
   736	//
   737	// The provided non-nil err is almost always io.EOF or a "use of
   738	// closed network connection". In any case, the error is not
   739	// particularly interesting, except perhaps for debugging during
   740	// development. Any error means the connection is dead and we should
   741	// down its context.
   742	//
   743	// It may be called from multiple goroutines.
   744	func (cr *connReader) handleReadError(_ error) {
   745		cr.conn.cancelCtx()
   746		cr.closeNotify()
   747	}
   748	
   749	// may be called from multiple goroutines.
   750	func (cr *connReader) closeNotify() {
   751		res, _ := cr.conn.curReq.Load().(*response)
   752		if res != nil && atomic.CompareAndSwapInt32(&res.didCloseNotify, 0, 1) {
   753			res.closeNotifyCh <- true
   754		}
   755	}
   756	
   757	func (cr *connReader) Read(p []byte) (n int, err error) {
   758		cr.lock()
   759		if cr.inRead {
   760			cr.unlock()
   761			if cr.conn.hijacked() {
   762				panic("invalid Body.Read call. After hijacked, the original Request must not be used")
   763			}
   764			panic("invalid concurrent Body.Read call")
   765		}
   766		if cr.hitReadLimit() {
   767			cr.unlock()
   768			return 0, io.EOF
   769		}
   770		if len(p) == 0 {
   771			cr.unlock()
   772			return 0, nil
   773		}
   774		if int64(len(p)) > cr.remain {
   775			p = p[:cr.remain]
   776		}
   777		if cr.hasByte {
   778			p[0] = cr.byteBuf[0]
   779			cr.hasByte = false
   780			cr.unlock()
   781			return 1, nil
   782		}
   783		cr.inRead = true
   784		cr.unlock()
   785		n, err = cr.conn.rwc.Read(p)
   786	
   787		cr.lock()
   788		cr.inRead = false
   789		if err != nil {
   790			cr.handleReadError(err)
   791		}
   792		cr.remain -= int64(n)
   793		cr.unlock()
   794	
   795		cr.cond.Broadcast()
   796		return n, err
   797	}
   798	
   799	var (
   800		bufioReaderPool   sync.Pool
   801		bufioWriter2kPool sync.Pool
   802		bufioWriter4kPool sync.Pool
   803	)
   804	
   805	var copyBufPool = sync.Pool{
   806		New: func() interface{} {
   807			b := make([]byte, 32*1024)
   808			return &b
   809		},
   810	}
   811	
   812	func bufioWriterPool(size int) *sync.Pool {
   813		switch size {
   814		case 2 << 10:
   815			return &bufioWriter2kPool
   816		case 4 << 10:
   817			return &bufioWriter4kPool
   818		}
   819		return nil
   820	}
   821	
   822	func newBufioReader(r io.Reader) *bufio.Reader {
   823		if v := bufioReaderPool.Get(); v != nil {
   824			br := v.(*bufio.Reader)
   825			br.Reset(r)
   826			return br
   827		}
   828		// Note: if this reader size is ever changed, update
   829		// TestHandlerBodyClose's assumptions.
   830		return bufio.NewReader(r)
   831	}
   832	
   833	func putBufioReader(br *bufio.Reader) {
   834		br.Reset(nil)
   835		bufioReaderPool.Put(br)
   836	}
   837	
   838	func newBufioWriterSize(w io.Writer, size int) *bufio.Writer {
   839		pool := bufioWriterPool(size)
   840		if pool != nil {
   841			if v := pool.Get(); v != nil {
   842				bw := v.(*bufio.Writer)
   843				bw.Reset(w)
   844				return bw
   845			}
   846		}
   847		return bufio.NewWriterSize(w, size)
   848	}
   849	
   850	func putBufioWriter(bw *bufio.Writer) {
   851		bw.Reset(nil)
   852		if pool := bufioWriterPool(bw.Available()); pool != nil {
   853			pool.Put(bw)
   854		}
   855	}
   856	
   857	// DefaultMaxHeaderBytes is the maximum permitted size of the headers
   858	// in an HTTP request.
   859	// This can be overridden by setting Server.MaxHeaderBytes.
   860	const DefaultMaxHeaderBytes = 1 << 20 // 1 MB
   861	
   862	func (srv *Server) maxHeaderBytes() int {
   863		if srv.MaxHeaderBytes > 0 {
   864			return srv.MaxHeaderBytes
   865		}
   866		return DefaultMaxHeaderBytes
   867	}
   868	
   869	func (srv *Server) initialReadLimitSize() int64 {
   870		return int64(srv.maxHeaderBytes()) + 4096 // bufio slop
   871	}
   872	
   873	// wrapper around io.ReadCloser which on first read, sends an
   874	// HTTP/1.1 100 Continue header
   875	type expectContinueReader struct {
   876		resp       *response
   877		readCloser io.ReadCloser
   878		closed     bool
   879		sawEOF     bool
   880	}
   881	
   882	func (ecr *expectContinueReader) Read(p []byte) (n int, err error) {
   883		if ecr.closed {
   884			return 0, ErrBodyReadAfterClose
   885		}
   886		if !ecr.resp.wroteContinue && !ecr.resp.conn.hijacked() {
   887			ecr.resp.wroteContinue = true
   888			ecr.resp.conn.bufw.WriteString("HTTP/1.1 100 Continue\r\n\r\n")
   889			ecr.resp.conn.bufw.Flush()
   890		}
   891		n, err = ecr.readCloser.Read(p)
   892		if err == io.EOF {
   893			ecr.sawEOF = true
   894		}
   895		return
   896	}
   897	
   898	func (ecr *expectContinueReader) Close() error {
   899		ecr.closed = true
   900		return ecr.readCloser.Close()
   901	}
   902	
   903	// TimeFormat is the time format to use when generating times in HTTP
   904	// headers. It is like time.RFC1123 but hard-codes GMT as the time
   905	// zone. The time being formatted must be in UTC for Format to
   906	// generate the correct format.
   907	//
   908	// For parsing this time format, see ParseTime.
   909	const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT"
   910	
   911	// appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat))
   912	func appendTime(b []byte, t time.Time) []byte {
   913		const days = "SunMonTueWedThuFriSat"
   914		const months = "JanFebMarAprMayJunJulAugSepOctNovDec"
   915	
   916		t = t.UTC()
   917		yy, mm, dd := t.Date()
   918		hh, mn, ss := t.Clock()
   919		day := days[3*t.Weekday():]
   920		mon := months[3*(mm-1):]
   921	
   922		return append(b,
   923			day[0], day[1], day[2], ',', ' ',
   924			byte('0'+dd/10), byte('0'+dd%10), ' ',
   925			mon[0], mon[1], mon[2], ' ',
   926			byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ',
   927			byte('0'+hh/10), byte('0'+hh%10), ':',
   928			byte('0'+mn/10), byte('0'+mn%10), ':',
   929			byte('0'+ss/10), byte('0'+ss%10), ' ',
   930			'G', 'M', 'T')
   931	}
   932	
   933	var errTooLarge = errors.New("http: request too large")
   934	
   935	// Read next request from connection.
   936	func (c *conn) readRequest(ctx context.Context) (w *response, err error) {
   937		if c.hijacked() {
   938			return nil, ErrHijacked
   939		}
   940	
   941		var (
   942			wholeReqDeadline time.Time // or zero if none
   943			hdrDeadline      time.Time // or zero if none
   944		)
   945		t0 := time.Now()
   946		if d := c.server.readHeaderTimeout(); d != 0 {
   947			hdrDeadline = t0.Add(d)
   948		}
   949		if d := c.server.ReadTimeout; d != 0 {
   950			wholeReqDeadline = t0.Add(d)
   951		}
   952		c.rwc.SetReadDeadline(hdrDeadline)
   953		if d := c.server.WriteTimeout; d != 0 {
   954			defer func() {
   955				c.rwc.SetWriteDeadline(time.Now().Add(d))
   956			}()
   957		}
   958	
   959		c.r.setReadLimit(c.server.initialReadLimitSize())
   960		if c.lastMethod == "POST" {
   961			// RFC 7230 section 3 tolerance for old buggy clients.
   962			peek, _ := c.bufr.Peek(4) // ReadRequest will get err below
   963			c.bufr.Discard(numLeadingCRorLF(peek))
   964		}
   965		req, err := readRequest(c.bufr, keepHostHeader)
   966		if err != nil {
   967			if c.r.hitReadLimit() {
   968				return nil, errTooLarge
   969			}
   970			return nil, err
   971		}
   972	
   973		if !http1ServerSupportsRequest(req) {
   974			return nil, badRequestError("unsupported protocol version")
   975		}
   976	
   977		c.lastMethod = req.Method
   978		c.r.setInfiniteReadLimit()
   979	
   980		hosts, haveHost := req.Header["Host"]
   981		isH2Upgrade := req.isH2Upgrade()
   982		if req.ProtoAtLeast(1, 1) && (!haveHost || len(hosts) == 0) && !isH2Upgrade && req.Method != "CONNECT" {
   983			return nil, badRequestError("missing required Host header")
   984		}
   985		if len(hosts) > 1 {
   986			return nil, badRequestError("too many Host headers")
   987		}
   988		if len(hosts) == 1 && !httpguts.ValidHostHeader(hosts[0]) {
   989			return nil, badRequestError("malformed Host header")
   990		}
   991		for k, vv := range req.Header {
   992			if !httpguts.ValidHeaderFieldName(k) {
   993				return nil, badRequestError("invalid header name")
   994			}
   995			for _, v := range vv {
   996				if !httpguts.ValidHeaderFieldValue(v) {
   997					return nil, badRequestError("invalid header value")
   998				}
   999			}
  1000		}
  1001		delete(req.Header, "Host")
  1002	
  1003		ctx, cancelCtx := context.WithCancel(ctx)
  1004		req.ctx = ctx
  1005		req.RemoteAddr = c.remoteAddr
  1006		req.TLS = c.tlsState
  1007		if body, ok := req.Body.(*body); ok {
  1008			body.doEarlyClose = true
  1009		}
  1010	
  1011		// Adjust the read deadline if necessary.
  1012		if !hdrDeadline.Equal(wholeReqDeadline) {
  1013			c.rwc.SetReadDeadline(wholeReqDeadline)
  1014		}
  1015	
  1016		w = &response{
  1017			conn:          c,
  1018			cancelCtx:     cancelCtx,
  1019			req:           req,
  1020			reqBody:       req.Body,
  1021			handlerHeader: make(Header),
  1022			contentLength: -1,
  1023			closeNotifyCh: make(chan bool, 1),
  1024	
  1025			// We populate these ahead of time so we're not
  1026			// reading from req.Header after their Handler starts
  1027			// and maybe mutates it (Issue 14940)
  1028			wants10KeepAlive: req.wantsHttp10KeepAlive(),
  1029			wantsClose:       req.wantsClose(),
  1030		}
  1031		if isH2Upgrade {
  1032			w.closeAfterReply = true
  1033		}
  1034		w.cw.res = w
  1035		w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize)
  1036		return w, nil
  1037	}
  1038	
  1039	// http1ServerSupportsRequest reports whether Go's HTTP/1.x server
  1040	// supports the given request.
  1041	func http1ServerSupportsRequest(req *Request) bool {
  1042		if req.ProtoMajor == 1 {
  1043			return true
  1044		}
  1045		// Accept "PRI * HTTP/2.0" upgrade requests, so Handlers can
  1046		// wire up their own HTTP/2 upgrades.
  1047		if req.ProtoMajor == 2 && req.ProtoMinor == 0 &&
  1048			req.Method == "PRI" && req.RequestURI == "*" {
  1049			return true
  1050		}
  1051		// Reject HTTP/0.x, and all other HTTP/2+ requests (which
  1052		// aren't encoded in ASCII anyway).
  1053		return false
  1054	}
  1055	
  1056	func (w *response) Header() Header {
  1057		if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader {
  1058			// Accessing the header between logically writing it
  1059			// and physically writing it means we need to allocate
  1060			// a clone to snapshot the logically written state.
  1061			w.cw.header = w.handlerHeader.Clone()
  1062		}
  1063		w.calledHeader = true
  1064		return w.handlerHeader
  1065	}
  1066	
  1067	// maxPostHandlerReadBytes is the max number of Request.Body bytes not
  1068	// consumed by a handler that the server will read from the client
  1069	// in order to keep a connection alive. If there are more bytes than
  1070	// this then the server to be paranoid instead sends a "Connection:
  1071	// close" response.
  1072	//
  1073	// This number is approximately what a typical machine's TCP buffer
  1074	// size is anyway.  (if we have the bytes on the machine, we might as
  1075	// well read them)
  1076	const maxPostHandlerReadBytes = 256 << 10
  1077	
  1078	func checkWriteHeaderCode(code int) {
  1079		// Issue 22880: require valid WriteHeader status codes.
  1080		// For now we only enforce that it's three digits.
  1081		// In the future we might block things over 599 (600 and above aren't defined
  1082		// at https://httpwg.org/specs/rfc7231.html#status.codes)
  1083		// and we might block under 200 (once we have more mature 1xx support).
  1084		// But for now any three digits.
  1085		//
  1086		// We used to send "HTTP/1.1 000 0" on the wire in responses but there's
  1087		// no equivalent bogus thing we can realistically send in HTTP/2,
  1088		// so we'll consistently panic instead and help people find their bugs
  1089		// early. (We can't return an error from WriteHeader even if we wanted to.)
  1090		if code < 100 || code > 999 {
  1091			panic(fmt.Sprintf("invalid WriteHeader code %v", code))
  1092		}
  1093	}
  1094	
  1095	// relevantCaller searches the call stack for the first function outside of net/http.
  1096	// The purpose of this function is to provide more helpful error messages.
  1097	func relevantCaller() runtime.Frame {
  1098		pc := make([]uintptr, 16)
  1099		n := runtime.Callers(1, pc)
  1100		frames := runtime.CallersFrames(pc[:n])
  1101		var frame runtime.Frame
  1102		for {
  1103			frame, more := frames.Next()
  1104			if !strings.HasPrefix(frame.Function, "net/http.") {
  1105				return frame
  1106			}
  1107			if !more {
  1108				break
  1109			}
  1110		}
  1111		return frame
  1112	}
  1113	
  1114	func (w *response) WriteHeader(code int) {
  1115		if w.conn.hijacked() {
  1116			caller := relevantCaller()
  1117			w.conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
  1118			return
  1119		}
  1120		if w.wroteHeader {
  1121			caller := relevantCaller()
  1122			w.conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
  1123			return
  1124		}
  1125		checkWriteHeaderCode(code)
  1126		w.wroteHeader = true
  1127		w.status = code
  1128	
  1129		if w.calledHeader && w.cw.header == nil {
  1130			w.cw.header = w.handlerHeader.Clone()
  1131		}
  1132	
  1133		if cl := w.handlerHeader.get("Content-Length"); cl != "" {
  1134			v, err := strconv.ParseInt(cl, 10, 64)
  1135			if err == nil && v >= 0 {
  1136				w.contentLength = v
  1137			} else {
  1138				w.conn.server.logf("http: invalid Content-Length of %q", cl)
  1139				w.handlerHeader.Del("Content-Length")
  1140			}
  1141		}
  1142	}
  1143	
  1144	// extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
  1145	// This type is used to avoid extra allocations from cloning and/or populating
  1146	// the response Header map and all its 1-element slices.
  1147	type extraHeader struct {
  1148		contentType      string
  1149		connection       string
  1150		transferEncoding string
  1151		date             []byte // written if not nil
  1152		contentLength    []byte // written if not nil
  1153	}
  1154	
  1155	// Sorted the same as extraHeader.Write's loop.
  1156	var extraHeaderKeys = [][]byte{
  1157		[]byte("Content-Type"),
  1158		[]byte("Connection"),
  1159		[]byte("Transfer-Encoding"),
  1160	}
  1161	
  1162	var (
  1163		headerContentLength = []byte("Content-Length: ")
  1164		headerDate          = []byte("Date: ")
  1165	)
  1166	
  1167	// Write writes the headers described in h to w.
  1168	//
  1169	// This method has a value receiver, despite the somewhat large size
  1170	// of h, because it prevents an allocation. The escape analysis isn't
  1171	// smart enough to realize this function doesn't mutate h.
  1172	func (h extraHeader) Write(w *bufio.Writer) {
  1173		if h.date != nil {
  1174			w.Write(headerDate)
  1175			w.Write(h.date)
  1176			w.Write(crlf)
  1177		}
  1178		if h.contentLength != nil {
  1179			w.Write(headerContentLength)
  1180			w.Write(h.contentLength)
  1181			w.Write(crlf)
  1182		}
  1183		for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
  1184			if v != "" {
  1185				w.Write(extraHeaderKeys[i])
  1186				w.Write(colonSpace)
  1187				w.WriteString(v)
  1188				w.Write(crlf)
  1189			}
  1190		}
  1191	}
  1192	
  1193	// writeHeader finalizes the header sent to the client and writes it
  1194	// to cw.res.conn.bufw.
  1195	//
  1196	// p is not written by writeHeader, but is the first chunk of the body
  1197	// that will be written. It is sniffed for a Content-Type if none is
  1198	// set explicitly. It's also used to set the Content-Length, if the
  1199	// total body size was small and the handler has already finished
  1200	// running.
  1201	func (cw *chunkWriter) writeHeader(p []byte) {
  1202		if cw.wroteHeader {
  1203			return
  1204		}
  1205		cw.wroteHeader = true
  1206	
  1207		w := cw.res
  1208		keepAlivesEnabled := w.conn.server.doKeepAlives()
  1209		isHEAD := w.req.Method == "HEAD"
  1210	
  1211		// header is written out to w.conn.buf below. Depending on the
  1212		// state of the handler, we either own the map or not. If we
  1213		// don't own it, the exclude map is created lazily for
  1214		// WriteSubset to remove headers. The setHeader struct holds
  1215		// headers we need to add.
  1216		header := cw.header
  1217		owned := header != nil
  1218		if !owned {
  1219			header = w.handlerHeader
  1220		}
  1221		var excludeHeader map[string]bool
  1222		delHeader := func(key string) {
  1223			if owned {
  1224				header.Del(key)
  1225				return
  1226			}
  1227			if _, ok := header[key]; !ok {
  1228				return
  1229			}
  1230			if excludeHeader == nil {
  1231				excludeHeader = make(map[string]bool)
  1232			}
  1233			excludeHeader[key] = true
  1234		}
  1235		var setHeader extraHeader
  1236	
  1237		// Don't write out the fake "Trailer:foo" keys. See TrailerPrefix.
  1238		trailers := false
  1239		for k := range cw.header {
  1240			if strings.HasPrefix(k, TrailerPrefix) {
  1241				if excludeHeader == nil {
  1242					excludeHeader = make(map[string]bool)
  1243				}
  1244				excludeHeader[k] = true
  1245				trailers = true
  1246			}
  1247		}
  1248		for _, v := range cw.header["Trailer"] {
  1249			trailers = true
  1250			foreachHeaderElement(v, cw.res.declareTrailer)
  1251		}
  1252	
  1253		te := header.get("Transfer-Encoding")
  1254		hasTE := te != ""
  1255	
  1256		// If the handler is done but never sent a Content-Length
  1257		// response header and this is our first (and last) write, set
  1258		// it, even to zero. This helps HTTP/1.0 clients keep their
  1259		// "keep-alive" connections alive.
  1260		// Exceptions: 304/204/1xx responses never get Content-Length, and if
  1261		// it was a HEAD request, we don't know the difference between
  1262		// 0 actual bytes and 0 bytes because the handler noticed it
  1263		// was a HEAD request and chose not to write anything. So for
  1264		// HEAD, the handler should either write the Content-Length or
  1265		// write non-zero bytes. If it's actually 0 bytes and the
  1266		// handler never looked at the Request.Method, we just don't
  1267		// send a Content-Length header.
  1268		// Further, we don't send an automatic Content-Length if they
  1269		// set a Transfer-Encoding, because they're generally incompatible.
  1270		if w.handlerDone.isSet() && !trailers && !hasTE && bodyAllowedForStatus(w.status) && header.get("Content-Length") == "" && (!isHEAD || len(p) > 0) {
  1271			w.contentLength = int64(len(p))
  1272			setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
  1273		}
  1274	
  1275		// If this was an HTTP/1.0 request with keep-alive and we sent a
  1276		// Content-Length back, we can make this a keep-alive response ...
  1277		if w.wants10KeepAlive && keepAlivesEnabled {
  1278			sentLength := header.get("Content-Length") != ""
  1279			if sentLength && header.get("Connection") == "keep-alive" {
  1280				w.closeAfterReply = false
  1281			}
  1282		}
  1283	
  1284		// Check for an explicit (and valid) Content-Length header.
  1285		hasCL := w.contentLength != -1
  1286	
  1287		if w.wants10KeepAlive && (isHEAD || hasCL || !bodyAllowedForStatus(w.status)) {
  1288			_, connectionHeaderSet := header["Connection"]
  1289			if !connectionHeaderSet {
  1290				setHeader.connection = "keep-alive"
  1291			}
  1292		} else if !w.req.ProtoAtLeast(1, 1) || w.wantsClose {
  1293			w.closeAfterReply = true
  1294		}
  1295	
  1296		if header.get("Connection") == "close" || !keepAlivesEnabled {
  1297			w.closeAfterReply = true
  1298		}
  1299	
  1300		// If the client wanted a 100-continue but we never sent it to
  1301		// them (or, more strictly: we never finished reading their
  1302		// request body), don't reuse this connection because it's now
  1303		// in an unknown state: we might be sending this response at
  1304		// the same time the client is now sending its request body
  1305		// after a timeout.  (Some HTTP clients send Expect:
  1306		// 100-continue but knowing that some servers don't support
  1307		// it, the clients set a timer and send the body later anyway)
  1308		// If we haven't seen EOF, we can't skip over the unread body
  1309		// because we don't know if the next bytes on the wire will be
  1310		// the body-following-the-timer or the subsequent request.
  1311		// See Issue 11549.
  1312		if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF {
  1313			w.closeAfterReply = true
  1314		}
  1315	
  1316		// Per RFC 2616, we should consume the request body before
  1317		// replying, if the handler hasn't already done so. But we
  1318		// don't want to do an unbounded amount of reading here for
  1319		// DoS reasons, so we only try up to a threshold.
  1320		// TODO(bradfitz): where does RFC 2616 say that? See Issue 15527
  1321		// about HTTP/1.x Handlers concurrently reading and writing, like
  1322		// HTTP/2 handlers can do. Maybe this code should be relaxed?
  1323		if w.req.ContentLength != 0 && !w.closeAfterReply {
  1324			var discard, tooBig bool
  1325	
  1326			switch bdy := w.req.Body.(type) {
  1327			case *expectContinueReader:
  1328				if bdy.resp.wroteContinue {
  1329					discard = true
  1330				}
  1331			case *body:
  1332				bdy.mu.Lock()
  1333				switch {
  1334				case bdy.closed:
  1335					if !bdy.sawEOF {
  1336						// Body was closed in handler with non-EOF error.
  1337						w.closeAfterReply = true
  1338					}
  1339				case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes:
  1340					tooBig = true
  1341				default:
  1342					discard = true
  1343				}
  1344				bdy.mu.Unlock()
  1345			default:
  1346				discard = true
  1347			}
  1348	
  1349			if discard {
  1350				_, err := io.CopyN(ioutil.Discard, w.reqBody, maxPostHandlerReadBytes+1)
  1351				switch err {
  1352				case nil:
  1353					// There must be even more data left over.
  1354					tooBig = true
  1355				case ErrBodyReadAfterClose:
  1356					// Body was already consumed and closed.
  1357				case io.EOF:
  1358					// The remaining body was just consumed, close it.
  1359					err = w.reqBody.Close()
  1360					if err != nil {
  1361						w.closeAfterReply = true
  1362					}
  1363				default:
  1364					// Some other kind of error occurred, like a read timeout, or
  1365					// corrupt chunked encoding. In any case, whatever remains
  1366					// on the wire must not be parsed as another HTTP request.
  1367					w.closeAfterReply = true
  1368				}
  1369			}
  1370	
  1371			if tooBig {
  1372				w.requestTooLarge()
  1373				delHeader("Connection")
  1374				setHeader.connection = "close"
  1375			}
  1376		}
  1377	
  1378		code := w.status
  1379		if bodyAllowedForStatus(code) {
  1380			// If no content type, apply sniffing algorithm to body.
  1381			_, haveType := header["Content-Type"]
  1382			if !haveType && !hasTE && len(p) > 0 {
  1383				setHeader.contentType = DetectContentType(p)
  1384			}
  1385		} else {
  1386			for _, k := range suppressedHeaders(code) {
  1387				delHeader(k)
  1388			}
  1389		}
  1390	
  1391		if !header.has("Date") {
  1392			setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now())
  1393		}
  1394	
  1395		if hasCL && hasTE && te != "identity" {
  1396			// TODO: return an error if WriteHeader gets a return parameter
  1397			// For now just ignore the Content-Length.
  1398			w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
  1399				te, w.contentLength)
  1400			delHeader("Content-Length")
  1401			hasCL = false
  1402		}
  1403	
  1404		if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) {
  1405			// do nothing
  1406		} else if code == StatusNoContent {
  1407			delHeader("Transfer-Encoding")
  1408		} else if hasCL {
  1409			delHeader("Transfer-Encoding")
  1410		} else if w.req.ProtoAtLeast(1, 1) {
  1411			// HTTP/1.1 or greater: Transfer-Encoding has been set to identity, and no
  1412			// content-length has been provided. The connection must be closed after the
  1413			// reply is written, and no chunking is to be done. This is the setup
  1414			// recommended in the Server-Sent Events candidate recommendation 11,
  1415			// section 8.
  1416			if hasTE && te == "identity" {
  1417				cw.chunking = false
  1418				w.closeAfterReply = true
  1419			} else {
  1420				// HTTP/1.1 or greater: use chunked transfer encoding
  1421				// to avoid closing the connection at EOF.
  1422				cw.chunking = true
  1423				setHeader.transferEncoding = "chunked"
  1424				if hasTE && te == "chunked" {
  1425					// We will send the chunked Transfer-Encoding header later.
  1426					delHeader("Transfer-Encoding")
  1427				}
  1428			}
  1429		} else {
  1430			// HTTP version < 1.1: cannot do chunked transfer
  1431			// encoding and we don't know the Content-Length so
  1432			// signal EOF by closing connection.
  1433			w.closeAfterReply = true
  1434			delHeader("Transfer-Encoding") // in case already set
  1435		}
  1436	
  1437		// Cannot use Content-Length with non-identity Transfer-Encoding.
  1438		if cw.chunking {
  1439			delHeader("Content-Length")
  1440		}
  1441		if !w.req.ProtoAtLeast(1, 0) {
  1442			return
  1443		}
  1444	
  1445		if w.closeAfterReply && (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) {
  1446			delHeader("Connection")
  1447			if w.req.ProtoAtLeast(1, 1) {
  1448				setHeader.connection = "close"
  1449			}
  1450		}
  1451	
  1452		writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
  1453		cw.header.WriteSubset(w.conn.bufw, excludeHeader)
  1454		setHeader.Write(w.conn.bufw)
  1455		w.conn.bufw.Write(crlf)
  1456	}
  1457	
  1458	// foreachHeaderElement splits v according to the "#rule" construction
  1459	// in RFC 7230 section 7 and calls fn for each non-empty element.
  1460	func foreachHeaderElement(v string, fn func(string)) {
  1461		v = textproto.TrimString(v)
  1462		if v == "" {
  1463			return
  1464		}
  1465		if !strings.Contains(v, ",") {
  1466			fn(v)
  1467			return
  1468		}
  1469		for _, f := range strings.Split(v, ",") {
  1470			if f = textproto.TrimString(f); f != "" {
  1471				fn(f)
  1472			}
  1473		}
  1474	}
  1475	
  1476	// writeStatusLine writes an HTTP/1.x Status-Line (RFC 7230 Section 3.1.2)
  1477	// to bw. is11 is whether the HTTP request is HTTP/1.1. false means HTTP/1.0.
  1478	// code is the response status code.
  1479	// scratch is an optional scratch buffer. If it has at least capacity 3, it's used.
  1480	func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) {
  1481		if is11 {
  1482			bw.WriteString("HTTP/1.1 ")
  1483		} else {
  1484			bw.WriteString("HTTP/1.0 ")
  1485		}
  1486		if text, ok := statusText[code]; ok {
  1487			bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10))
  1488			bw.WriteByte(' ')
  1489			bw.WriteString(text)
  1490			bw.WriteString("\r\n")
  1491		} else {
  1492			// don't worry about performance
  1493			fmt.Fprintf(bw, "%03d status code %d\r\n", code, code)
  1494		}
  1495	}
  1496	
  1497	// bodyAllowed reports whether a Write is allowed for this response type.
  1498	// It's illegal to call this before the header has been flushed.
  1499	func (w *response) bodyAllowed() bool {
  1500		if !w.wroteHeader {
  1501			panic("")
  1502		}
  1503		return bodyAllowedForStatus(w.status)
  1504	}
  1505	
  1506	// The Life Of A Write is like this:
  1507	//
  1508	// Handler starts. No header has been sent. The handler can either
  1509	// write a header, or just start writing. Writing before sending a header
  1510	// sends an implicitly empty 200 OK header.
  1511	//
  1512	// If the handler didn't declare a Content-Length up front, we either
  1513	// go into chunking mode or, if the handler finishes running before
  1514	// the chunking buffer size, we compute a Content-Length and send that
  1515	// in the header instead.
  1516	//
  1517	// Likewise, if the handler didn't set a Content-Type, we sniff that
  1518	// from the initial chunk of output.
  1519	//
  1520	// The Writers are wired together like:
  1521	//
  1522	// 1. *response (the ResponseWriter) ->
  1523	// 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes
  1524	// 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
  1525	//    and which writes the chunk headers, if needed.
  1526	// 4. conn.buf, a bufio.Writer of default (4kB) bytes, writing to ->
  1527	// 5. checkConnErrorWriter{c}, which notes any non-nil error on Write
  1528	//    and populates c.werr with it if so. but otherwise writes to:
  1529	// 6. the rwc, the net.Conn.
  1530	//
  1531	// TODO(bradfitz): short-circuit some of the buffering when the
  1532	// initial header contains both a Content-Type and Content-Length.
  1533	// Also short-circuit in (1) when the header's been sent and not in
  1534	// chunking mode, writing directly to (4) instead, if (2) has no
  1535	// buffered data. More generally, we could short-circuit from (1) to
  1536	// (3) even in chunking mode if the write size from (1) is over some
  1537	// threshold and nothing is in (2).  The answer might be mostly making
  1538	// bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
  1539	// with this instead.
  1540	func (w *response) Write(data []byte) (n int, err error) {
  1541		return w.write(len(data), data, "")
  1542	}
  1543	
  1544	func (w *response) WriteString(data string) (n int, err error) {
  1545		return w.write(len(data), nil, data)
  1546	}
  1547	
  1548	// either dataB or dataS is non-zero.
  1549	func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1550		if w.conn.hijacked() {
  1551			if lenData > 0 {
  1552				caller := relevantCaller()
  1553				w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
  1554			}
  1555			return 0, ErrHijacked
  1556		}
  1557		if !w.wroteHeader {
  1558			w.WriteHeader(StatusOK)
  1559		}
  1560		if lenData == 0 {
  1561			return 0, nil
  1562		}
  1563		if !w.bodyAllowed() {
  1564			return 0, ErrBodyNotAllowed
  1565		}
  1566	
  1567		w.written += int64(lenData) // ignoring errors, for errorKludge
  1568		if w.contentLength != -1 && w.written > w.contentLength {
  1569			return 0, ErrContentLength
  1570		}
  1571		if dataB != nil {
  1572			return w.w.Write(dataB)
  1573		} else {
  1574			return w.w.WriteString(dataS)
  1575		}
  1576	}
  1577	
  1578	func (w *response) finishRequest() {
  1579		w.handlerDone.setTrue()
  1580	
  1581		if !w.wroteHeader {
  1582			w.WriteHeader(StatusOK)
  1583		}
  1584	
  1585		w.w.Flush()
  1586		putBufioWriter(w.w)
  1587		w.cw.close()
  1588		w.conn.bufw.Flush()
  1589	
  1590		w.conn.r.abortPendingRead()
  1591	
  1592		// Close the body (regardless of w.closeAfterReply) so we can
  1593		// re-use its bufio.Reader later safely.
  1594		w.reqBody.Close()
  1595	
  1596		if w.req.MultipartForm != nil {
  1597			w.req.MultipartForm.RemoveAll()
  1598		}
  1599	}
  1600	
  1601	// shouldReuseConnection reports whether the underlying TCP connection can be reused.
  1602	// It must only be called after the handler is done executing.
  1603	func (w *response) shouldReuseConnection() bool {
  1604		if w.closeAfterReply {
  1605			// The request or something set while executing the
  1606			// handler indicated we shouldn't reuse this
  1607			// connection.
  1608			return false
  1609		}
  1610	
  1611		if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
  1612			// Did not write enough. Avoid getting out of sync.
  1613			return false
  1614		}
  1615	
  1616		// There was some error writing to the underlying connection
  1617		// during the request, so don't re-use this conn.
  1618		if w.conn.werr != nil {
  1619			return false
  1620		}
  1621	
  1622		if w.closedRequestBodyEarly() {
  1623			return false
  1624		}
  1625	
  1626		return true
  1627	}
  1628	
  1629	func (w *response) closedRequestBodyEarly() bool {
  1630		body, ok := w.req.Body.(*body)
  1631		return ok && body.didEarlyClose()
  1632	}
  1633	
  1634	func (w *response) Flush() {
  1635		if !w.wroteHeader {
  1636			w.WriteHeader(StatusOK)
  1637		}
  1638		w.w.Flush()
  1639		w.cw.flush()
  1640	}
  1641	
  1642	func (c *conn) finalFlush() {
  1643		if c.bufr != nil {
  1644			// Steal the bufio.Reader (~4KB worth of memory) and its associated
  1645			// reader for a future connection.
  1646			putBufioReader(c.bufr)
  1647			c.bufr = nil
  1648		}
  1649	
  1650		if c.bufw != nil {
  1651			c.bufw.Flush()
  1652			// Steal the bufio.Writer (~4KB worth of memory) and its associated
  1653			// writer for a future connection.
  1654			putBufioWriter(c.bufw)
  1655			c.bufw = nil
  1656		}
  1657	}
  1658	
  1659	// Close the connection.
  1660	func (c *conn) close() {
  1661		c.finalFlush()
  1662		c.rwc.Close()
  1663	}
  1664	
  1665	// rstAvoidanceDelay is the amount of time we sleep after closing the
  1666	// write side of a TCP connection before closing the entire socket.
  1667	// By sleeping, we increase the chances that the client sees our FIN
  1668	// and processes its final data before they process the subsequent RST
  1669	// from closing a connection with known unread data.
  1670	// This RST seems to occur mostly on BSD systems. (And Windows?)
  1671	// This timeout is somewhat arbitrary (~latency around the planet).
  1672	const rstAvoidanceDelay = 500 * time.Millisecond
  1673	
  1674	type closeWriter interface {
  1675		CloseWrite() error
  1676	}
  1677	
  1678	var _ closeWriter = (*net.TCPConn)(nil)
  1679	
  1680	// closeWrite flushes any outstanding data and sends a FIN packet (if
  1681	// client is connected via TCP), signalling that we're done. We then
  1682	// pause for a bit, hoping the client processes it before any
  1683	// subsequent RST.
  1684	//
  1685	// See https://golang.org/issue/3595
  1686	func (c *conn) closeWriteAndWait() {
  1687		c.finalFlush()
  1688		if tcp, ok := c.rwc.(closeWriter); ok {
  1689			tcp.CloseWrite()
  1690		}
  1691		time.Sleep(rstAvoidanceDelay)
  1692	}
  1693	
  1694	// validNPN reports whether the proto is not a blacklisted Next
  1695	// Protocol Negotiation protocol. Empty and built-in protocol types
  1696	// are blacklisted and can't be overridden with alternate
  1697	// implementations.
  1698	func validNPN(proto string) bool {
  1699		switch proto {
  1700		case "", "http/1.1", "http/1.0":
  1701			return false
  1702		}
  1703		return true
  1704	}
  1705	
  1706	func (c *conn) setState(nc net.Conn, state ConnState) {
  1707		srv := c.server
  1708		switch state {
  1709		case StateNew:
  1710			srv.trackConn(c, true)
  1711		case StateHijacked, StateClosed:
  1712			srv.trackConn(c, false)
  1713		}
  1714		if state > 0xff || state < 0 {
  1715			panic("internal error")
  1716		}
  1717		packedState := uint64(time.Now().Unix()<<8) | uint64(state)
  1718		atomic.StoreUint64(&c.curState.atomic, packedState)
  1719		if hook := srv.ConnState; hook != nil {
  1720			hook(nc, state)
  1721		}
  1722	}
  1723	
  1724	func (c *conn) getState() (state ConnState, unixSec int64) {
  1725		packedState := atomic.LoadUint64(&c.curState.atomic)
  1726		return ConnState(packedState & 0xff), int64(packedState >> 8)
  1727	}
  1728	
  1729	// badRequestError is a literal string (used by in the server in HTML,
  1730	// unescaped) to tell the user why their request was bad. It should
  1731	// be plain text without user info or other embedded errors.
  1732	type badRequestError string
  1733	
  1734	func (e badRequestError) Error() string { return "Bad Request: " + string(e) }
  1735	
  1736	// ErrAbortHandler is a sentinel panic value to abort a handler.
  1737	// While any panic from ServeHTTP aborts the response to the client,
  1738	// panicking with ErrAbortHandler also suppresses logging of a stack
  1739	// trace to the server's error log.
  1740	var ErrAbortHandler = errors.New("net/http: abort Handler")
  1741	
  1742	// isCommonNetReadError reports whether err is a common error
  1743	// encountered during reading a request off the network when the
  1744	// client has gone away or had its read fail somehow. This is used to
  1745	// determine which logs are interesting enough to log about.
  1746	func isCommonNetReadError(err error) bool {
  1747		if err == io.EOF {
  1748			return true
  1749		}
  1750		if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
  1751			return true
  1752		}
  1753		if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
  1754			return true
  1755		}
  1756		return false
  1757	}
  1758	
  1759	// Serve a new connection.
  1760	func (c *conn) serve(ctx context.Context) {
  1761		c.remoteAddr = c.rwc.RemoteAddr().String()
  1762		ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr())
  1763		defer func() {
  1764			if err := recover(); err != nil && err != ErrAbortHandler {
  1765				const size = 64 << 10
  1766				buf := make([]byte, size)
  1767				buf = buf[:runtime.Stack(buf, false)]
  1768				c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
  1769			}
  1770			if !c.hijacked() {
  1771				c.close()
  1772				c.setState(c.rwc, StateClosed)
  1773			}
  1774		}()
  1775	
  1776		if tlsConn, ok := c.rwc.(*tls.Conn); ok {
  1777			if d := c.server.ReadTimeout; d != 0 {
  1778				c.rwc.SetReadDeadline(time.Now().Add(d))
  1779			}
  1780			if d := c.server.WriteTimeout; d != 0 {
  1781				c.rwc.SetWriteDeadline(time.Now().Add(d))
  1782			}
  1783			if err := tlsConn.Handshake(); err != nil {
  1784				// If the handshake failed due to the client not speaking
  1785				// TLS, assume they're speaking plaintext HTTP and write a
  1786				// 400 response on the TLS conn's underlying net.Conn.
  1787				if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
  1788					io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
  1789					re.Conn.Close()
  1790					return
  1791				}
  1792				c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
  1793				return
  1794			}
  1795			c.tlsState = new(tls.ConnectionState)
  1796			*c.tlsState = tlsConn.ConnectionState()
  1797			if proto := c.tlsState.NegotiatedProtocol; validNPN(proto) {
  1798				if fn := c.server.TLSNextProto[proto]; fn != nil {
  1799					h := initNPNRequest{ctx, tlsConn, serverHandler{c.server}}
  1800					fn(c.server, tlsConn, h)
  1801				}
  1802				return
  1803			}
  1804		}
  1805	
  1806		// HTTP/1.x from here on.
  1807	
  1808		ctx, cancelCtx := context.WithCancel(ctx)
  1809		c.cancelCtx = cancelCtx
  1810		defer cancelCtx()
  1811	
  1812		c.r = &connReader{conn: c}
  1813		c.bufr = newBufioReader(c.r)
  1814		c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
  1815	
  1816		for {
  1817			w, err := c.readRequest(ctx)
  1818			if c.r.remain != c.server.initialReadLimitSize() {
  1819				// If we read any bytes off the wire, we're active.
  1820				c.setState(c.rwc, StateActive)
  1821			}
  1822			if err != nil {
  1823				const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
  1824	
  1825				switch {
  1826				case err == errTooLarge:
  1827					// Their HTTP client may or may not be
  1828					// able to read this if we're
  1829					// responding to them and hanging up
  1830					// while they're still writing their
  1831					// request. Undefined behavior.
  1832					const publicErr = "431 Request Header Fields Too Large"
  1833					fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
  1834					c.closeWriteAndWait()
  1835					return
  1836	
  1837				case isUnsupportedTEError(err):
  1838					// Respond as per RFC 7230 Section 3.3.1 which says,
  1839					//      A server that receives a request message with a
  1840					//      transfer coding it does not understand SHOULD
  1841					//      respond with 501 (Unimplemented).
  1842					code := StatusNotImplemented
  1843	
  1844					// We purposefully aren't echoing back the transfer-encoding's value,
  1845					// so as to mitigate the risk of cross side scripting by an attacker.
  1846					fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders)
  1847					return
  1848	
  1849				case isCommonNetReadError(err):
  1850					return // don't reply
  1851	
  1852				default:
  1853					publicErr := "400 Bad Request"
  1854					if v, ok := err.(badRequestError); ok {
  1855						publicErr = publicErr + ": " + string(v)
  1856					}
  1857	
  1858					fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
  1859					return
  1860				}
  1861			}
  1862	
  1863			// Expect 100 Continue support
  1864			req := w.req
  1865			if req.expectsContinue() {
  1866				if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
  1867					// Wrap the Body reader with one that replies on the connection
  1868					req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
  1869				}
  1870			} else if req.Header.get("Expect") != "" {
  1871				w.sendExpectationFailed()
  1872				return
  1873			}
  1874	
  1875			c.curReq.Store(w)
  1876	
  1877			if requestBodyRemains(req.Body) {
  1878				registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
  1879			} else {
  1880				w.conn.r.startBackgroundRead()
  1881			}
  1882	
  1883			// HTTP cannot have multiple simultaneous active requests.[*]
  1884			// Until the server replies to this request, it can't read another,
  1885			// so we might as well run the handler in this goroutine.
  1886			// [*] Not strictly true: HTTP pipelining. We could let them all process
  1887			// in parallel even if their responses need to be serialized.
  1888			// But we're not going to implement HTTP pipelining because it
  1889			// was never deployed in the wild and the answer is HTTP/2.
  1890			serverHandler{c.server}.ServeHTTP(w, w.req)
  1891			w.cancelCtx()
  1892			if c.hijacked() {
  1893				return
  1894			}
  1895			w.finishRequest()
  1896			if !w.shouldReuseConnection() {
  1897				if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
  1898					c.closeWriteAndWait()
  1899				}
  1900				return
  1901			}
  1902			c.setState(c.rwc, StateIdle)
  1903			c.curReq.Store((*response)(nil))
  1904	
  1905			if !w.conn.server.doKeepAlives() {
  1906				// We're in shutdown mode. We might've replied
  1907				// to the user without "Connection: close" and
  1908				// they might think they can send another
  1909				// request, but such is life with HTTP/1.1.
  1910				return
  1911			}
  1912	
  1913			if d := c.server.idleTimeout(); d != 0 {
  1914				c.rwc.SetReadDeadline(time.Now().Add(d))
  1915				if _, err := c.bufr.Peek(4); err != nil {
  1916					return
  1917				}
  1918			}
  1919			c.rwc.SetReadDeadline(time.Time{})
  1920		}
  1921	}
  1922	
  1923	func (w *response) sendExpectationFailed() {
  1924		// TODO(bradfitz): let ServeHTTP handlers handle
  1925		// requests with non-standard expectation[s]? Seems
  1926		// theoretical at best, and doesn't fit into the
  1927		// current ServeHTTP model anyway. We'd need to
  1928		// make the ResponseWriter an optional
  1929		// "ExpectReplier" interface or something.
  1930		//
  1931		// For now we'll just obey RFC 7231 5.1.1 which says
  1932		// "A server that receives an Expect field-value other
  1933		// than 100-continue MAY respond with a 417 (Expectation
  1934		// Failed) status code to indicate that the unexpected
  1935		// expectation cannot be met."
  1936		w.Header().Set("Connection", "close")
  1937		w.WriteHeader(StatusExpectationFailed)
  1938		w.finishRequest()
  1939	}
  1940	
  1941	// Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
  1942	// and a Hijacker.
  1943	func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
  1944		if w.handlerDone.isSet() {
  1945			panic("net/http: Hijack called after ServeHTTP finished")
  1946		}
  1947		if w.wroteHeader {
  1948			w.cw.flush()
  1949		}
  1950	
  1951		c := w.conn
  1952		c.mu.Lock()
  1953		defer c.mu.Unlock()
  1954	
  1955		// Release the bufioWriter that writes to the chunk writer, it is not
  1956		// used after a connection has been hijacked.
  1957		rwc, buf, err = c.hijackLocked()
  1958		if err == nil {
  1959			putBufioWriter(w.w)
  1960			w.w = nil
  1961		}
  1962		return rwc, buf, err
  1963	}
  1964	
  1965	func (w *response) CloseNotify() <-chan bool {
  1966		if w.handlerDone.isSet() {
  1967			panic("net/http: CloseNotify called after ServeHTTP finished")
  1968		}
  1969		return w.closeNotifyCh
  1970	}
  1971	
  1972	func registerOnHitEOF(rc io.ReadCloser, fn func()) {
  1973		switch v := rc.(type) {
  1974		case *expectContinueReader:
  1975			registerOnHitEOF(v.readCloser, fn)
  1976		case *body:
  1977			v.registerOnHitEOF(fn)
  1978		default:
  1979			panic("unexpected type " + fmt.Sprintf("%T", rc))
  1980		}
  1981	}
  1982	
  1983	// requestBodyRemains reports whether future calls to Read
  1984	// on rc might yield more data.
  1985	func requestBodyRemains(rc io.ReadCloser) bool {
  1986		if rc == NoBody {
  1987			return false
  1988		}
  1989		switch v := rc.(type) {
  1990		case *expectContinueReader:
  1991			return requestBodyRemains(v.readCloser)
  1992		case *body:
  1993			return v.bodyRemains()
  1994		default:
  1995			panic("unexpected type " + fmt.Sprintf("%T", rc))
  1996		}
  1997	}
  1998	
  1999	// The HandlerFunc type is an adapter to allow the use of
  2000	// ordinary functions as HTTP handlers. If f is a function
  2001	// with the appropriate signature, HandlerFunc(f) is a
  2002	// Handler that calls f.
  2003	type HandlerFunc func(ResponseWriter, *Request)
  2004	
  2005	// ServeHTTP calls f(w, r).
  2006	func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
  2007		f(w, r)
  2008	}
  2009	
  2010	// Helper handlers
  2011	
  2012	// Error replies to the request with the specified error message and HTTP code.
  2013	// It does not otherwise end the request; the caller should ensure no further
  2014	// writes are done to w.
  2015	// The error message should be plain text.
  2016	func Error(w ResponseWriter, error string, code int) {
  2017		w.Header().Set("Content-Type", "text/plain; charset=utf-8")
  2018		w.Header().Set("X-Content-Type-Options", "nosniff")
  2019		w.WriteHeader(code)
  2020		fmt.Fprintln(w, error)
  2021	}
  2022	
  2023	// NotFound replies to the request with an HTTP 404 not found error.
  2024	func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
  2025	
  2026	// NotFoundHandler returns a simple request handler
  2027	// that replies to each request with a ``404 page not found'' reply.
  2028	func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
  2029	
  2030	// StripPrefix returns a handler that serves HTTP requests
  2031	// by removing the given prefix from the request URL's Path
  2032	// and invoking the handler h. StripPrefix handles a
  2033	// request for a path that doesn't begin with prefix by
  2034	// replying with an HTTP 404 not found error.
  2035	func StripPrefix(prefix string, h Handler) Handler {
  2036		if prefix == "" {
  2037			return h
  2038		}
  2039		return HandlerFunc(func(w ResponseWriter, r *Request) {
  2040			if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
  2041				r2 := new(Request)
  2042				*r2 = *r
  2043				r2.URL = new(url.URL)
  2044				*r2.URL = *r.URL
  2045				r2.URL.Path = p
  2046				h.ServeHTTP(w, r2)
  2047			} else {
  2048				NotFound(w, r)
  2049			}
  2050		})
  2051	}
  2052	
  2053	// Redirect replies to the request with a redirect to url,
  2054	// which may be a path relative to the request path.
  2055	//
  2056	// The provided code should be in the 3xx range and is usually
  2057	// StatusMovedPermanently, StatusFound or StatusSeeOther.
  2058	//
  2059	// If the Content-Type header has not been set, Redirect sets it
  2060	// to "text/html; charset=utf-8" and writes a small HTML body.
  2061	// Setting the Content-Type header to any value, including nil,
  2062	// disables that behavior.
  2063	func Redirect(w ResponseWriter, r *Request, url string, code int) {
  2064		// parseURL is just url.Parse (url is shadowed for godoc).
  2065		if u, err := parseURL(url); err == nil {
  2066			// If url was relative, make its path absolute by
  2067			// combining with request path.
  2068			// The client would probably do this for us,
  2069			// but doing it ourselves is more reliable.
  2070			// See RFC 7231, section 7.1.2
  2071			if u.Scheme == "" && u.Host == "" {
  2072				oldpath := r.URL.Path
  2073				if oldpath == "" { // should not happen, but avoid a crash if it does
  2074					oldpath = "/"
  2075				}
  2076	
  2077				// no leading http://server
  2078				if url == "" || url[0] != '/' {
  2079					// make relative path absolute
  2080					olddir, _ := path.Split(oldpath)
  2081					url = olddir + url
  2082				}
  2083	
  2084				var query string
  2085				if i := strings.Index(url, "?"); i != -1 {
  2086					url, query = url[:i], url[i:]
  2087				}
  2088	
  2089				// clean up but preserve trailing slash
  2090				trailing := strings.HasSuffix(url, "/")
  2091				url = path.Clean(url)
  2092				if trailing && !strings.HasSuffix(url, "/") {
  2093					url += "/"
  2094				}
  2095				url += query
  2096			}
  2097		}
  2098	
  2099		h := w.Header()
  2100	
  2101		// RFC 7231 notes that a short HTML body is usually included in
  2102		// the response because older user agents may not understand 301/307.
  2103		// Do it only if the request didn't already have a Content-Type header.
  2104		_, hadCT := h["Content-Type"]
  2105	
  2106		h.Set("Location", hexEscapeNonASCII(url))
  2107		if !hadCT && (r.Method == "GET" || r.Method == "HEAD") {
  2108			h.Set("Content-Type", "text/html; charset=utf-8")
  2109		}
  2110		w.WriteHeader(code)
  2111	
  2112		// Shouldn't send the body for POST or HEAD; that leaves GET.
  2113		if !hadCT && r.Method == "GET" {
  2114			body := "<a href=\"" + htmlEscape(url) + "\">" + statusText[code] + "</a>.\n"
  2115			fmt.Fprintln(w, body)
  2116		}
  2117	}
  2118	
  2119	// parseURL is just url.Parse. It exists only so that url.Parse can be called
  2120	// in places where url is shadowed for godoc. See https://golang.org/cl/49930.
  2121	var parseURL = url.Parse
  2122	
  2123	var htmlReplacer = strings.NewReplacer(
  2124		"&", "&amp;",
  2125		"<", "&lt;",
  2126		">", "&gt;",
  2127		// "&#34;" is shorter than "&quot;".
  2128		`"`, "&#34;",
  2129		// "&#39;" is shorter than "&apos;" and apos was not in HTML until HTML5.
  2130		"'", "&#39;",
  2131	)
  2132	
  2133	func htmlEscape(s string) string {
  2134		return htmlReplacer.Replace(s)
  2135	}
  2136	
  2137	// Redirect to a fixed URL
  2138	type redirectHandler struct {
  2139		url  string
  2140		code int
  2141	}
  2142	
  2143	func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
  2144		Redirect(w, r, rh.url, rh.code)
  2145	}
  2146	
  2147	// RedirectHandler returns a request handler that redirects
  2148	// each request it receives to the given url using the given
  2149	// status code.
  2150	//
  2151	// The provided code should be in the 3xx range and is usually
  2152	// StatusMovedPermanently, StatusFound or StatusSeeOther.
  2153	func RedirectHandler(url string, code int) Handler {
  2154		return &redirectHandler{url, code}
  2155	}
  2156	
  2157	// ServeMux is an HTTP request multiplexer.
  2158	// It matches the URL of each incoming request against a list of registered
  2159	// patterns and calls the handler for the pattern that
  2160	// most closely matches the URL.
  2161	//
  2162	// Patterns name fixed, rooted paths, like "/favicon.ico",
  2163	// or rooted subtrees, like "/images/" (note the trailing slash).
  2164	// Longer patterns take precedence over shorter ones, so that
  2165	// if there are handlers registered for both "/images/"
  2166	// and "/images/thumbnails/", the latter handler will be
  2167	// called for paths beginning "/images/thumbnails/" and the
  2168	// former will receive requests for any other paths in the
  2169	// "/images/" subtree.
  2170	//
  2171	// Note that since a pattern ending in a slash names a rooted subtree,
  2172	// the pattern "/" matches all paths not matched by other registered
  2173	// patterns, not just the URL with Path == "/".
  2174	//
  2175	// If a subtree has been registered and a request is received naming the
  2176	// subtree root without its trailing slash, ServeMux redirects that
  2177	// request to the subtree root (adding the trailing slash). This behavior can
  2178	// be overridden with a separate registration for the path without
  2179	// the trailing slash. For example, registering "/images/" causes ServeMux
  2180	// to redirect a request for "/images" to "/images/", unless "/images" has
  2181	// been registered separately.
  2182	//
  2183	// Patterns may optionally begin with a host name, restricting matches to
  2184	// URLs on that host only. Host-specific patterns take precedence over
  2185	// general patterns, so that a handler might register for the two patterns
  2186	// "/codesearch" and "codesearch.google.com/" without also taking over
  2187	// requests for "http://www.google.com/".
  2188	//
  2189	// ServeMux also takes care of sanitizing the URL request path and the Host
  2190	// header, stripping the port number and redirecting any request containing . or
  2191	// .. elements or repeated slashes to an equivalent, cleaner URL.
  2192	type ServeMux struct {
  2193		mu    sync.RWMutex
  2194		m     map[string]muxEntry
  2195		es    []muxEntry // slice of entries sorted from longest to shortest.
  2196		hosts bool       // whether any patterns contain hostnames
  2197	}
  2198	
  2199	type muxEntry struct {
  2200		h       Handler
  2201		pattern string
  2202	}
  2203	
  2204	// NewServeMux allocates and returns a new ServeMux.
  2205	func NewServeMux() *ServeMux { return new(ServeMux) }
  2206	
  2207	// DefaultServeMux is the default ServeMux used by Serve.
  2208	var DefaultServeMux = &defaultServeMux
  2209	
  2210	var defaultServeMux ServeMux
  2211	
  2212	// cleanPath returns the canonical path for p, eliminating . and .. elements.
  2213	func cleanPath(p string) string {
  2214		if p == "" {
  2215			return "/"
  2216		}
  2217		if p[0] != '/' {
  2218			p = "/" + p
  2219		}
  2220		np := path.Clean(p)
  2221		// path.Clean removes trailing slash except for root;
  2222		// put the trailing slash back if necessary.
  2223		if p[len(p)-1] == '/' && np != "/" {
  2224			// Fast path for common case of p being the string we want:
  2225			if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
  2226				np = p
  2227			} else {
  2228				np += "/"
  2229			}
  2230		}
  2231		return np
  2232	}
  2233	
  2234	// stripHostPort returns h without any trailing ":<port>".
  2235	func stripHostPort(h string) string {
  2236		// If no port on host, return unchanged
  2237		if strings.IndexByte(h, ':') == -1 {
  2238			return h
  2239		}
  2240		host, _, err := net.SplitHostPort(h)
  2241		if err != nil {
  2242			return h // on error, return unchanged
  2243		}
  2244		return host
  2245	}
  2246	
  2247	// Find a handler on a handler map given a path string.
  2248	// Most-specific (longest) pattern wins.
  2249	func (mux *ServeMux) match(path string) (h Handler, pattern string) {
  2250		// Check for exact match first.
  2251		v, ok := mux.m[path]
  2252		if ok {
  2253			return v.h, v.pattern
  2254		}
  2255	
  2256		// Check for longest valid match.  mux.es contains all patterns
  2257		// that end in / sorted from longest to shortest.
  2258		for _, e := range mux.es {
  2259			if strings.HasPrefix(path, e.pattern) {
  2260				return e.h, e.pattern
  2261			}
  2262		}
  2263		return nil, ""
  2264	}
  2265	
  2266	// redirectToPathSlash determines if the given path needs appending "/" to it.
  2267	// This occurs when a handler for path + "/" was already registered, but
  2268	// not for path itself. If the path needs appending to, it creates a new
  2269	// URL, setting the path to u.Path + "/" and returning true to indicate so.
  2270	func (mux *ServeMux) redirectToPathSlash(host, path string, u *url.URL) (*url.URL, bool) {
  2271		mux.mu.RLock()
  2272		shouldRedirect := mux.shouldRedirectRLocked(host, path)
  2273		mux.mu.RUnlock()
  2274		if !shouldRedirect {
  2275			return u, false
  2276		}
  2277		path = path + "/"
  2278		u = &url.URL{Path: path, RawQuery: u.RawQuery}
  2279		return u, true
  2280	}
  2281	
  2282	// shouldRedirectRLocked reports whether the given path and host should be redirected to
  2283	// path+"/". This should happen if a handler is registered for path+"/" but
  2284	// not path -- see comments at ServeMux.
  2285	func (mux *ServeMux) shouldRedirectRLocked(host, path string) bool {
  2286		p := []string{path, host + path}
  2287	
  2288		for _, c := range p {
  2289			if _, exist := mux.m[c]; exist {
  2290				return false
  2291			}
  2292		}
  2293	
  2294		n := len(path)
  2295		if n == 0 {
  2296			return false
  2297		}
  2298		for _, c := range p {
  2299			if _, exist := mux.m[c+"/"]; exist {
  2300				return path[n-1] != '/'
  2301			}
  2302		}
  2303	
  2304		return false
  2305	}
  2306	
  2307	// Handler returns the handler to use for the given request,
  2308	// consulting r.Method, r.Host, and r.URL.Path. It always returns
  2309	// a non-nil handler. If the path is not in its canonical form, the
  2310	// handler will be an internally-generated handler that redirects
  2311	// to the canonical path. If the host contains a port, it is ignored
  2312	// when matching handlers.
  2313	//
  2314	// The path and host are used unchanged for CONNECT requests.
  2315	//
  2316	// Handler also returns the registered pattern that matches the
  2317	// request or, in the case of internally-generated redirects,
  2318	// the pattern that will match after following the redirect.
  2319	//
  2320	// If there is no registered handler that applies to the request,
  2321	// Handler returns a ``page not found'' handler and an empty pattern.
  2322	func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
  2323	
  2324		// CONNECT requests are not canonicalized.
  2325		if r.Method == "CONNECT" {
  2326			// If r.URL.Path is /tree and its handler is not registered,
  2327			// the /tree -> /tree/ redirect applies to CONNECT requests
  2328			// but the path canonicalization does not.
  2329			if u, ok := mux.redirectToPathSlash(r.URL.Host, r.URL.Path, r.URL); ok {
  2330				return RedirectHandler(u.String(), StatusMovedPermanently), u.Path
  2331			}
  2332	
  2333			return mux.handler(r.Host, r.URL.Path)
  2334		}
  2335	
  2336		// All other requests have any port stripped and path cleaned
  2337		// before passing to mux.handler.
  2338		host := stripHostPort(r.Host)
  2339		path := cleanPath(r.URL.Path)
  2340	
  2341		// If the given path is /tree and its handler is not registered,
  2342		// redirect for /tree/.
  2343		if u, ok := mux.redirectToPathSlash(host, path, r.URL); ok {
  2344			return RedirectHandler(u.String(), StatusMovedPermanently), u.Path
  2345		}
  2346	
  2347		if path != r.URL.Path {
  2348			_, pattern = mux.handler(host, path)
  2349			url := *r.URL
  2350			url.Path = path
  2351			return RedirectHandler(url.String(), StatusMovedPermanently), pattern
  2352		}
  2353	
  2354		return mux.handler(host, r.URL.Path)
  2355	}
  2356	
  2357	// handler is the main implementation of Handler.
  2358	// The path is known to be in canonical form, except for CONNECT methods.
  2359	func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {
  2360		mux.mu.RLock()
  2361		defer mux.mu.RUnlock()
  2362	
  2363		// Host-specific pattern takes precedence over generic ones
  2364		if mux.hosts {
  2365			h, pattern = mux.match(host + path)
  2366		}
  2367		if h == nil {
  2368			h, pattern = mux.match(path)
  2369		}
  2370		if h == nil {
  2371			h, pattern = NotFoundHandler(), ""
  2372		}
  2373		return
  2374	}
  2375	
  2376	// ServeHTTP dispatches the request to the handler whose
  2377	// pattern most closely matches the request URL.
  2378	func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
  2379		if r.RequestURI == "*" {
  2380			if r.ProtoAtLeast(1, 1) {
  2381				w.Header().Set("Connection", "close")
  2382			}
  2383			w.WriteHeader(StatusBadRequest)
  2384			return
  2385		}
  2386		h, _ := mux.Handler(r)
  2387		h.ServeHTTP(w, r)
  2388	}
  2389	
  2390	// Handle registers the handler for the given pattern.
  2391	// If a handler already exists for pattern, Handle panics.
  2392	func (mux *ServeMux) Handle(pattern string, handler Handler) {
  2393		mux.mu.Lock()
  2394		defer mux.mu.Unlock()
  2395	
  2396		if pattern == "" {
  2397			panic("http: invalid pattern")
  2398		}
  2399		if handler == nil {
  2400			panic("http: nil handler")
  2401		}
  2402		if _, exist := mux.m[pattern]; exist {
  2403			panic("http: multiple registrations for " + pattern)
  2404		}
  2405	
  2406		if mux.m == nil {
  2407			mux.m = make(map[string]muxEntry)
  2408		}
  2409		e := muxEntry{h: handler, pattern: pattern}
  2410		mux.m[pattern] = e
  2411		if pattern[len(pattern)-1] == '/' {
  2412			mux.es = appendSorted(mux.es, e)
  2413		}
  2414	
  2415		if pattern[0] != '/' {
  2416			mux.hosts = true
  2417		}
  2418	}
  2419	
  2420	func appendSorted(es []muxEntry, e muxEntry) []muxEntry {
  2421		n := len(es)
  2422		i := sort.Search(n, func(i int) bool {
  2423			return len(es[i].pattern) < len(e.pattern)
  2424		})
  2425		if i == n {
  2426			return append(es, e)
  2427		}
  2428		// we now know that i points at where we want to insert
  2429		es = append(es, muxEntry{}) // try to grow the slice in place, any entry works.
  2430		copy(es[i+1:], es[i:])      // Move shorter entries down
  2431		es[i] = e
  2432		return es
  2433	}
  2434	
  2435	// HandleFunc registers the handler function for the given pattern.
  2436	func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  2437		if handler == nil {
  2438			panic("http: nil handler")
  2439		}
  2440		mux.Handle(pattern, HandlerFunc(handler))
  2441	}
  2442	
  2443	// Handle registers the handler for the given pattern
  2444	// in the DefaultServeMux.
  2445	// The documentation for ServeMux explains how patterns are matched.
  2446	func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
  2447	
  2448	// HandleFunc registers the handler function for the given pattern
  2449	// in the DefaultServeMux.
  2450	// The documentation for ServeMux explains how patterns are matched.
  2451	func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  2452		DefaultServeMux.HandleFunc(pattern, handler)
  2453	}
  2454	
  2455	// Serve accepts incoming HTTP connections on the listener l,
  2456	// creating a new service goroutine for each. The service goroutines
  2457	// read requests and then call handler to reply to them.
  2458	//
  2459	// The handler is typically nil, in which case the DefaultServeMux is used.
  2460	//
  2461	// HTTP/2 support is only enabled if the Listener returns *tls.Conn
  2462	// connections and they were configured with "h2" in the TLS
  2463	// Config.NextProtos.
  2464	//
  2465	// Serve always returns a non-nil error.
  2466	func Serve(l net.Listener, handler Handler) error {
  2467		srv := &Server{Handler: handler}
  2468		return srv.Serve(l)
  2469	}
  2470	
  2471	// ServeTLS accepts incoming HTTPS connections on the listener l,
  2472	// creating a new service goroutine for each. The service goroutines
  2473	// read requests and then call handler to reply to them.
  2474	//
  2475	// The handler is typically nil, in which case the DefaultServeMux is used.
  2476	//
  2477	// Additionally, files containing a certificate and matching private key
  2478	// for the server must be provided. If the certificate is signed by a
  2479	// certificate authority, the certFile should be the concatenation
  2480	// of the server's certificate, any intermediates, and the CA's certificate.
  2481	//
  2482	// ServeTLS always returns a non-nil error.
  2483	func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {
  2484		srv := &Server{Handler: handler}
  2485		return srv.ServeTLS(l, certFile, keyFile)
  2486	}
  2487	
  2488	// A Server defines parameters for running an HTTP server.
  2489	// The zero value for Server is a valid configuration.
  2490	type Server struct {
  2491		Addr    string  // TCP address to listen on, ":http" if empty
  2492		Handler Handler // handler to invoke, http.DefaultServeMux if nil
  2493	
  2494		// TLSConfig optionally provides a TLS configuration for use
  2495		// by ServeTLS and ListenAndServeTLS. Note that this value is
  2496		// cloned by ServeTLS and ListenAndServeTLS, so it's not
  2497		// possible to modify the configuration with methods like
  2498		// tls.Config.SetSessionTicketKeys. To use
  2499		// SetSessionTicketKeys, use Server.Serve with a TLS Listener
  2500		// instead.
  2501		TLSConfig *tls.Config
  2502	
  2503		// ReadTimeout is the maximum duration for reading the entire
  2504		// request, including the body.
  2505		//
  2506		// Because ReadTimeout does not let Handlers make per-request
  2507		// decisions on each request body's acceptable deadline or
  2508		// upload rate, most users will prefer to use
  2509		// ReadHeaderTimeout. It is valid to use them both.
  2510		ReadTimeout time.Duration
  2511	
  2512		// ReadHeaderTimeout is the amount of time allowed to read
  2513		// request headers. The connection's read deadline is reset
  2514		// after reading the headers and the Handler can decide what
  2515		// is considered too slow for the body. If ReadHeaderTimeout
  2516		// is zero, the value of ReadTimeout is used. If both are
  2517		// zero, there is no timeout.
  2518		ReadHeaderTimeout time.Duration
  2519	
  2520		// WriteTimeout is the maximum duration before timing out
  2521		// writes of the response. It is reset whenever a new
  2522		// request's header is read. Like ReadTimeout, it does not
  2523		// let Handlers make decisions on a per-request basis.
  2524		WriteTimeout time.Duration
  2525	
  2526		// IdleTimeout is the maximum amount of time to wait for the
  2527		// next request when keep-alives are enabled. If IdleTimeout
  2528		// is zero, the value of ReadTimeout is used. If both are
  2529		// zero, there is no timeout.
  2530		IdleTimeout time.Duration
  2531	
  2532		// MaxHeaderBytes controls the maximum number of bytes the
  2533		// server will read parsing the request header's keys and
  2534		// values, including the request line. It does not limit the
  2535		// size of the request body.
  2536		// If zero, DefaultMaxHeaderBytes is used.
  2537		MaxHeaderBytes int
  2538	
  2539		// TLSNextProto optionally specifies a function to take over
  2540		// ownership of the provided TLS connection when an NPN/ALPN
  2541		// protocol upgrade has occurred. The map key is the protocol
  2542		// name negotiated. The Handler argument should be used to
  2543		// handle HTTP requests and will initialize the Request's TLS
  2544		// and RemoteAddr if not already set. The connection is
  2545		// automatically closed when the function returns.
  2546		// If TLSNextProto is not nil, HTTP/2 support is not enabled
  2547		// automatically.
  2548		TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
  2549	
  2550		// ConnState specifies an optional callback function that is
  2551		// called when a client connection changes state. See the
  2552		// ConnState type and associated constants for details.
  2553		ConnState func(net.Conn, ConnState)
  2554	
  2555		// ErrorLog specifies an optional logger for errors accepting
  2556		// connections, unexpected behavior from handlers, and
  2557		// underlying FileSystem errors.
  2558		// If nil, logging is done via the log package's standard logger.
  2559		ErrorLog *log.Logger
  2560	
  2561		// BaseContext optionally specifies a function that returns
  2562		// the base context for incoming requests on this server.
  2563		// The provided Listener is the specific Listener that's
  2564		// about to start accepting requests.
  2565		// If BaseContext is nil, the default is context.Background().
  2566		// If non-nil, it must return a non-nil context.
  2567		BaseContext func(net.Listener) context.Context
  2568	
  2569		// ConnContext optionally specifies a function that modifies
  2570		// the context used for a new connection c. The provided ctx
  2571		// is derived from the base context and has a ServerContextKey
  2572		// value.
  2573		ConnContext func(ctx context.Context, c net.Conn) context.Context
  2574	
  2575		disableKeepAlives int32     // accessed atomically.
  2576		inShutdown        int32     // accessed atomically (non-zero means we're in Shutdown)
  2577		nextProtoOnce     sync.Once // guards setupHTTP2_* init
  2578		nextProtoErr      error     // result of http2.ConfigureServer if used
  2579	
  2580		mu         sync.Mutex
  2581		listeners  map[*net.Listener]struct{}
  2582		activeConn map[*conn]struct{}
  2583		doneChan   chan struct{}
  2584		onShutdown []func()
  2585	}
  2586	
  2587	func (s *Server) getDoneChan() <-chan struct{} {
  2588		s.mu.Lock()
  2589		defer s.mu.Unlock()
  2590		return s.getDoneChanLocked()
  2591	}
  2592	
  2593	func (s *Server) getDoneChanLocked() chan struct{} {
  2594		if s.doneChan == nil {
  2595			s.doneChan = make(chan struct{})
  2596		}
  2597		return s.doneChan
  2598	}
  2599	
  2600	func (s *Server) closeDoneChanLocked() {
  2601		ch := s.getDoneChanLocked()
  2602		select {
  2603		case <-ch:
  2604			// Already closed. Don't close again.
  2605		default:
  2606			// Safe to close here. We're the only closer, guarded
  2607			// by s.mu.
  2608			close(ch)
  2609		}
  2610	}
  2611	
  2612	// Close immediately closes all active net.Listeners and any
  2613	// connections in state StateNew, StateActive, or StateIdle. For a
  2614	// graceful shutdown, use Shutdown.
  2615	//
  2616	// Close does not attempt to close (and does not even know about)
  2617	// any hijacked connections, such as WebSockets.
  2618	//
  2619	// Close returns any error returned from closing the Server's
  2620	// underlying Listener(s).
  2621	func (srv *Server) Close() error {
  2622		atomic.StoreInt32(&srv.inShutdown, 1)
  2623		srv.mu.Lock()
  2624		defer srv.mu.Unlock()
  2625		srv.closeDoneChanLocked()
  2626		err := srv.closeListenersLocked()
  2627		for c := range srv.activeConn {
  2628			c.rwc.Close()
  2629			delete(srv.activeConn, c)
  2630		}
  2631		return err
  2632	}
  2633	
  2634	// shutdownPollInterval is how often we poll for quiescence
  2635	// during Server.Shutdown. This is lower during tests, to
  2636	// speed up tests.
  2637	// Ideally we could find a solution that doesn't involve polling,
  2638	// but which also doesn't have a high runtime cost (and doesn't
  2639	// involve any contentious mutexes), but that is left as an
  2640	// exercise for the reader.
  2641	var shutdownPollInterval = 500 * time.Millisecond
  2642	
  2643	// Shutdown gracefully shuts down the server without interrupting any
  2644	// active connections. Shutdown works by first closing all open
  2645	// listeners, then closing all idle connections, and then waiting
  2646	// indefinitely for connections to return to idle and then shut down.
  2647	// If the provided context expires before the shutdown is complete,
  2648	// Shutdown returns the context's error, otherwise it returns any
  2649	// error returned from closing the Server's underlying Listener(s).
  2650	//
  2651	// When Shutdown is called, Serve, ListenAndServe, and
  2652	// ListenAndServeTLS immediately return ErrServerClosed. Make sure the
  2653	// program doesn't exit and waits instead for Shutdown to return.
  2654	//
  2655	// Shutdown does not attempt to close nor wait for hijacked
  2656	// connections such as WebSockets. The caller of Shutdown should
  2657	// separately notify such long-lived connections of shutdown and wait
  2658	// for them to close, if desired. See RegisterOnShutdown for a way to
  2659	// register shutdown notification functions.
  2660	//
  2661	// Once Shutdown has been called on a server, it may not be reused;
  2662	// future calls to methods such as Serve will return ErrServerClosed.
  2663	func (srv *Server) Shutdown(ctx context.Context) error {
  2664		atomic.StoreInt32(&srv.inShutdown, 1)
  2665	
  2666		srv.mu.Lock()
  2667		lnerr := srv.closeListenersLocked()
  2668		srv.closeDoneChanLocked()
  2669		for _, f := range srv.onShutdown {
  2670			go f()
  2671		}
  2672		srv.mu.Unlock()
  2673	
  2674		ticker := time.NewTicker(shutdownPollInterval)
  2675		defer ticker.Stop()
  2676		for {
  2677			if srv.closeIdleConns() {
  2678				return lnerr
  2679			}
  2680			select {
  2681			case <-ctx.Done():
  2682				return ctx.Err()
  2683			case <-ticker.C:
  2684			}
  2685		}
  2686	}
  2687	
  2688	// RegisterOnShutdown registers a function to call on Shutdown.
  2689	// This can be used to gracefully shutdown connections that have
  2690	// undergone NPN/ALPN protocol upgrade or that have been hijacked.
  2691	// This function should start protocol-specific graceful shutdown,
  2692	// but should not wait for shutdown to complete.
  2693	func (srv *Server) RegisterOnShutdown(f func()) {
  2694		srv.mu.Lock()
  2695		srv.onShutdown = append(srv.onShutdown, f)
  2696		srv.mu.Unlock()
  2697	}
  2698	
  2699	// closeIdleConns closes all idle connections and reports whether the
  2700	// server is quiescent.
  2701	func (s *Server) closeIdleConns() bool {
  2702		s.mu.Lock()
  2703		defer s.mu.Unlock()
  2704		quiescent := true
  2705		for c := range s.activeConn {
  2706			st, unixSec := c.getState()
  2707			// Issue 22682: treat StateNew connections as if
  2708			// they're idle if we haven't read the first request's
  2709			// header in over 5 seconds.
  2710			if st == StateNew && unixSec < time.Now().Unix()-5 {
  2711				st = StateIdle
  2712			}
  2713			if st != StateIdle || unixSec == 0 {
  2714				// Assume unixSec == 0 means it's a very new
  2715				// connection, without state set yet.
  2716				quiescent = false
  2717				continue
  2718			}
  2719			c.rwc.Close()
  2720			delete(s.activeConn, c)
  2721		}
  2722		return quiescent
  2723	}
  2724	
  2725	func (s *Server) closeListenersLocked() error {
  2726		var err error
  2727		for ln := range s.listeners {
  2728			if cerr := (*ln).Close(); cerr != nil && err == nil {
  2729				err = cerr
  2730			}
  2731			delete(s.listeners, ln)
  2732		}
  2733		return err
  2734	}
  2735	
  2736	// A ConnState represents the state of a client connection to a server.
  2737	// It's used by the optional Server.ConnState hook.
  2738	type ConnState int
  2739	
  2740	const (
  2741		// StateNew represents a new connection that is expected to
  2742		// send a request immediately. Connections begin at this
  2743		// state and then transition to either StateActive or
  2744		// StateClosed.
  2745		StateNew ConnState = iota
  2746	
  2747		// StateActive represents a connection that has read 1 or more
  2748		// bytes of a request. The Server.ConnState hook for
  2749		// StateActive fires before the request has entered a handler
  2750		// and doesn't fire again until the request has been
  2751		// handled. After the request is handled, the state
  2752		// transitions to StateClosed, StateHijacked, or StateIdle.
  2753		// For HTTP/2, StateActive fires on the transition from zero
  2754		// to one active request, and only transitions away once all
  2755		// active requests are complete. That means that ConnState
  2756		// cannot be used to do per-request work; ConnState only notes
  2757		// the overall state of the connection.
  2758		StateActive
  2759	
  2760		// StateIdle represents a connection that has finished
  2761		// handling a request and is in the keep-alive state, waiting
  2762		// for a new request. Connections transition from StateIdle
  2763		// to either StateActive or StateClosed.
  2764		StateIdle
  2765	
  2766		// StateHijacked represents a hijacked connection.
  2767		// This is a terminal state. It does not transition to StateClosed.
  2768		StateHijacked
  2769	
  2770		// StateClosed represents a closed connection.
  2771		// This is a terminal state. Hijacked connections do not
  2772		// transition to StateClosed.
  2773		StateClosed
  2774	)
  2775	
  2776	var stateName = map[ConnState]string{
  2777		StateNew:      "new",
  2778		StateActive:   "active",
  2779		StateIdle:     "idle",
  2780		StateHijacked: "hijacked",
  2781		StateClosed:   "closed",
  2782	}
  2783	
  2784	func (c ConnState) String() string {
  2785		return stateName[c]
  2786	}
  2787	
  2788	// serverHandler delegates to either the server's Handler or
  2789	// DefaultServeMux and also handles "OPTIONS *" requests.
  2790	type serverHandler struct {
  2791		srv *Server
  2792	}
  2793	
  2794	func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
  2795		handler := sh.srv.Handler
  2796		if handler == nil {
  2797			handler = DefaultServeMux
  2798		}
  2799		if req.RequestURI == "*" && req.Method == "OPTIONS" {
  2800			handler = globalOptionsHandler{}
  2801		}
  2802		handler.ServeHTTP(rw, req)
  2803	}
  2804	
  2805	// ListenAndServe listens on the TCP network address srv.Addr and then
  2806	// calls Serve to handle requests on incoming connections.
  2807	// Accepted connections are configured to enable TCP keep-alives.
  2808	//
  2809	// If srv.Addr is blank, ":http" is used.
  2810	//
  2811	// ListenAndServe always returns a non-nil error. After Shutdown or Close,
  2812	// the returned error is ErrServerClosed.
  2813	func (srv *Server) ListenAndServe() error {
  2814		if srv.shuttingDown() {
  2815			return ErrServerClosed
  2816		}
  2817		addr := srv.Addr
  2818		if addr == "" {
  2819			addr = ":http"
  2820		}
  2821		ln, err := net.Listen("tcp", addr)
  2822		if err != nil {
  2823			return err
  2824		}
  2825		return srv.Serve(ln)
  2826	}
  2827	
  2828	var testHookServerServe func(*Server, net.Listener) // used if non-nil
  2829	
  2830	// shouldDoServeHTTP2 reports whether Server.Serve should configure
  2831	// automatic HTTP/2. (which sets up the srv.TLSNextProto map)
  2832	func (srv *Server) shouldConfigureHTTP2ForServe() bool {
  2833		if srv.TLSConfig == nil {
  2834			// Compatibility with Go 1.6:
  2835			// If there's no TLSConfig, it's possible that the user just
  2836			// didn't set it on the http.Server, but did pass it to
  2837			// tls.NewListener and passed that listener to Serve.
  2838			// So we should configure HTTP/2 (to set up srv.TLSNextProto)
  2839			// in case the listener returns an "h2" *tls.Conn.
  2840			return true
  2841		}
  2842		// The user specified a TLSConfig on their http.Server.
  2843		// In this, case, only configure HTTP/2 if their tls.Config
  2844		// explicitly mentions "h2". Otherwise http2.ConfigureServer
  2845		// would modify the tls.Config to add it, but they probably already
  2846		// passed this tls.Config to tls.NewListener. And if they did,
  2847		// it's too late anyway to fix it. It would only be potentially racy.
  2848		// See Issue 15908.
  2849		return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
  2850	}
  2851	
  2852	// ErrServerClosed is returned by the Server's Serve, ServeTLS, ListenAndServe,
  2853	// and ListenAndServeTLS methods after a call to Shutdown or Close.
  2854	var ErrServerClosed = errors.New("http: Server closed")
  2855	
  2856	// Serve accepts incoming connections on the Listener l, creating a
  2857	// new service goroutine for each. The service goroutines read requests and
  2858	// then call srv.Handler to reply to them.
  2859	//
  2860	// HTTP/2 support is only enabled if the Listener returns *tls.Conn
  2861	// connections and they were configured with "h2" in the TLS
  2862	// Config.NextProtos.
  2863	//
  2864	// Serve always returns a non-nil error and closes l.
  2865	// After Shutdown or Close, the returned error is ErrServerClosed.
  2866	func (srv *Server) Serve(l net.Listener) error {
  2867		if fn := testHookServerServe; fn != nil {
  2868			fn(srv, l) // call hook with unwrapped listener
  2869		}
  2870	
  2871		origListener := l
  2872		l = &onceCloseListener{Listener: l}
  2873		defer l.Close()
  2874	
  2875		if err := srv.setupHTTP2_Serve(); err != nil {
  2876			return err
  2877		}
  2878	
  2879		if !srv.trackListener(&l, true) {
  2880			return ErrServerClosed
  2881		}
  2882		defer srv.trackListener(&l, false)
  2883	
  2884		var tempDelay time.Duration // how long to sleep on accept failure
  2885	
  2886		baseCtx := context.Background()
  2887		if srv.BaseContext != nil {
  2888			baseCtx = srv.BaseContext(origListener)
  2889			if baseCtx == nil {
  2890				panic("BaseContext returned a nil context")
  2891			}
  2892		}
  2893	
  2894		ctx := context.WithValue(baseCtx, ServerContextKey, srv)
  2895		for {
  2896			rw, e := l.Accept()
  2897			if e != nil {
  2898				select {
  2899				case <-srv.getDoneChan():
  2900					return ErrServerClosed
  2901				default:
  2902				}
  2903				if ne, ok := e.(net.Error); ok && ne.Temporary() {
  2904					if tempDelay == 0 {
  2905						tempDelay = 5 * time.Millisecond
  2906					} else {
  2907						tempDelay *= 2
  2908					}
  2909					if max := 1 * time.Second; tempDelay > max {
  2910						tempDelay = max
  2911					}
  2912					srv.logf("http: Accept error: %v; retrying in %v", e, tempDelay)
  2913					time.Sleep(tempDelay)
  2914					continue
  2915				}
  2916				return e
  2917			}
  2918			connCtx := ctx
  2919			if cc := srv.ConnContext; cc != nil {
  2920				connCtx = cc(connCtx, rw)
  2921				if connCtx == nil {
  2922					panic("ConnContext returned nil")
  2923				}
  2924			}
  2925			tempDelay = 0
  2926			c := srv.newConn(rw)
  2927			c.setState(c.rwc, StateNew) // before Serve can return
  2928			go c.serve(connCtx)
  2929		}
  2930	}
  2931	
  2932	// ServeTLS accepts incoming connections on the Listener l, creating a
  2933	// new service goroutine for each. The service goroutines perform TLS
  2934	// setup and then read requests, calling srv.Handler to reply to them.
  2935	//
  2936	// Files containing a certificate and matching private key for the
  2937	// server must be provided if neither the Server's
  2938	// TLSConfig.Certificates nor TLSConfig.GetCertificate are populated.
  2939	// If the certificate is signed by a certificate authority, the
  2940	// certFile should be the concatenation of the server's certificate,
  2941	// any intermediates, and the CA's certificate.
  2942	//
  2943	// ServeTLS always returns a non-nil error. After Shutdown or Close, the
  2944	// returned error is ErrServerClosed.
  2945	func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
  2946		// Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig
  2947		// before we clone it and create the TLS Listener.
  2948		if err := srv.setupHTTP2_ServeTLS(); err != nil {
  2949			return err
  2950		}
  2951	
  2952		config := cloneTLSConfig(srv.TLSConfig)
  2953		if !strSliceContains(config.NextProtos, "http/1.1") {
  2954			config.NextProtos = append(config.NextProtos, "http/1.1")
  2955		}
  2956	
  2957		configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil
  2958		if !configHasCert || certFile != "" || keyFile != "" {
  2959			var err error
  2960			config.Certificates = make([]tls.Certificate, 1)
  2961			config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
  2962			if err != nil {
  2963				return err
  2964			}
  2965		}
  2966	
  2967		tlsListener := tls.NewListener(l, config)
  2968		return srv.Serve(tlsListener)
  2969	}
  2970	
  2971	// trackListener adds or removes a net.Listener to the set of tracked
  2972	// listeners.
  2973	//
  2974	// We store a pointer to interface in the map set, in case the
  2975	// net.Listener is not comparable. This is safe because we only call
  2976	// trackListener via Serve and can track+defer untrack the same
  2977	// pointer to local variable there. We never need to compare a
  2978	// Listener from another caller.
  2979	//
  2980	// It reports whether the server is still up (not Shutdown or Closed).
  2981	func (s *Server) trackListener(ln *net.Listener, add bool) bool {
  2982		s.mu.Lock()
  2983		defer s.mu.Unlock()
  2984		if s.listeners == nil {
  2985			s.listeners = make(map[*net.Listener]struct{})
  2986		}
  2987		if add {
  2988			if s.shuttingDown() {
  2989				return false
  2990			}
  2991			s.listeners[ln] = struct{}{}
  2992		} else {
  2993			delete(s.listeners, ln)
  2994		}
  2995		return true
  2996	}
  2997	
  2998	func (s *Server) trackConn(c *conn, add bool) {
  2999		s.mu.Lock()
  3000		defer s.mu.Unlock()
  3001		if s.activeConn == nil {
  3002			s.activeConn = make(map[*conn]struct{})
  3003		}
  3004		if add {
  3005			s.activeConn[c] = struct{}{}
  3006		} else {
  3007			delete(s.activeConn, c)
  3008		}
  3009	}
  3010	
  3011	func (s *Server) idleTimeout() time.Duration {
  3012		if s.IdleTimeout != 0 {
  3013			return s.IdleTimeout
  3014		}
  3015		return s.ReadTimeout
  3016	}
  3017	
  3018	func (s *Server) readHeaderTimeout() time.Duration {
  3019		if s.ReadHeaderTimeout != 0 {
  3020			return s.ReadHeaderTimeout
  3021		}
  3022		return s.ReadTimeout
  3023	}
  3024	
  3025	func (s *Server) doKeepAlives() bool {
  3026		return atomic.LoadInt32(&s.disableKeepAlives) == 0 && !s.shuttingDown()
  3027	}
  3028	
  3029	func (s *Server) shuttingDown() bool {
  3030		// TODO: replace inShutdown with the existing atomicBool type;
  3031		// see https://github.com/golang/go/issues/20239#issuecomment-381434582
  3032		return atomic.LoadInt32(&s.inShutdown) != 0
  3033	}
  3034	
  3035	// SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
  3036	// By default, keep-alives are always enabled. Only very
  3037	// resource-constrained environments or servers in the process of
  3038	// shutting down should disable them.
  3039	func (srv *Server) SetKeepAlivesEnabled(v bool) {
  3040		if v {
  3041			atomic.StoreInt32(&srv.disableKeepAlives, 0)
  3042			return
  3043		}
  3044		atomic.StoreInt32(&srv.disableKeepAlives, 1)
  3045	
  3046		// Close idle HTTP/1 conns:
  3047		srv.closeIdleConns()
  3048	
  3049		// TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
  3050	}
  3051	
  3052	func (s *Server) logf(format string, args ...interface{}) {
  3053		if s.ErrorLog != nil {
  3054			s.ErrorLog.Printf(format, args...)
  3055		} else {
  3056			log.Printf(format, args...)
  3057		}
  3058	}
  3059	
  3060	// logf prints to the ErrorLog of the *Server associated with request r
  3061	// via ServerContextKey. If there's no associated server, or if ErrorLog
  3062	// is nil, logging is done via the log package's standard logger.
  3063	func logf(r *Request, format string, args ...interface{}) {
  3064		s, _ := r.Context().Value(ServerContextKey).(*Server)
  3065		if s != nil && s.ErrorLog != nil {
  3066			s.ErrorLog.Printf(format, args...)
  3067		} else {
  3068			log.Printf(format, args...)
  3069		}
  3070	}
  3071	
  3072	// ListenAndServe listens on the TCP network address addr and then calls
  3073	// Serve with handler to handle requests on incoming connections.
  3074	// Accepted connections are configured to enable TCP keep-alives.
  3075	//
  3076	// The handler is typically nil, in which case the DefaultServeMux is used.
  3077	//
  3078	// ListenAndServe always returns a non-nil error.
  3079	func ListenAndServe(addr string, handler Handler) error {
  3080		server := &Server{Addr: addr, Handler: handler}
  3081		return server.ListenAndServe()
  3082	}
  3083	
  3084	// ListenAndServeTLS acts identically to ListenAndServe, except that it
  3085	// expects HTTPS connections. Additionally, files containing a certificate and
  3086	// matching private key for the server must be provided. If the certificate
  3087	// is signed by a certificate authority, the certFile should be the concatenation
  3088	// of the server's certificate, any intermediates, and the CA's certificate.
  3089	func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
  3090		server := &Server{Addr: addr, Handler: handler}
  3091		return server.ListenAndServeTLS(certFile, keyFile)
  3092	}
  3093	
  3094	// ListenAndServeTLS listens on the TCP network address srv.Addr and
  3095	// then calls ServeTLS to handle requests on incoming TLS connections.
  3096	// Accepted connections are configured to enable TCP keep-alives.
  3097	//
  3098	// Filenames containing a certificate and matching private key for the
  3099	// server must be provided if neither the Server's TLSConfig.Certificates
  3100	// nor TLSConfig.GetCertificate are populated. If the certificate is
  3101	// signed by a certificate authority, the certFile should be the
  3102	// concatenation of the server's certificate, any intermediates, and
  3103	// the CA's certificate.
  3104	//
  3105	// If srv.Addr is blank, ":https" is used.
  3106	//
  3107	// ListenAndServeTLS always returns a non-nil error. After Shutdown or
  3108	// Close, the returned error is ErrServerClosed.
  3109	func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
  3110		if srv.shuttingDown() {
  3111			return ErrServerClosed
  3112		}
  3113		addr := srv.Addr
  3114		if addr == "" {
  3115			addr = ":https"
  3116		}
  3117	
  3118		ln, err := net.Listen("tcp", addr)
  3119		if err != nil {
  3120			return err
  3121		}
  3122	
  3123		defer ln.Close()
  3124	
  3125		return srv.ServeTLS(ln, certFile, keyFile)
  3126	}
  3127	
  3128	// setupHTTP2_ServeTLS conditionally configures HTTP/2 on
  3129	// srv and reports whether there was an error setting it up. If it is
  3130	// not configured for policy reasons, nil is returned.
  3131	func (srv *Server) setupHTTP2_ServeTLS() error {
  3132		srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
  3133		return srv.nextProtoErr
  3134	}
  3135	
  3136	// setupHTTP2_Serve is called from (*Server).Serve and conditionally
  3137	// configures HTTP/2 on srv using a more conservative policy than
  3138	// setupHTTP2_ServeTLS because Serve is called after tls.Listen,
  3139	// and may be called concurrently. See shouldConfigureHTTP2ForServe.
  3140	//
  3141	// The tests named TestTransportAutomaticHTTP2* and
  3142	// TestConcurrentServerServe in server_test.go demonstrate some
  3143	// of the supported use cases and motivations.
  3144	func (srv *Server) setupHTTP2_Serve() error {
  3145		srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
  3146		return srv.nextProtoErr
  3147	}
  3148	
  3149	func (srv *Server) onceSetNextProtoDefaults_Serve() {
  3150		if srv.shouldConfigureHTTP2ForServe() {
  3151			srv.onceSetNextProtoDefaults()
  3152		}
  3153	}
  3154	
  3155	// onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
  3156	// configured otherwise. (by setting srv.TLSNextProto non-nil)
  3157	// It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*).
  3158	func (srv *Server) onceSetNextProtoDefaults() {
  3159		if strings.Contains(os.Getenv("GODEBUG"), "http2server=0") {
  3160			return
  3161		}
  3162		// Enable HTTP/2 by default if the user hasn't otherwise
  3163		// configured their TLSNextProto map.
  3164		if srv.TLSNextProto == nil {
  3165			conf := &http2Server{
  3166				NewWriteScheduler: func() http2WriteScheduler { return http2NewPriorityWriteScheduler(nil) },
  3167			}
  3168			srv.nextProtoErr = http2ConfigureServer(srv, conf)
  3169		}
  3170	}
  3171	
  3172	// TimeoutHandler returns a Handler that runs h with the given time limit.
  3173	//
  3174	// The new Handler calls h.ServeHTTP to handle each request, but if a
  3175	// call runs for longer than its time limit, the handler responds with
  3176	// a 503 Service Unavailable error and the given message in its body.
  3177	// (If msg is empty, a suitable default message will be sent.)
  3178	// After such a timeout, writes by h to its ResponseWriter will return
  3179	// ErrHandlerTimeout.
  3180	//
  3181	// TimeoutHandler supports the Flusher and Pusher interfaces but does not
  3182	// support the Hijacker interface.
  3183	func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
  3184		return &timeoutHandler{
  3185			handler: h,
  3186			body:    msg,
  3187			dt:      dt,
  3188		}
  3189	}
  3190	
  3191	// ErrHandlerTimeout is returned on ResponseWriter Write calls
  3192	// in handlers which have timed out.
  3193	var ErrHandlerTimeout = errors.New("http: Handler timeout")
  3194	
  3195	type timeoutHandler struct {
  3196		handler Handler
  3197		body    string
  3198		dt      time.Duration
  3199	
  3200		// When set, no context will be created and this context will
  3201		// be used instead.
  3202		testContext context.Context
  3203	}
  3204	
  3205	func (h *timeoutHandler) errorBody() string {
  3206		if h.body != "" {
  3207			return h.body
  3208		}
  3209		return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
  3210	}
  3211	
  3212	func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
  3213		ctx := h.testContext
  3214		if ctx == nil {
  3215			var cancelCtx context.CancelFunc
  3216			ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
  3217			defer cancelCtx()
  3218		}
  3219		r = r.WithContext(ctx)
  3220		done := make(chan struct{})
  3221		tw := &timeoutWriter{
  3222			w: w,
  3223			h: make(Header),
  3224		}
  3225		panicChan := make(chan interface{}, 1)
  3226		go func() {
  3227			defer func() {
  3228				if p := recover(); p != nil {
  3229					panicChan <- p
  3230				}
  3231			}()
  3232			h.handler.ServeHTTP(tw, r)
  3233			close(done)
  3234		}()
  3235		select {
  3236		case p := <-panicChan:
  3237			panic(p)
  3238		case <-done:
  3239			tw.mu.Lock()
  3240			defer tw.mu.Unlock()
  3241			dst := w.Header()
  3242			for k, vv := range tw.h {
  3243				dst[k] = vv
  3244			}
  3245			if !tw.wroteHeader {
  3246				tw.code = StatusOK
  3247			}
  3248			w.WriteHeader(tw.code)
  3249			w.Write(tw.wbuf.Bytes())
  3250		case <-ctx.Done():
  3251			tw.mu.Lock()
  3252			defer tw.mu.Unlock()
  3253			w.WriteHeader(StatusServiceUnavailable)
  3254			io.WriteString(w, h.errorBody())
  3255			tw.timedOut = true
  3256		}
  3257	}
  3258	
  3259	type timeoutWriter struct {
  3260		w    ResponseWriter
  3261		h    Header
  3262		wbuf bytes.Buffer
  3263	
  3264		mu          sync.Mutex
  3265		timedOut    bool
  3266		wroteHeader bool
  3267		code        int
  3268	}
  3269	
  3270	var _ Pusher = (*timeoutWriter)(nil)
  3271	
  3272	// Push implements the Pusher interface.
  3273	func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
  3274		if pusher, ok := tw.w.(Pusher); ok {
  3275			return pusher.Push(target, opts)
  3276		}
  3277		return ErrNotSupported
  3278	}
  3279	
  3280	func (tw *timeoutWriter) Header() Header { return tw.h }
  3281	
  3282	func (tw *timeoutWriter) Write(p []byte) (int, error) {
  3283		tw.mu.Lock()
  3284		defer tw.mu.Unlock()
  3285		if tw.timedOut {
  3286			return 0, ErrHandlerTimeout
  3287		}
  3288		if !tw.wroteHeader {
  3289			tw.writeHeader(StatusOK)
  3290		}
  3291		return tw.wbuf.Write(p)
  3292	}
  3293	
  3294	func (tw *timeoutWriter) WriteHeader(code int) {
  3295		checkWriteHeaderCode(code)
  3296		tw.mu.Lock()
  3297		defer tw.mu.Unlock()
  3298		if tw.timedOut || tw.wroteHeader {
  3299			return
  3300		}
  3301		tw.writeHeader(code)
  3302	}
  3303	
  3304	func (tw *timeoutWriter) writeHeader(code int) {
  3305		tw.wroteHeader = true
  3306		tw.code = code
  3307	}
  3308	
  3309	// onceCloseListener wraps a net.Listener, protecting it from
  3310	// multiple Close calls.
  3311	type onceCloseListener struct {
  3312		net.Listener
  3313		once     sync.Once
  3314		closeErr error
  3315	}
  3316	
  3317	func (oc *onceCloseListener) Close() error {
  3318		oc.once.Do(oc.close)
  3319		return oc.closeErr
  3320	}
  3321	
  3322	func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
  3323	
  3324	// globalOptionsHandler responds to "OPTIONS *" requests.
  3325	type globalOptionsHandler struct{}
  3326	
  3327	func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
  3328		w.Header().Set("Content-Length", "0")
  3329		if r.ContentLength != 0 {
  3330			// Read up to 4KB of OPTIONS body (as mentioned in the
  3331			// spec as being reserved for future use), but anything
  3332			// over that is considered a waste of server resources
  3333			// (or an attack) and we abort and close the connection,
  3334			// courtesy of MaxBytesReader's EOF behavior.
  3335			mb := MaxBytesReader(w, r.Body, 4<<10)
  3336			io.Copy(ioutil.Discard, mb)
  3337		}
  3338	}
  3339	
  3340	// initNPNRequest is an HTTP handler that initializes certain
  3341	// uninitialized fields in its *Request. Such partially-initialized
  3342	// Requests come from NPN protocol handlers.
  3343	type initNPNRequest struct {
  3344		ctx context.Context
  3345		c   *tls.Conn
  3346		h   serverHandler
  3347	}
  3348	
  3349	// BaseContext is an exported but unadvertised http.Handler method
  3350	// recognized by x/net/http2 to pass down a context; the TLSNextProto
  3351	// API predates context support so we shoehorn through the only
  3352	// interface we have available.
  3353	func (h initNPNRequest) BaseContext() context.Context { return h.ctx }
  3354	
  3355	func (h initNPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
  3356		if req.TLS == nil {
  3357			req.TLS = &tls.ConnectionState{}
  3358			*req.TLS = h.c.ConnectionState()
  3359		}
  3360		if req.Body == nil {
  3361			req.Body = NoBody
  3362		}
  3363		if req.RemoteAddr == "" {
  3364			req.RemoteAddr = h.c.RemoteAddr().String()
  3365		}
  3366		h.h.ServeHTTP(rw, req)
  3367	}
  3368	
  3369	// loggingConn is used for debugging.
  3370	type loggingConn struct {
  3371		name string
  3372		net.Conn
  3373	}
  3374	
  3375	var (
  3376		uniqNameMu   sync.Mutex
  3377		uniqNameNext = make(map[string]int)
  3378	)
  3379	
  3380	func newLoggingConn(baseName string, c net.Conn) net.Conn {
  3381		uniqNameMu.Lock()
  3382		defer uniqNameMu.Unlock()
  3383		uniqNameNext[baseName]++
  3384		return &loggingConn{
  3385			name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
  3386			Conn: c,
  3387		}
  3388	}
  3389	
  3390	func (c *loggingConn) Write(p []byte) (n int, err error) {
  3391		log.Printf("%s.Write(%d) = ....", c.name, len(p))
  3392		n, err = c.Conn.Write(p)
  3393		log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
  3394		return
  3395	}
  3396	
  3397	func (c *loggingConn) Read(p []byte) (n int, err error) {
  3398		log.Printf("%s.Read(%d) = ....", c.name, len(p))
  3399		n, err = c.Conn.Read(p)
  3400		log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
  3401		return
  3402	}
  3403	
  3404	func (c *loggingConn) Close() (err error) {
  3405		log.Printf("%s.Close() = ...", c.name)
  3406		err = c.Conn.Close()
  3407		log.Printf("%s.Close() = %v", c.name, err)
  3408		return
  3409	}
  3410	
  3411	// checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
  3412	// It only contains one field (and a pointer field at that), so it
  3413	// fits in an interface value without an extra allocation.
  3414	type checkConnErrorWriter struct {
  3415		c *conn
  3416	}
  3417	
  3418	func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
  3419		n, err = w.c.rwc.Write(p)
  3420		if err != nil && w.c.werr == nil {
  3421			w.c.werr = err
  3422			w.c.cancelCtx()
  3423		}
  3424		return
  3425	}
  3426	
  3427	func numLeadingCRorLF(v []byte) (n int) {
  3428		for _, b := range v {
  3429			if b == '\r' || b == '\n' {
  3430				n++
  3431				continue
  3432			}
  3433			break
  3434		}
  3435		return
  3436	
  3437	}
  3438	
  3439	func strSliceContains(ss []string, s string) bool {
  3440		for _, v := range ss {
  3441			if v == s {
  3442				return true
  3443			}
  3444		}
  3445		return false
  3446	}
  3447	
  3448	// tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
  3449	// looks like it might've been a misdirected plaintext HTTP request.
  3450	func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
  3451		switch string(hdr[:]) {
  3452		case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
  3453			return true
  3454		}
  3455		return false
  3456	}
  3457	

View as plain text