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