Black Lives Matter. Support the Equal Justice Initiative.

Source file src/net/http/server.go

Documentation: net/http

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

View as plain text