Home | History | Annotate | Download | only in http
      1 // Copyright 2009 The Go Authors. All rights reserved.
      2 // Use of this source code is governed by a BSD-style
      3 // license that can be found in the LICENSE file.
      4 
      5 // HTTP server. See RFC 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.ReaderCloser 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 	defer func() {
   1718 		if err := recover(); err != nil && err != ErrAbortHandler {
   1719 			const size = 64 << 10
   1720 			buf := make([]byte, size)
   1721 			buf = buf[:runtime.Stack(buf, false)]
   1722 			c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
   1723 		}
   1724 		if !c.hijacked() {
   1725 			c.close()
   1726 			c.setState(c.rwc, StateClosed)
   1727 		}
   1728 	}()
   1729 
   1730 	if tlsConn, ok := c.rwc.(*tls.Conn); ok {
   1731 		if d := c.server.ReadTimeout; d != 0 {
   1732 			c.rwc.SetReadDeadline(time.Now().Add(d))
   1733 		}
   1734 		if d := c.server.WriteTimeout; d != 0 {
   1735 			c.rwc.SetWriteDeadline(time.Now().Add(d))
   1736 		}
   1737 		if err := tlsConn.Handshake(); err != nil {
   1738 			c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err)
   1739 			return
   1740 		}
   1741 		c.tlsState = new(tls.ConnectionState)
   1742 		*c.tlsState = tlsConn.ConnectionState()
   1743 		if proto := c.tlsState.NegotiatedProtocol; validNPN(proto) {
   1744 			if fn := c.server.TLSNextProto[proto]; fn != nil {
   1745 				h := initNPNRequest{tlsConn, serverHandler{c.server}}
   1746 				fn(c.server, tlsConn, h)
   1747 			}
   1748 			return
   1749 		}
   1750 	}
   1751 
   1752 	// HTTP/1.x from here on.
   1753 
   1754 	ctx, cancelCtx := context.WithCancel(ctx)
   1755 	c.cancelCtx = cancelCtx
   1756 	defer cancelCtx()
   1757 
   1758 	c.r = &connReader{conn: c}
   1759 	c.bufr = newBufioReader(c.r)
   1760 	c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
   1761 
   1762 	for {
   1763 		w, err := c.readRequest(ctx)
   1764 		if c.r.remain != c.server.initialReadLimitSize() {
   1765 			// If we read any bytes off the wire, we're active.
   1766 			c.setState(c.rwc, StateActive)
   1767 		}
   1768 		if err != nil {
   1769 			const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
   1770 
   1771 			if err == errTooLarge {
   1772 				// Their HTTP client may or may not be
   1773 				// able to read this if we're
   1774 				// responding to them and hanging up
   1775 				// while they're still writing their
   1776 				// request. Undefined behavior.
   1777 				const publicErr = "431 Request Header Fields Too Large"
   1778 				fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
   1779 				c.closeWriteAndWait()
   1780 				return
   1781 			}
   1782 			if isCommonNetReadError(err) {
   1783 				return // don't reply
   1784 			}
   1785 
   1786 			publicErr := "400 Bad Request"
   1787 			if v, ok := err.(badRequestError); ok {
   1788 				publicErr = publicErr + ": " + string(v)
   1789 			}
   1790 
   1791 			fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
   1792 			return
   1793 		}
   1794 
   1795 		// Expect 100 Continue support
   1796 		req := w.req
   1797 		if req.expectsContinue() {
   1798 			if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
   1799 				// Wrap the Body reader with one that replies on the connection
   1800 				req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
   1801 			}
   1802 		} else if req.Header.get("Expect") != "" {
   1803 			w.sendExpectationFailed()
   1804 			return
   1805 		}
   1806 
   1807 		c.curReq.Store(w)
   1808 
   1809 		if requestBodyRemains(req.Body) {
   1810 			registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
   1811 		} else {
   1812 			if w.conn.bufr.Buffered() > 0 {
   1813 				w.conn.r.closeNotifyFromPipelinedRequest()
   1814 			}
   1815 			w.conn.r.startBackgroundRead()
   1816 		}
   1817 
   1818 		// HTTP cannot have multiple simultaneous active requests.[*]
   1819 		// Until the server replies to this request, it can't read another,
   1820 		// so we might as well run the handler in this goroutine.
   1821 		// [*] Not strictly true: HTTP pipelining. We could let them all process
   1822 		// in parallel even if their responses need to be serialized.
   1823 		// But we're not going to implement HTTP pipelining because it
   1824 		// was never deployed in the wild and the answer is HTTP/2.
   1825 		serverHandler{c.server}.ServeHTTP(w, w.req)
   1826 		w.cancelCtx()
   1827 		if c.hijacked() {
   1828 			return
   1829 		}
   1830 		w.finishRequest()
   1831 		if !w.shouldReuseConnection() {
   1832 			if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
   1833 				c.closeWriteAndWait()
   1834 			}
   1835 			return
   1836 		}
   1837 		c.setState(c.rwc, StateIdle)
   1838 		c.curReq.Store((*response)(nil))
   1839 
   1840 		if !w.conn.server.doKeepAlives() {
   1841 			// We're in shutdown mode. We might've replied
   1842 			// to the user without "Connection: close" and
   1843 			// they might think they can send another
   1844 			// request, but such is life with HTTP/1.1.
   1845 			return
   1846 		}
   1847 
   1848 		if d := c.server.idleTimeout(); d != 0 {
   1849 			c.rwc.SetReadDeadline(time.Now().Add(d))
   1850 			if _, err := c.bufr.Peek(4); err != nil {
   1851 				return
   1852 			}
   1853 		}
   1854 		c.rwc.SetReadDeadline(time.Time{})
   1855 	}
   1856 }
   1857 
   1858 func (w *response) sendExpectationFailed() {
   1859 	// TODO(bradfitz): let ServeHTTP handlers handle
   1860 	// requests with non-standard expectation[s]? Seems
   1861 	// theoretical at best, and doesn't fit into the
   1862 	// current ServeHTTP model anyway. We'd need to
   1863 	// make the ResponseWriter an optional
   1864 	// "ExpectReplier" interface or something.
   1865 	//
   1866 	// For now we'll just obey RFC 2616 14.20 which says
   1867 	// "If a server receives a request containing an
   1868 	// Expect field that includes an expectation-
   1869 	// extension that it does not support, it MUST
   1870 	// respond with a 417 (Expectation Failed) status."
   1871 	w.Header().Set("Connection", "close")
   1872 	w.WriteHeader(StatusExpectationFailed)
   1873 	w.finishRequest()
   1874 }
   1875 
   1876 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter
   1877 // and a Hijacker.
   1878 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
   1879 	if w.handlerDone.isSet() {
   1880 		panic("net/http: Hijack called after ServeHTTP finished")
   1881 	}
   1882 	if w.wroteHeader {
   1883 		w.cw.flush()
   1884 	}
   1885 
   1886 	c := w.conn
   1887 	c.mu.Lock()
   1888 	defer c.mu.Unlock()
   1889 
   1890 	// Release the bufioWriter that writes to the chunk writer, it is not
   1891 	// used after a connection has been hijacked.
   1892 	rwc, buf, err = c.hijackLocked()
   1893 	if err == nil {
   1894 		putBufioWriter(w.w)
   1895 		w.w = nil
   1896 	}
   1897 	return rwc, buf, err
   1898 }
   1899 
   1900 func (w *response) CloseNotify() <-chan bool {
   1901 	if w.handlerDone.isSet() {
   1902 		panic("net/http: CloseNotify called after ServeHTTP finished")
   1903 	}
   1904 	return w.closeNotifyCh
   1905 }
   1906 
   1907 func registerOnHitEOF(rc io.ReadCloser, fn func()) {
   1908 	switch v := rc.(type) {
   1909 	case *expectContinueReader:
   1910 		registerOnHitEOF(v.readCloser, fn)
   1911 	case *body:
   1912 		v.registerOnHitEOF(fn)
   1913 	default:
   1914 		panic("unexpected type " + fmt.Sprintf("%T", rc))
   1915 	}
   1916 }
   1917 
   1918 // requestBodyRemains reports whether future calls to Read
   1919 // on rc might yield more data.
   1920 func requestBodyRemains(rc io.ReadCloser) bool {
   1921 	if rc == NoBody {
   1922 		return false
   1923 	}
   1924 	switch v := rc.(type) {
   1925 	case *expectContinueReader:
   1926 		return requestBodyRemains(v.readCloser)
   1927 	case *body:
   1928 		return v.bodyRemains()
   1929 	default:
   1930 		panic("unexpected type " + fmt.Sprintf("%T", rc))
   1931 	}
   1932 }
   1933 
   1934 // The HandlerFunc type is an adapter to allow the use of
   1935 // ordinary functions as HTTP handlers. If f is a function
   1936 // with the appropriate signature, HandlerFunc(f) is a
   1937 // Handler that calls f.
   1938 type HandlerFunc func(ResponseWriter, *Request)
   1939 
   1940 // ServeHTTP calls f(w, r).
   1941 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
   1942 	f(w, r)
   1943 }
   1944 
   1945 // Helper handlers
   1946 
   1947 // Error replies to the request with the specified error message and HTTP code.
   1948 // It does not otherwise end the request; the caller should ensure no further
   1949 // writes are done to w.
   1950 // The error message should be plain text.
   1951 func Error(w ResponseWriter, error string, code int) {
   1952 	w.Header().Set("Content-Type", "text/plain; charset=utf-8")
   1953 	w.Header().Set("X-Content-Type-Options", "nosniff")
   1954 	w.WriteHeader(code)
   1955 	fmt.Fprintln(w, error)
   1956 }
   1957 
   1958 // NotFound replies to the request with an HTTP 404 not found error.
   1959 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
   1960 
   1961 // NotFoundHandler returns a simple request handler
   1962 // that replies to each request with a ``404 page not found'' reply.
   1963 func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
   1964 
   1965 // StripPrefix returns a handler that serves HTTP requests
   1966 // by removing the given prefix from the request URL's Path
   1967 // and invoking the handler h. StripPrefix handles a
   1968 // request for a path that doesn't begin with prefix by
   1969 // replying with an HTTP 404 not found error.
   1970 func StripPrefix(prefix string, h Handler) Handler {
   1971 	if prefix == "" {
   1972 		return h
   1973 	}
   1974 	return HandlerFunc(func(w ResponseWriter, r *Request) {
   1975 		if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) {
   1976 			r.URL.Path = p
   1977 			h.ServeHTTP(w, r)
   1978 		} else {
   1979 			NotFound(w, r)
   1980 		}
   1981 	})
   1982 }
   1983 
   1984 // Redirect replies to the request with a redirect to url,
   1985 // which may be a path relative to the request path.
   1986 //
   1987 // The provided code should be in the 3xx range and is usually
   1988 // StatusMovedPermanently, StatusFound or StatusSeeOther.
   1989 func Redirect(w ResponseWriter, r *Request, urlStr string, code int) {
   1990 	if u, err := url.Parse(urlStr); err == nil {
   1991 		// If url was relative, make absolute by
   1992 		// combining with request path.
   1993 		// The browser would probably do this for us,
   1994 		// but doing it ourselves is more reliable.
   1995 
   1996 		// NOTE(rsc): RFC 2616 says that the Location
   1997 		// line must be an absolute URI, like
   1998 		// "http://www.google.com/redirect/",
   1999 		// not a path like "/redirect/".
   2000 		// Unfortunately, we don't know what to
   2001 		// put in the host name section to get the
   2002 		// client to connect to us again, so we can't
   2003 		// know the right absolute URI to send back.
   2004 		// Because of this problem, no one pays attention
   2005 		// to the RFC; they all send back just a new path.
   2006 		// So do we.
   2007 		if u.Scheme == "" && u.Host == "" {
   2008 			oldpath := r.URL.Path
   2009 			if oldpath == "" { // should not happen, but avoid a crash if it does
   2010 				oldpath = "/"
   2011 			}
   2012 
   2013 			// no leading http://server
   2014 			if urlStr == "" || urlStr[0] != '/' {
   2015 				// make relative path absolute
   2016 				olddir, _ := path.Split(oldpath)
   2017 				urlStr = olddir + urlStr
   2018 			}
   2019 
   2020 			var query string
   2021 			if i := strings.Index(urlStr, "?"); i != -1 {
   2022 				urlStr, query = urlStr[:i], urlStr[i:]
   2023 			}
   2024 
   2025 			// clean up but preserve trailing slash
   2026 			trailing := strings.HasSuffix(urlStr, "/")
   2027 			urlStr = path.Clean(urlStr)
   2028 			if trailing && !strings.HasSuffix(urlStr, "/") {
   2029 				urlStr += "/"
   2030 			}
   2031 			urlStr += query
   2032 		}
   2033 	}
   2034 
   2035 	w.Header().Set("Location", hexEscapeNonASCII(urlStr))
   2036 	w.WriteHeader(code)
   2037 
   2038 	// RFC 2616 recommends that a short note "SHOULD" be included in the
   2039 	// response because older user agents may not understand 301/307.
   2040 	// Shouldn't send the response for POST or HEAD; that leaves GET.
   2041 	if r.Method == "GET" {
   2042 		note := "<a href=\"" + htmlEscape(urlStr) + "\">" + statusText[code] + "</a>.\n"
   2043 		fmt.Fprintln(w, note)
   2044 	}
   2045 }
   2046 
   2047 var htmlReplacer = strings.NewReplacer(
   2048 	"&", "&amp;",
   2049 	"<", "&lt;",
   2050 	">", "&gt;",
   2051 	// "&#34;" is shorter than "&quot;".
   2052 	`"`, "&#34;",
   2053 	// "&#39;" is shorter than "&apos;" and apos was not in HTML until HTML5.
   2054 	"'", "&#39;",
   2055 )
   2056 
   2057 func htmlEscape(s string) string {
   2058 	return htmlReplacer.Replace(s)
   2059 }
   2060 
   2061 // Redirect to a fixed URL
   2062 type redirectHandler struct {
   2063 	url  string
   2064 	code int
   2065 }
   2066 
   2067 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
   2068 	Redirect(w, r, rh.url, rh.code)
   2069 }
   2070 
   2071 // RedirectHandler returns a request handler that redirects
   2072 // each request it receives to the given url using the given
   2073 // status code.
   2074 //
   2075 // The provided code should be in the 3xx range and is usually
   2076 // StatusMovedPermanently, StatusFound or StatusSeeOther.
   2077 func RedirectHandler(url string, code int) Handler {
   2078 	return &redirectHandler{url, code}
   2079 }
   2080 
   2081 // ServeMux is an HTTP request multiplexer.
   2082 // It matches the URL of each incoming request against a list of registered
   2083 // patterns and calls the handler for the pattern that
   2084 // most closely matches the URL.
   2085 //
   2086 // Patterns name fixed, rooted paths, like "/favicon.ico",
   2087 // or rooted subtrees, like "/images/" (note the trailing slash).
   2088 // Longer patterns take precedence over shorter ones, so that
   2089 // if there are handlers registered for both "/images/"
   2090 // and "/images/thumbnails/", the latter handler will be
   2091 // called for paths beginning "/images/thumbnails/" and the
   2092 // former will receive requests for any other paths in the
   2093 // "/images/" subtree.
   2094 //
   2095 // Note that since a pattern ending in a slash names a rooted subtree,
   2096 // the pattern "/" matches all paths not matched by other registered
   2097 // patterns, not just the URL with Path == "/".
   2098 //
   2099 // If a subtree has been registered and a request is received naming the
   2100 // subtree root without its trailing slash, ServeMux redirects that
   2101 // request to the subtree root (adding the trailing slash). This behavior can
   2102 // be overridden with a separate registration for the path without
   2103 // the trailing slash. For example, registering "/images/" causes ServeMux
   2104 // to redirect a request for "/images" to "/images/", unless "/images" has
   2105 // been registered separately.
   2106 //
   2107 // Patterns may optionally begin with a host name, restricting matches to
   2108 // URLs on that host only. Host-specific patterns take precedence over
   2109 // general patterns, so that a handler might register for the two patterns
   2110 // "/codesearch" and "codesearch.google.com/" without also taking over
   2111 // requests for "http://www.google.com/".
   2112 //
   2113 // ServeMux also takes care of sanitizing the URL request path,
   2114 // redirecting any request containing . or .. elements or repeated slashes
   2115 // to an equivalent, cleaner URL.
   2116 type ServeMux struct {
   2117 	mu    sync.RWMutex
   2118 	m     map[string]muxEntry
   2119 	hosts bool // whether any patterns contain hostnames
   2120 }
   2121 
   2122 type muxEntry struct {
   2123 	explicit bool
   2124 	h        Handler
   2125 	pattern  string
   2126 }
   2127 
   2128 // NewServeMux allocates and returns a new ServeMux.
   2129 func NewServeMux() *ServeMux { return new(ServeMux) }
   2130 
   2131 // DefaultServeMux is the default ServeMux used by Serve.
   2132 var DefaultServeMux = &defaultServeMux
   2133 
   2134 var defaultServeMux ServeMux
   2135 
   2136 // Does path match pattern?
   2137 func pathMatch(pattern, path string) bool {
   2138 	if len(pattern) == 0 {
   2139 		// should not happen
   2140 		return false
   2141 	}
   2142 	n := len(pattern)
   2143 	if pattern[n-1] != '/' {
   2144 		return pattern == path
   2145 	}
   2146 	return len(path) >= n && path[0:n] == pattern
   2147 }
   2148 
   2149 // Return the canonical path for p, eliminating . and .. elements.
   2150 func cleanPath(p string) string {
   2151 	if p == "" {
   2152 		return "/"
   2153 	}
   2154 	if p[0] != '/' {
   2155 		p = "/" + p
   2156 	}
   2157 	np := path.Clean(p)
   2158 	// path.Clean removes trailing slash except for root;
   2159 	// put the trailing slash back if necessary.
   2160 	if p[len(p)-1] == '/' && np != "/" {
   2161 		np += "/"
   2162 	}
   2163 	return np
   2164 }
   2165 
   2166 // Find a handler on a handler map given a path string
   2167 // Most-specific (longest) pattern wins
   2168 func (mux *ServeMux) match(path string) (h Handler, pattern string) {
   2169 	var n = 0
   2170 	for k, v := range mux.m {
   2171 		if !pathMatch(k, path) {
   2172 			continue
   2173 		}
   2174 		if h == nil || len(k) > n {
   2175 			n = len(k)
   2176 			h = v.h
   2177 			pattern = v.pattern
   2178 		}
   2179 	}
   2180 	return
   2181 }
   2182 
   2183 // Handler returns the handler to use for the given request,
   2184 // consulting r.Method, r.Host, and r.URL.Path. It always returns
   2185 // a non-nil handler. If the path is not in its canonical form, the
   2186 // handler will be an internally-generated handler that redirects
   2187 // to the canonical path.
   2188 //
   2189 // Handler also returns the registered pattern that matches the
   2190 // request or, in the case of internally-generated redirects,
   2191 // the pattern that will match after following the redirect.
   2192 //
   2193 // If there is no registered handler that applies to the request,
   2194 // Handler returns a ``page not found'' handler and an empty pattern.
   2195 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
   2196 	if r.Method != "CONNECT" {
   2197 		if p := cleanPath(r.URL.Path); p != r.URL.Path {
   2198 			_, pattern = mux.handler(r.Host, p)
   2199 			url := *r.URL
   2200 			url.Path = p
   2201 			return RedirectHandler(url.String(), StatusMovedPermanently), pattern
   2202 		}
   2203 	}
   2204 
   2205 	return mux.handler(r.Host, r.URL.Path)
   2206 }
   2207 
   2208 // handler is the main implementation of Handler.
   2209 // The path is known to be in canonical form, except for CONNECT methods.
   2210 func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) {
   2211 	mux.mu.RLock()
   2212 	defer mux.mu.RUnlock()
   2213 
   2214 	// Host-specific pattern takes precedence over generic ones
   2215 	if mux.hosts {
   2216 		h, pattern = mux.match(host + path)
   2217 	}
   2218 	if h == nil {
   2219 		h, pattern = mux.match(path)
   2220 	}
   2221 	if h == nil {
   2222 		h, pattern = NotFoundHandler(), ""
   2223 	}
   2224 	return
   2225 }
   2226 
   2227 // ServeHTTP dispatches the request to the handler whose
   2228 // pattern most closely matches the request URL.
   2229 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
   2230 	if r.RequestURI == "*" {
   2231 		if r.ProtoAtLeast(1, 1) {
   2232 			w.Header().Set("Connection", "close")
   2233 		}
   2234 		w.WriteHeader(StatusBadRequest)
   2235 		return
   2236 	}
   2237 	h, _ := mux.Handler(r)
   2238 	h.ServeHTTP(w, r)
   2239 }
   2240 
   2241 // Handle registers the handler for the given pattern.
   2242 // If a handler already exists for pattern, Handle panics.
   2243 func (mux *ServeMux) Handle(pattern string, handler Handler) {
   2244 	mux.mu.Lock()
   2245 	defer mux.mu.Unlock()
   2246 
   2247 	if pattern == "" {
   2248 		panic("http: invalid pattern " + pattern)
   2249 	}
   2250 	if handler == nil {
   2251 		panic("http: nil handler")
   2252 	}
   2253 	if mux.m[pattern].explicit {
   2254 		panic("http: multiple registrations for " + pattern)
   2255 	}
   2256 
   2257 	if mux.m == nil {
   2258 		mux.m = make(map[string]muxEntry)
   2259 	}
   2260 	mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern}
   2261 
   2262 	if pattern[0] != '/' {
   2263 		mux.hosts = true
   2264 	}
   2265 
   2266 	// Helpful behavior:
   2267 	// If pattern is /tree/, insert an implicit permanent redirect for /tree.
   2268 	// It can be overridden by an explicit registration.
   2269 	n := len(pattern)
   2270 	if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit {
   2271 		// If pattern contains a host name, strip it and use remaining
   2272 		// path for redirect.
   2273 		path := pattern
   2274 		if pattern[0] != '/' {
   2275 			// In pattern, at least the last character is a '/', so
   2276 			// strings.Index can't be -1.
   2277 			path = pattern[strings.Index(pattern, "/"):]
   2278 		}
   2279 		url := &url.URL{Path: path}
   2280 		mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(url.String(), StatusMovedPermanently), pattern: pattern}
   2281 	}
   2282 }
   2283 
   2284 // HandleFunc registers the handler function for the given pattern.
   2285 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
   2286 	mux.Handle(pattern, HandlerFunc(handler))
   2287 }
   2288 
   2289 // Handle registers the handler for the given pattern
   2290 // in the DefaultServeMux.
   2291 // The documentation for ServeMux explains how patterns are matched.
   2292 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) }
   2293 
   2294 // HandleFunc registers the handler function for the given pattern
   2295 // in the DefaultServeMux.
   2296 // The documentation for ServeMux explains how patterns are matched.
   2297 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
   2298 	DefaultServeMux.HandleFunc(pattern, handler)
   2299 }
   2300 
   2301 // Serve accepts incoming HTTP connections on the listener l,
   2302 // creating a new service goroutine for each. The service goroutines
   2303 // read requests and then call handler to reply to them.
   2304 // Handler is typically nil, in which case the DefaultServeMux is used.
   2305 func Serve(l net.Listener, handler Handler) error {
   2306 	srv := &Server{Handler: handler}
   2307 	return srv.Serve(l)
   2308 }
   2309 
   2310 // A Server defines parameters for running an HTTP server.
   2311 // The zero value for Server is a valid configuration.
   2312 type Server struct {
   2313 	Addr      string      // TCP address to listen on, ":http" if empty
   2314 	Handler   Handler     // handler to invoke, http.DefaultServeMux if nil
   2315 	TLSConfig *tls.Config // optional TLS config, used by ListenAndServeTLS
   2316 
   2317 	// ReadTimeout is the maximum duration for reading the entire
   2318 	// request, including the body.
   2319 	//
   2320 	// Because ReadTimeout does not let Handlers make per-request
   2321 	// decisions on each request body's acceptable deadline or
   2322 	// upload rate, most users will prefer to use
   2323 	// ReadHeaderTimeout. It is valid to use them both.
   2324 	ReadTimeout time.Duration
   2325 
   2326 	// ReadHeaderTimeout is the amount of time allowed to read
   2327 	// request headers. The connection's read deadline is reset
   2328 	// after reading the headers and the Handler can decide what
   2329 	// is considered too slow for the body.
   2330 	ReadHeaderTimeout time.Duration
   2331 
   2332 	// WriteTimeout is the maximum duration before timing out
   2333 	// writes of the response. It is reset whenever a new
   2334 	// request's header is read. Like ReadTimeout, it does not
   2335 	// let Handlers make decisions on a per-request basis.
   2336 	WriteTimeout time.Duration
   2337 
   2338 	// IdleTimeout is the maximum amount of time to wait for the
   2339 	// next request when keep-alives are enabled. If IdleTimeout
   2340 	// is zero, the value of ReadTimeout is used. If both are
   2341 	// zero, there is no timeout.
   2342 	IdleTimeout time.Duration
   2343 
   2344 	// MaxHeaderBytes controls the maximum number of bytes the
   2345 	// server will read parsing the request header's keys and
   2346 	// values, including the request line. It does not limit the
   2347 	// size of the request body.
   2348 	// If zero, DefaultMaxHeaderBytes is used.
   2349 	MaxHeaderBytes int
   2350 
   2351 	// TLSNextProto optionally specifies a function to take over
   2352 	// ownership of the provided TLS connection when an NPN/ALPN
   2353 	// protocol upgrade has occurred. The map key is the protocol
   2354 	// name negotiated. The Handler argument should be used to
   2355 	// handle HTTP requests and will initialize the Request's TLS
   2356 	// and RemoteAddr if not already set. The connection is
   2357 	// automatically closed when the function returns.
   2358 	// If TLSNextProto is not nil, HTTP/2 support is not enabled
   2359 	// automatically.
   2360 	TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
   2361 
   2362 	// ConnState specifies an optional callback function that is
   2363 	// called when a client connection changes state. See the
   2364 	// ConnState type and associated constants for details.
   2365 	ConnState func(net.Conn, ConnState)
   2366 
   2367 	// ErrorLog specifies an optional logger for errors accepting
   2368 	// connections and unexpected behavior from handlers.
   2369 	// If nil, logging goes to os.Stderr via the log package's
   2370 	// standard logger.
   2371 	ErrorLog *log.Logger
   2372 
   2373 	disableKeepAlives int32     // accessed atomically.
   2374 	inShutdown        int32     // accessed atomically (non-zero means we're in Shutdown)
   2375 	nextProtoOnce     sync.Once // guards setupHTTP2_* init
   2376 	nextProtoErr      error     // result of http2.ConfigureServer if used
   2377 
   2378 	mu         sync.Mutex
   2379 	listeners  map[net.Listener]struct{}
   2380 	activeConn map[*conn]struct{}
   2381 	doneChan   chan struct{}
   2382 }
   2383 
   2384 func (s *Server) getDoneChan() <-chan struct{} {
   2385 	s.mu.Lock()
   2386 	defer s.mu.Unlock()
   2387 	return s.getDoneChanLocked()
   2388 }
   2389 
   2390 func (s *Server) getDoneChanLocked() chan struct{} {
   2391 	if s.doneChan == nil {
   2392 		s.doneChan = make(chan struct{})
   2393 	}
   2394 	return s.doneChan
   2395 }
   2396 
   2397 func (s *Server) closeDoneChanLocked() {
   2398 	ch := s.getDoneChanLocked()
   2399 	select {
   2400 	case <-ch:
   2401 		// Already closed. Don't close again.
   2402 	default:
   2403 		// Safe to close here. We're the only closer, guarded
   2404 		// by s.mu.
   2405 		close(ch)
   2406 	}
   2407 }
   2408 
   2409 // Close immediately closes all active net.Listeners and any
   2410 // connections in state StateNew, StateActive, or StateIdle. For a
   2411 // graceful shutdown, use Shutdown.
   2412 //
   2413 // Close does not attempt to close (and does not even know about)
   2414 // any hijacked connections, such as WebSockets.
   2415 //
   2416 // Close returns any error returned from closing the Server's
   2417 // underlying Listener(s).
   2418 func (srv *Server) Close() error {
   2419 	srv.mu.Lock()
   2420 	defer srv.mu.Unlock()
   2421 	srv.closeDoneChanLocked()
   2422 	err := srv.closeListenersLocked()
   2423 	for c := range srv.activeConn {
   2424 		c.rwc.Close()
   2425 		delete(srv.activeConn, c)
   2426 	}
   2427 	return err
   2428 }
   2429 
   2430 // shutdownPollInterval is how often we poll for quiescence
   2431 // during Server.Shutdown. This is lower during tests, to
   2432 // speed up tests.
   2433 // Ideally we could find a solution that doesn't involve polling,
   2434 // but which also doesn't have a high runtime cost (and doesn't
   2435 // involve any contentious mutexes), but that is left as an
   2436 // exercise for the reader.
   2437 var shutdownPollInterval = 500 * time.Millisecond
   2438 
   2439 // Shutdown gracefully shuts down the server without interrupting any
   2440 // active connections. Shutdown works by first closing all open
   2441 // listeners, then closing all idle connections, and then waiting
   2442 // indefinitely for connections to return to idle and then shut down.
   2443 // If the provided context expires before the shutdown is complete,
   2444 // then the context's error is returned.
   2445 //
   2446 // Shutdown does not attempt to close nor wait for hijacked
   2447 // connections such as WebSockets. The caller of Shutdown should
   2448 // separately notify such long-lived connections of shutdown and wait
   2449 // for them to close, if desired.
   2450 func (srv *Server) Shutdown(ctx context.Context) error {
   2451 	atomic.AddInt32(&srv.inShutdown, 1)
   2452 	defer atomic.AddInt32(&srv.inShutdown, -1)
   2453 
   2454 	srv.mu.Lock()
   2455 	lnerr := srv.closeListenersLocked()
   2456 	srv.closeDoneChanLocked()
   2457 	srv.mu.Unlock()
   2458 
   2459 	ticker := time.NewTicker(shutdownPollInterval)
   2460 	defer ticker.Stop()
   2461 	for {
   2462 		if srv.closeIdleConns() {
   2463 			return lnerr
   2464 		}
   2465 		select {
   2466 		case <-ctx.Done():
   2467 			return ctx.Err()
   2468 		case <-ticker.C:
   2469 		}
   2470 	}
   2471 }
   2472 
   2473 // closeIdleConns closes all idle connections and reports whether the
   2474 // server is quiescent.
   2475 func (s *Server) closeIdleConns() bool {
   2476 	s.mu.Lock()
   2477 	defer s.mu.Unlock()
   2478 	quiescent := true
   2479 	for c := range s.activeConn {
   2480 		st, ok := c.curState.Load().(ConnState)
   2481 		if !ok || st != StateIdle {
   2482 			quiescent = false
   2483 			continue
   2484 		}
   2485 		c.rwc.Close()
   2486 		delete(s.activeConn, c)
   2487 	}
   2488 	return quiescent
   2489 }
   2490 
   2491 func (s *Server) closeListenersLocked() error {
   2492 	var err error
   2493 	for ln := range s.listeners {
   2494 		if cerr := ln.Close(); cerr != nil && err == nil {
   2495 			err = cerr
   2496 		}
   2497 		delete(s.listeners, ln)
   2498 	}
   2499 	return err
   2500 }
   2501 
   2502 // A ConnState represents the state of a client connection to a server.
   2503 // It's used by the optional Server.ConnState hook.
   2504 type ConnState int
   2505 
   2506 const (
   2507 	// StateNew represents a new connection that is expected to
   2508 	// send a request immediately. Connections begin at this
   2509 	// state and then transition to either StateActive or
   2510 	// StateClosed.
   2511 	StateNew ConnState = iota
   2512 
   2513 	// StateActive represents a connection that has read 1 or more
   2514 	// bytes of a request. The Server.ConnState hook for
   2515 	// StateActive fires before the request has entered a handler
   2516 	// and doesn't fire again until the request has been
   2517 	// handled. After the request is handled, the state
   2518 	// transitions to StateClosed, StateHijacked, or StateIdle.
   2519 	// For HTTP/2, StateActive fires on the transition from zero
   2520 	// to one active request, and only transitions away once all
   2521 	// active requests are complete. That means that ConnState
   2522 	// cannot be used to do per-request work; ConnState only notes
   2523 	// the overall state of the connection.
   2524 	StateActive
   2525 
   2526 	// StateIdle represents a connection that has finished
   2527 	// handling a request and is in the keep-alive state, waiting
   2528 	// for a new request. Connections transition from StateIdle
   2529 	// to either StateActive or StateClosed.
   2530 	StateIdle
   2531 
   2532 	// StateHijacked represents a hijacked connection.
   2533 	// This is a terminal state. It does not transition to StateClosed.
   2534 	StateHijacked
   2535 
   2536 	// StateClosed represents a closed connection.
   2537 	// This is a terminal state. Hijacked connections do not
   2538 	// transition to StateClosed.
   2539 	StateClosed
   2540 )
   2541 
   2542 var stateName = map[ConnState]string{
   2543 	StateNew:      "new",
   2544 	StateActive:   "active",
   2545 	StateIdle:     "idle",
   2546 	StateHijacked: "hijacked",
   2547 	StateClosed:   "closed",
   2548 }
   2549 
   2550 func (c ConnState) String() string {
   2551 	return stateName[c]
   2552 }
   2553 
   2554 // serverHandler delegates to either the server's Handler or
   2555 // DefaultServeMux and also handles "OPTIONS *" requests.
   2556 type serverHandler struct {
   2557 	srv *Server
   2558 }
   2559 
   2560 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
   2561 	handler := sh.srv.Handler
   2562 	if handler == nil {
   2563 		handler = DefaultServeMux
   2564 	}
   2565 	if req.RequestURI == "*" && req.Method == "OPTIONS" {
   2566 		handler = globalOptionsHandler{}
   2567 	}
   2568 	handler.ServeHTTP(rw, req)
   2569 }
   2570 
   2571 // ListenAndServe listens on the TCP network address srv.Addr and then
   2572 // calls Serve to handle requests on incoming connections.
   2573 // Accepted connections are configured to enable TCP keep-alives.
   2574 // If srv.Addr is blank, ":http" is used.
   2575 // ListenAndServe always returns a non-nil error.
   2576 func (srv *Server) ListenAndServe() error {
   2577 	addr := srv.Addr
   2578 	if addr == "" {
   2579 		addr = ":http"
   2580 	}
   2581 	ln, err := net.Listen("tcp", addr)
   2582 	if err != nil {
   2583 		return err
   2584 	}
   2585 	return srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)})
   2586 }
   2587 
   2588 var testHookServerServe func(*Server, net.Listener) // used if non-nil
   2589 
   2590 // shouldDoServeHTTP2 reports whether Server.Serve should configure
   2591 // automatic HTTP/2. (which sets up the srv.TLSNextProto map)
   2592 func (srv *Server) shouldConfigureHTTP2ForServe() bool {
   2593 	if srv.TLSConfig == nil {
   2594 		// Compatibility with Go 1.6:
   2595 		// If there's no TLSConfig, it's possible that the user just
   2596 		// didn't set it on the http.Server, but did pass it to
   2597 		// tls.NewListener and passed that listener to Serve.
   2598 		// So we should configure HTTP/2 (to set up srv.TLSNextProto)
   2599 		// in case the listener returns an "h2" *tls.Conn.
   2600 		return true
   2601 	}
   2602 	// The user specified a TLSConfig on their http.Server.
   2603 	// In this, case, only configure HTTP/2 if their tls.Config
   2604 	// explicitly mentions "h2". Otherwise http2.ConfigureServer
   2605 	// would modify the tls.Config to add it, but they probably already
   2606 	// passed this tls.Config to tls.NewListener. And if they did,
   2607 	// it's too late anyway to fix it. It would only be potentially racy.
   2608 	// See Issue 15908.
   2609 	return strSliceContains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
   2610 }
   2611 
   2612 var ErrServerClosed = errors.New("http: Server closed")
   2613 
   2614 // Serve accepts incoming connections on the Listener l, creating a
   2615 // new service goroutine for each. The service goroutines read requests and
   2616 // then call srv.Handler to reply to them.
   2617 //
   2618 // For HTTP/2 support, srv.TLSConfig should be initialized to the
   2619 // provided listener's TLS Config before calling Serve. If
   2620 // srv.TLSConfig is non-nil and doesn't include the string "h2" in
   2621 // Config.NextProtos, HTTP/2 support is not enabled.
   2622 //
   2623 // Serve always returns a non-nil error. After Shutdown or Close, the
   2624 // returned error is ErrServerClosed.
   2625 func (srv *Server) Serve(l net.Listener) error {
   2626 	defer l.Close()
   2627 	if fn := testHookServerServe; fn != nil {
   2628 		fn(srv, l)
   2629 	}
   2630 	var tempDelay time.Duration // how long to sleep on accept failure
   2631 
   2632 	if err := srv.setupHTTP2_Serve(); err != nil {
   2633 		return err
   2634 	}
   2635 
   2636 	srv.trackListener(l, true)
   2637 	defer srv.trackListener(l, false)
   2638 
   2639 	baseCtx := context.Background() // base is always background, per Issue 16220
   2640 	ctx := context.WithValue(baseCtx, ServerContextKey, srv)
   2641 	ctx = context.WithValue(ctx, LocalAddrContextKey, l.Addr())
   2642 	for {
   2643 		rw, e := l.Accept()
   2644 		if e != nil {
   2645 			select {
   2646 			case <-srv.getDoneChan():
   2647 				return ErrServerClosed
   2648 			default:
   2649 			}
   2650 			if ne, ok := e.(net.Error); ok && ne.Temporary() {
   2651 				if tempDelay == 0 {
   2652 					tempDelay = 5 * time.Millisecond
   2653 				} else {
   2654 					tempDelay *= 2
   2655 				}
   2656 				if max := 1 * time.Second; tempDelay > max {
   2657 					tempDelay = max
   2658 				}
   2659 				srv.logf("http: Accept error: %v; retrying in %v", e, tempDelay)
   2660 				time.Sleep(tempDelay)
   2661 				continue
   2662 			}
   2663 			return e
   2664 		}
   2665 		tempDelay = 0
   2666 		c := srv.newConn(rw)
   2667 		c.setState(c.rwc, StateNew) // before Serve can return
   2668 		go c.serve(ctx)
   2669 	}
   2670 }
   2671 
   2672 func (s *Server) trackListener(ln net.Listener, add bool) {
   2673 	s.mu.Lock()
   2674 	defer s.mu.Unlock()
   2675 	if s.listeners == nil {
   2676 		s.listeners = make(map[net.Listener]struct{})
   2677 	}
   2678 	if add {
   2679 		// If the *Server is being reused after a previous
   2680 		// Close or Shutdown, reset its doneChan:
   2681 		if len(s.listeners) == 0 && len(s.activeConn) == 0 {
   2682 			s.doneChan = nil
   2683 		}
   2684 		s.listeners[ln] = struct{}{}
   2685 	} else {
   2686 		delete(s.listeners, ln)
   2687 	}
   2688 }
   2689 
   2690 func (s *Server) trackConn(c *conn, add bool) {
   2691 	s.mu.Lock()
   2692 	defer s.mu.Unlock()
   2693 	if s.activeConn == nil {
   2694 		s.activeConn = make(map[*conn]struct{})
   2695 	}
   2696 	if add {
   2697 		s.activeConn[c] = struct{}{}
   2698 	} else {
   2699 		delete(s.activeConn, c)
   2700 	}
   2701 }
   2702 
   2703 func (s *Server) idleTimeout() time.Duration {
   2704 	if s.IdleTimeout != 0 {
   2705 		return s.IdleTimeout
   2706 	}
   2707 	return s.ReadTimeout
   2708 }
   2709 
   2710 func (s *Server) readHeaderTimeout() time.Duration {
   2711 	if s.ReadHeaderTimeout != 0 {
   2712 		return s.ReadHeaderTimeout
   2713 	}
   2714 	return s.ReadTimeout
   2715 }
   2716 
   2717 func (s *Server) doKeepAlives() bool {
   2718 	return atomic.LoadInt32(&s.disableKeepAlives) == 0 && !s.shuttingDown()
   2719 }
   2720 
   2721 func (s *Server) shuttingDown() bool {
   2722 	return atomic.LoadInt32(&s.inShutdown) != 0
   2723 }
   2724 
   2725 // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
   2726 // By default, keep-alives are always enabled. Only very
   2727 // resource-constrained environments or servers in the process of
   2728 // shutting down should disable them.
   2729 func (srv *Server) SetKeepAlivesEnabled(v bool) {
   2730 	if v {
   2731 		atomic.StoreInt32(&srv.disableKeepAlives, 0)
   2732 		return
   2733 	}
   2734 	atomic.StoreInt32(&srv.disableKeepAlives, 1)
   2735 
   2736 	// Close idle HTTP/1 conns:
   2737 	srv.closeIdleConns()
   2738 
   2739 	// Close HTTP/2 conns, as soon as they become idle, but reset
   2740 	// the chan so future conns (if the listener is still active)
   2741 	// still work and don't get a GOAWAY immediately, before their
   2742 	// first request:
   2743 	srv.mu.Lock()
   2744 	defer srv.mu.Unlock()
   2745 	srv.closeDoneChanLocked() // closes http2 conns
   2746 	srv.doneChan = nil
   2747 }
   2748 
   2749 func (s *Server) logf(format string, args ...interface{}) {
   2750 	if s.ErrorLog != nil {
   2751 		s.ErrorLog.Printf(format, args...)
   2752 	} else {
   2753 		log.Printf(format, args...)
   2754 	}
   2755 }
   2756 
   2757 // ListenAndServe listens on the TCP network address addr
   2758 // and then calls Serve with handler to handle requests
   2759 // on incoming connections.
   2760 // Accepted connections are configured to enable TCP keep-alives.
   2761 // Handler is typically nil, in which case the DefaultServeMux is
   2762 // used.
   2763 //
   2764 // A trivial example server is:
   2765 //
   2766 //	package main
   2767 //
   2768 //	import (
   2769 //		"io"
   2770 //		"net/http"
   2771 //		"log"
   2772 //	)
   2773 //
   2774 //	// hello world, the web server
   2775 //	func HelloServer(w http.ResponseWriter, req *http.Request) {
   2776 //		io.WriteString(w, "hello, world!\n")
   2777 //	}
   2778 //
   2779 //	func main() {
   2780 //		http.HandleFunc("/hello", HelloServer)
   2781 //		log.Fatal(http.ListenAndServe(":12345", nil))
   2782 //	}
   2783 //
   2784 // ListenAndServe always returns a non-nil error.
   2785 func ListenAndServe(addr string, handler Handler) error {
   2786 	server := &Server{Addr: addr, Handler: handler}
   2787 	return server.ListenAndServe()
   2788 }
   2789 
   2790 // ListenAndServeTLS acts identically to ListenAndServe, except that it
   2791 // expects HTTPS connections. Additionally, files containing a certificate and
   2792 // matching private key for the server must be provided. If the certificate
   2793 // is signed by a certificate authority, the certFile should be the concatenation
   2794 // of the server's certificate, any intermediates, and the CA's certificate.
   2795 //
   2796 // A trivial example server is:
   2797 //
   2798 //	import (
   2799 //		"log"
   2800 //		"net/http"
   2801 //	)
   2802 //
   2803 //	func handler(w http.ResponseWriter, req *http.Request) {
   2804 //		w.Header().Set("Content-Type", "text/plain")
   2805 //		w.Write([]byte("This is an example server.\n"))
   2806 //	}
   2807 //
   2808 //	func main() {
   2809 //		http.HandleFunc("/", handler)
   2810 //		log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/")
   2811 //		err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil)
   2812 //		log.Fatal(err)
   2813 //	}
   2814 //
   2815 // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem.
   2816 //
   2817 // ListenAndServeTLS always returns a non-nil error.
   2818 func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
   2819 	server := &Server{Addr: addr, Handler: handler}
   2820 	return server.ListenAndServeTLS(certFile, keyFile)
   2821 }
   2822 
   2823 // ListenAndServeTLS listens on the TCP network address srv.Addr and
   2824 // then calls Serve to handle requests on incoming TLS connections.
   2825 // Accepted connections are configured to enable TCP keep-alives.
   2826 //
   2827 // Filenames containing a certificate and matching private key for the
   2828 // server must be provided if neither the Server's TLSConfig.Certificates
   2829 // nor TLSConfig.GetCertificate are populated. If the certificate is
   2830 // signed by a certificate authority, the certFile should be the
   2831 // concatenation of the server's certificate, any intermediates, and
   2832 // the CA's certificate.
   2833 //
   2834 // If srv.Addr is blank, ":https" is used.
   2835 //
   2836 // ListenAndServeTLS always returns a non-nil error.
   2837 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
   2838 	addr := srv.Addr
   2839 	if addr == "" {
   2840 		addr = ":https"
   2841 	}
   2842 
   2843 	// Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig
   2844 	// before we clone it and create the TLS Listener.
   2845 	if err := srv.setupHTTP2_ListenAndServeTLS(); err != nil {
   2846 		return err
   2847 	}
   2848 
   2849 	config := cloneTLSConfig(srv.TLSConfig)
   2850 	if !strSliceContains(config.NextProtos, "http/1.1") {
   2851 		config.NextProtos = append(config.NextProtos, "http/1.1")
   2852 	}
   2853 
   2854 	configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil
   2855 	if !configHasCert || certFile != "" || keyFile != "" {
   2856 		var err error
   2857 		config.Certificates = make([]tls.Certificate, 1)
   2858 		config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
   2859 		if err != nil {
   2860 			return err
   2861 		}
   2862 	}
   2863 
   2864 	ln, err := net.Listen("tcp", addr)
   2865 	if err != nil {
   2866 		return err
   2867 	}
   2868 
   2869 	tlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config)
   2870 	return srv.Serve(tlsListener)
   2871 }
   2872 
   2873 // setupHTTP2_ListenAndServeTLS conditionally configures HTTP/2 on
   2874 // srv and returns whether there was an error setting it up. If it is
   2875 // not configured for policy reasons, nil is returned.
   2876 func (srv *Server) setupHTTP2_ListenAndServeTLS() error {
   2877 	srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
   2878 	return srv.nextProtoErr
   2879 }
   2880 
   2881 // setupHTTP2_Serve is called from (*Server).Serve and conditionally
   2882 // configures HTTP/2 on srv using a more conservative policy than
   2883 // setupHTTP2_ListenAndServeTLS because Serve may be called
   2884 // concurrently.
   2885 //
   2886 // The tests named TestTransportAutomaticHTTP2* and
   2887 // TestConcurrentServerServe in server_test.go demonstrate some
   2888 // of the supported use cases and motivations.
   2889 func (srv *Server) setupHTTP2_Serve() error {
   2890 	srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
   2891 	return srv.nextProtoErr
   2892 }
   2893 
   2894 func (srv *Server) onceSetNextProtoDefaults_Serve() {
   2895 	if srv.shouldConfigureHTTP2ForServe() {
   2896 		srv.onceSetNextProtoDefaults()
   2897 	}
   2898 }
   2899 
   2900 // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
   2901 // configured otherwise. (by setting srv.TLSNextProto non-nil)
   2902 // It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*).
   2903 func (srv *Server) onceSetNextProtoDefaults() {
   2904 	if strings.Contains(os.Getenv("GODEBUG"), "http2server=0") {
   2905 		return
   2906 	}
   2907 	// Enable HTTP/2 by default if the user hasn't otherwise
   2908 	// configured their TLSNextProto map.
   2909 	if srv.TLSNextProto == nil {
   2910 		srv.nextProtoErr = http2ConfigureServer(srv, nil)
   2911 	}
   2912 }
   2913 
   2914 // TimeoutHandler returns a Handler that runs h with the given time limit.
   2915 //
   2916 // The new Handler calls h.ServeHTTP to handle each request, but if a
   2917 // call runs for longer than its time limit, the handler responds with
   2918 // a 503 Service Unavailable error and the given message in its body.
   2919 // (If msg is empty, a suitable default message will be sent.)
   2920 // After such a timeout, writes by h to its ResponseWriter will return
   2921 // ErrHandlerTimeout.
   2922 //
   2923 // TimeoutHandler buffers all Handler writes to memory and does not
   2924 // support the Hijacker or Flusher interfaces.
   2925 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
   2926 	return &timeoutHandler{
   2927 		handler: h,
   2928 		body:    msg,
   2929 		dt:      dt,
   2930 	}
   2931 }
   2932 
   2933 // ErrHandlerTimeout is returned on ResponseWriter Write calls
   2934 // in handlers which have timed out.
   2935 var ErrHandlerTimeout = errors.New("http: Handler timeout")
   2936 
   2937 type timeoutHandler struct {
   2938 	handler Handler
   2939 	body    string
   2940 	dt      time.Duration
   2941 
   2942 	// When set, no timer will be created and this channel will
   2943 	// be used instead.
   2944 	testTimeout <-chan time.Time
   2945 }
   2946 
   2947 func (h *timeoutHandler) errorBody() string {
   2948 	if h.body != "" {
   2949 		return h.body
   2950 	}
   2951 	return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
   2952 }
   2953 
   2954 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
   2955 	var t *time.Timer
   2956 	timeout := h.testTimeout
   2957 	if timeout == nil {
   2958 		t = time.NewTimer(h.dt)
   2959 		timeout = t.C
   2960 	}
   2961 	done := make(chan struct{})
   2962 	tw := &timeoutWriter{
   2963 		w: w,
   2964 		h: make(Header),
   2965 	}
   2966 	go func() {
   2967 		h.handler.ServeHTTP(tw, r)
   2968 		close(done)
   2969 	}()
   2970 	select {
   2971 	case <-done:
   2972 		tw.mu.Lock()
   2973 		defer tw.mu.Unlock()
   2974 		dst := w.Header()
   2975 		for k, vv := range tw.h {
   2976 			dst[k] = vv
   2977 		}
   2978 		if !tw.wroteHeader {
   2979 			tw.code = StatusOK
   2980 		}
   2981 		w.WriteHeader(tw.code)
   2982 		w.Write(tw.wbuf.Bytes())
   2983 		if t != nil {
   2984 			t.Stop()
   2985 		}
   2986 	case <-timeout:
   2987 		tw.mu.Lock()
   2988 		defer tw.mu.Unlock()
   2989 		w.WriteHeader(StatusServiceUnavailable)
   2990 		io.WriteString(w, h.errorBody())
   2991 		tw.timedOut = true
   2992 		return
   2993 	}
   2994 }
   2995 
   2996 type timeoutWriter struct {
   2997 	w    ResponseWriter
   2998 	h    Header
   2999 	wbuf bytes.Buffer
   3000 
   3001 	mu          sync.Mutex
   3002 	timedOut    bool
   3003 	wroteHeader bool
   3004 	code        int
   3005 }
   3006 
   3007 func (tw *timeoutWriter) Header() Header { return tw.h }
   3008 
   3009 func (tw *timeoutWriter) Write(p []byte) (int, error) {
   3010 	tw.mu.Lock()
   3011 	defer tw.mu.Unlock()
   3012 	if tw.timedOut {
   3013 		return 0, ErrHandlerTimeout
   3014 	}
   3015 	if !tw.wroteHeader {
   3016 		tw.writeHeader(StatusOK)
   3017 	}
   3018 	return tw.wbuf.Write(p)
   3019 }
   3020 
   3021 func (tw *timeoutWriter) WriteHeader(code int) {
   3022 	tw.mu.Lock()
   3023 	defer tw.mu.Unlock()
   3024 	if tw.timedOut || tw.wroteHeader {
   3025 		return
   3026 	}
   3027 	tw.writeHeader(code)
   3028 }
   3029 
   3030 func (tw *timeoutWriter) writeHeader(code int) {
   3031 	tw.wroteHeader = true
   3032 	tw.code = code
   3033 }
   3034 
   3035 // tcpKeepAliveListener sets TCP keep-alive timeouts on accepted
   3036 // connections. It's used by ListenAndServe and ListenAndServeTLS so
   3037 // dead TCP connections (e.g. closing laptop mid-download) eventually
   3038 // go away.
   3039 type tcpKeepAliveListener struct {
   3040 	*net.TCPListener
   3041 }
   3042 
   3043 func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) {
   3044 	tc, err := ln.AcceptTCP()
   3045 	if err != nil {
   3046 		return
   3047 	}
   3048 	tc.SetKeepAlive(true)
   3049 	tc.SetKeepAlivePeriod(3 * time.Minute)
   3050 	return tc, nil
   3051 }
   3052 
   3053 // globalOptionsHandler responds to "OPTIONS *" requests.
   3054 type globalOptionsHandler struct{}
   3055 
   3056 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
   3057 	w.Header().Set("Content-Length", "0")
   3058 	if r.ContentLength != 0 {
   3059 		// Read up to 4KB of OPTIONS body (as mentioned in the
   3060 		// spec as being reserved for future use), but anything
   3061 		// over that is considered a waste of server resources
   3062 		// (or an attack) and we abort and close the connection,
   3063 		// courtesy of MaxBytesReader's EOF behavior.
   3064 		mb := MaxBytesReader(w, r.Body, 4<<10)
   3065 		io.Copy(ioutil.Discard, mb)
   3066 	}
   3067 }
   3068 
   3069 // initNPNRequest is an HTTP handler that initializes certain
   3070 // uninitialized fields in its *Request. Such partially-initialized
   3071 // Requests come from NPN protocol handlers.
   3072 type initNPNRequest struct {
   3073 	c *tls.Conn
   3074 	h serverHandler
   3075 }
   3076 
   3077 func (h initNPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
   3078 	if req.TLS == nil {
   3079 		req.TLS = &tls.ConnectionState{}
   3080 		*req.TLS = h.c.ConnectionState()
   3081 	}
   3082 	if req.Body == nil {
   3083 		req.Body = NoBody
   3084 	}
   3085 	if req.RemoteAddr == "" {
   3086 		req.RemoteAddr = h.c.RemoteAddr().String()
   3087 	}
   3088 	h.h.ServeHTTP(rw, req)
   3089 }
   3090 
   3091 // loggingConn is used for debugging.
   3092 type loggingConn struct {
   3093 	name string
   3094 	net.Conn
   3095 }
   3096 
   3097 var (
   3098 	uniqNameMu   sync.Mutex
   3099 	uniqNameNext = make(map[string]int)
   3100 )
   3101 
   3102 func newLoggingConn(baseName string, c net.Conn) net.Conn {
   3103 	uniqNameMu.Lock()
   3104 	defer uniqNameMu.Unlock()
   3105 	uniqNameNext[baseName]++
   3106 	return &loggingConn{
   3107 		name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
   3108 		Conn: c,
   3109 	}
   3110 }
   3111 
   3112 func (c *loggingConn) Write(p []byte) (n int, err error) {
   3113 	log.Printf("%s.Write(%d) = ....", c.name, len(p))
   3114 	n, err = c.Conn.Write(p)
   3115 	log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
   3116 	return
   3117 }
   3118 
   3119 func (c *loggingConn) Read(p []byte) (n int, err error) {
   3120 	log.Printf("%s.Read(%d) = ....", c.name, len(p))
   3121 	n, err = c.Conn.Read(p)
   3122 	log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
   3123 	return
   3124 }
   3125 
   3126 func (c *loggingConn) Close() (err error) {
   3127 	log.Printf("%s.Close() = ...", c.name)
   3128 	err = c.Conn.Close()
   3129 	log.Printf("%s.Close() = %v", c.name, err)
   3130 	return
   3131 }
   3132 
   3133 // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
   3134 // It only contains one field (and a pointer field at that), so it
   3135 // fits in an interface value without an extra allocation.
   3136 type checkConnErrorWriter struct {
   3137 	c *conn
   3138 }
   3139 
   3140 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
   3141 	n, err = w.c.rwc.Write(p)
   3142 	if err != nil && w.c.werr == nil {
   3143 		w.c.werr = err
   3144 		w.c.cancelCtx()
   3145 	}
   3146 	return
   3147 }
   3148 
   3149 func numLeadingCRorLF(v []byte) (n int) {
   3150 	for _, b := range v {
   3151 		if b == '\r' || b == '\n' {
   3152 			n++
   3153 			continue
   3154 		}
   3155 		break
   3156 	}
   3157 	return
   3158 
   3159 }
   3160 
   3161 func strSliceContains(ss []string, s string) bool {
   3162 	for _, v := range ss {
   3163 		if v == s {
   3164 			return true
   3165 		}
   3166 	}
   3167 	return false
   3168 }
   3169