github.com/slayercat/go@v0.0.0-20170428012452-c51559813f61/src/net/http/server.go (about)

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