...
Run Format

Source file src/net/http/server.go

Documentation: net/http

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

View as plain text