Source file src/net/http/server.go

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

View as plain text