Black Lives Matter. Support the Equal Justice Initiative.

Source file src/net/http/server.go

Documentation: net/http

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

View as plain text