Source file src/net/http/server.go

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

View as plain text