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  		var more bool
  1164  		frame, more = frames.Next()
  1165  		if !strings.HasPrefix(frame.Function, "net/http.") {
  1166  			return frame
  1167  		}
  1168  		if !more {
  1169  			break
  1170  		}
  1171  	}
  1172  	return frame
  1173  }
  1174  
  1175  func (w *response) WriteHeader(code int) {
  1176  	if w.conn.hijacked() {
  1177  		caller := relevantCaller()
  1178  		w.conn.server.logf("http: response.WriteHeader on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
  1179  		return
  1180  	}
  1181  	if w.wroteHeader {
  1182  		caller := relevantCaller()
  1183  		w.conn.server.logf("http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
  1184  		return
  1185  	}
  1186  	checkWriteHeaderCode(code)
  1187  
  1188  	if code < 101 || code > 199 {
  1189  		// Sending a 100 Continue or any non-1xx header disables the
  1190  		// automatically-sent 100 Continue from Request.Body.Read.
  1191  		w.disableWriteContinue()
  1192  	}
  1193  
  1194  	// Handle informational headers.
  1195  	//
  1196  	// We shouldn't send any further headers after 101 Switching Protocols,
  1197  	// so it takes the non-informational path.
  1198  	if code >= 100 && code <= 199 && code != StatusSwitchingProtocols {
  1199  		writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
  1200  
  1201  		// Per RFC 8297 we must not clear the current header map
  1202  		w.handlerHeader.WriteSubset(w.conn.bufw, excludedHeadersNoBody)
  1203  		w.conn.bufw.Write(crlf)
  1204  		w.conn.bufw.Flush()
  1205  
  1206  		return
  1207  	}
  1208  
  1209  	w.wroteHeader = true
  1210  	w.status = code
  1211  
  1212  	if w.calledHeader && w.cw.header == nil {
  1213  		w.cw.header = w.handlerHeader.Clone()
  1214  	}
  1215  
  1216  	if cl := w.handlerHeader.get("Content-Length"); cl != "" {
  1217  		v, err := strconv.ParseInt(cl, 10, 64)
  1218  		if err == nil && v >= 0 {
  1219  			w.contentLength = v
  1220  		} else {
  1221  			w.conn.server.logf("http: invalid Content-Length of %q", cl)
  1222  			w.handlerHeader.Del("Content-Length")
  1223  		}
  1224  	}
  1225  }
  1226  
  1227  // extraHeader is the set of headers sometimes added by chunkWriter.writeHeader.
  1228  // This type is used to avoid extra allocations from cloning and/or populating
  1229  // the response Header map and all its 1-element slices.
  1230  type extraHeader struct {
  1231  	contentType      string
  1232  	connection       string
  1233  	transferEncoding string
  1234  	date             []byte // written if not nil
  1235  	contentLength    []byte // written if not nil
  1236  }
  1237  
  1238  // Sorted the same as extraHeader.Write's loop.
  1239  var extraHeaderKeys = [][]byte{
  1240  	[]byte("Content-Type"),
  1241  	[]byte("Connection"),
  1242  	[]byte("Transfer-Encoding"),
  1243  }
  1244  
  1245  var (
  1246  	headerContentLength = []byte("Content-Length: ")
  1247  	headerDate          = []byte("Date: ")
  1248  )
  1249  
  1250  // Write writes the headers described in h to w.
  1251  //
  1252  // This method has a value receiver, despite the somewhat large size
  1253  // of h, because it prevents an allocation. The escape analysis isn't
  1254  // smart enough to realize this function doesn't mutate h.
  1255  func (h extraHeader) Write(w *bufio.Writer) {
  1256  	if h.date != nil {
  1257  		w.Write(headerDate)
  1258  		w.Write(h.date)
  1259  		w.Write(crlf)
  1260  	}
  1261  	if h.contentLength != nil {
  1262  		w.Write(headerContentLength)
  1263  		w.Write(h.contentLength)
  1264  		w.Write(crlf)
  1265  	}
  1266  	for i, v := range []string{h.contentType, h.connection, h.transferEncoding} {
  1267  		if v != "" {
  1268  			w.Write(extraHeaderKeys[i])
  1269  			w.Write(colonSpace)
  1270  			w.WriteString(v)
  1271  			w.Write(crlf)
  1272  		}
  1273  	}
  1274  }
  1275  
  1276  // writeHeader finalizes the header sent to the client and writes it
  1277  // to cw.res.conn.bufw.
  1278  //
  1279  // p is not written by writeHeader, but is the first chunk of the body
  1280  // that will be written. It is sniffed for a Content-Type if none is
  1281  // set explicitly. It's also used to set the Content-Length, if the
  1282  // total body size was small and the handler has already finished
  1283  // running.
  1284  func (cw *chunkWriter) writeHeader(p []byte) {
  1285  	if cw.wroteHeader {
  1286  		return
  1287  	}
  1288  	cw.wroteHeader = true
  1289  
  1290  	w := cw.res
  1291  	keepAlivesEnabled := w.conn.server.doKeepAlives()
  1292  	isHEAD := w.req.Method == "HEAD"
  1293  
  1294  	// header is written out to w.conn.buf below. Depending on the
  1295  	// state of the handler, we either own the map or not. If we
  1296  	// don't own it, the exclude map is created lazily for
  1297  	// WriteSubset to remove headers. The setHeader struct holds
  1298  	// headers we need to add.
  1299  	header := cw.header
  1300  	owned := header != nil
  1301  	if !owned {
  1302  		header = w.handlerHeader
  1303  	}
  1304  	var excludeHeader map[string]bool
  1305  	delHeader := func(key string) {
  1306  		if owned {
  1307  			header.Del(key)
  1308  			return
  1309  		}
  1310  		if _, ok := header[key]; !ok {
  1311  			return
  1312  		}
  1313  		if excludeHeader == nil {
  1314  			excludeHeader = make(map[string]bool)
  1315  		}
  1316  		excludeHeader[key] = true
  1317  	}
  1318  	var setHeader extraHeader
  1319  
  1320  	// Don't write out the fake "Trailer:foo" keys. See TrailerPrefix.
  1321  	trailers := false
  1322  	for k := range cw.header {
  1323  		if strings.HasPrefix(k, TrailerPrefix) {
  1324  			if excludeHeader == nil {
  1325  				excludeHeader = make(map[string]bool)
  1326  			}
  1327  			excludeHeader[k] = true
  1328  			trailers = true
  1329  		}
  1330  	}
  1331  	for _, v := range cw.header["Trailer"] {
  1332  		trailers = true
  1333  		foreachHeaderElement(v, cw.res.declareTrailer)
  1334  	}
  1335  
  1336  	te := header.get("Transfer-Encoding")
  1337  	hasTE := te != ""
  1338  
  1339  	// If the handler is done but never sent a Content-Length
  1340  	// response header and this is our first (and last) write, set
  1341  	// it, even to zero. This helps HTTP/1.0 clients keep their
  1342  	// "keep-alive" connections alive.
  1343  	// Exceptions: 304/204/1xx responses never get Content-Length, and if
  1344  	// it was a HEAD request, we don't know the difference between
  1345  	// 0 actual bytes and 0 bytes because the handler noticed it
  1346  	// was a HEAD request and chose not to write anything. So for
  1347  	// HEAD, the handler should either write the Content-Length or
  1348  	// write non-zero bytes. If it's actually 0 bytes and the
  1349  	// handler never looked at the Request.Method, we just don't
  1350  	// send a Content-Length header.
  1351  	// Further, we don't send an automatic Content-Length if they
  1352  	// set a Transfer-Encoding, because they're generally incompatible.
  1353  	if w.handlerDone.Load() && !trailers && !hasTE && bodyAllowedForStatus(w.status) && !header.has("Content-Length") && (!isHEAD || len(p) > 0) {
  1354  		w.contentLength = int64(len(p))
  1355  		setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10)
  1356  	}
  1357  
  1358  	// If this was an HTTP/1.0 request with keep-alive and we sent a
  1359  	// Content-Length back, we can make this a keep-alive response ...
  1360  	if w.wants10KeepAlive && keepAlivesEnabled {
  1361  		sentLength := header.get("Content-Length") != ""
  1362  		if sentLength && header.get("Connection") == "keep-alive" {
  1363  			w.closeAfterReply = false
  1364  		}
  1365  	}
  1366  
  1367  	// Check for an explicit (and valid) Content-Length header.
  1368  	hasCL := w.contentLength != -1
  1369  
  1370  	if w.wants10KeepAlive && (isHEAD || hasCL || !bodyAllowedForStatus(w.status)) {
  1371  		_, connectionHeaderSet := header["Connection"]
  1372  		if !connectionHeaderSet {
  1373  			setHeader.connection = "keep-alive"
  1374  		}
  1375  	} else if !w.req.ProtoAtLeast(1, 1) || w.wantsClose {
  1376  		w.closeAfterReply = true
  1377  	}
  1378  
  1379  	if header.get("Connection") == "close" || !keepAlivesEnabled {
  1380  		w.closeAfterReply = true
  1381  	}
  1382  
  1383  	// If the client wanted a 100-continue but we never sent it to
  1384  	// them (or, more strictly: we never finished reading their
  1385  	// request body), don't reuse this connection.
  1386  	//
  1387  	// This behavior was first added on the theory that we don't know
  1388  	// if the next bytes on the wire are going to be the remainder of
  1389  	// the request body or the subsequent request (see issue 11549),
  1390  	// but that's not correct: If we keep using the connection,
  1391  	// the client is required to send the request body whether we
  1392  	// asked for it or not.
  1393  	//
  1394  	// We probably do want to skip reusing the connection in most cases,
  1395  	// however. If the client is offering a large request body that we
  1396  	// don't intend to use, then it's better to close the connection
  1397  	// than to read the body. For now, assume that if we're sending
  1398  	// headers, the handler is done reading the body and we should
  1399  	// drop the connection if we haven't seen EOF.
  1400  	if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF.Load() {
  1401  		w.closeAfterReply = true
  1402  	}
  1403  
  1404  	// We do this by default because there are a number of clients that
  1405  	// send a full request before starting to read the response, and they
  1406  	// can deadlock if we start writing the response with unconsumed body
  1407  	// remaining. See Issue 15527 for some history.
  1408  	//
  1409  	// If full duplex mode has been enabled with ResponseController.EnableFullDuplex,
  1410  	// then leave the request body alone.
  1411  	//
  1412  	// We don't take this path when w.closeAfterReply is set.
  1413  	// We may not need to consume the request to get ready for the next one
  1414  	// (since we're closing the conn), but a client which sends a full request
  1415  	// before reading a response may deadlock in this case.
  1416  	// This behavior has been present since CL 5268043 (2011), however,
  1417  	// so it doesn't seem to be causing problems.
  1418  	if w.req.ContentLength != 0 && !w.closeAfterReply && !w.fullDuplex {
  1419  		var discard, tooBig bool
  1420  
  1421  		switch bdy := w.req.Body.(type) {
  1422  		case *expectContinueReader:
  1423  			// We only get here if we have already fully consumed the request body
  1424  			// (see above).
  1425  		case *body:
  1426  			bdy.mu.Lock()
  1427  			switch {
  1428  			case bdy.closed:
  1429  				if !bdy.sawEOF {
  1430  					// Body was closed in handler with non-EOF error.
  1431  					w.closeAfterReply = true
  1432  				}
  1433  			case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes:
  1434  				tooBig = true
  1435  			default:
  1436  				discard = true
  1437  			}
  1438  			bdy.mu.Unlock()
  1439  		default:
  1440  			discard = true
  1441  		}
  1442  
  1443  		if discard {
  1444  			_, err := io.CopyN(io.Discard, w.reqBody, maxPostHandlerReadBytes+1)
  1445  			switch err {
  1446  			case nil:
  1447  				// There must be even more data left over.
  1448  				tooBig = true
  1449  			case ErrBodyReadAfterClose:
  1450  				// Body was already consumed and closed.
  1451  			case io.EOF:
  1452  				// The remaining body was just consumed, close it.
  1453  				err = w.reqBody.Close()
  1454  				if err != nil {
  1455  					w.closeAfterReply = true
  1456  				}
  1457  			default:
  1458  				// Some other kind of error occurred, like a read timeout, or
  1459  				// corrupt chunked encoding. In any case, whatever remains
  1460  				// on the wire must not be parsed as another HTTP request.
  1461  				w.closeAfterReply = true
  1462  			}
  1463  		}
  1464  
  1465  		if tooBig {
  1466  			w.requestTooLarge()
  1467  			delHeader("Connection")
  1468  			setHeader.connection = "close"
  1469  		}
  1470  	}
  1471  
  1472  	code := w.status
  1473  	if bodyAllowedForStatus(code) {
  1474  		// If no content type, apply sniffing algorithm to body.
  1475  		_, haveType := header["Content-Type"]
  1476  
  1477  		// If the Content-Encoding was set and is non-blank,
  1478  		// we shouldn't sniff the body. See Issue 31753.
  1479  		ce := header.Get("Content-Encoding")
  1480  		hasCE := len(ce) > 0
  1481  		if !hasCE && !haveType && !hasTE && len(p) > 0 {
  1482  			setHeader.contentType = DetectContentType(p)
  1483  		}
  1484  	} else {
  1485  		for _, k := range suppressedHeaders(code) {
  1486  			delHeader(k)
  1487  		}
  1488  	}
  1489  
  1490  	if !header.has("Date") {
  1491  		setHeader.date = time.Now().UTC().AppendFormat(cw.res.dateBuf[:0], TimeFormat)
  1492  	}
  1493  
  1494  	if hasCL && hasTE && te != "identity" {
  1495  		// TODO: return an error if WriteHeader gets a return parameter
  1496  		// For now just ignore the Content-Length.
  1497  		w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d",
  1498  			te, w.contentLength)
  1499  		delHeader("Content-Length")
  1500  		hasCL = false
  1501  	}
  1502  
  1503  	if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) || code == StatusNoContent {
  1504  		// Response has no body.
  1505  		delHeader("Transfer-Encoding")
  1506  	} else if hasCL {
  1507  		// Content-Length has been provided, so no chunking is to be done.
  1508  		delHeader("Transfer-Encoding")
  1509  	} else if w.req.ProtoAtLeast(1, 1) {
  1510  		// HTTP/1.1 or greater: Transfer-Encoding has been set to identity, and no
  1511  		// content-length has been provided. The connection must be closed after the
  1512  		// reply is written, and no chunking is to be done. This is the setup
  1513  		// recommended in the Server-Sent Events candidate recommendation 11,
  1514  		// section 8.
  1515  		if hasTE && te == "identity" {
  1516  			cw.chunking = false
  1517  			w.closeAfterReply = true
  1518  			delHeader("Transfer-Encoding")
  1519  		} else {
  1520  			// HTTP/1.1 or greater: use chunked transfer encoding
  1521  			// to avoid closing the connection at EOF.
  1522  			cw.chunking = true
  1523  			setHeader.transferEncoding = "chunked"
  1524  			if hasTE && te == "chunked" {
  1525  				// We will send the chunked Transfer-Encoding header later.
  1526  				delHeader("Transfer-Encoding")
  1527  			}
  1528  		}
  1529  	} else {
  1530  		// HTTP version < 1.1: cannot do chunked transfer
  1531  		// encoding and we don't know the Content-Length so
  1532  		// signal EOF by closing connection.
  1533  		w.closeAfterReply = true
  1534  		delHeader("Transfer-Encoding") // in case already set
  1535  	}
  1536  
  1537  	// Cannot use Content-Length with non-identity Transfer-Encoding.
  1538  	if cw.chunking {
  1539  		delHeader("Content-Length")
  1540  	}
  1541  	if !w.req.ProtoAtLeast(1, 0) {
  1542  		return
  1543  	}
  1544  
  1545  	// Only override the Connection header if it is not a successful
  1546  	// protocol switch response and if KeepAlives are not enabled.
  1547  	// See https://golang.org/issue/36381.
  1548  	delConnectionHeader := w.closeAfterReply &&
  1549  		(!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) &&
  1550  		!isProtocolSwitchResponse(w.status, header)
  1551  	if delConnectionHeader {
  1552  		delHeader("Connection")
  1553  		if w.req.ProtoAtLeast(1, 1) {
  1554  			setHeader.connection = "close"
  1555  		}
  1556  	}
  1557  
  1558  	writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:])
  1559  	cw.header.WriteSubset(w.conn.bufw, excludeHeader)
  1560  	setHeader.Write(w.conn.bufw)
  1561  	w.conn.bufw.Write(crlf)
  1562  }
  1563  
  1564  // foreachHeaderElement splits v according to the "#rule" construction
  1565  // in RFC 7230 section 7 and calls fn for each non-empty element.
  1566  func foreachHeaderElement(v string, fn func(string)) {
  1567  	v = textproto.TrimString(v)
  1568  	if v == "" {
  1569  		return
  1570  	}
  1571  	if !strings.Contains(v, ",") {
  1572  		fn(v)
  1573  		return
  1574  	}
  1575  	for f := range strings.SplitSeq(v, ",") {
  1576  		if f = textproto.TrimString(f); f != "" {
  1577  			fn(f)
  1578  		}
  1579  	}
  1580  }
  1581  
  1582  // writeStatusLine writes an HTTP/1.x Status-Line (RFC 7230 Section 3.1.2)
  1583  // to bw. is11 is whether the HTTP request is HTTP/1.1. false means HTTP/1.0.
  1584  // code is the response status code.
  1585  // scratch is an optional scratch buffer. If it has at least capacity 3, it's used.
  1586  func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) {
  1587  	if is11 {
  1588  		bw.WriteString("HTTP/1.1 ")
  1589  	} else {
  1590  		bw.WriteString("HTTP/1.0 ")
  1591  	}
  1592  	if text := StatusText(code); text != "" {
  1593  		bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10))
  1594  		bw.WriteByte(' ')
  1595  		bw.WriteString(text)
  1596  		bw.WriteString("\r\n")
  1597  	} else {
  1598  		// don't worry about performance
  1599  		fmt.Fprintf(bw, "%03d status code %d\r\n", code, code)
  1600  	}
  1601  }
  1602  
  1603  // bodyAllowed reports whether a Write is allowed for this response type.
  1604  // It's illegal to call this before the header has been flushed.
  1605  func (w *response) bodyAllowed() bool {
  1606  	if !w.wroteHeader {
  1607  		panic("net/http: bodyAllowed called before the header was written")
  1608  	}
  1609  	return bodyAllowedForStatus(w.status)
  1610  }
  1611  
  1612  // The Life Of A Write is like this:
  1613  //
  1614  // Handler starts. No header has been sent. The handler can either
  1615  // write a header, or just start writing. Writing before sending a header
  1616  // sends an implicitly empty 200 OK header.
  1617  //
  1618  // If the handler didn't declare a Content-Length up front, we either
  1619  // go into chunking mode or, if the handler finishes running before
  1620  // the chunking buffer size, we compute a Content-Length and send that
  1621  // in the header instead.
  1622  //
  1623  // Likewise, if the handler didn't set a Content-Type, we sniff that
  1624  // from the initial chunk of output.
  1625  //
  1626  // The Writers are wired together like:
  1627  //
  1628  //  1. *response (the ResponseWriter) ->
  1629  //  2. (*response).w, a [*bufio.Writer] of bufferBeforeChunkingSize bytes ->
  1630  //  3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type)
  1631  //     and which writes the chunk headers, if needed ->
  1632  //  4. conn.bufw, a *bufio.Writer of default (4kB) bytes, writing to ->
  1633  //  5. checkConnErrorWriter{c}, which notes any non-nil error on Write
  1634  //     and populates c.werr with it if so, but otherwise writes to ->
  1635  //  6. the rwc, the [net.Conn].
  1636  //
  1637  // TODO(bradfitz): short-circuit some of the buffering when the
  1638  // initial header contains both a Content-Type and Content-Length.
  1639  // Also short-circuit in (1) when the header's been sent and not in
  1640  // chunking mode, writing directly to (4) instead, if (2) has no
  1641  // buffered data. More generally, we could short-circuit from (1) to
  1642  // (3) even in chunking mode if the write size from (1) is over some
  1643  // threshold and nothing is in (2).  The answer might be mostly making
  1644  // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal
  1645  // with this instead.
  1646  func (w *response) Write(data []byte) (n int, err error) {
  1647  	return w.write(len(data), data, "")
  1648  }
  1649  
  1650  func (w *response) WriteString(data string) (n int, err error) {
  1651  	return w.write(len(data), nil, data)
  1652  }
  1653  
  1654  // either dataB or dataS is non-zero.
  1655  func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1656  	if w.conn.hijacked() {
  1657  		if lenData > 0 {
  1658  			caller := relevantCaller()
  1659  			w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
  1660  		}
  1661  		return 0, ErrHijacked
  1662  	}
  1663  
  1664  	if w.canWriteContinue.Load() {
  1665  		// Body reader wants to write 100 Continue but hasn't yet. Tell it not to.
  1666  		w.disableWriteContinue()
  1667  	}
  1668  
  1669  	if !w.wroteHeader {
  1670  		w.WriteHeader(StatusOK)
  1671  	}
  1672  	if lenData == 0 {
  1673  		return 0, nil
  1674  	}
  1675  	if !w.bodyAllowed() {
  1676  		return 0, ErrBodyNotAllowed
  1677  	}
  1678  
  1679  	w.written += int64(lenData) // ignoring errors, for errorKludge
  1680  	if w.contentLength != -1 && w.written > w.contentLength {
  1681  		return 0, ErrContentLength
  1682  	}
  1683  	if dataB != nil {
  1684  		return w.w.Write(dataB)
  1685  	} else {
  1686  		return w.w.WriteString(dataS)
  1687  	}
  1688  }
  1689  
  1690  func (w *response) finishRequest() {
  1691  	w.handlerDone.Store(true)
  1692  
  1693  	if !w.wroteHeader {
  1694  		w.WriteHeader(StatusOK)
  1695  	}
  1696  
  1697  	w.w.Flush()
  1698  	putBufioWriter(w.w)
  1699  	w.cw.close()
  1700  	w.conn.bufw.Flush()
  1701  
  1702  	w.conn.r.abortPendingRead()
  1703  
  1704  	// Close the body (regardless of w.closeAfterReply) so we can
  1705  	// re-use its bufio.Reader later safely.
  1706  	w.reqBody.Close()
  1707  
  1708  	if w.req.MultipartForm != nil {
  1709  		w.req.MultipartForm.RemoveAll()
  1710  	}
  1711  }
  1712  
  1713  // shouldReuseConnection reports whether the underlying TCP connection can be reused.
  1714  // It must only be called after the handler is done executing.
  1715  func (w *response) shouldReuseConnection() bool {
  1716  	if w.closeAfterReply {
  1717  		// The request or something set while executing the
  1718  		// handler indicated we shouldn't reuse this
  1719  		// connection.
  1720  		return false
  1721  	}
  1722  
  1723  	if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written {
  1724  		// Did not write enough. Avoid getting out of sync.
  1725  		return false
  1726  	}
  1727  
  1728  	// There was some error writing to the underlying connection
  1729  	// during the request, so don't re-use this conn.
  1730  	if w.conn.werr != nil {
  1731  		return false
  1732  	}
  1733  
  1734  	if w.closedRequestBodyEarly() {
  1735  		return false
  1736  	}
  1737  
  1738  	return true
  1739  }
  1740  
  1741  func (w *response) closedRequestBodyEarly() bool {
  1742  	body, ok := w.req.Body.(*body)
  1743  	return ok && body.didEarlyClose()
  1744  }
  1745  
  1746  func (w *response) Flush() {
  1747  	w.FlushError()
  1748  }
  1749  
  1750  func (w *response) FlushError() error {
  1751  	if !w.wroteHeader {
  1752  		w.WriteHeader(StatusOK)
  1753  	}
  1754  	err := w.w.Flush()
  1755  	e2 := w.cw.flush()
  1756  	if err == nil {
  1757  		err = e2
  1758  	}
  1759  	return err
  1760  }
  1761  
  1762  func (c *conn) finalFlush() {
  1763  	if c.bufr != nil {
  1764  		// Steal the bufio.Reader (~4KB worth of memory) and its associated
  1765  		// reader for a future connection.
  1766  		putBufioReader(c.bufr)
  1767  		c.bufr = nil
  1768  	}
  1769  
  1770  	if c.bufw != nil {
  1771  		c.bufw.Flush()
  1772  		// Steal the bufio.Writer (~4KB worth of memory) and its associated
  1773  		// writer for a future connection.
  1774  		putBufioWriter(c.bufw)
  1775  		c.bufw = nil
  1776  	}
  1777  }
  1778  
  1779  // Close the connection.
  1780  func (c *conn) close() {
  1781  	c.finalFlush()
  1782  	c.rwc.Close()
  1783  }
  1784  
  1785  // rstAvoidanceDelay is the amount of time we sleep after closing the
  1786  // write side of a TCP connection before closing the entire socket.
  1787  // By sleeping, we increase the chances that the client sees our FIN
  1788  // and processes its final data before they process the subsequent RST
  1789  // from closing a connection with known unread data.
  1790  // This RST seems to occur mostly on BSD systems. (And Windows?)
  1791  // This timeout is somewhat arbitrary (~latency around the planet),
  1792  // and may be modified by tests.
  1793  //
  1794  // TODO(bcmills): This should arguably be a server configuration parameter,
  1795  // not a hard-coded value.
  1796  var rstAvoidanceDelay = 500 * time.Millisecond
  1797  
  1798  type closeWriter interface {
  1799  	CloseWrite() error
  1800  }
  1801  
  1802  var _ closeWriter = (*net.TCPConn)(nil)
  1803  
  1804  // closeWriteAndWait flushes any outstanding data and sends a FIN packet (if
  1805  // client is connected via TCP), signaling that we're done. We then
  1806  // pause for a bit, hoping the client processes it before any
  1807  // subsequent RST.
  1808  //
  1809  // See https://golang.org/issue/3595
  1810  func (c *conn) closeWriteAndWait() {
  1811  	c.finalFlush()
  1812  	if tcp, ok := c.rwc.(closeWriter); ok {
  1813  		tcp.CloseWrite()
  1814  	}
  1815  
  1816  	// When we return from closeWriteAndWait, the caller will fully close the
  1817  	// connection. If client is still writing to the connection, this will cause
  1818  	// the write to fail with ECONNRESET or similar. Unfortunately, many TCP
  1819  	// implementations will also drop unread packets from the client's read buffer
  1820  	// when a write fails, causing our final response to be truncated away too.
  1821  	//
  1822  	// As a result, https://www.rfc-editor.org/rfc/rfc7230#section-6.6 recommends
  1823  	// that “[t]he server … continues to read from the connection until it
  1824  	// receives a corresponding close by the client, or until the server is
  1825  	// reasonably certain that its own TCP stack has received the client's
  1826  	// acknowledgement of the packet(s) containing the server's last response.”
  1827  	//
  1828  	// Unfortunately, we have no straightforward way to be “reasonably certain”
  1829  	// that we have received the client's ACK, and at any rate we don't want to
  1830  	// allow a misbehaving client to soak up server connections indefinitely by
  1831  	// withholding an ACK, nor do we want to go through the complexity or overhead
  1832  	// of using low-level APIs to figure out when a TCP round-trip has completed.
  1833  	//
  1834  	// Instead, we declare that we are “reasonably certain” that we received the
  1835  	// ACK if maxRSTAvoidanceDelay has elapsed.
  1836  	time.Sleep(rstAvoidanceDelay)
  1837  }
  1838  
  1839  // validNextProto reports whether the proto is a valid ALPN protocol name.
  1840  // Everything is valid except the empty string and built-in protocol types,
  1841  // so that those can't be overridden with alternate implementations.
  1842  func validNextProto(proto string) bool {
  1843  	switch proto {
  1844  	case "", "http/1.1", "http/1.0":
  1845  		return false
  1846  	}
  1847  	return true
  1848  }
  1849  
  1850  const (
  1851  	runHooks  = true
  1852  	skipHooks = false
  1853  )
  1854  
  1855  func (c *conn) setState(nc net.Conn, state ConnState, runHook bool) {
  1856  	srv := c.server
  1857  	switch state {
  1858  	case StateNew:
  1859  		srv.trackConn(c, true)
  1860  	case StateHijacked, StateClosed:
  1861  		srv.trackConn(c, false)
  1862  	}
  1863  	if state > 0xff || state < 0 {
  1864  		panic("internal error")
  1865  	}
  1866  	packedState := uint64(time.Now().Unix()<<8) | uint64(state)
  1867  	c.curState.Store(packedState)
  1868  	if !runHook {
  1869  		return
  1870  	}
  1871  	if hook := srv.ConnState; hook != nil {
  1872  		hook(nc, state)
  1873  	}
  1874  }
  1875  
  1876  func (c *conn) getState() (state ConnState, unixSec int64) {
  1877  	packedState := c.curState.Load()
  1878  	return ConnState(packedState & 0xff), int64(packedState >> 8)
  1879  }
  1880  
  1881  // badRequestError is a literal string (used by in the server in HTML,
  1882  // unescaped) to tell the user why their request was bad. It should
  1883  // be plain text without user info or other embedded errors.
  1884  func badRequestError(e string) error { return statusError{StatusBadRequest, e} }
  1885  
  1886  // statusError is an error used to respond to a request with an HTTP status.
  1887  // The text should be plain text without user info or other embedded errors.
  1888  type statusError struct {
  1889  	code int
  1890  	text string
  1891  }
  1892  
  1893  func (e statusError) Error() string { return StatusText(e.code) + ": " + e.text }
  1894  
  1895  // ErrAbortHandler is a sentinel panic value to abort a handler.
  1896  // While any panic from ServeHTTP aborts the response to the client,
  1897  // panicking with ErrAbortHandler also suppresses logging of a stack
  1898  // trace to the server's error log.
  1899  var ErrAbortHandler = internal.ErrAbortHandler
  1900  
  1901  // isCommonNetReadError reports whether err is a common error
  1902  // encountered during reading a request off the network when the
  1903  // client has gone away or had its read fail somehow. This is used to
  1904  // determine which logs are interesting enough to log about.
  1905  func isCommonNetReadError(err error) bool {
  1906  	if err == io.EOF {
  1907  		return true
  1908  	}
  1909  	if neterr, ok := err.(net.Error); ok && neterr.Timeout() {
  1910  		return true
  1911  	}
  1912  	if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
  1913  		return true
  1914  	}
  1915  	return false
  1916  }
  1917  
  1918  type connectionStater interface {
  1919  	ConnectionState() tls.ConnectionState
  1920  }
  1921  
  1922  // Serve a new connection.
  1923  func (c *conn) serve(ctx context.Context) {
  1924  	if ra := c.rwc.RemoteAddr(); ra != nil {
  1925  		c.remoteAddr = ra.String()
  1926  	}
  1927  	ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr())
  1928  	var inFlightResponse *response
  1929  	defer func() {
  1930  		if err := recover(); err != nil && err != ErrAbortHandler {
  1931  			const size = 64 << 10
  1932  			buf := make([]byte, size)
  1933  			buf = buf[:runtime.Stack(buf, false)]
  1934  			c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf)
  1935  		}
  1936  		if inFlightResponse != nil {
  1937  			inFlightResponse.cancelCtx()
  1938  			inFlightResponse.disableWriteContinue()
  1939  		}
  1940  		if !c.hijacked() {
  1941  			if inFlightResponse != nil {
  1942  				inFlightResponse.conn.r.abortPendingRead()
  1943  				inFlightResponse.reqBody.Close()
  1944  			}
  1945  			c.close()
  1946  			c.setState(c.rwc, StateClosed, runHooks)
  1947  		}
  1948  	}()
  1949  
  1950  	if tlsConn, ok := c.rwc.(*tls.Conn); ok {
  1951  		tlsTO := c.server.tlsHandshakeTimeout()
  1952  		if tlsTO > 0 {
  1953  			dl := time.Now().Add(tlsTO)
  1954  			c.rwc.SetReadDeadline(dl)
  1955  			c.rwc.SetWriteDeadline(dl)
  1956  		}
  1957  		if err := tlsConn.HandshakeContext(ctx); err != nil {
  1958  			// If the handshake failed due to the client not speaking
  1959  			// TLS, assume they're speaking plaintext HTTP and write a
  1960  			// 400 response on the TLS conn's underlying net.Conn.
  1961  			var reason string
  1962  			if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
  1963  				io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
  1964  				re.Conn.Close()
  1965  				reason = "client sent an HTTP request to an HTTPS server"
  1966  			} else {
  1967  				reason = err.Error()
  1968  			}
  1969  			c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), reason)
  1970  			return
  1971  		}
  1972  		// Restore Conn-level deadlines.
  1973  		if tlsTO > 0 {
  1974  			c.rwc.SetReadDeadline(time.Time{})
  1975  			c.rwc.SetWriteDeadline(time.Time{})
  1976  		}
  1977  		c.tlsState = new(tls.ConnectionState)
  1978  		*c.tlsState = tlsConn.ConnectionState()
  1979  		if proto := c.tlsState.NegotiatedProtocol; validNextProto(proto) {
  1980  			if fn := c.server.TLSNextProto[proto]; fn != nil {
  1981  				h := initALPNRequest{ctx, tlsConn, serverHandler{c.server}}
  1982  				// Mark freshly created HTTP/2 as active and prevent any server state hooks
  1983  				// from being run on these connections. This prevents closeIdleConns from
  1984  				// closing such connections. See issue https://golang.org/issue/39776.
  1985  				c.setState(c.rwc, StateActive, skipHooks)
  1986  				fn(c.server, tlsConn, h)
  1987  			}
  1988  			return
  1989  		}
  1990  	}
  1991  
  1992  	// HTTP/1.x from here on.
  1993  
  1994  	// Set Request.TLS if the conn is not a *tls.Conn, but implements ConnectionState.
  1995  	if c.tlsState == nil {
  1996  		if tc, ok := c.rwc.(connectionStater); ok {
  1997  			c.tlsState = new(tls.ConnectionState)
  1998  			*c.tlsState = tc.ConnectionState()
  1999  		}
  2000  	}
  2001  
  2002  	ctx, cancelCtx := context.WithCancel(ctx)
  2003  	c.cancelCtx = cancelCtx
  2004  	defer cancelCtx()
  2005  
  2006  	c.r = &connReader{conn: c, rwc: c.rwc}
  2007  	c.bufr = newBufioReader(c.r)
  2008  	c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
  2009  
  2010  	protos := c.server.protocols()
  2011  	if c.tlsState == nil && protos.UnencryptedHTTP2() {
  2012  		if c.maybeServeUnencryptedHTTP2(ctx) {
  2013  			return
  2014  		}
  2015  	}
  2016  	if !protos.HTTP1() {
  2017  		return
  2018  	}
  2019  
  2020  	for {
  2021  		w, err := c.readRequest(ctx)
  2022  		if c.r.remain != c.server.initialReadLimitSize() {
  2023  			// If we read any bytes off the wire, we're active.
  2024  			c.setState(c.rwc, StateActive, runHooks)
  2025  		}
  2026  		if c.server.shuttingDown() {
  2027  			return
  2028  		}
  2029  		if err != nil {
  2030  			const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
  2031  
  2032  			switch {
  2033  			case err == errTooLarge:
  2034  				// Their HTTP client may or may not be
  2035  				// able to read this if we're
  2036  				// responding to them and hanging up
  2037  				// while they're still writing their
  2038  				// request. Undefined behavior.
  2039  				const publicErr = "431 Request Header Fields Too Large"
  2040  				fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
  2041  				c.closeWriteAndWait()
  2042  				return
  2043  
  2044  			case isUnsupportedTEError(err):
  2045  				// Respond as per RFC 7230 Section 3.3.1 which says,
  2046  				//      A server that receives a request message with a
  2047  				//      transfer coding it does not understand SHOULD
  2048  				//      respond with 501 (Unimplemented).
  2049  				code := StatusNotImplemented
  2050  
  2051  				// We purposefully aren't echoing back the transfer-encoding's value,
  2052  				// so as to mitigate the risk of cross side scripting by an attacker.
  2053  				fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders)
  2054  				return
  2055  
  2056  			case isCommonNetReadError(err):
  2057  				return // don't reply
  2058  
  2059  			default:
  2060  				if v, ok := err.(statusError); ok {
  2061  					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)
  2062  					return
  2063  				}
  2064  				const publicErr = "400 Bad Request"
  2065  				fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
  2066  				return
  2067  			}
  2068  		}
  2069  
  2070  		// Expect 100 Continue support
  2071  		req := w.req
  2072  		if req.expectsContinue() {
  2073  			if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
  2074  				// Wrap the Body reader with one that replies on the connection
  2075  				req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
  2076  				w.canWriteContinue.Store(true)
  2077  			}
  2078  		} else if req.Header.get("Expect") != "" {
  2079  			w.sendExpectationFailed()
  2080  			return
  2081  		}
  2082  
  2083  		c.curReq.Store(w)
  2084  
  2085  		if requestBodyRemains(req.Body) {
  2086  			registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
  2087  		} else {
  2088  			w.conn.r.startBackgroundRead()
  2089  		}
  2090  
  2091  		// HTTP cannot have multiple simultaneous active requests.[*]
  2092  		// Until the server replies to this request, it can't read another,
  2093  		// so we might as well run the handler in this goroutine.
  2094  		// [*] Not strictly true: HTTP pipelining. We could let them all process
  2095  		// in parallel even if their responses need to be serialized.
  2096  		// But we're not going to implement HTTP pipelining because it
  2097  		// was never deployed in the wild and the answer is HTTP/2.
  2098  		inFlightResponse = w
  2099  		serverHandler{c.server}.ServeHTTP(w, w.req)
  2100  		inFlightResponse = nil
  2101  		w.cancelCtx()
  2102  		if c.hijacked() {
  2103  			c.r.releaseConn()
  2104  			return
  2105  		}
  2106  		w.finishRequest()
  2107  		c.rwc.SetWriteDeadline(time.Time{})
  2108  		if !w.shouldReuseConnection() {
  2109  			if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
  2110  				c.closeWriteAndWait()
  2111  			}
  2112  			return
  2113  		}
  2114  		c.setState(c.rwc, StateIdle, runHooks)
  2115  		c.curReq.Store(nil)
  2116  
  2117  		if !w.conn.server.doKeepAlives() {
  2118  			// We're in shutdown mode. We might've replied
  2119  			// to the user without "Connection: close" and
  2120  			// they might think they can send another
  2121  			// request, but such is life with HTTP/1.1.
  2122  			return
  2123  		}
  2124  
  2125  		if d := c.server.idleTimeout(); d > 0 {
  2126  			c.rwc.SetReadDeadline(time.Now().Add(d))
  2127  		} else {
  2128  			c.rwc.SetReadDeadline(time.Time{})
  2129  		}
  2130  
  2131  		// Wait for the connection to become readable again before trying to
  2132  		// read the next request. This prevents a ReadHeaderTimeout or
  2133  		// ReadTimeout from starting until the first bytes of the next request
  2134  		// have been received.
  2135  		if _, err := c.bufr.Peek(4); err != nil {
  2136  			return
  2137  		}
  2138  
  2139  		c.rwc.SetReadDeadline(time.Time{})
  2140  	}
  2141  }
  2142  
  2143  // unencryptedHTTP2Request is an HTTP handler that initializes
  2144  // certain uninitialized fields in its *Request.
  2145  //
  2146  // It's the unencrypted version of initALPNRequest.
  2147  type unencryptedHTTP2Request struct {
  2148  	ctx context.Context
  2149  	c   net.Conn
  2150  	h   serverHandler
  2151  }
  2152  
  2153  func (h unencryptedHTTP2Request) BaseContext() context.Context { return h.ctx }
  2154  
  2155  func (h unencryptedHTTP2Request) ServeHTTP(rw ResponseWriter, req *Request) {
  2156  	if req.Body == nil {
  2157  		req.Body = NoBody
  2158  	}
  2159  	if req.RemoteAddr == "" {
  2160  		req.RemoteAddr = h.c.RemoteAddr().String()
  2161  	}
  2162  	h.h.ServeHTTP(rw, req)
  2163  }
  2164  
  2165  // unencryptedNetConnInTLSConn is used to pass an unencrypted net.Conn to
  2166  // functions that only accept a *tls.Conn.
  2167  type unencryptedNetConnInTLSConn struct {
  2168  	net.Conn // panic on all net.Conn methods
  2169  	conn     net.Conn
  2170  }
  2171  
  2172  func (c unencryptedNetConnInTLSConn) UnencryptedNetConn() net.Conn {
  2173  	return c.conn
  2174  }
  2175  
  2176  func unencryptedTLSConn(c net.Conn) *tls.Conn {
  2177  	return tls.Client(unencryptedNetConnInTLSConn{conn: c}, nil)
  2178  }
  2179  
  2180  // TLSNextProto key to use for unencrypted HTTP/2 connections.
  2181  // Not actually a TLS-negotiated protocol.
  2182  const nextProtoUnencryptedHTTP2 = "unencrypted_http2"
  2183  
  2184  func (c *conn) maybeServeUnencryptedHTTP2(ctx context.Context) bool {
  2185  	fn, ok := c.server.TLSNextProto[nextProtoUnencryptedHTTP2]
  2186  	if !ok {
  2187  		return false
  2188  	}
  2189  	hasPreface := func(c *conn, preface []byte) bool {
  2190  		c.r.setReadLimit(int64(len(preface)) - int64(c.bufr.Buffered()))
  2191  		got, err := c.bufr.Peek(len(preface))
  2192  		c.r.setInfiniteReadLimit()
  2193  		return err == nil && bytes.Equal(got, preface)
  2194  	}
  2195  	if !hasPreface(c, []byte("PRI * HTTP/2.0")) {
  2196  		return false
  2197  	}
  2198  	if !hasPreface(c, []byte("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")) {
  2199  		return false
  2200  	}
  2201  	c.setState(c.rwc, StateActive, skipHooks)
  2202  	h := unencryptedHTTP2Request{ctx, c.rwc, serverHandler{c.server}}
  2203  	fn(c.server, unencryptedTLSConn(c.rwc), h)
  2204  	return true
  2205  }
  2206  
  2207  func (w *response) sendExpectationFailed() {
  2208  	// TODO(bradfitz): let ServeHTTP handlers handle
  2209  	// requests with non-standard expectation[s]? Seems
  2210  	// theoretical at best, and doesn't fit into the
  2211  	// current ServeHTTP model anyway. We'd need to
  2212  	// make the ResponseWriter an optional
  2213  	// "ExpectReplier" interface or something.
  2214  	//
  2215  	// For now we'll just obey RFC 7231 5.1.1 which says
  2216  	// "A server that receives an Expect field-value other
  2217  	// than 100-continue MAY respond with a 417 (Expectation
  2218  	// Failed) status code to indicate that the unexpected
  2219  	// expectation cannot be met."
  2220  	w.Header().Set("Connection", "close")
  2221  	w.WriteHeader(StatusExpectationFailed)
  2222  	w.finishRequest()
  2223  }
  2224  
  2225  // Hijack implements the [Hijacker.Hijack] method. Our response is both a [ResponseWriter]
  2226  // and a [Hijacker].
  2227  func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
  2228  	if w.handlerDone.Load() {
  2229  		panic("net/http: Hijack called after ServeHTTP finished")
  2230  	}
  2231  	w.disableWriteContinue()
  2232  	if w.wroteHeader {
  2233  		w.cw.flush()
  2234  	}
  2235  
  2236  	c := w.conn
  2237  	c.mu.Lock()
  2238  	defer c.mu.Unlock()
  2239  
  2240  	// Release the bufioWriter that writes to the chunk writer, it is not
  2241  	// used after a connection has been hijacked.
  2242  	rwc, buf, err = c.hijackLocked()
  2243  	if err == nil {
  2244  		putBufioWriter(w.w)
  2245  		w.w = nil
  2246  	}
  2247  	return rwc, buf, err
  2248  }
  2249  
  2250  func (w *response) CloseNotify() <-chan bool {
  2251  	w.lazyCloseNotifyMu.Lock()
  2252  	defer w.lazyCloseNotifyMu.Unlock()
  2253  	if w.handlerDone.Load() {
  2254  		panic("net/http: CloseNotify called after ServeHTTP finished")
  2255  	}
  2256  	if w.closeNotifyCh == nil {
  2257  		w.closeNotifyCh = make(chan bool, 1)
  2258  		if w.closeNotifyTriggered {
  2259  			w.closeNotifyCh <- true // action prior closeNotify call
  2260  		}
  2261  	}
  2262  	return w.closeNotifyCh
  2263  }
  2264  
  2265  func (w *response) closeNotify() {
  2266  	w.lazyCloseNotifyMu.Lock()
  2267  	defer w.lazyCloseNotifyMu.Unlock()
  2268  	if w.closeNotifyTriggered {
  2269  		return // already triggered
  2270  	}
  2271  	w.closeNotifyTriggered = true
  2272  	if w.closeNotifyCh != nil {
  2273  		w.closeNotifyCh <- true
  2274  	}
  2275  }
  2276  
  2277  func registerOnHitEOF(rc io.ReadCloser, fn func()) {
  2278  	switch v := rc.(type) {
  2279  	case *expectContinueReader:
  2280  		registerOnHitEOF(v.readCloser, fn)
  2281  	case *body:
  2282  		v.registerOnHitEOF(fn)
  2283  	default:
  2284  		panic("unexpected type " + fmt.Sprintf("%T", rc))
  2285  	}
  2286  }
  2287  
  2288  // requestBodyRemains reports whether future calls to Read
  2289  // on rc might yield more data.
  2290  func requestBodyRemains(rc io.ReadCloser) bool {
  2291  	if rc == NoBody {
  2292  		return false
  2293  	}
  2294  	switch v := rc.(type) {
  2295  	case *expectContinueReader:
  2296  		return requestBodyRemains(v.readCloser)
  2297  	case *body:
  2298  		return v.bodyRemains()
  2299  	default:
  2300  		panic("unexpected type " + fmt.Sprintf("%T", rc))
  2301  	}
  2302  }
  2303  
  2304  // The HandlerFunc type is an adapter to allow the use of
  2305  // ordinary functions as HTTP handlers. If f is a function
  2306  // with the appropriate signature, HandlerFunc(f) is a
  2307  // [Handler] that calls f.
  2308  type HandlerFunc func(ResponseWriter, *Request)
  2309  
  2310  // ServeHTTP calls f(w, r).
  2311  func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
  2312  	f(w, r)
  2313  }
  2314  
  2315  // Helper handlers
  2316  
  2317  // Error replies to the request with the specified error message and HTTP code.
  2318  // It does not otherwise end the request; the caller should ensure no further
  2319  // writes are done to w.
  2320  // The error message should be plain text.
  2321  //
  2322  // Error deletes the Content-Length header,
  2323  // sets Content-Type to “text/plain; charset=utf-8”,
  2324  // and sets X-Content-Type-Options to “nosniff”.
  2325  // This configures the header properly for the error message,
  2326  // in case the caller had set it up expecting a successful output.
  2327  func Error(w ResponseWriter, error string, code int) {
  2328  	h := w.Header()
  2329  
  2330  	// Delete the Content-Length header, which might be for some other content.
  2331  	// Assuming the error string fits in the writer's buffer, we'll figure
  2332  	// out the correct Content-Length for it later.
  2333  	//
  2334  	// We don't delete Content-Encoding, because some middleware sets
  2335  	// Content-Encoding: gzip and wraps the ResponseWriter to compress on-the-fly.
  2336  	// See https://go.dev/issue/66343.
  2337  	h.Del("Content-Length")
  2338  
  2339  	// There might be content type already set, but we reset it to
  2340  	// text/plain for the error message.
  2341  	h.Set("Content-Type", "text/plain; charset=utf-8")
  2342  	h.Set("X-Content-Type-Options", "nosniff")
  2343  	w.WriteHeader(code)
  2344  	fmt.Fprintln(w, error)
  2345  }
  2346  
  2347  // NotFound replies to the request with an HTTP 404 not found error.
  2348  func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
  2349  
  2350  // NotFoundHandler returns a simple request handler
  2351  // that replies to each request with a “404 page not found” reply.
  2352  func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
  2353  
  2354  // StripPrefix returns a handler that serves HTTP requests by removing the
  2355  // given prefix from the request URL's Path (and RawPath if set) and invoking
  2356  // the handler h. StripPrefix handles a request for a path that doesn't begin
  2357  // with prefix by replying with an HTTP 404 not found error. The prefix must
  2358  // match exactly: if the prefix in the request contains escaped characters
  2359  // the reply is also an HTTP 404 not found error.
  2360  func StripPrefix(prefix string, h Handler) Handler {
  2361  	if prefix == "" {
  2362  		return h
  2363  	}
  2364  	return HandlerFunc(func(w ResponseWriter, r *Request) {
  2365  		p := strings.TrimPrefix(r.URL.Path, prefix)
  2366  		rp := strings.TrimPrefix(r.URL.RawPath, prefix)
  2367  		if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
  2368  			r2 := new(Request)
  2369  			*r2 = *r
  2370  			r2.URL = new(url.URL)
  2371  			*r2.URL = *r.URL
  2372  			r2.URL.Path = p
  2373  			r2.URL.RawPath = rp
  2374  			h.ServeHTTP(w, r2)
  2375  		} else {
  2376  			NotFound(w, r)
  2377  		}
  2378  	})
  2379  }
  2380  
  2381  // Redirect replies to the request with a redirect to url,
  2382  // which may be a path relative to the request path.
  2383  // Any non-ASCII characters in url will be percent-encoded,
  2384  // but existing percent encodings will not be changed.
  2385  //
  2386  // The provided code should be in the 3xx range and is usually
  2387  // [StatusMovedPermanently], [StatusFound] or [StatusSeeOther].
  2388  //
  2389  // If the Content-Type header has not been set, [Redirect] sets it
  2390  // to "text/html; charset=utf-8" and writes a small HTML body.
  2391  // Setting the Content-Type header to any value, including nil,
  2392  // disables that behavior.
  2393  func Redirect(w ResponseWriter, r *Request, url string, code int) {
  2394  	if u, err := urlpkg.Parse(url); err == nil {
  2395  		// If url was relative, make its path absolute by
  2396  		// combining with request path.
  2397  		// The client would probably do this for us,
  2398  		// but doing it ourselves is more reliable.
  2399  		// See RFC 7231, section 7.1.2
  2400  		if u.Scheme == "" && u.Host == "" {
  2401  			oldpath := r.URL.EscapedPath()
  2402  			if oldpath == "" { // should not happen, but avoid a crash if it does
  2403  				oldpath = "/"
  2404  			}
  2405  
  2406  			// no leading http://server
  2407  			if url == "" || url[0] != '/' {
  2408  				// make relative path absolute
  2409  				olddir, _ := path.Split(oldpath)
  2410  				url = olddir + url
  2411  			}
  2412  
  2413  			var query string
  2414  			if i := strings.Index(url, "?"); i != -1 {
  2415  				url, query = url[:i], url[i:]
  2416  			}
  2417  
  2418  			// clean up but preserve trailing slash
  2419  			trailing := strings.HasSuffix(url, "/")
  2420  			url = path.Clean(url)
  2421  			if trailing && !strings.HasSuffix(url, "/") {
  2422  				url += "/"
  2423  			}
  2424  			url += query
  2425  		}
  2426  	}
  2427  
  2428  	h := w.Header()
  2429  
  2430  	// RFC 7231 notes that a short HTML body is usually included in
  2431  	// the response because older user agents may not understand 301/307.
  2432  	// Do it only if the request didn't already have a Content-Type header.
  2433  	_, hadCT := h["Content-Type"]
  2434  
  2435  	h.Set("Location", hexEscapeNonASCII(url))
  2436  	if !hadCT && (r.Method == "GET" || r.Method == "HEAD") {
  2437  		h.Set("Content-Type", "text/html; charset=utf-8")
  2438  	}
  2439  	w.WriteHeader(code)
  2440  
  2441  	// Shouldn't send the body for POST or HEAD; that leaves GET.
  2442  	if !hadCT && r.Method == "GET" {
  2443  		body := "<a href=\"" + htmlEscape(url) + "\">" + StatusText(code) + "</a>.\n"
  2444  		fmt.Fprintln(w, body)
  2445  	}
  2446  }
  2447  
  2448  var htmlReplacer = strings.NewReplacer(
  2449  	"&", "&amp;",
  2450  	"<", "&lt;",
  2451  	">", "&gt;",
  2452  	// "&#34;" is shorter than "&quot;".
  2453  	`"`, "&#34;",
  2454  	// "&#39;" is shorter than "&apos;" and apos was not in HTML until HTML5.
  2455  	"'", "&#39;",
  2456  )
  2457  
  2458  func htmlEscape(s string) string {
  2459  	return htmlReplacer.Replace(s)
  2460  }
  2461  
  2462  // Redirect to a fixed URL
  2463  type redirectHandler struct {
  2464  	url  string
  2465  	code int
  2466  }
  2467  
  2468  func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
  2469  	Redirect(w, r, rh.url, rh.code)
  2470  }
  2471  
  2472  // RedirectHandler returns a request handler that redirects
  2473  // each request it receives to the given url using the given
  2474  // status code.
  2475  //
  2476  // The provided code should be in the 3xx range and is usually
  2477  // [StatusMovedPermanently], [StatusFound] or [StatusSeeOther].
  2478  func RedirectHandler(url string, code int) Handler {
  2479  	return &redirectHandler{url, code}
  2480  }
  2481  
  2482  // ServeMux is an HTTP request multiplexer.
  2483  // It matches the URL of each incoming request against a list of registered
  2484  // patterns and calls the handler for the pattern that
  2485  // most closely matches the URL.
  2486  //
  2487  // # Patterns
  2488  //
  2489  // Patterns can match the method, host and path of a request.
  2490  // Some examples:
  2491  //
  2492  //   - "/index.html" matches the path "/index.html" for any host and method.
  2493  //   - "GET /static/" matches a GET request whose path begins with "/static/".
  2494  //   - "example.com/" matches any request to the host "example.com".
  2495  //   - "example.com/{$}" matches requests with host "example.com" and path "/".
  2496  //   - "/b/{bucket}/o/{objectname...}" matches paths whose first segment is "b"
  2497  //     and whose third segment is "o". The name "bucket" denotes the second
  2498  //     segment and "objectname" denotes the remainder of the path.
  2499  //
  2500  // In general, a pattern looks like
  2501  //
  2502  //	[METHOD ][HOST]/[PATH]
  2503  //
  2504  // All three parts are optional; "/" is a valid pattern.
  2505  // If METHOD is present, it must be followed by at least one space or tab.
  2506  //
  2507  // Literal (that is, non-wildcard) parts of a pattern match
  2508  // the corresponding parts of a request case-sensitively.
  2509  //
  2510  // A pattern with no method matches every method. A pattern
  2511  // with the method GET matches both GET and HEAD requests.
  2512  // Otherwise, the method must match exactly.
  2513  //
  2514  // A pattern with no host matches every host.
  2515  // A pattern with a host matches URLs on that host only.
  2516  //
  2517  // A path can include wildcard segments of the form {NAME} or {NAME...}.
  2518  // For example, "/b/{bucket}/o/{objectname...}".
  2519  // The wildcard name must be a valid Go identifier.
  2520  // Wildcards must be full path segments: they must be preceded by a slash and followed by
  2521  // either a slash or the end of the string.
  2522  // For example, "/b_{bucket}" is not a valid pattern.
  2523  //
  2524  // Normally a wildcard matches only a single path segment,
  2525  // ending at the next literal slash (not %2F) in the request URL.
  2526  // But if the "..." is present, then the wildcard matches the remainder of the URL path, including slashes.
  2527  // (Therefore it is invalid for a "..." wildcard to appear anywhere but at the end of a pattern.)
  2528  // The match for a wildcard can be obtained by calling [Request.PathValue] with the wildcard's name.
  2529  // A trailing slash in a path acts as an anonymous "..." wildcard.
  2530  //
  2531  // The special wildcard {$} matches only the end of the URL.
  2532  // For example, the pattern "/{$}" matches only the path "/",
  2533  // whereas the pattern "/" matches every path.
  2534  //
  2535  // For matching, both pattern paths and incoming request paths are unescaped segment by segment.
  2536  // So, for example, the path "/a%2Fb/100%25" is treated as having two segments, "a/b" and "100%".
  2537  // The pattern "/a%2fb/" matches it, but the pattern "/a/b/" does not.
  2538  //
  2539  // # Precedence
  2540  //
  2541  // If two or more patterns match a request, then the most specific pattern takes precedence.
  2542  // A pattern P1 is more specific than P2 if P1 matches a strict subset of P2’s requests;
  2543  // that is, if P2 matches all the requests of P1 and more.
  2544  // If neither is more specific, then the patterns conflict.
  2545  // There is one exception to this rule, for backwards compatibility:
  2546  // if two patterns would otherwise conflict and one has a host while the other does not,
  2547  // then the pattern with the host takes precedence.
  2548  // If a pattern passed to [ServeMux.Handle] or [ServeMux.HandleFunc] conflicts with
  2549  // another pattern that is already registered, those functions panic.
  2550  //
  2551  // As an example of the general rule, "/images/thumbnails/" is more specific than "/images/",
  2552  // so both can be registered.
  2553  // The former matches paths beginning with "/images/thumbnails/"
  2554  // and the latter will match any other path in the "/images/" subtree.
  2555  //
  2556  // As another example, consider the patterns "GET /" and "/index.html":
  2557  // both match a GET request for "/index.html", but the former pattern
  2558  // matches all other GET and HEAD requests, while the latter matches any
  2559  // request for "/index.html" that uses a different method.
  2560  // The patterns conflict.
  2561  //
  2562  // # Trailing-slash redirection
  2563  //
  2564  // Consider a [ServeMux] with a handler for a subtree, registered using a trailing slash or "..." wildcard.
  2565  // If the ServeMux receives a request for the subtree root without a trailing slash,
  2566  // it redirects the request by adding the trailing slash.
  2567  // This behavior can be overridden with a separate registration for the path without
  2568  // the trailing slash or "..." wildcard. For example, registering "/images/" causes ServeMux
  2569  // to redirect a request for "/images" to "/images/", unless "/images" has
  2570  // been registered separately.
  2571  //
  2572  // # Request sanitizing
  2573  //
  2574  // ServeMux also takes care of sanitizing the URL request path and the Host
  2575  // header, stripping the port number and redirecting any request containing . or
  2576  // .. segments or repeated slashes to an equivalent, cleaner URL.
  2577  // Escaped path elements such as "%2e" for "." and "%2f" for "/" are preserved
  2578  // and aren't considered separators for request routing.
  2579  //
  2580  // # Compatibility
  2581  //
  2582  // The pattern syntax and matching behavior of ServeMux changed significantly
  2583  // in Go 1.22. To restore the old behavior, set the GODEBUG environment variable
  2584  // to "httpmuxgo121=1". This setting is read once, at program startup; changes
  2585  // during execution will be ignored.
  2586  //
  2587  // The backwards-incompatible changes include:
  2588  //   - Wildcards are just ordinary literal path segments in 1.21.
  2589  //     For example, the pattern "/{x}" will match only that path in 1.21,
  2590  //     but will match any one-segment path in 1.22.
  2591  //   - In 1.21, no pattern was rejected, unless it was empty or conflicted with an existing pattern.
  2592  //     In 1.22, syntactically invalid patterns will cause [ServeMux.Handle] and [ServeMux.HandleFunc] to panic.
  2593  //     For example, in 1.21, the patterns "/{"  and "/a{x}" match themselves,
  2594  //     but in 1.22 they are invalid and will cause a panic when registered.
  2595  //   - In 1.22, each segment of a pattern is unescaped; this was not done in 1.21.
  2596  //     For example, in 1.22 the pattern "/%61" matches the path "/a" ("%61" being the URL escape sequence for "a"),
  2597  //     but in 1.21 it would match only the path "/%2561" (where "%25" is the escape for the percent sign).
  2598  //   - When matching patterns to paths, in 1.22 each segment of the path is unescaped; in 1.21, the entire path is unescaped.
  2599  //     This change mostly affects how paths with %2F escapes adjacent to slashes are treated.
  2600  //     See https://go.dev/issue/21955 for details.
  2601  type ServeMux struct {
  2602  	mu     sync.RWMutex
  2603  	tree   routingNode
  2604  	index  routingIndex
  2605  	mux121 serveMux121 // used only when GODEBUG=httpmuxgo121=1
  2606  }
  2607  
  2608  // NewServeMux allocates and returns a new [ServeMux].
  2609  func NewServeMux() *ServeMux {
  2610  	return &ServeMux{}
  2611  }
  2612  
  2613  // DefaultServeMux is the default [ServeMux] used by [Serve].
  2614  var DefaultServeMux = &defaultServeMux
  2615  
  2616  var defaultServeMux ServeMux
  2617  
  2618  // cleanPath returns the canonical path for p, eliminating . and .. elements.
  2619  func cleanPath(p string) string {
  2620  	if p == "" {
  2621  		return "/"
  2622  	}
  2623  	if p[0] != '/' {
  2624  		p = "/" + p
  2625  	}
  2626  	np := path.Clean(p)
  2627  	// path.Clean removes trailing slash except for root;
  2628  	// put the trailing slash back if necessary.
  2629  	if p[len(p)-1] == '/' && np != "/" {
  2630  		// Fast path for common case of p being the string we want:
  2631  		if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
  2632  			np = p
  2633  		} else {
  2634  			np += "/"
  2635  		}
  2636  	}
  2637  	return np
  2638  }
  2639  
  2640  // stripHostPort returns h without any trailing ":<port>".
  2641  func stripHostPort(h string) string {
  2642  	// If no port on host, return unchanged
  2643  	if !strings.Contains(h, ":") {
  2644  		return h
  2645  	}
  2646  	host, _, err := net.SplitHostPort(h)
  2647  	if err != nil {
  2648  		return h // on error, return unchanged
  2649  	}
  2650  	return host
  2651  }
  2652  
  2653  // Handler returns the handler to use for the given request,
  2654  // consulting r.Method, r.Host, and r.URL.Path. It always returns
  2655  // a non-nil handler. If the path is not in its canonical form, the
  2656  // handler will be an internally-generated handler that redirects
  2657  // to the canonical path. If the host contains a port, it is ignored
  2658  // when matching handlers.
  2659  //
  2660  // The path and host are used unchanged for CONNECT requests.
  2661  //
  2662  // Handler also returns the registered pattern that matches the
  2663  // request or, in the case of internally-generated redirects,
  2664  // the path that will match after following the redirect.
  2665  //
  2666  // If there is no registered handler that applies to the request,
  2667  // Handler returns a “page not found” or “method not supported”
  2668  // handler and an empty pattern.
  2669  //
  2670  // Handler does not modify its argument. In particular, it does not
  2671  // populate named path wildcards, so r.PathValue will always return
  2672  // the empty string.
  2673  func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
  2674  	if use121 {
  2675  		return mux.mux121.findHandler(r)
  2676  	}
  2677  	h, p, _, _ := mux.findHandler(r)
  2678  	return h, p
  2679  }
  2680  
  2681  // findHandler finds a handler for a request.
  2682  // If there is a matching handler, it returns it and the pattern that matched.
  2683  // Otherwise it returns a Redirect or NotFound handler with the path that would match
  2684  // after the redirect.
  2685  func (mux *ServeMux) findHandler(r *Request) (h Handler, patStr string, _ *pattern, matches []string) {
  2686  	var n *routingNode
  2687  	host := r.URL.Host
  2688  	escapedPath := r.URL.EscapedPath()
  2689  	path := escapedPath
  2690  	// CONNECT requests are not canonicalized.
  2691  	if r.Method == "CONNECT" {
  2692  		// If r.URL.Path is /tree and its handler is not registered,
  2693  		// the /tree -> /tree/ redirect applies to CONNECT requests
  2694  		// but the path canonicalization does not.
  2695  		_, _, u := mux.matchOrRedirect(host, r.Method, path, r.URL)
  2696  		if u != nil {
  2697  			return RedirectHandler(u.String(), StatusTemporaryRedirect), u.Path, nil, nil
  2698  		}
  2699  		// Redo the match, this time with r.Host instead of r.URL.Host.
  2700  		// Pass a nil URL to skip the trailing-slash redirect logic.
  2701  		n, matches, _ = mux.matchOrRedirect(r.Host, r.Method, path, nil)
  2702  	} else {
  2703  		// All other requests have any port stripped and path cleaned
  2704  		// before passing to mux.handler.
  2705  		host = stripHostPort(r.Host)
  2706  		path = cleanPath(path)
  2707  
  2708  		// If the given path is /tree and its handler is not registered,
  2709  		// redirect for /tree/.
  2710  		var u *url.URL
  2711  		n, matches, u = mux.matchOrRedirect(host, r.Method, path, r.URL)
  2712  		if u != nil {
  2713  			return RedirectHandler(u.String(), StatusTemporaryRedirect), n.pattern.String(), nil, nil
  2714  		}
  2715  		if path != escapedPath {
  2716  			// Redirect to cleaned path.
  2717  			patStr := ""
  2718  			if n != nil {
  2719  				patStr = n.pattern.String()
  2720  			}
  2721  			u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
  2722  			return RedirectHandler(u.String(), StatusTemporaryRedirect), patStr, nil, nil
  2723  		}
  2724  	}
  2725  	if n == nil {
  2726  		// We didn't find a match with the request method. To distinguish between
  2727  		// Not Found and Method Not Allowed, see if there is another pattern that
  2728  		// matches except for the method.
  2729  		allowedMethods := mux.matchingMethods(host, path)
  2730  		if len(allowedMethods) > 0 {
  2731  			return HandlerFunc(func(w ResponseWriter, r *Request) {
  2732  				w.Header().Set("Allow", strings.Join(allowedMethods, ", "))
  2733  				Error(w, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed)
  2734  			}), "", nil, nil
  2735  		}
  2736  		return NotFoundHandler(), "", nil, nil
  2737  	}
  2738  	return n.handler, n.pattern.String(), n.pattern, matches
  2739  }
  2740  
  2741  // matchOrRedirect looks up a node in the tree that matches the host, method and path.
  2742  //
  2743  // If the url argument is non-nil, handler also deals with trailing-slash
  2744  // redirection: when a path doesn't match exactly, the match is tried again
  2745  // after appending "/" to the path. If that second match succeeds, the last
  2746  // return value is the URL to redirect to.
  2747  func (mux *ServeMux) matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL) {
  2748  	mux.mu.RLock()
  2749  	defer mux.mu.RUnlock()
  2750  
  2751  	n, matches := mux.tree.match(host, method, path)
  2752  	// We can terminate here if any of the following is true:
  2753  	// - We have an exact match already.
  2754  	// - We were asked not to try trailing slash redirection.
  2755  	// - The URL already has a trailing slash.
  2756  	// - The URL is an empty string.
  2757  	if !exactMatch(n, path) && u != nil && !strings.HasSuffix(path, "/") && path != "" {
  2758  		// If there is an exact match with a trailing slash, then redirect.
  2759  		path += "/"
  2760  		n2, _ := mux.tree.match(host, method, path)
  2761  		if exactMatch(n2, path) {
  2762  			// It is safe to return n2 here: it is used only in the second RedirectHandler case
  2763  			// of findHandler, and that method returns before it does the "n == nil" check where
  2764  			// the first return value matters. We return it here only to make the pattern available
  2765  			// to findHandler.
  2766  			return n2, nil, &url.URL{Path: cleanPath(u.Path) + "/", RawQuery: u.RawQuery}
  2767  		}
  2768  	}
  2769  	return n, matches, nil
  2770  }
  2771  
  2772  // exactMatch reports whether the node's pattern exactly matches the path.
  2773  // As a special case, if the node is nil, exactMatch return false.
  2774  //
  2775  // Before wildcards were introduced, it was clear that an exact match meant
  2776  // that the pattern and path were the same string. The only other possibility
  2777  // was that a trailing-slash pattern, like "/", matched a path longer than
  2778  // it, like "/a".
  2779  //
  2780  // With wildcards, we define an inexact match as any one where a multi wildcard
  2781  // matches a non-empty string. All other matches are exact.
  2782  // For example, these are all exact matches:
  2783  //
  2784  //	pattern   path
  2785  //	/a        /a
  2786  //	/{x}      /a
  2787  //	/a/{$}    /a/
  2788  //	/a/       /a/
  2789  //
  2790  // The last case has a multi wildcard (implicitly), but the match is exact because
  2791  // the wildcard matches the empty string.
  2792  //
  2793  // Examples of matches that are not exact:
  2794  //
  2795  //	pattern   path
  2796  //	/         /a
  2797  //	/a/{x...} /a/b
  2798  func exactMatch(n *routingNode, path string) bool {
  2799  	if n == nil {
  2800  		return false
  2801  	}
  2802  	// We can't directly implement the definition (empty match for multi
  2803  	// wildcard) because we don't record a match for anonymous multis.
  2804  
  2805  	// If there is no multi, the match is exact.
  2806  	if !n.pattern.lastSegment().multi {
  2807  		return true
  2808  	}
  2809  
  2810  	// If the path doesn't end in a trailing slash, then the multi match
  2811  	// is non-empty.
  2812  	if len(path) > 0 && path[len(path)-1] != '/' {
  2813  		return false
  2814  	}
  2815  	// Only patterns ending in {$} or a multi wildcard can
  2816  	// match a path with a trailing slash.
  2817  	// For the match to be exact, the number of pattern
  2818  	// segments should be the same as the number of slashes in the path.
  2819  	// E.g. "/a/b/{$}" and "/a/b/{...}" exactly match "/a/b/", but "/a/" does not.
  2820  	return len(n.pattern.segments) == strings.Count(path, "/")
  2821  }
  2822  
  2823  // matchingMethods return a sorted list of all methods that would match with the given host and path.
  2824  func (mux *ServeMux) matchingMethods(host, path string) []string {
  2825  	// Hold the read lock for the entire method so that the two matches are done
  2826  	// on the same set of registered patterns.
  2827  	mux.mu.RLock()
  2828  	defer mux.mu.RUnlock()
  2829  	ms := map[string]bool{}
  2830  	mux.tree.matchingMethods(host, path, ms)
  2831  	// matchOrRedirect will try appending a trailing slash if there is no match.
  2832  	if !strings.HasSuffix(path, "/") {
  2833  		mux.tree.matchingMethods(host, path+"/", ms)
  2834  	}
  2835  	return slices.Sorted(maps.Keys(ms))
  2836  }
  2837  
  2838  // ServeHTTP dispatches the request to the handler whose
  2839  // pattern most closely matches the request URL.
  2840  func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
  2841  	if r.RequestURI == "*" {
  2842  		if r.ProtoAtLeast(1, 1) {
  2843  			w.Header().Set("Connection", "close")
  2844  		}
  2845  		w.WriteHeader(StatusBadRequest)
  2846  		return
  2847  	}
  2848  	var h Handler
  2849  	if use121 {
  2850  		h, _ = mux.mux121.findHandler(r)
  2851  	} else {
  2852  		h, r.Pattern, r.pat, r.matches = mux.findHandler(r)
  2853  	}
  2854  	h.ServeHTTP(w, r)
  2855  }
  2856  
  2857  // The four functions below all call ServeMux.register so that callerLocation
  2858  // always refers to user code.
  2859  
  2860  // Handle registers the handler for the given pattern.
  2861  // If the given pattern conflicts with one that is already registered
  2862  // or if the pattern is invalid, Handle panics.
  2863  //
  2864  // See [ServeMux] for details on valid patterns and conflict rules.
  2865  func (mux *ServeMux) Handle(pattern string, handler Handler) {
  2866  	if use121 {
  2867  		mux.mux121.handle(pattern, handler)
  2868  	} else {
  2869  		mux.register(pattern, handler)
  2870  	}
  2871  }
  2872  
  2873  // HandleFunc registers the handler function for the given pattern.
  2874  // If the given pattern conflicts with one that is already registered
  2875  // or if the pattern is invalid, HandleFunc panics.
  2876  //
  2877  // See [ServeMux] for details on valid patterns and conflict rules.
  2878  func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  2879  	if use121 {
  2880  		mux.mux121.handleFunc(pattern, handler)
  2881  	} else {
  2882  		mux.register(pattern, HandlerFunc(handler))
  2883  	}
  2884  }
  2885  
  2886  // Handle registers the handler for the given pattern in [DefaultServeMux].
  2887  // The documentation for [ServeMux] explains how patterns are matched.
  2888  func Handle(pattern string, handler Handler) {
  2889  	if use121 {
  2890  		DefaultServeMux.mux121.handle(pattern, handler)
  2891  	} else {
  2892  		DefaultServeMux.register(pattern, handler)
  2893  	}
  2894  }
  2895  
  2896  // HandleFunc registers the handler function for the given pattern in [DefaultServeMux].
  2897  // The documentation for [ServeMux] explains how patterns are matched.
  2898  func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  2899  	if use121 {
  2900  		DefaultServeMux.mux121.handleFunc(pattern, handler)
  2901  	} else {
  2902  		DefaultServeMux.register(pattern, HandlerFunc(handler))
  2903  	}
  2904  }
  2905  
  2906  func (mux *ServeMux) register(pattern string, handler Handler) {
  2907  	if err := mux.registerErr(pattern, handler); err != nil {
  2908  		panic(err)
  2909  	}
  2910  }
  2911  
  2912  func (mux *ServeMux) registerErr(patstr string, handler Handler) error {
  2913  	if patstr == "" {
  2914  		return errors.New("http: invalid pattern")
  2915  	}
  2916  	if handler == nil {
  2917  		return errors.New("http: nil handler")
  2918  	}
  2919  	if f, ok := handler.(HandlerFunc); ok && f == nil {
  2920  		return errors.New("http: nil handler")
  2921  	}
  2922  
  2923  	pat, err := parsePattern(patstr)
  2924  	if err != nil {
  2925  		return fmt.Errorf("parsing %q: %w", patstr, err)
  2926  	}
  2927  
  2928  	// Get the caller's location, for better conflict error messages.
  2929  	// Skip register and whatever calls it.
  2930  	_, file, line, ok := runtime.Caller(3)
  2931  	if !ok {
  2932  		pat.loc = "unknown location"
  2933  	} else {
  2934  		pat.loc = fmt.Sprintf("%s:%d", file, line)
  2935  	}
  2936  
  2937  	mux.mu.Lock()
  2938  	defer mux.mu.Unlock()
  2939  	// Check for conflict.
  2940  	if err := mux.index.possiblyConflictingPatterns(pat, func(pat2 *pattern) error {
  2941  		if pat.conflictsWith(pat2) {
  2942  			d := describeConflict(pat, pat2)
  2943  			return fmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s):\n%s",
  2944  				pat, pat.loc, pat2, pat2.loc, d)
  2945  		}
  2946  		return nil
  2947  	}); err != nil {
  2948  		return err
  2949  	}
  2950  	mux.tree.addPattern(pat, handler)
  2951  	mux.index.addPattern(pat)
  2952  	return nil
  2953  }
  2954  
  2955  // Serve accepts incoming HTTP connections on the listener l,
  2956  // creating a new service goroutine for each. The service goroutines
  2957  // read requests and then call handler to reply to them.
  2958  //
  2959  // The handler is typically nil, in which case [DefaultServeMux] is used.
  2960  //
  2961  // HTTP/2 support is only enabled if the Listener returns [*tls.Conn]
  2962  // connections and they were configured with "h2" in the TLS
  2963  // Config.NextProtos.
  2964  //
  2965  // Serve always returns a non-nil error.
  2966  func Serve(l net.Listener, handler Handler) error {
  2967  	srv := &Server{Handler: handler}
  2968  	return srv.Serve(l)
  2969  }
  2970  
  2971  // ServeTLS accepts incoming HTTPS connections on the listener l,
  2972  // creating a new service goroutine for each. The service goroutines
  2973  // read requests and then call handler to reply to them.
  2974  //
  2975  // The handler is typically nil, in which case [DefaultServeMux] is used.
  2976  //
  2977  // Additionally, files containing a certificate and matching private key
  2978  // for the server must be provided. If the certificate is signed by a
  2979  // certificate authority, the certFile should be the concatenation
  2980  // of the server's certificate, any intermediates, and the CA's certificate.
  2981  //
  2982  // ServeTLS always returns a non-nil error.
  2983  func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {
  2984  	srv := &Server{Handler: handler}
  2985  	return srv.ServeTLS(l, certFile, keyFile)
  2986  }
  2987  
  2988  // A Server defines parameters for running an HTTP server.
  2989  // The zero value for Server is a valid configuration.
  2990  type Server struct {
  2991  	// Addr optionally specifies the TCP address for the server to listen on,
  2992  	// in the form "host:port". If empty, ":http" (port 80) is used.
  2993  	// The service names are defined in RFC 6335 and assigned by IANA.
  2994  	// See net.Dial for details of the address format.
  2995  	Addr string
  2996  
  2997  	Handler Handler // handler to invoke, http.DefaultServeMux if nil
  2998  
  2999  	// DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
  3000  	// otherwise responds with 200 OK and Content-Length: 0.
  3001  	DisableGeneralOptionsHandler bool
  3002  
  3003  	// TLSConfig optionally provides a TLS configuration for use
  3004  	// by ServeTLS and ListenAndServeTLS. Note that this value is
  3005  	// cloned by ServeTLS and ListenAndServeTLS, so it's not
  3006  	// possible to modify the configuration with methods like
  3007  	// tls.Config.SetSessionTicketKeys. To use
  3008  	// SetSessionTicketKeys, use Server.Serve with a TLS Listener
  3009  	// instead.
  3010  	TLSConfig *tls.Config
  3011  
  3012  	// ReadTimeout is the maximum duration for reading the entire
  3013  	// request, including the body. A zero or negative value means
  3014  	// there will be no timeout.
  3015  	//
  3016  	// Because ReadTimeout does not let Handlers make per-request
  3017  	// decisions on each request body's acceptable deadline or
  3018  	// upload rate, most users will prefer to use
  3019  	// ReadHeaderTimeout. It is valid to use them both.
  3020  	ReadTimeout time.Duration
  3021  
  3022  	// ReadHeaderTimeout is the amount of time allowed to read
  3023  	// request headers. The connection's read deadline is reset
  3024  	// after reading the headers and the Handler can decide what
  3025  	// is considered too slow for the body. If zero, the value of
  3026  	// ReadTimeout is used. If negative, or if zero and ReadTimeout
  3027  	// is zero or negative, there is no timeout.
  3028  	ReadHeaderTimeout time.Duration
  3029  
  3030  	// WriteTimeout is the maximum duration before timing out
  3031  	// writes of the response. It is reset whenever a new
  3032  	// request's header is read. Like ReadTimeout, it does not
  3033  	// let Handlers make decisions on a per-request basis.
  3034  	// A zero or negative value means there will be no timeout.
  3035  	WriteTimeout time.Duration
  3036  
  3037  	// IdleTimeout is the maximum amount of time to wait for the
  3038  	// next request when keep-alives are enabled. If zero, the value
  3039  	// of ReadTimeout is used. If negative, or if zero and ReadTimeout
  3040  	// is zero or negative, there is no timeout.
  3041  	IdleTimeout time.Duration
  3042  
  3043  	// MaxHeaderBytes controls the maximum number of bytes the
  3044  	// server will read parsing the request header's keys and
  3045  	// values, including the request line. It does not limit the
  3046  	// size of the request body.
  3047  	// If zero, DefaultMaxHeaderBytes is used.
  3048  	MaxHeaderBytes int
  3049  
  3050  	// TLSNextProto optionally specifies a function to take over
  3051  	// ownership of the provided TLS connection when an ALPN
  3052  	// protocol upgrade has occurred. The map key is the protocol
  3053  	// name negotiated. The Handler argument should be used to
  3054  	// handle HTTP requests and will initialize the Request's TLS
  3055  	// and RemoteAddr if not already set. The connection is
  3056  	// automatically closed when the function returns.
  3057  	// If TLSNextProto is not nil, HTTP/2 support is not enabled
  3058  	// automatically.
  3059  	//
  3060  	// Historically, TLSNextProto was used to disable HTTP/2 support.
  3061  	// The Server.Protocols field now provides a simpler way to do this.
  3062  	TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
  3063  
  3064  	// ConnState specifies an optional callback function that is
  3065  	// called when a client connection changes state. See the
  3066  	// ConnState type and associated constants for details.
  3067  	ConnState func(net.Conn, ConnState)
  3068  
  3069  	// ErrorLog specifies an optional logger for errors accepting
  3070  	// connections, unexpected behavior from handlers, and
  3071  	// underlying FileSystem errors.
  3072  	// If nil, logging is done via the log package's standard logger.
  3073  	ErrorLog *log.Logger
  3074  
  3075  	// BaseContext optionally specifies a function that returns
  3076  	// the base context for incoming requests on this server.
  3077  	// The provided Listener is the specific Listener that's
  3078  	// about to start accepting requests.
  3079  	// If BaseContext is nil, the default is context.Background().
  3080  	// If non-nil, it must return a non-nil context.
  3081  	BaseContext func(net.Listener) context.Context
  3082  
  3083  	// ConnContext optionally specifies a function that modifies
  3084  	// the context used for a new connection c. The provided ctx
  3085  	// is derived from the base context and has a ServerContextKey
  3086  	// value.
  3087  	ConnContext func(ctx context.Context, c net.Conn) context.Context
  3088  
  3089  	// HTTP2 configures HTTP/2 connections.
  3090  	HTTP2 *HTTP2Config
  3091  
  3092  	// Protocols is the set of protocols accepted by the server.
  3093  	//
  3094  	// If Protocols includes UnencryptedHTTP2, the server will accept
  3095  	// unencrypted HTTP/2 connections. The server can serve both
  3096  	// HTTP/1 and unencrypted HTTP/2 on the same address and port.
  3097  	//
  3098  	// If Protocols is nil, the default is usually HTTP/1 and HTTP/2.
  3099  	// If TLSNextProto is non-nil and does not contain an "h2" entry,
  3100  	// the default is HTTP/1 only.
  3101  	Protocols *Protocols
  3102  
  3103  	// DisableClientPriority specifies whether client-specified priority, as
  3104  	// specified in RFC 9218, should be respected or not.
  3105  	//
  3106  	// This field only takes effect if using HTTP/2, and if no custom write
  3107  	// scheduler is defined for the HTTP/2 server. Otherwise, this field is a
  3108  	// no-op.
  3109  	//
  3110  	// If set to true, requests will be served in a round-robin manner, without
  3111  	// prioritization.
  3112  	DisableClientPriority bool
  3113  
  3114  	inShutdown atomic.Bool // true when server is in shutdown
  3115  
  3116  	disableKeepAlives atomic.Bool
  3117  	nextProtoOnce     sync.Once // guards setupHTTP2_* init
  3118  	nextProtoErr      error     // result of http2.ConfigureServer if used
  3119  
  3120  	mu         sync.Mutex
  3121  	listeners  map[*net.Listener]struct{}
  3122  	activeConn map[*conn]struct{}
  3123  	onShutdown []func()
  3124  	h2         *http2Server
  3125  	h3         *http3ServerHandler
  3126  
  3127  	listenerGroup sync.WaitGroup
  3128  }
  3129  
  3130  // Close immediately closes all active net.Listeners and any
  3131  // connections in state [StateNew], [StateActive], or [StateIdle]. For a
  3132  // graceful shutdown, use [Server.Shutdown].
  3133  //
  3134  // Close does not attempt to close (and does not even know about)
  3135  // any hijacked connections, such as WebSockets.
  3136  //
  3137  // Close returns any error returned from closing the [Server]'s
  3138  // underlying Listener(s).
  3139  func (s *Server) Close() error {
  3140  	s.inShutdown.Store(true)
  3141  	s.mu.Lock()
  3142  	defer s.mu.Unlock()
  3143  	err := s.closeListenersLocked()
  3144  
  3145  	// Unlock s.mu while waiting for listenerGroup.
  3146  	// The group Add and Done calls are made with s.mu held,
  3147  	// to avoid adding a new listener in the window between
  3148  	// us setting inShutdown above and waiting here.
  3149  	s.mu.Unlock()
  3150  	s.listenerGroup.Wait()
  3151  	s.mu.Lock()
  3152  
  3153  	for c := range s.activeConn {
  3154  		c.rwc.Close()
  3155  		delete(s.activeConn, c)
  3156  	}
  3157  	return err
  3158  }
  3159  
  3160  // shutdownPollIntervalMax is the max polling interval when checking
  3161  // quiescence during Server.Shutdown. Polling starts with a small
  3162  // interval and backs off to the max.
  3163  // Ideally we could find a solution that doesn't involve polling,
  3164  // but which also doesn't have a high runtime cost (and doesn't
  3165  // involve any contentious mutexes), but that is left as an
  3166  // exercise for the reader.
  3167  const shutdownPollIntervalMax = 500 * time.Millisecond
  3168  
  3169  // Shutdown gracefully shuts down the server without interrupting any
  3170  // active connections. Shutdown works by first closing all open
  3171  // listeners, then closing all idle connections, and then waiting
  3172  // indefinitely for connections to return to idle and then shut down.
  3173  // If the provided context expires before the shutdown is complete,
  3174  // Shutdown returns the context's error, otherwise it returns any
  3175  // error returned from closing the [Server]'s underlying Listener(s).
  3176  //
  3177  // When Shutdown is called, [Serve], [ServeTLS], [ListenAndServe], and
  3178  // [ListenAndServeTLS] immediately return [ErrServerClosed]. Make sure the
  3179  // program doesn't exit and waits instead for Shutdown to return.
  3180  //
  3181  // Shutdown does not attempt to close nor wait for hijacked
  3182  // connections such as WebSockets. The caller of Shutdown should
  3183  // separately notify such long-lived connections of shutdown and wait
  3184  // for them to close, if desired. See [Server.RegisterOnShutdown] for a way to
  3185  // register shutdown notification functions.
  3186  //
  3187  // Once Shutdown has been called on a server, it may not be reused;
  3188  // future calls to methods such as Serve will return ErrServerClosed.
  3189  func (s *Server) Shutdown(ctx context.Context) error {
  3190  	s.inShutdown.Store(true)
  3191  
  3192  	s.mu.Lock()
  3193  	if s.h3 != nil {
  3194  		s.h3.shutdownCtx = ctx
  3195  	}
  3196  	lnerr := s.closeListenersLocked()
  3197  	for _, f := range s.onShutdown {
  3198  		go f()
  3199  	}
  3200  	s.mu.Unlock()
  3201  	s.listenerGroup.Wait()
  3202  
  3203  	pollIntervalBase := time.Millisecond
  3204  	nextPollInterval := func() time.Duration {
  3205  		// Add 10% jitter.
  3206  		interval := pollIntervalBase + time.Duration(rand.IntN(int(pollIntervalBase/10)))
  3207  		// Double and clamp for next time.
  3208  		pollIntervalBase *= 2
  3209  		if pollIntervalBase > shutdownPollIntervalMax {
  3210  			pollIntervalBase = shutdownPollIntervalMax
  3211  		}
  3212  		return interval
  3213  	}
  3214  
  3215  	timer := time.NewTimer(nextPollInterval())
  3216  	defer timer.Stop()
  3217  	for {
  3218  		if s.closeIdleConns() {
  3219  			return lnerr
  3220  		}
  3221  		select {
  3222  		case <-ctx.Done():
  3223  			return ctx.Err()
  3224  		case <-timer.C:
  3225  			timer.Reset(nextPollInterval())
  3226  		}
  3227  	}
  3228  }
  3229  
  3230  // RegisterOnShutdown registers a function to call on [Server.Shutdown].
  3231  // This can be used to gracefully shutdown connections that have
  3232  // undergone ALPN protocol upgrade or that have been hijacked.
  3233  // This function should start protocol-specific graceful shutdown,
  3234  // but should not wait for shutdown to complete.
  3235  func (s *Server) RegisterOnShutdown(f func()) {
  3236  	s.mu.Lock()
  3237  	s.onShutdown = append(s.onShutdown, f)
  3238  	s.mu.Unlock()
  3239  }
  3240  
  3241  // closeIdleConns closes all idle connections and reports whether the
  3242  // server is quiescent.
  3243  func (s *Server) closeIdleConns() bool {
  3244  	s.mu.Lock()
  3245  	defer s.mu.Unlock()
  3246  	quiescent := true
  3247  	for c := range s.activeConn {
  3248  		st, unixSec := c.getState()
  3249  		// Issue 22682: treat StateNew connections as if
  3250  		// they're idle if we haven't read the first request's
  3251  		// header in over 5 seconds.
  3252  		if st == StateNew && unixSec < time.Now().Unix()-5 {
  3253  			st = StateIdle
  3254  		}
  3255  		if st != StateIdle || unixSec == 0 {
  3256  			// Assume unixSec == 0 means it's a very new
  3257  			// connection, without state set yet.
  3258  			quiescent = false
  3259  			continue
  3260  		}
  3261  		c.rwc.Close()
  3262  		delete(s.activeConn, c)
  3263  	}
  3264  	return quiescent
  3265  }
  3266  
  3267  func (s *Server) closeListenersLocked() error {
  3268  	var err error
  3269  	for ln := range s.listeners {
  3270  		if cerr := (*ln).Close(); cerr != nil && err == nil {
  3271  			err = cerr
  3272  		}
  3273  	}
  3274  	return err
  3275  }
  3276  
  3277  // A ConnState represents the state of a client connection to a server.
  3278  // It's used by the optional [Server.ConnState] hook.
  3279  type ConnState int
  3280  
  3281  const (
  3282  	// StateNew represents a new connection that is expected to
  3283  	// send a request immediately. Connections begin at this
  3284  	// state and then transition to either StateActive or
  3285  	// StateClosed.
  3286  	StateNew ConnState = iota
  3287  
  3288  	// StateActive represents a connection that has read 1 or more
  3289  	// bytes of a request. The Server.ConnState hook for
  3290  	// StateActive fires before the request has entered a handler
  3291  	// and doesn't fire again until the request has been
  3292  	// handled. After the request is handled, the state
  3293  	// transitions to StateClosed, StateHijacked, or StateIdle.
  3294  	// For HTTP/2, StateActive fires on the transition from zero
  3295  	// to one active request, and only transitions away once all
  3296  	// active requests are complete. That means that ConnState
  3297  	// cannot be used to do per-request work; ConnState only notes
  3298  	// the overall state of the connection.
  3299  	StateActive
  3300  
  3301  	// StateIdle represents a connection that has finished
  3302  	// handling a request and is in the keep-alive state, waiting
  3303  	// for a new request. Connections transition from StateIdle
  3304  	// to either StateActive or StateClosed.
  3305  	StateIdle
  3306  
  3307  	// StateHijacked represents a hijacked connection.
  3308  	// This is a terminal state. It does not transition to StateClosed.
  3309  	StateHijacked
  3310  
  3311  	// StateClosed represents a closed connection.
  3312  	// This is a terminal state. Hijacked connections do not
  3313  	// transition to StateClosed.
  3314  	StateClosed
  3315  )
  3316  
  3317  var stateName = map[ConnState]string{
  3318  	StateNew:      "new",
  3319  	StateActive:   "active",
  3320  	StateIdle:     "idle",
  3321  	StateHijacked: "hijacked",
  3322  	StateClosed:   "closed",
  3323  }
  3324  
  3325  func (c ConnState) String() string {
  3326  	return stateName[c]
  3327  }
  3328  
  3329  // serverHandler delegates to either the server's Handler or
  3330  // DefaultServeMux and also handles "OPTIONS *" requests.
  3331  type serverHandler struct {
  3332  	srv *Server
  3333  }
  3334  
  3335  // ServeHTTP should be an internal detail,
  3336  // but widely used packages access it using linkname.
  3337  // Notable members of the hall of shame include:
  3338  //   - github.com/erda-project/erda-infra
  3339  //
  3340  // Do not remove or change the type signature.
  3341  // See go.dev/issue/67401.
  3342  //
  3343  //go:linkname badServeHTTP net/http.serverHandler.ServeHTTP
  3344  func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
  3345  	handler := sh.srv.Handler
  3346  	if handler == nil {
  3347  		handler = DefaultServeMux
  3348  	}
  3349  	if !sh.srv.DisableGeneralOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" {
  3350  		handler = globalOptionsHandler{}
  3351  	}
  3352  
  3353  	handler.ServeHTTP(rw, req)
  3354  }
  3355  
  3356  func badServeHTTP(serverHandler, ResponseWriter, *Request)
  3357  
  3358  // AllowQuerySemicolons returns a handler that serves requests by converting any
  3359  // unescaped semicolons in the URL query to ampersands, and invoking the handler h.
  3360  //
  3361  // This restores the pre-Go 1.17 behavior of splitting query parameters on both
  3362  // semicolons and ampersands. (See golang.org/issue/25192). Note that this
  3363  // behavior doesn't match that of many proxies, and the mismatch can lead to
  3364  // security issues.
  3365  //
  3366  // AllowQuerySemicolons should be invoked before [Request.ParseForm] is called.
  3367  func AllowQuerySemicolons(h Handler) Handler {
  3368  	return HandlerFunc(func(w ResponseWriter, r *Request) {
  3369  		if strings.Contains(r.URL.RawQuery, ";") {
  3370  			r2 := new(Request)
  3371  			*r2 = *r
  3372  			r2.URL = new(url.URL)
  3373  			*r2.URL = *r.URL
  3374  			r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&")
  3375  			h.ServeHTTP(w, r2)
  3376  		} else {
  3377  			h.ServeHTTP(w, r)
  3378  		}
  3379  	})
  3380  }
  3381  
  3382  // ListenAndServe listens on the TCP network address s.Addr and then
  3383  // calls [Serve] to handle requests on incoming connections.
  3384  // Accepted connections are configured to enable TCP keep-alives.
  3385  //
  3386  // If s.Addr is blank, ":http" is used.
  3387  //
  3388  // ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close],
  3389  // the returned error is [ErrServerClosed].
  3390  func (s *Server) ListenAndServe() error {
  3391  	if s.shuttingDown() {
  3392  		return ErrServerClosed
  3393  	}
  3394  	addr := s.Addr
  3395  	if addr == "" {
  3396  		addr = ":http"
  3397  	}
  3398  	ln, err := net.Listen("tcp", addr)
  3399  	if err != nil {
  3400  		return err
  3401  	}
  3402  	return s.Serve(ln)
  3403  }
  3404  
  3405  var testHookServerServe func(*Server, net.Listener) // used if non-nil
  3406  
  3407  // shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
  3408  // automatic HTTP/2. (which sets up the s.TLSNextProto map)
  3409  func (s *Server) shouldConfigureHTTP2ForServe() bool {
  3410  	if s.TLSConfig == nil {
  3411  		// Compatibility with Go 1.6:
  3412  		// If there's no TLSConfig, it's possible that the user just
  3413  		// didn't set it on the http.Server, but did pass it to
  3414  		// tls.NewListener and passed that listener to Serve.
  3415  		// So we should configure HTTP/2 (to set up s.TLSNextProto)
  3416  		// in case the listener returns an "h2" *tls.Conn.
  3417  		return true
  3418  	}
  3419  	if s.protocols().UnencryptedHTTP2() {
  3420  		return true
  3421  	}
  3422  	// The user specified a TLSConfig on their http.Server.
  3423  	// In this, case, only configure HTTP/2 if their tls.Config
  3424  	// explicitly mentions "h2". Otherwise http2.ConfigureServer
  3425  	// would modify the tls.Config to add it, but they probably already
  3426  	// passed this tls.Config to tls.NewListener. And if they did,
  3427  	// it's too late anyway to fix it. It would only be potentially racy.
  3428  	// See Issue 15908.
  3429  	return slices.Contains(s.TLSConfig.NextProtos, "h2")
  3430  }
  3431  
  3432  // ErrServerClosed is returned by the [Server.Serve], [ServeTLS], [ListenAndServe],
  3433  // and [ListenAndServeTLS] methods after a call to [Server.Shutdown] or [Server.Close].
  3434  var ErrServerClosed = errors.New("http: Server closed")
  3435  
  3436  // Serve accepts incoming connections on the Listener l, creating a
  3437  // new service goroutine for each. The service goroutines read requests and
  3438  // then call s.Handler to reply to them.
  3439  //
  3440  // HTTP/2 support is only enabled if the Listener returns [*tls.Conn]
  3441  // connections and they were configured with "h2" in the TLS
  3442  // Config.NextProtos.
  3443  //
  3444  // Serve always returns a non-nil error and closes l.
  3445  // After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed].
  3446  func (s *Server) Serve(l net.Listener) error {
  3447  	if fn := testHookServerServe; fn != nil {
  3448  		fn(s, l) // call hook with unwrapped listener
  3449  	}
  3450  
  3451  	origListener := l
  3452  	l = &onceCloseListener{Listener: l}
  3453  	defer l.Close()
  3454  
  3455  	if err := s.setupHTTP2_Serve(); err != nil {
  3456  		return err
  3457  	}
  3458  
  3459  	if !s.trackListener(&l, true) {
  3460  		return ErrServerClosed
  3461  	}
  3462  	defer s.trackListener(&l, false)
  3463  
  3464  	baseCtx := context.Background()
  3465  	if s.BaseContext != nil {
  3466  		baseCtx = s.BaseContext(origListener)
  3467  		if baseCtx == nil {
  3468  			panic("BaseContext returned a nil context")
  3469  		}
  3470  	}
  3471  
  3472  	var tempDelay time.Duration // how long to sleep on accept failure
  3473  
  3474  	ctx := context.WithValue(baseCtx, ServerContextKey, s)
  3475  	for {
  3476  		rw, err := l.Accept()
  3477  		if err != nil {
  3478  			if s.shuttingDown() {
  3479  				return ErrServerClosed
  3480  			}
  3481  			if ne, ok := err.(net.Error); ok && ne.Temporary() {
  3482  				if tempDelay == 0 {
  3483  					tempDelay = 5 * time.Millisecond
  3484  				} else {
  3485  					tempDelay *= 2
  3486  				}
  3487  				if max := 1 * time.Second; tempDelay > max {
  3488  					tempDelay = max
  3489  				}
  3490  				s.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
  3491  				time.Sleep(tempDelay)
  3492  				continue
  3493  			}
  3494  			return err
  3495  		}
  3496  		connCtx := ctx
  3497  		if cc := s.ConnContext; cc != nil {
  3498  			connCtx = cc(connCtx, rw)
  3499  			if connCtx == nil {
  3500  				panic("ConnContext returned nil")
  3501  			}
  3502  		}
  3503  		tempDelay = 0
  3504  		c := s.newConn(rw)
  3505  		c.setState(c.rwc, StateNew, runHooks) // before Serve can return
  3506  		go c.serve(connCtx)
  3507  	}
  3508  }
  3509  
  3510  func (s *Server) setupTLSConfig(certFile, keyFile string, nextProtos []string) (*tls.Config, error) {
  3511  	config := cloneTLSConfig(s.TLSConfig)
  3512  	config.NextProtos = nextProtos
  3513  
  3514  	configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil || config.GetConfigForClient != nil
  3515  	if !configHasCert || certFile != "" || keyFile != "" {
  3516  		var err error
  3517  		config.Certificates = make([]tls.Certificate, 1)
  3518  		config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
  3519  		if err != nil {
  3520  			return nil, err
  3521  		}
  3522  	}
  3523  	return config, nil
  3524  }
  3525  
  3526  // ServeTLS accepts incoming connections on the Listener l, creating a
  3527  // new service goroutine for each. The service goroutines perform TLS
  3528  // setup and then read requests, calling s.Handler to reply to them.
  3529  //
  3530  // Files containing a certificate and matching private key for the
  3531  // server must be provided if neither the [Server]'s
  3532  // TLSConfig.Certificates, TLSConfig.GetCertificate nor
  3533  // config.GetConfigForClient are populated.
  3534  // If the certificate is signed by a certificate authority, the
  3535  // certFile should be the concatenation of the server's certificate,
  3536  // any intermediates, and the CA's certificate.
  3537  //
  3538  // ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the
  3539  // returned error is [ErrServerClosed].
  3540  func (s *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
  3541  	// Setup HTTP/2 before s.Serve, to initialize s.TLSConfig
  3542  	// before we clone it and create the TLS Listener.
  3543  	if err := s.setupHTTP2_ServeTLS(); err != nil {
  3544  		return err
  3545  	}
  3546  
  3547  	var nextProtos []string
  3548  	if s.TLSConfig != nil {
  3549  		nextProtos = s.TLSConfig.NextProtos
  3550  	}
  3551  	config, err := s.setupTLSConfig(certFile, keyFile, adjustNextProtos(nextProtos, s.protocols()))
  3552  	if err != nil {
  3553  		return err
  3554  	}
  3555  
  3556  	tlsListener := tls.NewListener(l, config)
  3557  	return s.Serve(tlsListener)
  3558  }
  3559  
  3560  func (s *Server) protocols() Protocols {
  3561  	if s.Protocols != nil {
  3562  		// Historically, even when Protocols for a Server was set to be empty,
  3563  		// the Server can still run normally with just HTTP/1.
  3564  		// To keep backward-compatibility, the zero value of Protocols is
  3565  		// defined as having only HTTP/1 enabled.
  3566  		if s.Protocols.empty() {
  3567  			var p Protocols
  3568  			p.SetHTTP1(true)
  3569  			return p
  3570  		}
  3571  		return *s.Protocols // user-configured set
  3572  	}
  3573  
  3574  	// The historic way of disabling HTTP/2 is to set TLSNextProto to
  3575  	// a non-nil map with no "h2" entry.
  3576  	_, hasH2 := s.TLSNextProto["h2"]
  3577  	http2Disabled := s.TLSNextProto != nil && !hasH2
  3578  
  3579  	// If GODEBUG=http2server=0, then HTTP/2 is disabled unless
  3580  	// the user has manually added an "h2" entry to TLSNextProto
  3581  	// (probably by using x/net/http2 directly).
  3582  	if http2server.Value() == "0" && !hasH2 {
  3583  		http2Disabled = true
  3584  	}
  3585  
  3586  	var p Protocols
  3587  	p.SetHTTP1(true) // default always includes HTTP/1
  3588  	if !http2Disabled {
  3589  		p.SetHTTP2(true)
  3590  	}
  3591  	return p
  3592  }
  3593  
  3594  // adjustNextProtos adds or removes "http/1.1" and "h2" entries from
  3595  // a tls.Config.NextProtos list, according to the set of protocols in protos.
  3596  func adjustNextProtos(nextProtos []string, protos Protocols) []string {
  3597  	// Make a copy of NextProtos since it might be shared with some other tls.Config.
  3598  	// (tls.Config.Clone doesn't do a deep copy.)
  3599  	//
  3600  	// We could avoid an allocation in the common case by checking to see if the slice
  3601  	// is already in order, but this is just one small allocation per connection.
  3602  	nextProtos = slices.Clone(nextProtos)
  3603  	var have Protocols
  3604  	nextProtos = slices.DeleteFunc(nextProtos, func(s string) bool {
  3605  		switch s {
  3606  		case "http/1.1":
  3607  			if !protos.HTTP1() {
  3608  				return true
  3609  			}
  3610  			have.SetHTTP1(true)
  3611  		case "h2":
  3612  			if !protos.HTTP2() {
  3613  				return true
  3614  			}
  3615  			have.SetHTTP2(true)
  3616  		}
  3617  		return false
  3618  	})
  3619  	if protos.HTTP2() && !have.HTTP2() {
  3620  		nextProtos = append(nextProtos, "h2")
  3621  	}
  3622  	if protos.HTTP1() && !have.HTTP1() {
  3623  		nextProtos = append(nextProtos, "http/1.1")
  3624  	}
  3625  	return nextProtos
  3626  }
  3627  
  3628  // trackListener adds or removes a net.Listener to the set of tracked
  3629  // listeners.
  3630  //
  3631  // We store a pointer to interface in the map set, in case the
  3632  // net.Listener is not comparable. This is safe because we only call
  3633  // trackListener via Serve and can track+defer untrack the same
  3634  // pointer to local variable there. We never need to compare a
  3635  // Listener from another caller.
  3636  //
  3637  // It reports whether the server is still up (not Shutdown or Closed).
  3638  func (s *Server) trackListener(ln *net.Listener, add bool) bool {
  3639  	s.mu.Lock()
  3640  	defer s.mu.Unlock()
  3641  	if s.listeners == nil {
  3642  		s.listeners = make(map[*net.Listener]struct{})
  3643  	}
  3644  	if add {
  3645  		if s.shuttingDown() {
  3646  			return false
  3647  		}
  3648  		s.listeners[ln] = struct{}{}
  3649  		s.listenerGroup.Add(1)
  3650  	} else {
  3651  		delete(s.listeners, ln)
  3652  		s.listenerGroup.Done()
  3653  	}
  3654  	return true
  3655  }
  3656  
  3657  func (s *Server) trackConn(c *conn, add bool) {
  3658  	s.mu.Lock()
  3659  	defer s.mu.Unlock()
  3660  	if s.activeConn == nil {
  3661  		s.activeConn = make(map[*conn]struct{})
  3662  	}
  3663  	if add {
  3664  		s.activeConn[c] = struct{}{}
  3665  	} else {
  3666  		delete(s.activeConn, c)
  3667  	}
  3668  }
  3669  
  3670  func (s *Server) idleTimeout() time.Duration {
  3671  	if s.IdleTimeout != 0 {
  3672  		return s.IdleTimeout
  3673  	}
  3674  	return s.ReadTimeout
  3675  }
  3676  
  3677  func (s *Server) readHeaderTimeout() time.Duration {
  3678  	if s.ReadHeaderTimeout != 0 {
  3679  		return s.ReadHeaderTimeout
  3680  	}
  3681  	return s.ReadTimeout
  3682  }
  3683  
  3684  func (s *Server) doKeepAlives() bool {
  3685  	return !s.disableKeepAlives.Load() && !s.shuttingDown()
  3686  }
  3687  
  3688  func (s *Server) shuttingDown() bool {
  3689  	return s.inShutdown.Load()
  3690  }
  3691  
  3692  // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
  3693  // By default, keep-alives are always enabled. Only very
  3694  // resource-constrained environments or servers in the process of
  3695  // shutting down should disable them.
  3696  func (s *Server) SetKeepAlivesEnabled(v bool) {
  3697  	if v {
  3698  		s.disableKeepAlives.Store(false)
  3699  		return
  3700  	}
  3701  	s.disableKeepAlives.Store(true)
  3702  
  3703  	// Close idle HTTP/1 conns:
  3704  	s.closeIdleConns()
  3705  
  3706  	// TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
  3707  }
  3708  
  3709  func (s *Server) logf(format string, args ...any) {
  3710  	if s.ErrorLog != nil {
  3711  		s.ErrorLog.Printf(format, args...)
  3712  	} else {
  3713  		log.Printf(format, args...)
  3714  	}
  3715  }
  3716  
  3717  // logf prints to the ErrorLog of the *Server associated with request r
  3718  // via ServerContextKey. If there's no associated server, or if ErrorLog
  3719  // is nil, logging is done via the log package's standard logger.
  3720  func logf(r *Request, format string, args ...any) {
  3721  	s, _ := r.Context().Value(ServerContextKey).(*Server)
  3722  	if s != nil && s.ErrorLog != nil {
  3723  		s.ErrorLog.Printf(format, args...)
  3724  	} else {
  3725  		log.Printf(format, args...)
  3726  	}
  3727  }
  3728  
  3729  // ListenAndServe listens on the TCP network address addr and then calls
  3730  // [Serve] with handler to handle requests on incoming connections.
  3731  // Accepted connections are configured to enable TCP keep-alives.
  3732  //
  3733  // The handler is typically nil, in which case [DefaultServeMux] is used.
  3734  //
  3735  // ListenAndServe always returns a non-nil error.
  3736  func ListenAndServe(addr string, handler Handler) error {
  3737  	server := &Server{Addr: addr, Handler: handler}
  3738  	return server.ListenAndServe()
  3739  }
  3740  
  3741  // ListenAndServeTLS acts identically to [ListenAndServe], except that it
  3742  // expects HTTPS connections. Additionally, files containing a certificate and
  3743  // matching private key for the server must be provided. If the certificate
  3744  // is signed by a certificate authority, the certFile should be the concatenation
  3745  // of the server's certificate, any intermediates, and the CA's certificate.
  3746  func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
  3747  	server := &Server{Addr: addr, Handler: handler}
  3748  	return server.ListenAndServeTLS(certFile, keyFile)
  3749  }
  3750  
  3751  // http3ServerHandler implements an interface in an external library that
  3752  // supports HTTP/3, allowing an external implementation of HTTP/3 to be used
  3753  // via net/http. See https://go.dev/issue/77440 for details.
  3754  //
  3755  // This is currently only used with golang.org/x/net/internal/http3, to allow
  3756  // us to test our HTTP/3 implementation againts tests in net/http. HTTP/3 is
  3757  // not yet accessible to end-users.
  3758  type http3ServerHandler struct {
  3759  	handler     serverHandler
  3760  	tlsConfig   *tls.Config
  3761  	baseCtx     context.Context
  3762  	errc        chan error
  3763  	shutdownCtx context.Context
  3764  }
  3765  
  3766  // ServeHTTP ensures that http3ServerHandler implements the Handler interface,
  3767  // and gives an HTTP/3 server implementation access to the net/http handler.
  3768  func (h *http3ServerHandler) ServeHTTP(w ResponseWriter, r *Request) {
  3769  	h.handler.ServeHTTP(w, r)
  3770  }
  3771  
  3772  // Addr gives an HTTP/3 server implementation the address that it should listen
  3773  // on.
  3774  func (h *http3ServerHandler) Addr() string {
  3775  	return h.handler.srv.Addr
  3776  }
  3777  
  3778  // TLSConfig gives an HTTP/3 server implementation the *tls.Config that it
  3779  // should use.
  3780  func (h *http3ServerHandler) TLSConfig() *tls.Config {
  3781  	return h.tlsConfig
  3782  }
  3783  
  3784  // BaseContext gives an HTTP/3 server implementation the base context to use
  3785  // for server requests.
  3786  func (h *http3ServerHandler) BaseContext() context.Context {
  3787  	return h.baseCtx
  3788  }
  3789  
  3790  // ListenErrHook should be called by an HTTP/3 server implementation to
  3791  // propagate any error it encounters when trying to listen, if any, to
  3792  // net/http.
  3793  func (h *http3ServerHandler) ListenErrHook(err error) {
  3794  	h.errc <- err
  3795  }
  3796  
  3797  // ShutdownContext gives an HTTP/3 server implementation the context that is
  3798  // used when [Server.Shutdown] is called. This allows an HTTP/3 server
  3799  // implementation to know how long it can take to gracefully shutdown in the
  3800  // function it registers with [Server.RegisterOnShutdown]. Callers must not use
  3801  // this method for any other purpose.
  3802  func (h *http3ServerHandler) ShutdownContext() context.Context {
  3803  	return h.shutdownCtx
  3804  }
  3805  
  3806  // ListenAndServeTLS listens on the TCP network address s.Addr and
  3807  // then calls [ServeTLS] to handle requests on incoming TLS connections.
  3808  // Accepted connections are configured to enable TCP keep-alives.
  3809  //
  3810  // Filenames containing a certificate and matching private key for the
  3811  // server must be provided if neither the [Server]'s TLSConfig.Certificates
  3812  // nor TLSConfig.GetCertificate are populated. If the certificate is
  3813  // signed by a certificate authority, the certFile should be the
  3814  // concatenation of the server's certificate, any intermediates, and
  3815  // the CA's certificate.
  3816  //
  3817  // If s.Addr is blank, ":https" is used.
  3818  //
  3819  // ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or
  3820  // [Server.Close], the returned error is [ErrServerClosed].
  3821  func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {
  3822  	if s.shuttingDown() {
  3823  		return ErrServerClosed
  3824  	}
  3825  	addr := s.Addr
  3826  	if addr == "" {
  3827  		addr = ":https"
  3828  	}
  3829  
  3830  	p := s.protocols()
  3831  	if p.http3() {
  3832  		fn, ok := s.TLSNextProto["http/3"]
  3833  		if !ok {
  3834  			return errors.New("http: Server.Protocols contains HTTP3, but Server does not support HTTP/3")
  3835  		}
  3836  		config, err := s.setupTLSConfig(certFile, keyFile, []string{"h3"})
  3837  		if err != nil {
  3838  			return err
  3839  		}
  3840  		errc := make(chan error, 1)
  3841  		s.mu.Lock()
  3842  		s.h3 = &http3ServerHandler{
  3843  			handler:   serverHandler{s},
  3844  			tlsConfig: config,
  3845  			baseCtx:   context.WithValue(context.Background(), ServerContextKey, s),
  3846  			errc:      errc,
  3847  		}
  3848  		s.mu.Unlock()
  3849  		go fn(s, nil, s.h3)
  3850  		if err := <-errc; err != nil {
  3851  			return err
  3852  		}
  3853  	}
  3854  
  3855  	// Only start a TCP listener if HTTP/1 or HTTP/2 is used.
  3856  	if !p.HTTP1() && !p.HTTP2() && !p.UnencryptedHTTP2() {
  3857  		return nil
  3858  	}
  3859  	ln, err := net.Listen("tcp", addr)
  3860  	if err != nil {
  3861  		return err
  3862  	}
  3863  	defer ln.Close()
  3864  	return s.ServeTLS(ln, certFile, keyFile)
  3865  }
  3866  
  3867  // setupHTTP2_ServeTLS conditionally configures HTTP/2 on
  3868  // s and reports whether there was an error setting it up. If it is
  3869  // not configured for policy reasons, nil is returned.
  3870  func (s *Server) setupHTTP2_ServeTLS() error {
  3871  	s.nextProtoOnce.Do(s.onceSetNextProtoDefaults)
  3872  	return s.nextProtoErr
  3873  }
  3874  
  3875  // setupHTTP2_Serve is called from (*Server).Serve and conditionally
  3876  // configures HTTP/2 on s using a more conservative policy than
  3877  // setupHTTP2_ServeTLS because Serve is called after tls.Listen,
  3878  // and may be called concurrently. See shouldConfigureHTTP2ForServe.
  3879  //
  3880  // The tests named TestTransportAutomaticHTTP2* and
  3881  // TestConcurrentServerServe in server_test.go demonstrate some
  3882  // of the supported use cases and motivations.
  3883  func (s *Server) setupHTTP2_Serve() error {
  3884  	s.nextProtoOnce.Do(s.onceSetNextProtoDefaults_Serve)
  3885  	return s.nextProtoErr
  3886  }
  3887  
  3888  func (s *Server) onceSetNextProtoDefaults_Serve() {
  3889  	if s.shouldConfigureHTTP2ForServe() {
  3890  		s.onceSetNextProtoDefaults()
  3891  	}
  3892  }
  3893  
  3894  var http2server = godebug.New("http2server")
  3895  
  3896  // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
  3897  // configured otherwise. (by setting s.TLSNextProto non-nil)
  3898  // It must only be called via s.nextProtoOnce (use s.setupHTTP2_*).
  3899  func (s *Server) onceSetNextProtoDefaults() {
  3900  	if omitBundledHTTP2 {
  3901  		return
  3902  	}
  3903  	p := s.protocols()
  3904  	if !p.HTTP2() && !p.UnencryptedHTTP2() {
  3905  		return
  3906  	}
  3907  	if http2server.Value() == "0" {
  3908  		http2server.IncNonDefault()
  3909  		return
  3910  	}
  3911  	if _, ok := s.TLSNextProto["h2"]; ok {
  3912  		// TLSNextProto already contains an HTTP/2 implementation.
  3913  		// The user probably called golang.org/x/net/http2.ConfigureServer
  3914  		// to add it.
  3915  		return
  3916  	}
  3917  	s.configureHTTP2()
  3918  }
  3919  
  3920  // TimeoutHandler returns a [Handler] that runs h with the given time limit.
  3921  //
  3922  // The new Handler calls h.ServeHTTP to handle each request, but if a
  3923  // call runs for longer than its time limit, the handler responds with
  3924  // a 503 Service Unavailable error and the given message in its body.
  3925  // (If msg is empty, a suitable default message will be sent.)
  3926  // After such a timeout, writes by h to its [ResponseWriter] will return
  3927  // [ErrHandlerTimeout].
  3928  //
  3929  // TimeoutHandler supports the [Pusher] interface but does not support
  3930  // the [Hijacker] or [Flusher] interfaces.
  3931  func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
  3932  	return &timeoutHandler{
  3933  		handler: h,
  3934  		body:    msg,
  3935  		dt:      dt,
  3936  	}
  3937  }
  3938  
  3939  // ErrHandlerTimeout is returned on [ResponseWriter] Write calls
  3940  // in handlers which have timed out.
  3941  var ErrHandlerTimeout = errors.New("http: Handler timeout")
  3942  
  3943  type timeoutHandler struct {
  3944  	handler Handler
  3945  	body    string
  3946  	dt      time.Duration
  3947  
  3948  	// When set, no context will be created and this context will
  3949  	// be used instead.
  3950  	testContext context.Context
  3951  }
  3952  
  3953  func (h *timeoutHandler) errorBody() string {
  3954  	if h.body != "" {
  3955  		return h.body
  3956  	}
  3957  	return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
  3958  }
  3959  
  3960  func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
  3961  	ctx := h.testContext
  3962  	if ctx == nil {
  3963  		var cancelCtx context.CancelFunc
  3964  		ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
  3965  		defer cancelCtx()
  3966  	}
  3967  	r = r.WithContext(ctx)
  3968  	done := make(chan struct{})
  3969  	tw := &timeoutWriter{
  3970  		w:   w,
  3971  		h:   make(Header),
  3972  		req: r,
  3973  	}
  3974  	panicChan := make(chan any, 1)
  3975  	go func() {
  3976  		defer func() {
  3977  			if p := recover(); p != nil {
  3978  				panicChan <- p
  3979  			}
  3980  		}()
  3981  		h.handler.ServeHTTP(tw, r)
  3982  		close(done)
  3983  	}()
  3984  	select {
  3985  	case p := <-panicChan:
  3986  		panic(p)
  3987  	case <-done:
  3988  		tw.mu.Lock()
  3989  		defer tw.mu.Unlock()
  3990  		dst := w.Header()
  3991  		maps.Copy(dst, tw.h)
  3992  		if !tw.wroteHeader {
  3993  			tw.code = StatusOK
  3994  		}
  3995  		w.WriteHeader(tw.code)
  3996  		w.Write(tw.wbuf.Bytes())
  3997  	case <-ctx.Done():
  3998  		tw.mu.Lock()
  3999  		defer tw.mu.Unlock()
  4000  		switch err := ctx.Err(); err {
  4001  		case context.DeadlineExceeded:
  4002  			w.WriteHeader(StatusServiceUnavailable)
  4003  			io.WriteString(w, h.errorBody())
  4004  			tw.err = ErrHandlerTimeout
  4005  		default:
  4006  			w.WriteHeader(StatusServiceUnavailable)
  4007  			tw.err = err
  4008  		}
  4009  	}
  4010  }
  4011  
  4012  type timeoutWriter struct {
  4013  	w    ResponseWriter
  4014  	h    Header
  4015  	wbuf bytes.Buffer
  4016  	req  *Request
  4017  
  4018  	mu          sync.Mutex
  4019  	err         error
  4020  	wroteHeader bool
  4021  	code        int
  4022  }
  4023  
  4024  var _ Pusher = (*timeoutWriter)(nil)
  4025  
  4026  // Push implements the [Pusher] interface.
  4027  func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
  4028  	if pusher, ok := tw.w.(Pusher); ok {
  4029  		return pusher.Push(target, opts)
  4030  	}
  4031  	return ErrNotSupported
  4032  }
  4033  
  4034  func (tw *timeoutWriter) Header() Header { return tw.h }
  4035  
  4036  func (tw *timeoutWriter) Write(p []byte) (int, error) {
  4037  	tw.mu.Lock()
  4038  	defer tw.mu.Unlock()
  4039  	if tw.err != nil {
  4040  		return 0, tw.err
  4041  	}
  4042  	if !tw.wroteHeader {
  4043  		tw.writeHeaderLocked(StatusOK)
  4044  	}
  4045  	return tw.wbuf.Write(p)
  4046  }
  4047  
  4048  func (tw *timeoutWriter) writeHeaderLocked(code int) {
  4049  	checkWriteHeaderCode(code)
  4050  
  4051  	switch {
  4052  	case tw.err != nil:
  4053  		return
  4054  	case tw.wroteHeader:
  4055  		if tw.req != nil {
  4056  			caller := relevantCaller()
  4057  			logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
  4058  		}
  4059  	default:
  4060  		tw.wroteHeader = true
  4061  		tw.code = code
  4062  	}
  4063  }
  4064  
  4065  func (tw *timeoutWriter) WriteHeader(code int) {
  4066  	tw.mu.Lock()
  4067  	defer tw.mu.Unlock()
  4068  	tw.writeHeaderLocked(code)
  4069  }
  4070  
  4071  // onceCloseListener wraps a net.Listener, protecting it from
  4072  // multiple Close calls.
  4073  type onceCloseListener struct {
  4074  	net.Listener
  4075  	once     sync.Once
  4076  	closeErr error
  4077  }
  4078  
  4079  func (oc *onceCloseListener) Close() error {
  4080  	oc.once.Do(oc.close)
  4081  	return oc.closeErr
  4082  }
  4083  
  4084  func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
  4085  
  4086  // globalOptionsHandler responds to "OPTIONS *" requests.
  4087  type globalOptionsHandler struct{}
  4088  
  4089  func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
  4090  	w.Header().Set("Content-Length", "0")
  4091  	if r.ContentLength != 0 {
  4092  		// Read up to 4KB of OPTIONS body (as mentioned in the
  4093  		// spec as being reserved for future use), but anything
  4094  		// over that is considered a waste of server resources
  4095  		// (or an attack) and we abort and close the connection,
  4096  		// courtesy of MaxBytesReader's EOF behavior.
  4097  		mb := MaxBytesReader(w, r.Body, 4<<10)
  4098  		io.Copy(io.Discard, mb)
  4099  	}
  4100  }
  4101  
  4102  // initALPNRequest is an HTTP handler that initializes certain
  4103  // uninitialized fields in its *Request. Such partially-initialized
  4104  // Requests come from ALPN protocol handlers.
  4105  type initALPNRequest struct {
  4106  	ctx context.Context
  4107  	c   *tls.Conn
  4108  	h   serverHandler
  4109  }
  4110  
  4111  // BaseContext is an exported but unadvertised [http.Handler] method
  4112  // recognized by x/net/http2 to pass down a context; the TLSNextProto
  4113  // API predates context support so we shoehorn through the only
  4114  // interface we have available.
  4115  func (h initALPNRequest) BaseContext() context.Context { return h.ctx }
  4116  
  4117  func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
  4118  	if req.TLS == nil {
  4119  		req.TLS = &tls.ConnectionState{}
  4120  		*req.TLS = h.c.ConnectionState()
  4121  	}
  4122  	if req.Body == nil {
  4123  		req.Body = NoBody
  4124  	}
  4125  	if req.RemoteAddr == "" {
  4126  		req.RemoteAddr = h.c.RemoteAddr().String()
  4127  	}
  4128  	h.h.ServeHTTP(rw, req)
  4129  }
  4130  
  4131  // loggingConn is used for debugging.
  4132  type loggingConn struct {
  4133  	name string
  4134  	net.Conn
  4135  }
  4136  
  4137  var (
  4138  	uniqNameMu   sync.Mutex
  4139  	uniqNameNext = make(map[string]int)
  4140  )
  4141  
  4142  func newLoggingConn(baseName string, c net.Conn) net.Conn {
  4143  	uniqNameMu.Lock()
  4144  	defer uniqNameMu.Unlock()
  4145  	uniqNameNext[baseName]++
  4146  	return &loggingConn{
  4147  		name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
  4148  		Conn: c,
  4149  	}
  4150  }
  4151  
  4152  func (c *loggingConn) Write(p []byte) (n int, err error) {
  4153  	log.Printf("%s.Write(%d) = ....", c.name, len(p))
  4154  	n, err = c.Conn.Write(p)
  4155  	log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
  4156  	return
  4157  }
  4158  
  4159  func (c *loggingConn) Read(p []byte) (n int, err error) {
  4160  	log.Printf("%s.Read(%d) = ....", c.name, len(p))
  4161  	n, err = c.Conn.Read(p)
  4162  	log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
  4163  	return
  4164  }
  4165  
  4166  func (c *loggingConn) Close() (err error) {
  4167  	log.Printf("%s.Close() = ...", c.name)
  4168  	err = c.Conn.Close()
  4169  	log.Printf("%s.Close() = %v", c.name, err)
  4170  	return
  4171  }
  4172  
  4173  // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
  4174  // It only contains one field (and a pointer field at that), so it
  4175  // fits in an interface value without an extra allocation.
  4176  type checkConnErrorWriter struct {
  4177  	c *conn
  4178  }
  4179  
  4180  func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
  4181  	n, err = w.c.rwc.Write(p)
  4182  	if err != nil && w.c.werr == nil {
  4183  		w.c.werr = err
  4184  		w.c.cancelCtx()
  4185  	}
  4186  	return
  4187  }
  4188  
  4189  func numLeadingCRorLF(v []byte) (n int) {
  4190  	for _, b := range v {
  4191  		if b == '\r' || b == '\n' {
  4192  			n++
  4193  			continue
  4194  		}
  4195  		break
  4196  	}
  4197  	return
  4198  }
  4199  
  4200  // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
  4201  // looks like it might've been a misdirected plaintext HTTP request.
  4202  func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
  4203  	switch string(hdr[:]) {
  4204  	case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
  4205  		return true
  4206  	}
  4207  	return false
  4208  }
  4209  
  4210  // MaxBytesHandler returns a [Handler] that runs h with its [ResponseWriter] and [Request.Body] wrapped by a MaxBytesReader.
  4211  func MaxBytesHandler(h Handler, n int64) Handler {
  4212  	return HandlerFunc(func(w ResponseWriter, r *Request) {
  4213  		r2 := *r
  4214  		r2.Body = MaxBytesReader(w, r.Body, n)
  4215  		h.ServeHTTP(w, &r2)
  4216  	})
  4217  }
  4218  

View as plain text