...
Run Format

Source file src/net/http/server.go

Documentation: net/http

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

View as plain text