github.com/twelsh-aw/go/src@v0.0.0-20230516233729-a56fe86a7c81/net/http/server.go (about)

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