github.com/geraldss/go/src@v0.0.0-20210511222824-ac7d0ebfc235/net/http/server.go (about)

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