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 connStater, ok := c.rwc.(connectionStater); 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  		type handshakeContexter interface {
  1958  			HandshakeContext(ctx context.Context) error
  1959  		}
  1960  		var err error
  1961  		if handshaker, ok := c.rwc.(handshakeContexter); ok {
  1962  			err = handshaker.HandshakeContext(ctx)
  1963  		}
  1964  		if err != nil {
  1965  			// If the handshake failed due to the client not speaking
  1966  			// TLS, assume they're speaking plaintext HTTP and write a
  1967  			// 400 response on the TLS conn's underlying net.Conn.
  1968  			var reason string
  1969  			if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) {
  1970  				io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n")
  1971  				re.Conn.Close()
  1972  				reason = "client sent an HTTP request to an HTTPS server"
  1973  			} else {
  1974  				reason = err.Error()
  1975  			}
  1976  			c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), reason)
  1977  			return
  1978  		}
  1979  		// Restore Conn-level deadlines.
  1980  		if tlsTO > 0 {
  1981  			c.rwc.SetReadDeadline(time.Time{})
  1982  			c.rwc.SetWriteDeadline(time.Time{})
  1983  		}
  1984  		c.tlsState = new(tls.ConnectionState)
  1985  		*c.tlsState = connStater.ConnectionState()
  1986  		proto := c.tlsState.NegotiatedProtocol
  1987  		if proto == "h2" && c.server.h2 != nil {
  1988  			// net/http/internal/http2 path.
  1989  			//
  1990  			// Mark freshly created HTTP/2 as active and prevent any server state hooks
  1991  			// from being run on these connections. This prevents closeIdleConns from
  1992  			// closing such connections. See issue https://golang.org/issue/39776.
  1993  			c.setState(c.rwc, StateActive, skipHooks)
  1994  			const sawClientPreface = false
  1995  			c.server.serveHTTP2Conn(ctx, c.rwc, serverHandler{c.server}, sawClientPreface)
  1996  			return
  1997  		}
  1998  		tlsConn, tlsConnOK := c.rwc.(*tls.Conn)
  1999  		if validNextProto(proto) && tlsConnOK {
  2000  			// Legacy TLSNextProto path.
  2001  			if fn := c.server.TLSNextProto[proto]; fn != nil {
  2002  				h := initALPNRequest{ctx, tlsConn, serverHandler{c.server}}
  2003  				// Mark freshly created HTTP/2 as active (see above).
  2004  				c.setState(c.rwc, StateActive, skipHooks)
  2005  				fn(c.server, tlsConn, h)
  2006  			}
  2007  			return
  2008  		}
  2009  	}
  2010  
  2011  	// HTTP/1.x or unencrypted HTTP/2.
  2012  
  2013  	// Set Request.TLS if the conn is not a *tls.Conn, but implements ConnectionState.
  2014  	if c.tlsState == nil {
  2015  		if tc, ok := c.rwc.(connectionStater); ok {
  2016  			c.tlsState = new(tls.ConnectionState)
  2017  			*c.tlsState = tc.ConnectionState()
  2018  		}
  2019  	}
  2020  
  2021  	ctx, cancelCtx := context.WithCancel(ctx)
  2022  	c.cancelCtx = cancelCtx
  2023  	defer cancelCtx()
  2024  
  2025  	c.r = &connReader{conn: c, rwc: c.rwc}
  2026  	c.bufr = newBufioReader(c.r)
  2027  	c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10)
  2028  
  2029  	protos := c.server.protocols()
  2030  	if c.tlsState == nil && protos.UnencryptedHTTP2() {
  2031  		if c.maybeServeUnencryptedHTTP2(ctx) {
  2032  			return
  2033  		}
  2034  	}
  2035  	if !protos.HTTP1() {
  2036  		return
  2037  	}
  2038  
  2039  	// HTTP/1.x from here on.
  2040  
  2041  	for {
  2042  		w, err := c.readRequest(ctx)
  2043  		if c.r.remain != c.server.initialReadLimitSize() {
  2044  			// If we read any bytes off the wire, we're active.
  2045  			c.setState(c.rwc, StateActive, runHooks)
  2046  		}
  2047  		if c.server.shuttingDown() {
  2048  			return
  2049  		}
  2050  		if err != nil {
  2051  			const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n"
  2052  
  2053  			switch {
  2054  			case err == errTooLarge:
  2055  				// Their HTTP client may or may not be
  2056  				// able to read this if we're
  2057  				// responding to them and hanging up
  2058  				// while they're still writing their
  2059  				// request. Undefined behavior.
  2060  				const publicErr = "431 Request Header Fields Too Large"
  2061  				fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
  2062  				c.closeWriteAndWait()
  2063  				return
  2064  
  2065  			case isUnsupportedTEError(err):
  2066  				// Respond as per RFC 7230 Section 3.3.1 which says,
  2067  				//      A server that receives a request message with a
  2068  				//      transfer coding it does not understand SHOULD
  2069  				//      respond with 501 (Unimplemented).
  2070  				code := StatusNotImplemented
  2071  
  2072  				// We purposefully aren't echoing back the transfer-encoding's value,
  2073  				// so as to mitigate the risk of cross side scripting by an attacker.
  2074  				fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders)
  2075  				return
  2076  
  2077  			case isCommonNetReadError(err):
  2078  				return // don't reply
  2079  
  2080  			default:
  2081  				if v, ok := err.(statusError); ok {
  2082  					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)
  2083  					return
  2084  				}
  2085  				const publicErr = "400 Bad Request"
  2086  				fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr)
  2087  				return
  2088  			}
  2089  		}
  2090  
  2091  		// Expect 100 Continue support
  2092  		req := w.req
  2093  		if req.expectsContinue() {
  2094  			if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 {
  2095  				// Wrap the Body reader with one that replies on the connection
  2096  				req.Body = &expectContinueReader{readCloser: req.Body, resp: w}
  2097  				w.canWriteContinue.Store(true)
  2098  			}
  2099  		} else if req.Header.get("Expect") != "" {
  2100  			w.sendExpectationFailed()
  2101  			return
  2102  		}
  2103  
  2104  		c.curReq.Store(w)
  2105  
  2106  		if requestBodyRemains(req.Body) {
  2107  			registerOnHitEOF(req.Body, w.conn.r.startBackgroundRead)
  2108  		} else {
  2109  			w.conn.r.startBackgroundRead()
  2110  		}
  2111  
  2112  		// HTTP cannot have multiple simultaneous active requests.[*]
  2113  		// Until the server replies to this request, it can't read another,
  2114  		// so we might as well run the handler in this goroutine.
  2115  		// [*] Not strictly true: HTTP pipelining. We could let them all process
  2116  		// in parallel even if their responses need to be serialized.
  2117  		// But we're not going to implement HTTP pipelining because it
  2118  		// was never deployed in the wild and the answer is HTTP/2.
  2119  		inFlightResponse = w
  2120  		serverHandler{c.server}.ServeHTTP(w, w.req)
  2121  		inFlightResponse = nil
  2122  		w.cancelCtx()
  2123  		if c.hijacked() {
  2124  			c.r.releaseConn()
  2125  			return
  2126  		}
  2127  		w.finishRequest()
  2128  		c.rwc.SetWriteDeadline(time.Time{})
  2129  		if !w.shouldReuseConnection() {
  2130  			if w.requestBodyLimitHit || w.closedRequestBodyEarly() {
  2131  				c.closeWriteAndWait()
  2132  			}
  2133  			return
  2134  		}
  2135  		c.setState(c.rwc, StateIdle, runHooks)
  2136  		c.curReq.Store(nil)
  2137  
  2138  		if !w.conn.server.doKeepAlives() {
  2139  			// We're in shutdown mode. We might've replied
  2140  			// to the user without "Connection: close" and
  2141  			// they might think they can send another
  2142  			// request, but such is life with HTTP/1.1.
  2143  			return
  2144  		}
  2145  
  2146  		if d := c.server.idleTimeout(); d > 0 {
  2147  			c.rwc.SetReadDeadline(time.Now().Add(d))
  2148  		} else {
  2149  			c.rwc.SetReadDeadline(time.Time{})
  2150  		}
  2151  
  2152  		// Wait for the connection to become readable again before trying to
  2153  		// read the next request. This prevents a ReadHeaderTimeout or
  2154  		// ReadTimeout from starting until the first bytes of the next request
  2155  		// have been received.
  2156  		if _, err := c.bufr.Peek(4); err != nil {
  2157  			return
  2158  		}
  2159  
  2160  		c.rwc.SetReadDeadline(time.Time{})
  2161  	}
  2162  }
  2163  
  2164  // unencryptedHTTP2Request is an HTTP handler that initializes
  2165  // certain uninitialized fields in its *Request.
  2166  //
  2167  // It's the unencrypted version of initALPNRequest.
  2168  type unencryptedHTTP2Request struct {
  2169  	ctx context.Context
  2170  	c   net.Conn
  2171  	h   serverHandler
  2172  }
  2173  
  2174  func (h unencryptedHTTP2Request) BaseContext() context.Context { return h.ctx }
  2175  
  2176  func (h unencryptedHTTP2Request) ServeHTTP(rw ResponseWriter, req *Request) {
  2177  	if req.Body == nil {
  2178  		req.Body = NoBody
  2179  	}
  2180  	if req.RemoteAddr == "" {
  2181  		req.RemoteAddr = h.c.RemoteAddr().String()
  2182  	}
  2183  	h.h.ServeHTTP(rw, req)
  2184  }
  2185  
  2186  // unencryptedNetConnInTLSConn is used to pass an unencrypted net.Conn to
  2187  // functions that only accept a *tls.Conn.
  2188  type unencryptedNetConnInTLSConn struct {
  2189  	net.Conn // panic on all net.Conn methods
  2190  	conn     net.Conn
  2191  }
  2192  
  2193  func (c unencryptedNetConnInTLSConn) UnencryptedNetConn() net.Conn {
  2194  	return c.conn
  2195  }
  2196  
  2197  func unencryptedTLSConn(c net.Conn) *tls.Conn {
  2198  	return tls.Client(unencryptedNetConnInTLSConn{conn: c}, nil)
  2199  }
  2200  
  2201  // TLSNextProto key to use for unencrypted HTTP/2 connections.
  2202  // Not actually a TLS-negotiated protocol.
  2203  const nextProtoUnencryptedHTTP2 = "unencrypted_http2"
  2204  
  2205  func (c *conn) maybeServeUnencryptedHTTP2(ctx context.Context) bool {
  2206  	var nextFunc func(*Server, *tls.Conn, Handler)
  2207  	if c.server.h2 == nil {
  2208  		var ok bool
  2209  		nextFunc, ok = c.server.TLSNextProto[nextProtoUnencryptedHTTP2]
  2210  		if !ok {
  2211  			return false
  2212  		}
  2213  	}
  2214  	hasPreface := func(c *conn, preface []byte) bool {
  2215  		c.r.setReadLimit(int64(len(preface)) - int64(c.bufr.Buffered()))
  2216  		got, err := c.bufr.Peek(len(preface))
  2217  		c.r.setInfiniteReadLimit()
  2218  		return err == nil && bytes.Equal(got, preface)
  2219  	}
  2220  	if !hasPreface(c, []byte("PRI * HTTP/2.0")) {
  2221  		return false
  2222  	}
  2223  	if !hasPreface(c, []byte("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")) {
  2224  		return false
  2225  	}
  2226  	c.setState(c.rwc, StateActive, skipHooks)
  2227  	if c.server.h2 != nil {
  2228  		const sawClientPreface = true
  2229  		c.server.serveHTTP2Conn(ctx, c.rwc, serverHandler{c.server}, sawClientPreface)
  2230  	} else {
  2231  		h := unencryptedHTTP2Request{ctx, c.rwc, serverHandler{c.server}}
  2232  		nextFunc(c.server, unencryptedTLSConn(c.rwc), h)
  2233  	}
  2234  	return true
  2235  }
  2236  
  2237  func (w *response) sendExpectationFailed() {
  2238  	// TODO(bradfitz): let ServeHTTP handlers handle
  2239  	// requests with non-standard expectation[s]? Seems
  2240  	// theoretical at best, and doesn't fit into the
  2241  	// current ServeHTTP model anyway. We'd need to
  2242  	// make the ResponseWriter an optional
  2243  	// "ExpectReplier" interface or something.
  2244  	//
  2245  	// For now we'll just obey RFC 7231 5.1.1 which says
  2246  	// "A server that receives an Expect field-value other
  2247  	// than 100-continue MAY respond with a 417 (Expectation
  2248  	// Failed) status code to indicate that the unexpected
  2249  	// expectation cannot be met."
  2250  	w.Header().Set("Connection", "close")
  2251  	w.WriteHeader(StatusExpectationFailed)
  2252  	w.finishRequest()
  2253  }
  2254  
  2255  // Hijack implements the [Hijacker.Hijack] method. Our response is both a [ResponseWriter]
  2256  // and a [Hijacker].
  2257  func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) {
  2258  	if w.handlerDone.Load() {
  2259  		panic("net/http: Hijack called after ServeHTTP finished")
  2260  	}
  2261  	w.disableWriteContinue()
  2262  	if w.wroteHeader {
  2263  		w.cw.flush()
  2264  	}
  2265  
  2266  	c := w.conn
  2267  	c.mu.Lock()
  2268  	defer c.mu.Unlock()
  2269  
  2270  	// Release the bufioWriter that writes to the chunk writer, it is not
  2271  	// used after a connection has been hijacked.
  2272  	rwc, buf, err = c.hijackLocked()
  2273  	if err == nil {
  2274  		putBufioWriter(w.w)
  2275  		w.w = nil
  2276  	}
  2277  	return rwc, buf, err
  2278  }
  2279  
  2280  func (w *response) CloseNotify() <-chan bool {
  2281  	w.lazyCloseNotifyMu.Lock()
  2282  	defer w.lazyCloseNotifyMu.Unlock()
  2283  	if w.handlerDone.Load() {
  2284  		panic("net/http: CloseNotify called after ServeHTTP finished")
  2285  	}
  2286  	if w.closeNotifyCh == nil {
  2287  		w.closeNotifyCh = make(chan bool, 1)
  2288  		if w.closeNotifyTriggered {
  2289  			w.closeNotifyCh <- true // action prior closeNotify call
  2290  		}
  2291  	}
  2292  	return w.closeNotifyCh
  2293  }
  2294  
  2295  func (w *response) closeNotify() {
  2296  	w.lazyCloseNotifyMu.Lock()
  2297  	defer w.lazyCloseNotifyMu.Unlock()
  2298  	if w.closeNotifyTriggered {
  2299  		return // already triggered
  2300  	}
  2301  	w.closeNotifyTriggered = true
  2302  	if w.closeNotifyCh != nil {
  2303  		w.closeNotifyCh <- true
  2304  	}
  2305  }
  2306  
  2307  func registerOnHitEOF(rc io.ReadCloser, fn func()) {
  2308  	switch v := rc.(type) {
  2309  	case *expectContinueReader:
  2310  		registerOnHitEOF(v.readCloser, fn)
  2311  	case *body:
  2312  		v.registerOnHitEOF(fn)
  2313  	default:
  2314  		panic("unexpected type " + fmt.Sprintf("%T", rc))
  2315  	}
  2316  }
  2317  
  2318  // requestBodyRemains reports whether future calls to Read
  2319  // on rc might yield more data.
  2320  func requestBodyRemains(rc io.ReadCloser) bool {
  2321  	if rc == NoBody {
  2322  		return false
  2323  	}
  2324  	switch v := rc.(type) {
  2325  	case *expectContinueReader:
  2326  		return requestBodyRemains(v.readCloser)
  2327  	case *body:
  2328  		return v.bodyRemains()
  2329  	default:
  2330  		panic("unexpected type " + fmt.Sprintf("%T", rc))
  2331  	}
  2332  }
  2333  
  2334  // The HandlerFunc type is an adapter to allow the use of
  2335  // ordinary functions as HTTP handlers. If f is a function
  2336  // with the appropriate signature, HandlerFunc(f) is a
  2337  // [Handler] that calls f.
  2338  type HandlerFunc func(ResponseWriter, *Request)
  2339  
  2340  // ServeHTTP calls f(w, r).
  2341  func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) {
  2342  	f(w, r)
  2343  }
  2344  
  2345  // Helper handlers
  2346  
  2347  // Error replies to the request with the specified error message and HTTP code.
  2348  // It does not otherwise end the request; the caller should ensure no further
  2349  // writes are done to w.
  2350  // The error message should be plain text.
  2351  //
  2352  // Error deletes the Content-Length header,
  2353  // sets Content-Type to “text/plain; charset=utf-8”,
  2354  // and sets X-Content-Type-Options to “nosniff”.
  2355  // This configures the header properly for the error message,
  2356  // in case the caller had set it up expecting a successful output.
  2357  func Error(w ResponseWriter, error string, code int) {
  2358  	h := w.Header()
  2359  
  2360  	// Delete the Content-Length header, which might be for some other content.
  2361  	// Assuming the error string fits in the writer's buffer, we'll figure
  2362  	// out the correct Content-Length for it later.
  2363  	//
  2364  	// We don't delete Content-Encoding, because some middleware sets
  2365  	// Content-Encoding: gzip and wraps the ResponseWriter to compress on-the-fly.
  2366  	// See https://go.dev/issue/66343.
  2367  	h.Del("Content-Length")
  2368  
  2369  	// There might be content type already set, but we reset it to
  2370  	// text/plain for the error message.
  2371  	h.Set("Content-Type", "text/plain; charset=utf-8")
  2372  	h.Set("X-Content-Type-Options", "nosniff")
  2373  	w.WriteHeader(code)
  2374  	fmt.Fprintln(w, error)
  2375  }
  2376  
  2377  // NotFound replies to the request with an HTTP 404 not found error.
  2378  func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) }
  2379  
  2380  // NotFoundHandler returns a simple request handler
  2381  // that replies to each request with a “404 page not found” reply.
  2382  func NotFoundHandler() Handler { return HandlerFunc(NotFound) }
  2383  
  2384  // StripPrefix returns a handler that serves HTTP requests by removing the
  2385  // given prefix from the request URL's Path (and RawPath if set) and invoking
  2386  // the handler h. StripPrefix handles a request for a path that doesn't begin
  2387  // with prefix by replying with an HTTP 404 not found error. The prefix must
  2388  // match exactly: if the prefix in the request contains escaped characters
  2389  // the reply is also an HTTP 404 not found error.
  2390  func StripPrefix(prefix string, h Handler) Handler {
  2391  	if prefix == "" {
  2392  		return h
  2393  	}
  2394  	return HandlerFunc(func(w ResponseWriter, r *Request) {
  2395  		p := strings.TrimPrefix(r.URL.Path, prefix)
  2396  		rp := strings.TrimPrefix(r.URL.RawPath, prefix)
  2397  		if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) {
  2398  			r2 := new(Request)
  2399  			*r2 = *r
  2400  			r2.URL = new(url.URL)
  2401  			*r2.URL = *r.URL
  2402  			r2.URL.Path = p
  2403  			r2.URL.RawPath = rp
  2404  			h.ServeHTTP(w, r2)
  2405  		} else {
  2406  			NotFound(w, r)
  2407  		}
  2408  	})
  2409  }
  2410  
  2411  // Redirect replies to the request with a redirect to url,
  2412  // which may be a path relative to the request path.
  2413  // Any non-ASCII characters in url will be percent-encoded,
  2414  // but existing percent encodings will not be changed.
  2415  //
  2416  // The provided code should be in the 3xx range and is usually
  2417  // [StatusMovedPermanently], [StatusFound] or [StatusSeeOther].
  2418  //
  2419  // If the Content-Type header has not been set, [Redirect] sets it
  2420  // to "text/html; charset=utf-8" and writes a small HTML body.
  2421  // Setting the Content-Type header to any value, including nil,
  2422  // disables that behavior.
  2423  func Redirect(w ResponseWriter, r *Request, url string, code int) {
  2424  	if u, err := urlpkg.Parse(url); err == nil {
  2425  		// If url was relative, make its path absolute by
  2426  		// combining with request path.
  2427  		// The client would probably do this for us,
  2428  		// but doing it ourselves is more reliable.
  2429  		// See RFC 7231, section 7.1.2
  2430  		if u.Scheme == "" && u.Host == "" {
  2431  			oldpath := r.URL.EscapedPath()
  2432  			if oldpath == "" { // should not happen, but avoid a crash if it does
  2433  				oldpath = "/"
  2434  			}
  2435  
  2436  			// no leading http://server
  2437  			if url == "" || url[0] != '/' {
  2438  				// make relative path absolute
  2439  				olddir, _ := path.Split(oldpath)
  2440  				url = olddir + url
  2441  			}
  2442  
  2443  			var query string
  2444  			if i := strings.Index(url, "?"); i != -1 {
  2445  				url, query = url[:i], url[i:]
  2446  			}
  2447  
  2448  			// clean up but preserve trailing slash
  2449  			trailing := strings.HasSuffix(url, "/")
  2450  			url = path.Clean(url)
  2451  			if trailing && !strings.HasSuffix(url, "/") {
  2452  				url += "/"
  2453  			}
  2454  			url += query
  2455  		}
  2456  	}
  2457  
  2458  	h := w.Header()
  2459  
  2460  	// RFC 7231 notes that a short HTML body is usually included in
  2461  	// the response because older user agents may not understand 301/307.
  2462  	// Do it only if the request didn't already have a Content-Type header.
  2463  	_, hadCT := h["Content-Type"]
  2464  
  2465  	h.Set("Location", hexEscapeNonASCII(url))
  2466  	if !hadCT && (r.Method == "GET" || r.Method == "HEAD") {
  2467  		h.Set("Content-Type", "text/html; charset=utf-8")
  2468  	}
  2469  	w.WriteHeader(code)
  2470  
  2471  	// Shouldn't send the body for POST or HEAD; that leaves GET.
  2472  	if !hadCT && r.Method == "GET" {
  2473  		body := "<a href=\"" + htmlEscape(url) + "\">" + StatusText(code) + "</a>.\n"
  2474  		fmt.Fprintln(w, body)
  2475  	}
  2476  }
  2477  
  2478  var htmlReplacer = strings.NewReplacer(
  2479  	"&", "&amp;",
  2480  	"<", "&lt;",
  2481  	">", "&gt;",
  2482  	// "&#34;" is shorter than "&quot;".
  2483  	`"`, "&#34;",
  2484  	// "&#39;" is shorter than "&apos;" and apos was not in HTML until HTML5.
  2485  	"'", "&#39;",
  2486  )
  2487  
  2488  func htmlEscape(s string) string {
  2489  	return htmlReplacer.Replace(s)
  2490  }
  2491  
  2492  // Redirect to a fixed URL
  2493  type redirectHandler struct {
  2494  	url  string
  2495  	code int
  2496  }
  2497  
  2498  func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) {
  2499  	Redirect(w, r, rh.url, rh.code)
  2500  }
  2501  
  2502  // RedirectHandler returns a request handler that redirects
  2503  // each request it receives to the given url using the given
  2504  // status code.
  2505  //
  2506  // The provided code should be in the 3xx range and is usually
  2507  // [StatusMovedPermanently], [StatusFound] or [StatusSeeOther].
  2508  func RedirectHandler(url string, code int) Handler {
  2509  	return &redirectHandler{url, code}
  2510  }
  2511  
  2512  // ServeMux is an HTTP request multiplexer.
  2513  // It matches the URL of each incoming request against a list of registered
  2514  // patterns and calls the handler for the pattern that
  2515  // most closely matches the URL.
  2516  //
  2517  // # Patterns
  2518  //
  2519  // Patterns can match the method, host and path of a request.
  2520  // Some examples:
  2521  //
  2522  //   - "/index.html" matches the path "/index.html" for any host and method.
  2523  //   - "GET /static/" matches a GET request whose path begins with "/static/".
  2524  //   - "example.com/" matches any request to the host "example.com".
  2525  //   - "example.com/{$}" matches requests with host "example.com" and path "/".
  2526  //   - "/b/{bucket}/o/{objectname...}" matches paths whose first segment is "b"
  2527  //     and whose third segment is "o". The name "bucket" denotes the second
  2528  //     segment and "objectname" denotes the remainder of the path.
  2529  //
  2530  // In general, a pattern looks like
  2531  //
  2532  //	[METHOD ][HOST]/[PATH]
  2533  //
  2534  // All three parts are optional; "/" is a valid pattern.
  2535  // If METHOD is present, it must be followed by at least one space or tab.
  2536  //
  2537  // Literal (that is, non-wildcard) parts of a pattern match
  2538  // the corresponding parts of a request case-sensitively.
  2539  //
  2540  // A pattern with no method matches every method. A pattern
  2541  // with the method GET matches both GET and HEAD requests.
  2542  // Otherwise, the method must match exactly.
  2543  //
  2544  // A pattern with no host matches every host.
  2545  // A pattern with a host matches URLs on that host only.
  2546  //
  2547  // A path can include wildcard segments of the form {NAME} or {NAME...}.
  2548  // For example, "/b/{bucket}/o/{objectname...}".
  2549  // The wildcard name must be a valid Go identifier.
  2550  // Wildcards must be full path segments: they must be preceded by a slash and followed by
  2551  // either a slash or the end of the string.
  2552  // For example, "/b_{bucket}" is not a valid pattern.
  2553  //
  2554  // Normally a wildcard matches only a single path segment,
  2555  // ending at the next literal slash (not %2F) in the request URL.
  2556  // But if the "..." is present, then the wildcard matches the remainder of the URL path, including slashes.
  2557  // (Therefore it is invalid for a "..." wildcard to appear anywhere but at the end of a pattern.)
  2558  // The match for a wildcard can be obtained by calling [Request.PathValue] with the wildcard's name.
  2559  // A trailing slash in a path acts as an anonymous "..." wildcard.
  2560  //
  2561  // The special wildcard {$} matches only the end of the URL.
  2562  // For example, the pattern "/{$}" matches only the path "/",
  2563  // whereas the pattern "/" matches every path.
  2564  //
  2565  // For matching, both pattern paths and incoming request paths are unescaped segment by segment.
  2566  // So, for example, the path "/a%2Fb/100%25" is treated as having two segments, "a/b" and "100%".
  2567  // The pattern "/a%2fb/" matches it, but the pattern "/a/b/" does not.
  2568  //
  2569  // # Precedence
  2570  //
  2571  // If two or more patterns match a request, then the most specific pattern takes precedence.
  2572  // A pattern P1 is more specific than P2 if P1 matches a strict subset of P2’s requests;
  2573  // that is, if P2 matches all the requests of P1 and more.
  2574  // If neither is more specific, then the patterns conflict.
  2575  // There is one exception to this rule, for backwards compatibility:
  2576  // if two patterns would otherwise conflict and one has a host while the other does not,
  2577  // then the pattern with the host takes precedence.
  2578  // If a pattern passed to [ServeMux.Handle] or [ServeMux.HandleFunc] conflicts with
  2579  // another pattern that is already registered, those functions panic.
  2580  //
  2581  // As an example of the general rule, "/images/thumbnails/" is more specific than "/images/",
  2582  // so both can be registered.
  2583  // The former matches paths beginning with "/images/thumbnails/"
  2584  // and the latter will match any other path in the "/images/" subtree.
  2585  //
  2586  // As another example, consider the patterns "GET /" and "/index.html":
  2587  // both match a GET request for "/index.html", but the former pattern
  2588  // matches all other GET and HEAD requests, while the latter matches any
  2589  // request for "/index.html" that uses a different method.
  2590  // The patterns conflict.
  2591  //
  2592  // # Trailing-slash redirection
  2593  //
  2594  // Consider a [ServeMux] with a handler for a subtree, registered using a trailing slash or "..." wildcard.
  2595  // If the ServeMux receives a request for the subtree root without a trailing slash,
  2596  // it redirects the request by adding the trailing slash.
  2597  // This behavior can be overridden with a separate registration for the path without
  2598  // the trailing slash or "..." wildcard. For example, registering "/images/" causes ServeMux
  2599  // to redirect a request for "/images" to "/images/", unless "/images" has
  2600  // been registered separately.
  2601  //
  2602  // # Request sanitizing
  2603  //
  2604  // ServeMux also takes care of sanitizing the URL request path and the Host
  2605  // header, stripping the port number and redirecting any request containing . or
  2606  // .. segments or repeated slashes to an equivalent, cleaner URL.
  2607  // Escaped path elements such as "%2e" for "." and "%2f" for "/" are preserved
  2608  // and aren't considered separators for request routing.
  2609  //
  2610  // # Compatibility
  2611  //
  2612  // The pattern syntax and matching behavior of ServeMux changed significantly
  2613  // in Go 1.22. To restore the old behavior, set the GODEBUG environment variable
  2614  // to "httpmuxgo121=1". This setting is read once, at program startup; changes
  2615  // during execution will be ignored.
  2616  //
  2617  // The backwards-incompatible changes include:
  2618  //   - Wildcards are just ordinary literal path segments in 1.21.
  2619  //     For example, the pattern "/{x}" will match only that path in 1.21,
  2620  //     but will match any one-segment path in 1.22.
  2621  //   - In 1.21, no pattern was rejected, unless it was empty or conflicted with an existing pattern.
  2622  //     In 1.22, syntactically invalid patterns will cause [ServeMux.Handle] and [ServeMux.HandleFunc] to panic.
  2623  //     For example, in 1.21, the patterns "/{"  and "/a{x}" match themselves,
  2624  //     but in 1.22 they are invalid and will cause a panic when registered.
  2625  //   - In 1.22, each segment of a pattern is unescaped; this was not done in 1.21.
  2626  //     For example, in 1.22 the pattern "/%61" matches the path "/a" ("%61" being the URL escape sequence for "a"),
  2627  //     but in 1.21 it would match only the path "/%2561" (where "%25" is the escape for the percent sign).
  2628  //   - When matching patterns to paths, in 1.22 each segment of the path is unescaped; in 1.21, the entire path is unescaped.
  2629  //     This change mostly affects how paths with %2F escapes adjacent to slashes are treated.
  2630  //     See https://go.dev/issue/21955 for details.
  2631  type ServeMux struct {
  2632  	mu     sync.RWMutex
  2633  	tree   routingNode
  2634  	index  routingIndex
  2635  	mux121 serveMux121 // used only when GODEBUG=httpmuxgo121=1
  2636  }
  2637  
  2638  // NewServeMux allocates and returns a new [ServeMux].
  2639  func NewServeMux() *ServeMux {
  2640  	return &ServeMux{}
  2641  }
  2642  
  2643  // DefaultServeMux is the default [ServeMux] used by [Serve].
  2644  var DefaultServeMux = &defaultServeMux
  2645  
  2646  var defaultServeMux ServeMux
  2647  
  2648  // cleanPath returns the canonical path for p, eliminating . and .. elements.
  2649  func cleanPath(p string) string {
  2650  	if p == "" {
  2651  		return "/"
  2652  	}
  2653  	if p[0] != '/' {
  2654  		p = "/" + p
  2655  	}
  2656  	np := path.Clean(p)
  2657  	// path.Clean removes trailing slash except for root;
  2658  	// put the trailing slash back if necessary.
  2659  	if p[len(p)-1] == '/' && np != "/" {
  2660  		// Fast path for common case of p being the string we want:
  2661  		if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
  2662  			np = p
  2663  		} else {
  2664  			np += "/"
  2665  		}
  2666  	}
  2667  	return np
  2668  }
  2669  
  2670  // stripHostPort returns h without any trailing ":<port>".
  2671  func stripHostPort(h string) string {
  2672  	// If no port on host, return unchanged
  2673  	if !strings.Contains(h, ":") {
  2674  		return h
  2675  	}
  2676  	host, _, err := net.SplitHostPort(h)
  2677  	if err != nil {
  2678  		return h // on error, return unchanged
  2679  	}
  2680  	return host
  2681  }
  2682  
  2683  // Handler returns the handler to use for the given request,
  2684  // consulting r.Method, r.Host, and r.URL.Path. It always returns
  2685  // a non-nil handler. If the path is not in its canonical form, the
  2686  // handler will be an internally-generated handler that redirects
  2687  // to the canonical path. If the host contains a port, it is ignored
  2688  // when matching handlers.
  2689  //
  2690  // The path and host are used unchanged for CONNECT requests.
  2691  //
  2692  // Handler also returns the registered pattern that matches the
  2693  // request or, in the case of internally-generated redirects,
  2694  // the path that will match after following the redirect.
  2695  //
  2696  // If there is no registered handler that applies to the request,
  2697  // Handler returns a “page not found” or “method not supported”
  2698  // handler and an empty pattern.
  2699  //
  2700  // Handler does not modify its argument. In particular, it does not
  2701  // populate named path wildcards, so r.PathValue will always return
  2702  // the empty string.
  2703  func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
  2704  	if use121 {
  2705  		return mux.mux121.findHandler(r)
  2706  	}
  2707  	h, p, _, _ := mux.findHandler(r)
  2708  	return h, p
  2709  }
  2710  
  2711  // findHandler finds a handler for a request.
  2712  // If there is a matching handler, it returns it and the pattern that matched.
  2713  // Otherwise it returns a Redirect or NotFound handler with the path that would match
  2714  // after the redirect.
  2715  func (mux *ServeMux) findHandler(r *Request) (h Handler, patStr string, _ *pattern, matches []string) {
  2716  	var n *routingNode
  2717  	host := r.URL.Host
  2718  	escapedPath := r.URL.EscapedPath()
  2719  	path := escapedPath
  2720  	// CONNECT requests are not canonicalized.
  2721  	if r.Method == "CONNECT" {
  2722  		// If r.URL.Path is /tree and its handler is not registered,
  2723  		// the /tree -> /tree/ redirect applies to CONNECT requests
  2724  		// but the path canonicalization does not.
  2725  		_, _, u := mux.matchOrRedirect(host, r.Method, path, r.URL)
  2726  		if u != nil {
  2727  			return RedirectHandler(u.String(), StatusTemporaryRedirect), u.Path, nil, nil
  2728  		}
  2729  		// Redo the match, this time with r.Host instead of r.URL.Host.
  2730  		// Pass a nil URL to skip the trailing-slash redirect logic.
  2731  		n, matches, _ = mux.matchOrRedirect(r.Host, r.Method, path, nil)
  2732  	} else {
  2733  		// All other requests have any port stripped and path cleaned
  2734  		// before passing to mux.handler.
  2735  		host = stripHostPort(r.Host)
  2736  		path = cleanPath(path)
  2737  
  2738  		// If the given path is /tree and its handler is not registered,
  2739  		// redirect for /tree/.
  2740  		var u *url.URL
  2741  		n, matches, u = mux.matchOrRedirect(host, r.Method, path, r.URL)
  2742  		if u != nil {
  2743  			return RedirectHandler(u.String(), StatusTemporaryRedirect), n.pattern.String(), nil, nil
  2744  		}
  2745  		if path != escapedPath {
  2746  			// Redirect to cleaned path.
  2747  			patStr := ""
  2748  			if n != nil {
  2749  				patStr = n.pattern.String()
  2750  			}
  2751  			u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
  2752  			return RedirectHandler(u.String(), StatusTemporaryRedirect), patStr, nil, nil
  2753  		}
  2754  	}
  2755  	if n == nil {
  2756  		// We didn't find a match with the request method. To distinguish between
  2757  		// Not Found and Method Not Allowed, see if there is another pattern that
  2758  		// matches except for the method.
  2759  		allowedMethods := mux.matchingMethods(host, path)
  2760  		if len(allowedMethods) > 0 {
  2761  			return HandlerFunc(func(w ResponseWriter, r *Request) {
  2762  				w.Header().Set("Allow", strings.Join(allowedMethods, ", "))
  2763  				Error(w, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed)
  2764  			}), "", nil, nil
  2765  		}
  2766  		return NotFoundHandler(), "", nil, nil
  2767  	}
  2768  	return n.handler, n.pattern.String(), n.pattern, matches
  2769  }
  2770  
  2771  // matchOrRedirect looks up a node in the tree that matches the host, method and path.
  2772  //
  2773  // If the url argument is non-nil, handler also deals with trailing-slash
  2774  // redirection: when a path doesn't match exactly, the match is tried again
  2775  // after appending "/" to the path. If that second match succeeds, the last
  2776  // return value is the URL to redirect to.
  2777  func (mux *ServeMux) matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL) {
  2778  	mux.mu.RLock()
  2779  	defer mux.mu.RUnlock()
  2780  
  2781  	n, matches := mux.tree.match(host, method, path)
  2782  	// We can terminate here if any of the following is true:
  2783  	// - We have an exact match already.
  2784  	// - We were asked not to try trailing slash redirection.
  2785  	// - The URL already has a trailing slash.
  2786  	// - The URL is an empty string.
  2787  	if !exactMatch(n, path) && u != nil && !strings.HasSuffix(path, "/") && path != "" {
  2788  		// If there is an exact match with a trailing slash, then redirect.
  2789  		path += "/"
  2790  		n2, _ := mux.tree.match(host, method, path)
  2791  		if exactMatch(n2, path) {
  2792  			// It is safe to return n2 here: it is used only in the second RedirectHandler case
  2793  			// of findHandler, and that method returns before it does the "n == nil" check where
  2794  			// the first return value matters. We return it here only to make the pattern available
  2795  			// to findHandler.
  2796  			return n2, nil, &url.URL{Path: cleanPath(u.Path) + "/", RawQuery: u.RawQuery}
  2797  		}
  2798  	}
  2799  	return n, matches, nil
  2800  }
  2801  
  2802  // exactMatch reports whether the node's pattern exactly matches the path.
  2803  // As a special case, if the node is nil, exactMatch return false.
  2804  //
  2805  // Before wildcards were introduced, it was clear that an exact match meant
  2806  // that the pattern and path were the same string. The only other possibility
  2807  // was that a trailing-slash pattern, like "/", matched a path longer than
  2808  // it, like "/a".
  2809  //
  2810  // With wildcards, we define an inexact match as any one where a multi wildcard
  2811  // matches a non-empty string. All other matches are exact.
  2812  // For example, these are all exact matches:
  2813  //
  2814  //	pattern   path
  2815  //	/a        /a
  2816  //	/{x}      /a
  2817  //	/a/{$}    /a/
  2818  //	/a/       /a/
  2819  //
  2820  // The last case has a multi wildcard (implicitly), but the match is exact because
  2821  // the wildcard matches the empty string.
  2822  //
  2823  // Examples of matches that are not exact:
  2824  //
  2825  //	pattern   path
  2826  //	/         /a
  2827  //	/a/{x...} /a/b
  2828  func exactMatch(n *routingNode, path string) bool {
  2829  	if n == nil {
  2830  		return false
  2831  	}
  2832  	// We can't directly implement the definition (empty match for multi
  2833  	// wildcard) because we don't record a match for anonymous multis.
  2834  
  2835  	// If there is no multi, the match is exact.
  2836  	if !n.pattern.lastSegment().multi {
  2837  		return true
  2838  	}
  2839  
  2840  	// If the path doesn't end in a trailing slash, then the multi match
  2841  	// is non-empty.
  2842  	if len(path) > 0 && path[len(path)-1] != '/' {
  2843  		return false
  2844  	}
  2845  	// Only patterns ending in {$} or a multi wildcard can
  2846  	// match a path with a trailing slash.
  2847  	// For the match to be exact, the number of pattern
  2848  	// segments should be the same as the number of slashes in the path.
  2849  	// E.g. "/a/b/{$}" and "/a/b/{...}" exactly match "/a/b/", but "/a/" does not.
  2850  	return len(n.pattern.segments) == strings.Count(path, "/")
  2851  }
  2852  
  2853  // matchingMethods return a sorted list of all methods that would match with the given host and path.
  2854  func (mux *ServeMux) matchingMethods(host, path string) []string {
  2855  	// Hold the read lock for the entire method so that the two matches are done
  2856  	// on the same set of registered patterns.
  2857  	mux.mu.RLock()
  2858  	defer mux.mu.RUnlock()
  2859  	ms := map[string]bool{}
  2860  	mux.tree.matchingMethods(host, path, ms)
  2861  	// matchOrRedirect will try appending a trailing slash if there is no match.
  2862  	if !strings.HasSuffix(path, "/") {
  2863  		mux.tree.matchingMethods(host, path+"/", ms)
  2864  	}
  2865  	return slices.Sorted(maps.Keys(ms))
  2866  }
  2867  
  2868  // ServeHTTP dispatches the request to the handler whose
  2869  // pattern most closely matches the request URL.
  2870  func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
  2871  	if r.RequestURI == "*" {
  2872  		if r.ProtoAtLeast(1, 1) {
  2873  			w.Header().Set("Connection", "close")
  2874  		}
  2875  		w.WriteHeader(StatusBadRequest)
  2876  		return
  2877  	}
  2878  	var h Handler
  2879  	if use121 {
  2880  		h, _ = mux.mux121.findHandler(r)
  2881  	} else {
  2882  		h, r.Pattern, r.pat, r.matches = mux.findHandler(r)
  2883  	}
  2884  	h.ServeHTTP(w, r)
  2885  }
  2886  
  2887  // The four functions below all call ServeMux.register so that callerLocation
  2888  // always refers to user code.
  2889  
  2890  // Handle registers the handler for the given pattern.
  2891  // If the given pattern conflicts with one that is already registered
  2892  // or if the pattern is invalid, Handle panics.
  2893  //
  2894  // See [ServeMux] for details on valid patterns and conflict rules.
  2895  func (mux *ServeMux) Handle(pattern string, handler Handler) {
  2896  	if use121 {
  2897  		mux.mux121.handle(pattern, handler)
  2898  	} else {
  2899  		mux.register(pattern, handler)
  2900  	}
  2901  }
  2902  
  2903  // HandleFunc registers the handler function for the given pattern.
  2904  // If the given pattern conflicts with one that is already registered
  2905  // or if the pattern is invalid, HandleFunc panics.
  2906  //
  2907  // See [ServeMux] for details on valid patterns and conflict rules.
  2908  func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  2909  	if use121 {
  2910  		mux.mux121.handleFunc(pattern, handler)
  2911  	} else {
  2912  		mux.register(pattern, HandlerFunc(handler))
  2913  	}
  2914  }
  2915  
  2916  // Handle registers the handler for the given pattern in [DefaultServeMux].
  2917  // The documentation for [ServeMux] explains how patterns are matched.
  2918  func Handle(pattern string, handler Handler) {
  2919  	if use121 {
  2920  		DefaultServeMux.mux121.handle(pattern, handler)
  2921  	} else {
  2922  		DefaultServeMux.register(pattern, handler)
  2923  	}
  2924  }
  2925  
  2926  // HandleFunc registers the handler function for the given pattern in [DefaultServeMux].
  2927  // The documentation for [ServeMux] explains how patterns are matched.
  2928  func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  2929  	if use121 {
  2930  		DefaultServeMux.mux121.handleFunc(pattern, handler)
  2931  	} else {
  2932  		DefaultServeMux.register(pattern, HandlerFunc(handler))
  2933  	}
  2934  }
  2935  
  2936  func (mux *ServeMux) register(pattern string, handler Handler) {
  2937  	if err := mux.registerErr(pattern, handler); err != nil {
  2938  		panic(err)
  2939  	}
  2940  }
  2941  
  2942  func (mux *ServeMux) registerErr(patstr string, handler Handler) error {
  2943  	if patstr == "" {
  2944  		return errors.New("http: invalid pattern")
  2945  	}
  2946  	if handler == nil {
  2947  		return errors.New("http: nil handler")
  2948  	}
  2949  	if f, ok := handler.(HandlerFunc); ok && f == nil {
  2950  		return errors.New("http: nil handler")
  2951  	}
  2952  
  2953  	pat, err := parsePattern(patstr)
  2954  	if err != nil {
  2955  		return fmt.Errorf("parsing %q: %w", patstr, err)
  2956  	}
  2957  
  2958  	// Get the caller's location, for better conflict error messages.
  2959  	// Skip register and whatever calls it.
  2960  	_, file, line, ok := runtime.Caller(3)
  2961  	if !ok {
  2962  		pat.loc = "unknown location"
  2963  	} else {
  2964  		pat.loc = fmt.Sprintf("%s:%d", file, line)
  2965  	}
  2966  
  2967  	mux.mu.Lock()
  2968  	defer mux.mu.Unlock()
  2969  	// Check for conflict.
  2970  	if err := mux.index.possiblyConflictingPatterns(pat, func(pat2 *pattern) error {
  2971  		if pat.conflictsWith(pat2) {
  2972  			d := describeConflict(pat, pat2)
  2973  			return fmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s):\n%s",
  2974  				pat, pat.loc, pat2, pat2.loc, d)
  2975  		}
  2976  		return nil
  2977  	}); err != nil {
  2978  		return err
  2979  	}
  2980  	mux.tree.addPattern(pat, handler)
  2981  	mux.index.addPattern(pat)
  2982  	return nil
  2983  }
  2984  
  2985  // Serve accepts incoming HTTP connections on the listener l,
  2986  // creating a new service goroutine for each. The service goroutines
  2987  // read requests and then call handler to reply to them.
  2988  //
  2989  // The handler is typically nil, in which case [DefaultServeMux] is used.
  2990  //
  2991  // HTTP/2 support is only enabled if the Listener returns [*tls.Conn]
  2992  // connections and they were configured with "h2" in the TLS
  2993  // Config.NextProtos.
  2994  //
  2995  // Serve always returns a non-nil error.
  2996  func Serve(l net.Listener, handler Handler) error {
  2997  	srv := &Server{Handler: handler}
  2998  	return srv.Serve(l)
  2999  }
  3000  
  3001  // ServeTLS accepts incoming HTTPS connections on the listener l,
  3002  // creating a new service goroutine for each. The service goroutines
  3003  // read requests and then call handler to reply to them.
  3004  //
  3005  // The handler is typically nil, in which case [DefaultServeMux] is used.
  3006  //
  3007  // Additionally, files containing a certificate and matching private key
  3008  // for the server must be provided. If the certificate is signed by a
  3009  // certificate authority, the certFile should be the concatenation
  3010  // of the server's certificate, any intermediates, and the CA's certificate.
  3011  //
  3012  // ServeTLS always returns a non-nil error.
  3013  func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error {
  3014  	srv := &Server{Handler: handler}
  3015  	return srv.ServeTLS(l, certFile, keyFile)
  3016  }
  3017  
  3018  // A Server defines parameters for running an HTTP server.
  3019  // The zero value for Server is a valid configuration.
  3020  type Server struct {
  3021  	// Addr optionally specifies the TCP address for the server to listen on,
  3022  	// in the form "host:port". If empty, ":http" (port 80) is used.
  3023  	// The service names are defined in RFC 6335 and assigned by IANA.
  3024  	// See net.Dial for details of the address format.
  3025  	Addr string
  3026  
  3027  	Handler Handler // handler to invoke, http.DefaultServeMux if nil
  3028  
  3029  	// DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler,
  3030  	// otherwise responds with 200 OK and Content-Length: 0.
  3031  	DisableGeneralOptionsHandler bool
  3032  
  3033  	// TLSConfig optionally provides a TLS configuration for use
  3034  	// by ServeTLS and ListenAndServeTLS. Note that this value is
  3035  	// cloned by ServeTLS and ListenAndServeTLS, so it's not
  3036  	// possible to modify the configuration with methods like
  3037  	// tls.Config.SetSessionTicketKeys. To use
  3038  	// SetSessionTicketKeys, use Server.Serve with a TLS Listener
  3039  	// instead.
  3040  	TLSConfig *tls.Config
  3041  
  3042  	// ReadTimeout is the maximum duration for reading the entire
  3043  	// request, including the body. A zero or negative value means
  3044  	// there will be no timeout.
  3045  	//
  3046  	// Because ReadTimeout does not let Handlers make per-request
  3047  	// decisions on each request body's acceptable deadline or
  3048  	// upload rate, most users will prefer to use
  3049  	// ReadHeaderTimeout. It is valid to use them both.
  3050  	ReadTimeout time.Duration
  3051  
  3052  	// ReadHeaderTimeout is the amount of time allowed to read
  3053  	// request headers. The connection's read deadline is reset
  3054  	// after reading the headers and the Handler can decide what
  3055  	// is considered too slow for the body. If zero, the value of
  3056  	// ReadTimeout is used. If negative, or if zero and ReadTimeout
  3057  	// is zero or negative, there is no timeout.
  3058  	ReadHeaderTimeout time.Duration
  3059  
  3060  	// WriteTimeout is the maximum duration before timing out
  3061  	// writes of the response. It is reset whenever a new
  3062  	// request's header is read. Like ReadTimeout, it does not
  3063  	// let Handlers make decisions on a per-request basis.
  3064  	// A zero or negative value means there will be no timeout.
  3065  	WriteTimeout time.Duration
  3066  
  3067  	// IdleTimeout is the maximum amount of time to wait for the
  3068  	// next request when keep-alives are enabled. If zero, the value
  3069  	// of ReadTimeout is used. If negative, or if zero and ReadTimeout
  3070  	// is zero or negative, there is no timeout.
  3071  	IdleTimeout time.Duration
  3072  
  3073  	// MaxHeaderBytes controls the maximum number of bytes the
  3074  	// server will read parsing the request header's keys and
  3075  	// values, including the request line. It does not limit the
  3076  	// size of the request body.
  3077  	// If zero, DefaultMaxHeaderBytes is used.
  3078  	MaxHeaderBytes int
  3079  
  3080  	// TLSNextProto optionally specifies a function to take over
  3081  	// ownership of the provided TLS connection when an ALPN
  3082  	// protocol upgrade has occurred. The map key is the protocol
  3083  	// name negotiated. The Handler argument should be used to
  3084  	// handle HTTP requests and will initialize the Request's TLS
  3085  	// and RemoteAddr if not already set. The connection is
  3086  	// automatically closed when the function returns.
  3087  	// If TLSNextProto is not nil, HTTP/2 support is not enabled
  3088  	// automatically.
  3089  	//
  3090  	// Historically, TLSNextProto was used to disable HTTP/2 support.
  3091  	// The Server.Protocols field now provides a simpler way to do this.
  3092  	TLSNextProto map[string]func(*Server, *tls.Conn, Handler)
  3093  
  3094  	// ConnState specifies an optional callback function that is
  3095  	// called when a client connection changes state. See the
  3096  	// ConnState type and associated constants for details.
  3097  	ConnState func(net.Conn, ConnState)
  3098  
  3099  	// ErrorLog specifies an optional logger for errors accepting
  3100  	// connections, unexpected behavior from handlers, and
  3101  	// underlying FileSystem errors.
  3102  	// If nil, logging is done via the log package's standard logger.
  3103  	ErrorLog *log.Logger
  3104  
  3105  	// BaseContext optionally specifies a function that returns
  3106  	// the base context for incoming requests on this server.
  3107  	// The provided Listener is the specific Listener that's
  3108  	// about to start accepting requests.
  3109  	// If BaseContext is nil, the default is context.Background().
  3110  	// If non-nil, it must return a non-nil context.
  3111  	BaseContext func(net.Listener) context.Context
  3112  
  3113  	// ConnContext optionally specifies a function that modifies
  3114  	// the context used for a new connection c. The provided ctx
  3115  	// is derived from the base context and has a ServerContextKey
  3116  	// value.
  3117  	ConnContext func(ctx context.Context, c net.Conn) context.Context
  3118  
  3119  	// HTTP2 configures HTTP/2 connections.
  3120  	HTTP2 *HTTP2Config
  3121  
  3122  	// Protocols is the set of protocols accepted by the server.
  3123  	//
  3124  	// If Protocols includes UnencryptedHTTP2, the server will accept
  3125  	// unencrypted HTTP/2 connections. The server can serve both
  3126  	// HTTP/1 and unencrypted HTTP/2 on the same address and port.
  3127  	//
  3128  	// If Protocols is nil, the default is usually HTTP/1 and HTTP/2.
  3129  	// If TLSNextProto is non-nil and does not contain an "h2" entry,
  3130  	// the default is HTTP/1 only.
  3131  	Protocols *Protocols
  3132  
  3133  	// DisableClientPriority specifies whether client-specified priority, as
  3134  	// specified in RFC 9218, should be respected or not.
  3135  	//
  3136  	// This field only takes effect if using HTTP/2, and if no custom write
  3137  	// scheduler is defined for the HTTP/2 server. Otherwise, this field is a
  3138  	// no-op.
  3139  	//
  3140  	// If set to true, requests will be served in a round-robin manner, without
  3141  	// prioritization.
  3142  	DisableClientPriority bool
  3143  
  3144  	inShutdown atomic.Bool // true when server is in shutdown
  3145  
  3146  	disableKeepAlives atomic.Bool
  3147  	nextProtoOnce     sync.Once // guards setupHTTP2_* init
  3148  	nextProtoErr      error     // result of http2.ConfigureServer if used
  3149  
  3150  	mu         sync.Mutex
  3151  	listeners  map[*net.Listener]struct{}
  3152  	activeConn map[*conn]struct{}
  3153  	onShutdown []func()
  3154  	h2         *http2Server
  3155  	h3         *http3ServerHandler
  3156  
  3157  	listenerGroup sync.WaitGroup
  3158  }
  3159  
  3160  // Close immediately closes all active net.Listeners and any
  3161  // connections in state [StateNew], [StateActive], or [StateIdle]. For a
  3162  // graceful shutdown, use [Server.Shutdown].
  3163  //
  3164  // Close does not attempt to close (and does not even know about)
  3165  // any hijacked connections, such as WebSockets.
  3166  //
  3167  // Close returns any error returned from closing the [Server]'s
  3168  // underlying Listener(s).
  3169  func (s *Server) Close() error {
  3170  	s.inShutdown.Store(true)
  3171  	s.mu.Lock()
  3172  	defer s.mu.Unlock()
  3173  	err := s.closeListenersLocked()
  3174  
  3175  	// Unlock s.mu while waiting for listenerGroup.
  3176  	// The group Add and Done calls are made with s.mu held,
  3177  	// to avoid adding a new listener in the window between
  3178  	// us setting inShutdown above and waiting here.
  3179  	s.mu.Unlock()
  3180  	s.listenerGroup.Wait()
  3181  	s.mu.Lock()
  3182  
  3183  	for c := range s.activeConn {
  3184  		c.rwc.Close()
  3185  		delete(s.activeConn, c)
  3186  	}
  3187  	return err
  3188  }
  3189  
  3190  // shutdownPollIntervalMax is the max polling interval when checking
  3191  // quiescence during Server.Shutdown. Polling starts with a small
  3192  // interval and backs off to the max.
  3193  // Ideally we could find a solution that doesn't involve polling,
  3194  // but which also doesn't have a high runtime cost (and doesn't
  3195  // involve any contentious mutexes), but that is left as an
  3196  // exercise for the reader.
  3197  const shutdownPollIntervalMax = 500 * time.Millisecond
  3198  
  3199  // Shutdown gracefully shuts down the server without interrupting any
  3200  // active connections. Shutdown works by first closing all open
  3201  // listeners, then closing all idle connections, and then waiting
  3202  // indefinitely for connections to return to idle and then shut down.
  3203  // If the provided context expires before the shutdown is complete,
  3204  // Shutdown returns the context's error, otherwise it returns any
  3205  // error returned from closing the [Server]'s underlying Listener(s).
  3206  //
  3207  // When Shutdown is called, [Serve], [ServeTLS], [ListenAndServe], and
  3208  // [ListenAndServeTLS] immediately return [ErrServerClosed]. Make sure the
  3209  // program doesn't exit and waits instead for Shutdown to return.
  3210  //
  3211  // Shutdown does not attempt to close nor wait for hijacked
  3212  // connections such as WebSockets. The caller of Shutdown should
  3213  // separately notify such long-lived connections of shutdown and wait
  3214  // for them to close, if desired. See [Server.RegisterOnShutdown] for a way to
  3215  // register shutdown notification functions.
  3216  //
  3217  // Once Shutdown has been called on a server, it may not be reused;
  3218  // future calls to methods such as Serve will return ErrServerClosed.
  3219  func (s *Server) Shutdown(ctx context.Context) error {
  3220  	s.inShutdown.Store(true)
  3221  
  3222  	s.mu.Lock()
  3223  	if s.h3 != nil {
  3224  		s.h3.shutdownCtx = ctx
  3225  	}
  3226  	lnerr := s.closeListenersLocked()
  3227  	for _, f := range s.onShutdown {
  3228  		go f()
  3229  	}
  3230  	s.mu.Unlock()
  3231  	s.listenerGroup.Wait()
  3232  
  3233  	pollIntervalBase := time.Millisecond
  3234  	nextPollInterval := func() time.Duration {
  3235  		// Add 10% jitter.
  3236  		interval := pollIntervalBase + time.Duration(rand.IntN(int(pollIntervalBase/10)))
  3237  		// Double and clamp for next time.
  3238  		pollIntervalBase *= 2
  3239  		if pollIntervalBase > shutdownPollIntervalMax {
  3240  			pollIntervalBase = shutdownPollIntervalMax
  3241  		}
  3242  		return interval
  3243  	}
  3244  
  3245  	timer := time.NewTimer(nextPollInterval())
  3246  	defer timer.Stop()
  3247  	for {
  3248  		if s.closeIdleConns() {
  3249  			return lnerr
  3250  		}
  3251  		select {
  3252  		case <-ctx.Done():
  3253  			return ctx.Err()
  3254  		case <-timer.C:
  3255  			timer.Reset(nextPollInterval())
  3256  		}
  3257  	}
  3258  }
  3259  
  3260  // RegisterOnShutdown registers a function to call on [Server.Shutdown].
  3261  // This can be used to gracefully shutdown connections that have
  3262  // undergone ALPN protocol upgrade or that have been hijacked.
  3263  // This function should start protocol-specific graceful shutdown,
  3264  // but should not wait for shutdown to complete.
  3265  func (s *Server) RegisterOnShutdown(f func()) {
  3266  	s.mu.Lock()
  3267  	s.onShutdown = append(s.onShutdown, f)
  3268  	s.mu.Unlock()
  3269  }
  3270  
  3271  // closeIdleConns closes all idle connections and reports whether the
  3272  // server is quiescent.
  3273  func (s *Server) closeIdleConns() bool {
  3274  	s.mu.Lock()
  3275  	defer s.mu.Unlock()
  3276  	quiescent := true
  3277  	for c := range s.activeConn {
  3278  		st, unixSec := c.getState()
  3279  		// Issue 22682: treat StateNew connections as if
  3280  		// they're idle if we haven't read the first request's
  3281  		// header in over 5 seconds.
  3282  		if st == StateNew && unixSec < time.Now().Unix()-5 {
  3283  			st = StateIdle
  3284  		}
  3285  		if st != StateIdle || unixSec == 0 {
  3286  			// Assume unixSec == 0 means it's a very new
  3287  			// connection, without state set yet.
  3288  			quiescent = false
  3289  			continue
  3290  		}
  3291  		c.rwc.Close()
  3292  		delete(s.activeConn, c)
  3293  	}
  3294  	return quiescent
  3295  }
  3296  
  3297  func (s *Server) closeListenersLocked() error {
  3298  	var err error
  3299  	for ln := range s.listeners {
  3300  		if cerr := (*ln).Close(); cerr != nil && err == nil {
  3301  			err = cerr
  3302  		}
  3303  	}
  3304  	return err
  3305  }
  3306  
  3307  // A ConnState represents the state of a client connection to a server.
  3308  // It's used by the optional [Server.ConnState] hook.
  3309  type ConnState int
  3310  
  3311  const (
  3312  	// StateNew represents a new connection that is expected to
  3313  	// send a request immediately. Connections begin at this
  3314  	// state and then transition to either StateActive or
  3315  	// StateClosed.
  3316  	StateNew ConnState = iota
  3317  
  3318  	// StateActive represents a connection that has read 1 or more
  3319  	// bytes of a request. The Server.ConnState hook for
  3320  	// StateActive fires before the request has entered a handler
  3321  	// and doesn't fire again until the request has been
  3322  	// handled. After the request is handled, the state
  3323  	// transitions to StateClosed, StateHijacked, or StateIdle.
  3324  	// For HTTP/2, StateActive fires on the transition from zero
  3325  	// to one active request, and only transitions away once all
  3326  	// active requests are complete. That means that ConnState
  3327  	// cannot be used to do per-request work; ConnState only notes
  3328  	// the overall state of the connection.
  3329  	StateActive
  3330  
  3331  	// StateIdle represents a connection that has finished
  3332  	// handling a request and is in the keep-alive state, waiting
  3333  	// for a new request. Connections transition from StateIdle
  3334  	// to either StateActive or StateClosed.
  3335  	StateIdle
  3336  
  3337  	// StateHijacked represents a hijacked connection.
  3338  	// This is a terminal state. It does not transition to StateClosed.
  3339  	StateHijacked
  3340  
  3341  	// StateClosed represents a closed connection.
  3342  	// This is a terminal state. Hijacked connections do not
  3343  	// transition to StateClosed.
  3344  	StateClosed
  3345  )
  3346  
  3347  var stateName = map[ConnState]string{
  3348  	StateNew:      "new",
  3349  	StateActive:   "active",
  3350  	StateIdle:     "idle",
  3351  	StateHijacked: "hijacked",
  3352  	StateClosed:   "closed",
  3353  }
  3354  
  3355  func (c ConnState) String() string {
  3356  	return stateName[c]
  3357  }
  3358  
  3359  // serverHandler delegates to either the server's Handler or
  3360  // DefaultServeMux and also handles "OPTIONS *" requests.
  3361  type serverHandler struct {
  3362  	srv *Server
  3363  }
  3364  
  3365  // ServeHTTP should be an internal detail,
  3366  // but widely used packages access it using linkname.
  3367  // Notable members of the hall of shame include:
  3368  //   - github.com/erda-project/erda-infra
  3369  //
  3370  // Do not remove or change the type signature.
  3371  // See go.dev/issue/67401.
  3372  //
  3373  //go:linkname badServeHTTP net/http.serverHandler.ServeHTTP
  3374  func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
  3375  	handler := sh.srv.Handler
  3376  	if handler == nil {
  3377  		handler = DefaultServeMux
  3378  	}
  3379  	if !sh.srv.DisableGeneralOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" {
  3380  		handler = globalOptionsHandler{}
  3381  	}
  3382  
  3383  	handler.ServeHTTP(rw, req)
  3384  }
  3385  
  3386  func badServeHTTP(serverHandler, ResponseWriter, *Request)
  3387  
  3388  // AllowQuerySemicolons returns a handler that serves requests by converting any
  3389  // unescaped semicolons in the URL query to ampersands, and invoking the handler h.
  3390  //
  3391  // This restores the pre-Go 1.17 behavior of splitting query parameters on both
  3392  // semicolons and ampersands. (See golang.org/issue/25192). Note that this
  3393  // behavior doesn't match that of many proxies, and the mismatch can lead to
  3394  // security issues.
  3395  //
  3396  // AllowQuerySemicolons should be invoked before [Request.ParseForm] is called.
  3397  func AllowQuerySemicolons(h Handler) Handler {
  3398  	return HandlerFunc(func(w ResponseWriter, r *Request) {
  3399  		if strings.Contains(r.URL.RawQuery, ";") {
  3400  			r2 := new(Request)
  3401  			*r2 = *r
  3402  			r2.URL = new(url.URL)
  3403  			*r2.URL = *r.URL
  3404  			r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&")
  3405  			h.ServeHTTP(w, r2)
  3406  		} else {
  3407  			h.ServeHTTP(w, r)
  3408  		}
  3409  	})
  3410  }
  3411  
  3412  // ListenAndServe listens on the TCP network address s.Addr and then
  3413  // calls [Serve] to handle requests on incoming connections.
  3414  // Accepted connections are configured to enable TCP keep-alives.
  3415  //
  3416  // If s.Addr is blank, ":http" is used.
  3417  //
  3418  // ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close],
  3419  // the returned error is [ErrServerClosed].
  3420  func (s *Server) ListenAndServe() error {
  3421  	if s.shuttingDown() {
  3422  		return ErrServerClosed
  3423  	}
  3424  	addr := s.Addr
  3425  	if addr == "" {
  3426  		addr = ":http"
  3427  	}
  3428  	ln, err := net.Listen("tcp", addr)
  3429  	if err != nil {
  3430  		return err
  3431  	}
  3432  	return s.Serve(ln)
  3433  }
  3434  
  3435  var testHookServerServe func(*Server, net.Listener) // used if non-nil
  3436  
  3437  // shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
  3438  // automatic HTTP/2. (which sets up the s.TLSNextProto map)
  3439  func (s *Server) shouldConfigureHTTP2ForServe() bool {
  3440  	if s.TLSConfig == nil {
  3441  		// Compatibility with Go 1.6:
  3442  		// If there's no TLSConfig, it's possible that the user just
  3443  		// didn't set it on the http.Server, but did pass it to
  3444  		// tls.NewListener and passed that listener to Serve.
  3445  		// So we should configure HTTP/2 (to set up s.TLSNextProto)
  3446  		// in case the listener returns an "h2" *tls.Conn.
  3447  		return true
  3448  	}
  3449  	if s.protocols().UnencryptedHTTP2() {
  3450  		return true
  3451  	}
  3452  	// The user specified a TLSConfig on their http.Server.
  3453  	// In this, case, only configure HTTP/2 if their tls.Config
  3454  	// explicitly mentions "h2". Otherwise http2.ConfigureServer
  3455  	// would modify the tls.Config to add it, but they probably already
  3456  	// passed this tls.Config to tls.NewListener. And if they did,
  3457  	// it's too late anyway to fix it. It would only be potentially racy.
  3458  	// See Issue 15908.
  3459  	return slices.Contains(s.TLSConfig.NextProtos, "h2")
  3460  }
  3461  
  3462  // ErrServerClosed is returned by the [Server.Serve], [ServeTLS], [ListenAndServe],
  3463  // and [ListenAndServeTLS] methods after a call to [Server.Shutdown] or [Server.Close].
  3464  var ErrServerClosed = errors.New("http: Server closed")
  3465  
  3466  // Serve accepts incoming connections on the Listener l, creating a
  3467  // new service goroutine for each. The service goroutines read requests and
  3468  // then call s.Handler to reply to them.
  3469  //
  3470  // HTTP/2 support is only enabled if the Listener returns [*tls.Conn]
  3471  // connections and they were configured with "h2" in the TLS
  3472  // Config.NextProtos.
  3473  //
  3474  // Serve always returns a non-nil error and closes l.
  3475  // After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed].
  3476  func (s *Server) Serve(l net.Listener) error {
  3477  	if fn := testHookServerServe; fn != nil {
  3478  		fn(s, l) // call hook with unwrapped listener
  3479  	}
  3480  
  3481  	origListener := l
  3482  	l = &onceCloseListener{Listener: l}
  3483  	defer l.Close()
  3484  
  3485  	if err := s.setupHTTP2_Serve(); err != nil {
  3486  		return err
  3487  	}
  3488  
  3489  	if !s.trackListener(&l, true) {
  3490  		return ErrServerClosed
  3491  	}
  3492  	defer s.trackListener(&l, false)
  3493  
  3494  	baseCtx := context.Background()
  3495  	if s.BaseContext != nil {
  3496  		baseCtx = s.BaseContext(origListener)
  3497  		if baseCtx == nil {
  3498  			panic("BaseContext returned a nil context")
  3499  		}
  3500  	}
  3501  
  3502  	var tempDelay time.Duration // how long to sleep on accept failure
  3503  
  3504  	ctx := context.WithValue(baseCtx, ServerContextKey, s)
  3505  	for {
  3506  		rw, err := l.Accept()
  3507  		if err != nil {
  3508  			if s.shuttingDown() {
  3509  				return ErrServerClosed
  3510  			}
  3511  			if ne, ok := err.(net.Error); ok && ne.Temporary() {
  3512  				if tempDelay == 0 {
  3513  					tempDelay = 5 * time.Millisecond
  3514  				} else {
  3515  					tempDelay *= 2
  3516  				}
  3517  				if max := 1 * time.Second; tempDelay > max {
  3518  					tempDelay = max
  3519  				}
  3520  				s.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
  3521  				time.Sleep(tempDelay)
  3522  				continue
  3523  			}
  3524  			return err
  3525  		}
  3526  		connCtx := ctx
  3527  		if cc := s.ConnContext; cc != nil {
  3528  			connCtx = cc(connCtx, rw)
  3529  			if connCtx == nil {
  3530  				panic("ConnContext returned nil")
  3531  			}
  3532  		}
  3533  		tempDelay = 0
  3534  		c := s.newConn(rw)
  3535  		c.setState(c.rwc, StateNew, runHooks) // before Serve can return
  3536  		go c.serve(connCtx)
  3537  	}
  3538  }
  3539  
  3540  func (s *Server) setupTLSConfig(certFile, keyFile string, nextProtos []string) (*tls.Config, error) {
  3541  	config := cloneTLSConfig(s.TLSConfig)
  3542  	config.NextProtos = nextProtos
  3543  
  3544  	configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil || config.GetConfigForClient != nil
  3545  	if !configHasCert || certFile != "" || keyFile != "" {
  3546  		var err error
  3547  		config.Certificates = make([]tls.Certificate, 1)
  3548  		config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
  3549  		if err != nil {
  3550  			return nil, err
  3551  		}
  3552  	}
  3553  	return config, nil
  3554  }
  3555  
  3556  // ServeTLS accepts incoming connections on the Listener l, creating a
  3557  // new service goroutine for each. The service goroutines perform TLS
  3558  // setup and then read requests, calling s.Handler to reply to them.
  3559  //
  3560  // Files containing a certificate and matching private key for the
  3561  // server must be provided if neither the [Server]'s
  3562  // TLSConfig.Certificates, TLSConfig.GetCertificate nor
  3563  // config.GetConfigForClient are populated.
  3564  // If the certificate is signed by a certificate authority, the
  3565  // certFile should be the concatenation of the server's certificate,
  3566  // any intermediates, and the CA's certificate.
  3567  //
  3568  // ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the
  3569  // returned error is [ErrServerClosed].
  3570  func (s *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
  3571  	// Setup HTTP/2 before s.Serve, to initialize s.TLSConfig
  3572  	// before we clone it and create the TLS Listener.
  3573  	if err := s.setupHTTP2_ServeTLS(); err != nil {
  3574  		return err
  3575  	}
  3576  
  3577  	var nextProtos []string
  3578  	if s.TLSConfig != nil {
  3579  		nextProtos = s.TLSConfig.NextProtos
  3580  	}
  3581  	config, err := s.setupTLSConfig(certFile, keyFile, adjustNextProtos(nextProtos, s.protocols()))
  3582  	if err != nil {
  3583  		return err
  3584  	}
  3585  
  3586  	tlsListener := tls.NewListener(l, config)
  3587  	return s.Serve(tlsListener)
  3588  }
  3589  
  3590  func (s *Server) protocols() Protocols {
  3591  	if s.Protocols != nil {
  3592  		// Historically, even when Protocols for a Server was set to be empty,
  3593  		// the Server can still run normally with just HTTP/1.
  3594  		// To keep backward-compatibility, the zero value of Protocols is
  3595  		// defined as having only HTTP/1 enabled.
  3596  		if s.Protocols.empty() {
  3597  			var p Protocols
  3598  			p.SetHTTP1(true)
  3599  			return p
  3600  		}
  3601  		return *s.Protocols // user-configured set
  3602  	}
  3603  
  3604  	// The historic way of disabling HTTP/2 is to set TLSNextProto to
  3605  	// a non-nil map with no "h2" entry.
  3606  	_, hasH2 := s.TLSNextProto["h2"]
  3607  	http2Disabled := s.TLSNextProto != nil && !hasH2
  3608  
  3609  	// If GODEBUG=http2server=0, then HTTP/2 is disabled unless
  3610  	// the user has manually added an "h2" entry to TLSNextProto
  3611  	// (probably by using x/net/http2 directly).
  3612  	if http2server.Value() == "0" && !hasH2 {
  3613  		http2Disabled = true
  3614  	}
  3615  
  3616  	var p Protocols
  3617  	p.SetHTTP1(true) // default always includes HTTP/1
  3618  	if !http2Disabled {
  3619  		p.SetHTTP2(true)
  3620  	}
  3621  	return p
  3622  }
  3623  
  3624  // adjustNextProtos adds or removes "http/1.1" and "h2" entries from
  3625  // a tls.Config.NextProtos list, according to the set of protocols in protos.
  3626  func adjustNextProtos(nextProtos []string, protos Protocols) []string {
  3627  	// Make a copy of NextProtos since it might be shared with some other tls.Config.
  3628  	// (tls.Config.Clone doesn't do a deep copy.)
  3629  	//
  3630  	// We could avoid an allocation in the common case by checking to see if the slice
  3631  	// is already in order, but this is just one small allocation per connection.
  3632  	nextProtos = slices.Clone(nextProtos)
  3633  	var have Protocols
  3634  	nextProtos = slices.DeleteFunc(nextProtos, func(s string) bool {
  3635  		switch s {
  3636  		case "http/1.1":
  3637  			if !protos.HTTP1() {
  3638  				return true
  3639  			}
  3640  			have.SetHTTP1(true)
  3641  		case "h2":
  3642  			if !protos.HTTP2() {
  3643  				return true
  3644  			}
  3645  			have.SetHTTP2(true)
  3646  		}
  3647  		return false
  3648  	})
  3649  	if protos.HTTP2() && !have.HTTP2() {
  3650  		nextProtos = append(nextProtos, "h2")
  3651  	}
  3652  	if protos.HTTP1() && !have.HTTP1() {
  3653  		nextProtos = append(nextProtos, "http/1.1")
  3654  	}
  3655  	return nextProtos
  3656  }
  3657  
  3658  // trackListener adds or removes a net.Listener to the set of tracked
  3659  // listeners.
  3660  //
  3661  // We store a pointer to interface in the map set, in case the
  3662  // net.Listener is not comparable. This is safe because we only call
  3663  // trackListener via Serve and can track+defer untrack the same
  3664  // pointer to local variable there. We never need to compare a
  3665  // Listener from another caller.
  3666  //
  3667  // It reports whether the server is still up (not Shutdown or Closed).
  3668  func (s *Server) trackListener(ln *net.Listener, add bool) bool {
  3669  	s.mu.Lock()
  3670  	defer s.mu.Unlock()
  3671  	if s.listeners == nil {
  3672  		s.listeners = make(map[*net.Listener]struct{})
  3673  	}
  3674  	if add {
  3675  		if s.shuttingDown() {
  3676  			return false
  3677  		}
  3678  		s.listeners[ln] = struct{}{}
  3679  		s.listenerGroup.Add(1)
  3680  	} else {
  3681  		delete(s.listeners, ln)
  3682  		s.listenerGroup.Done()
  3683  	}
  3684  	return true
  3685  }
  3686  
  3687  func (s *Server) trackConn(c *conn, add bool) {
  3688  	s.mu.Lock()
  3689  	defer s.mu.Unlock()
  3690  	if s.activeConn == nil {
  3691  		s.activeConn = make(map[*conn]struct{})
  3692  	}
  3693  	if add {
  3694  		s.activeConn[c] = struct{}{}
  3695  	} else {
  3696  		delete(s.activeConn, c)
  3697  	}
  3698  }
  3699  
  3700  func (s *Server) idleTimeout() time.Duration {
  3701  	if s.IdleTimeout != 0 {
  3702  		return s.IdleTimeout
  3703  	}
  3704  	return s.ReadTimeout
  3705  }
  3706  
  3707  func (s *Server) readHeaderTimeout() time.Duration {
  3708  	if s.ReadHeaderTimeout != 0 {
  3709  		return s.ReadHeaderTimeout
  3710  	}
  3711  	return s.ReadTimeout
  3712  }
  3713  
  3714  func (s *Server) doKeepAlives() bool {
  3715  	return !s.disableKeepAlives.Load() && !s.shuttingDown()
  3716  }
  3717  
  3718  func (s *Server) shuttingDown() bool {
  3719  	return s.inShutdown.Load()
  3720  }
  3721  
  3722  // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
  3723  // By default, keep-alives are always enabled. Only very
  3724  // resource-constrained environments or servers in the process of
  3725  // shutting down should disable them.
  3726  func (s *Server) SetKeepAlivesEnabled(v bool) {
  3727  	if v {
  3728  		s.disableKeepAlives.Store(false)
  3729  		return
  3730  	}
  3731  	s.disableKeepAlives.Store(true)
  3732  
  3733  	// Close idle HTTP/1 conns:
  3734  	s.closeIdleConns()
  3735  
  3736  	// TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
  3737  }
  3738  
  3739  func (s *Server) logf(format string, args ...any) {
  3740  	if s.ErrorLog != nil {
  3741  		s.ErrorLog.Printf(format, args...)
  3742  	} else {
  3743  		log.Printf(format, args...)
  3744  	}
  3745  }
  3746  
  3747  // logf prints to the ErrorLog of the *Server associated with request r
  3748  // via ServerContextKey. If there's no associated server, or if ErrorLog
  3749  // is nil, logging is done via the log package's standard logger.
  3750  func logf(r *Request, format string, args ...any) {
  3751  	s, _ := r.Context().Value(ServerContextKey).(*Server)
  3752  	if s != nil && s.ErrorLog != nil {
  3753  		s.ErrorLog.Printf(format, args...)
  3754  	} else {
  3755  		log.Printf(format, args...)
  3756  	}
  3757  }
  3758  
  3759  // ListenAndServe listens on the TCP network address addr and then calls
  3760  // [Serve] with handler to handle requests on incoming connections.
  3761  // Accepted connections are configured to enable TCP keep-alives.
  3762  //
  3763  // The handler is typically nil, in which case [DefaultServeMux] is used.
  3764  //
  3765  // ListenAndServe always returns a non-nil error.
  3766  func ListenAndServe(addr string, handler Handler) error {
  3767  	server := &Server{Addr: addr, Handler: handler}
  3768  	return server.ListenAndServe()
  3769  }
  3770  
  3771  // ListenAndServeTLS acts identically to [ListenAndServe], except that it
  3772  // expects HTTPS connections. Additionally, files containing a certificate and
  3773  // matching private key for the server must be provided. If the certificate
  3774  // is signed by a certificate authority, the certFile should be the concatenation
  3775  // of the server's certificate, any intermediates, and the CA's certificate.
  3776  func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
  3777  	server := &Server{Addr: addr, Handler: handler}
  3778  	return server.ListenAndServeTLS(certFile, keyFile)
  3779  }
  3780  
  3781  // http3ServerHandler implements an interface in an external library that
  3782  // supports HTTP/3, allowing an external implementation of HTTP/3 to be used
  3783  // via net/http. See https://go.dev/issue/77440 for details.
  3784  //
  3785  // This is currently only used with golang.org/x/net/internal/http3, to allow
  3786  // us to test our HTTP/3 implementation againts tests in net/http. HTTP/3 is
  3787  // not yet accessible to end-users.
  3788  type http3ServerHandler struct {
  3789  	handler     serverHandler
  3790  	tlsConfig   *tls.Config
  3791  	baseCtx     context.Context
  3792  	errc        chan error
  3793  	shutdownCtx context.Context
  3794  }
  3795  
  3796  // ServeHTTP ensures that http3ServerHandler implements the Handler interface,
  3797  // and gives an HTTP/3 server implementation access to the net/http handler.
  3798  func (h *http3ServerHandler) ServeHTTP(w ResponseWriter, r *Request) {
  3799  	h.handler.ServeHTTP(w, r)
  3800  }
  3801  
  3802  // Addr gives an HTTP/3 server implementation the address that it should listen
  3803  // on.
  3804  func (h *http3ServerHandler) Addr() string {
  3805  	return h.handler.srv.Addr
  3806  }
  3807  
  3808  // TLSConfig gives an HTTP/3 server implementation the *tls.Config that it
  3809  // should use.
  3810  func (h *http3ServerHandler) TLSConfig() *tls.Config {
  3811  	return h.tlsConfig
  3812  }
  3813  
  3814  // BaseContext gives an HTTP/3 server implementation the base context to use
  3815  // for server requests.
  3816  func (h *http3ServerHandler) BaseContext() context.Context {
  3817  	return h.baseCtx
  3818  }
  3819  
  3820  // ListenErrHook should be called by an HTTP/3 server implementation to
  3821  // propagate any error it encounters when trying to listen, if any, to
  3822  // net/http.
  3823  func (h *http3ServerHandler) ListenErrHook(err error) {
  3824  	h.errc <- err
  3825  }
  3826  
  3827  // ShutdownContext gives an HTTP/3 server implementation the context that is
  3828  // used when [Server.Shutdown] is called. This allows an HTTP/3 server
  3829  // implementation to know how long it can take to gracefully shutdown in the
  3830  // function it registers with [Server.RegisterOnShutdown]. Callers must not use
  3831  // this method for any other purpose.
  3832  func (h *http3ServerHandler) ShutdownContext() context.Context {
  3833  	return h.shutdownCtx
  3834  }
  3835  
  3836  // ListenAndServeTLS listens on the TCP network address s.Addr and
  3837  // then calls [ServeTLS] to handle requests on incoming TLS connections.
  3838  // Accepted connections are configured to enable TCP keep-alives.
  3839  //
  3840  // Filenames containing a certificate and matching private key for the
  3841  // server must be provided if neither the [Server]'s TLSConfig.Certificates
  3842  // nor TLSConfig.GetCertificate are populated. If the certificate is
  3843  // signed by a certificate authority, the certFile should be the
  3844  // concatenation of the server's certificate, any intermediates, and
  3845  // the CA's certificate.
  3846  //
  3847  // If s.Addr is blank, ":https" is used.
  3848  //
  3849  // ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or
  3850  // [Server.Close], the returned error is [ErrServerClosed].
  3851  func (s *Server) ListenAndServeTLS(certFile, keyFile string) error {
  3852  	if s.shuttingDown() {
  3853  		return ErrServerClosed
  3854  	}
  3855  	addr := s.Addr
  3856  	if addr == "" {
  3857  		addr = ":https"
  3858  	}
  3859  
  3860  	p := s.protocols()
  3861  	if p.http3() {
  3862  		fn, ok := s.TLSNextProto["http/3"]
  3863  		if !ok {
  3864  			return errors.New("http: Server.Protocols contains HTTP3, but Server does not support HTTP/3")
  3865  		}
  3866  		config, err := s.setupTLSConfig(certFile, keyFile, []string{"h3"})
  3867  		if err != nil {
  3868  			return err
  3869  		}
  3870  		errc := make(chan error, 1)
  3871  		s.mu.Lock()
  3872  		s.h3 = &http3ServerHandler{
  3873  			handler:   serverHandler{s},
  3874  			tlsConfig: config,
  3875  			baseCtx:   context.WithValue(context.Background(), ServerContextKey, s),
  3876  			errc:      errc,
  3877  		}
  3878  		s.mu.Unlock()
  3879  		go fn(s, nil, s.h3)
  3880  		if err := <-errc; err != nil {
  3881  			return err
  3882  		}
  3883  	}
  3884  
  3885  	// Only start a TCP listener if HTTP/1 or HTTP/2 is used.
  3886  	if !p.HTTP1() && !p.HTTP2() && !p.UnencryptedHTTP2() {
  3887  		return nil
  3888  	}
  3889  	ln, err := net.Listen("tcp", addr)
  3890  	if err != nil {
  3891  		return err
  3892  	}
  3893  	defer ln.Close()
  3894  	return s.ServeTLS(ln, certFile, keyFile)
  3895  }
  3896  
  3897  // setupHTTP2_ServeTLS conditionally configures HTTP/2 on
  3898  // s and reports whether there was an error setting it up. If it is
  3899  // not configured for policy reasons, nil is returned.
  3900  func (s *Server) setupHTTP2_ServeTLS() error {
  3901  	s.nextProtoOnce.Do(s.onceSetNextProtoDefaults)
  3902  	return s.nextProtoErr
  3903  }
  3904  
  3905  // setupHTTP2_Serve is called from (*Server).Serve and conditionally
  3906  // configures HTTP/2 on s using a more conservative policy than
  3907  // setupHTTP2_ServeTLS because Serve is called after tls.Listen,
  3908  // and may be called concurrently. See shouldConfigureHTTP2ForServe.
  3909  //
  3910  // The tests named TestTransportAutomaticHTTP2* and
  3911  // TestConcurrentServerServe in server_test.go demonstrate some
  3912  // of the supported use cases and motivations.
  3913  func (s *Server) setupHTTP2_Serve() error {
  3914  	s.nextProtoOnce.Do(s.onceSetNextProtoDefaults_Serve)
  3915  	return s.nextProtoErr
  3916  }
  3917  
  3918  func (s *Server) onceSetNextProtoDefaults_Serve() {
  3919  	if s.shouldConfigureHTTP2ForServe() {
  3920  		s.onceSetNextProtoDefaults()
  3921  	}
  3922  }
  3923  
  3924  var http2server = godebug.New("http2server")
  3925  
  3926  // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
  3927  // configured otherwise. (by setting s.TLSNextProto non-nil)
  3928  // It must only be called via s.nextProtoOnce (use s.setupHTTP2_*).
  3929  func (s *Server) onceSetNextProtoDefaults() {
  3930  	if omitBundledHTTP2 {
  3931  		return
  3932  	}
  3933  	p := s.protocols()
  3934  	if !p.HTTP2() && !p.UnencryptedHTTP2() {
  3935  		return
  3936  	}
  3937  	if http2server.Value() == "0" {
  3938  		http2server.IncNonDefault()
  3939  		return
  3940  	}
  3941  	if _, ok := s.TLSNextProto["h2"]; ok {
  3942  		// TLSNextProto already contains an HTTP/2 implementation.
  3943  		// The user probably called golang.org/x/net/http2.ConfigureServer
  3944  		// to add it.
  3945  		return
  3946  	}
  3947  	s.configureHTTP2()
  3948  }
  3949  
  3950  // TimeoutHandler returns a [Handler] that runs h with the given time limit.
  3951  //
  3952  // The new Handler calls h.ServeHTTP to handle each request, but if a
  3953  // call runs for longer than its time limit, the handler responds with
  3954  // a 503 Service Unavailable error and the given message in its body.
  3955  // (If msg is empty, a suitable default message will be sent.)
  3956  // After such a timeout, writes by h to its [ResponseWriter] will return
  3957  // [ErrHandlerTimeout].
  3958  //
  3959  // TimeoutHandler supports the [Pusher] interface but does not support
  3960  // the [Hijacker] or [Flusher] interfaces.
  3961  func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
  3962  	return &timeoutHandler{
  3963  		handler: h,
  3964  		body:    msg,
  3965  		dt:      dt,
  3966  	}
  3967  }
  3968  
  3969  // ErrHandlerTimeout is returned on [ResponseWriter] Write calls
  3970  // in handlers which have timed out.
  3971  var ErrHandlerTimeout = errors.New("http: Handler timeout")
  3972  
  3973  type timeoutHandler struct {
  3974  	handler Handler
  3975  	body    string
  3976  	dt      time.Duration
  3977  
  3978  	// When set, no context will be created and this context will
  3979  	// be used instead.
  3980  	testContext context.Context
  3981  }
  3982  
  3983  func (h *timeoutHandler) errorBody() string {
  3984  	if h.body != "" {
  3985  		return h.body
  3986  	}
  3987  	return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
  3988  }
  3989  
  3990  func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
  3991  	ctx := h.testContext
  3992  	if ctx == nil {
  3993  		var cancelCtx context.CancelFunc
  3994  		ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
  3995  		defer cancelCtx()
  3996  	}
  3997  	r = r.WithContext(ctx)
  3998  	done := make(chan struct{})
  3999  	tw := &timeoutWriter{
  4000  		w:   w,
  4001  		h:   make(Header),
  4002  		req: r,
  4003  	}
  4004  	panicChan := make(chan any, 1)
  4005  	go func() {
  4006  		defer func() {
  4007  			if p := recover(); p != nil {
  4008  				panicChan <- p
  4009  			}
  4010  		}()
  4011  		h.handler.ServeHTTP(tw, r)
  4012  		close(done)
  4013  	}()
  4014  	select {
  4015  	case p := <-panicChan:
  4016  		panic(p)
  4017  	case <-done:
  4018  		tw.mu.Lock()
  4019  		defer tw.mu.Unlock()
  4020  		dst := w.Header()
  4021  		maps.Copy(dst, tw.h)
  4022  		if !tw.wroteHeader {
  4023  			tw.code = StatusOK
  4024  		}
  4025  		w.WriteHeader(tw.code)
  4026  		w.Write(tw.wbuf.Bytes())
  4027  	case <-ctx.Done():
  4028  		tw.mu.Lock()
  4029  		defer tw.mu.Unlock()
  4030  		switch err := ctx.Err(); err {
  4031  		case context.DeadlineExceeded:
  4032  			w.WriteHeader(StatusServiceUnavailable)
  4033  			io.WriteString(w, h.errorBody())
  4034  			tw.err = ErrHandlerTimeout
  4035  		default:
  4036  			w.WriteHeader(StatusServiceUnavailable)
  4037  			tw.err = err
  4038  		}
  4039  	}
  4040  }
  4041  
  4042  type timeoutWriter struct {
  4043  	w    ResponseWriter
  4044  	h    Header
  4045  	wbuf bytes.Buffer
  4046  	req  *Request
  4047  
  4048  	mu          sync.Mutex
  4049  	err         error
  4050  	wroteHeader bool
  4051  	code        int
  4052  }
  4053  
  4054  var _ Pusher = (*timeoutWriter)(nil)
  4055  
  4056  // Push implements the [Pusher] interface.
  4057  func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
  4058  	if pusher, ok := tw.w.(Pusher); ok {
  4059  		return pusher.Push(target, opts)
  4060  	}
  4061  	return ErrNotSupported
  4062  }
  4063  
  4064  func (tw *timeoutWriter) Header() Header { return tw.h }
  4065  
  4066  func (tw *timeoutWriter) Write(p []byte) (int, error) {
  4067  	tw.mu.Lock()
  4068  	defer tw.mu.Unlock()
  4069  	if tw.err != nil {
  4070  		return 0, tw.err
  4071  	}
  4072  	if !tw.wroteHeader {
  4073  		tw.writeHeaderLocked(StatusOK)
  4074  	}
  4075  	return tw.wbuf.Write(p)
  4076  }
  4077  
  4078  func (tw *timeoutWriter) writeHeaderLocked(code int) {
  4079  	checkWriteHeaderCode(code)
  4080  
  4081  	switch {
  4082  	case tw.err != nil:
  4083  		return
  4084  	case tw.wroteHeader:
  4085  		if tw.req != nil {
  4086  			caller := relevantCaller()
  4087  			logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
  4088  		}
  4089  	default:
  4090  		tw.wroteHeader = true
  4091  		tw.code = code
  4092  	}
  4093  }
  4094  
  4095  func (tw *timeoutWriter) WriteHeader(code int) {
  4096  	tw.mu.Lock()
  4097  	defer tw.mu.Unlock()
  4098  	tw.writeHeaderLocked(code)
  4099  }
  4100  
  4101  // onceCloseListener wraps a net.Listener, protecting it from
  4102  // multiple Close calls.
  4103  type onceCloseListener struct {
  4104  	net.Listener
  4105  	once     sync.Once
  4106  	closeErr error
  4107  }
  4108  
  4109  func (oc *onceCloseListener) Close() error {
  4110  	oc.once.Do(oc.close)
  4111  	return oc.closeErr
  4112  }
  4113  
  4114  func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
  4115  
  4116  // globalOptionsHandler responds to "OPTIONS *" requests.
  4117  type globalOptionsHandler struct{}
  4118  
  4119  func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
  4120  	w.Header().Set("Content-Length", "0")
  4121  	if r.ContentLength != 0 {
  4122  		// Read up to 4KB of OPTIONS body (as mentioned in the
  4123  		// spec as being reserved for future use), but anything
  4124  		// over that is considered a waste of server resources
  4125  		// (or an attack) and we abort and close the connection,
  4126  		// courtesy of MaxBytesReader's EOF behavior.
  4127  		mb := MaxBytesReader(w, r.Body, 4<<10)
  4128  		io.Copy(io.Discard, mb)
  4129  	}
  4130  }
  4131  
  4132  // initALPNRequest is an HTTP handler that initializes certain
  4133  // uninitialized fields in its *Request. Such partially-initialized
  4134  // Requests come from ALPN protocol handlers.
  4135  type initALPNRequest struct {
  4136  	ctx context.Context
  4137  	c   *tls.Conn
  4138  	h   serverHandler
  4139  }
  4140  
  4141  // BaseContext is an exported but unadvertised [http.Handler] method
  4142  // recognized by x/net/http2 to pass down a context; the TLSNextProto
  4143  // API predates context support so we shoehorn through the only
  4144  // interface we have available.
  4145  func (h initALPNRequest) BaseContext() context.Context { return h.ctx }
  4146  
  4147  func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
  4148  	if req.TLS == nil {
  4149  		req.TLS = &tls.ConnectionState{}
  4150  		*req.TLS = h.c.ConnectionState()
  4151  	}
  4152  	if req.Body == nil {
  4153  		req.Body = NoBody
  4154  	}
  4155  	if req.RemoteAddr == "" {
  4156  		req.RemoteAddr = h.c.RemoteAddr().String()
  4157  	}
  4158  	h.h.ServeHTTP(rw, req)
  4159  }
  4160  
  4161  // loggingConn is used for debugging.
  4162  type loggingConn struct {
  4163  	name string
  4164  	net.Conn
  4165  }
  4166  
  4167  var (
  4168  	uniqNameMu   sync.Mutex
  4169  	uniqNameNext = make(map[string]int)
  4170  )
  4171  
  4172  func newLoggingConn(baseName string, c net.Conn) net.Conn {
  4173  	uniqNameMu.Lock()
  4174  	defer uniqNameMu.Unlock()
  4175  	uniqNameNext[baseName]++
  4176  	return &loggingConn{
  4177  		name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
  4178  		Conn: c,
  4179  	}
  4180  }
  4181  
  4182  func (c *loggingConn) Write(p []byte) (n int, err error) {
  4183  	log.Printf("%s.Write(%d) = ....", c.name, len(p))
  4184  	n, err = c.Conn.Write(p)
  4185  	log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
  4186  	return
  4187  }
  4188  
  4189  func (c *loggingConn) Read(p []byte) (n int, err error) {
  4190  	log.Printf("%s.Read(%d) = ....", c.name, len(p))
  4191  	n, err = c.Conn.Read(p)
  4192  	log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
  4193  	return
  4194  }
  4195  
  4196  func (c *loggingConn) Close() (err error) {
  4197  	log.Printf("%s.Close() = ...", c.name)
  4198  	err = c.Conn.Close()
  4199  	log.Printf("%s.Close() = %v", c.name, err)
  4200  	return
  4201  }
  4202  
  4203  // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
  4204  // It only contains one field (and a pointer field at that), so it
  4205  // fits in an interface value without an extra allocation.
  4206  type checkConnErrorWriter struct {
  4207  	c *conn
  4208  }
  4209  
  4210  func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
  4211  	n, err = w.c.rwc.Write(p)
  4212  	if err != nil && w.c.werr == nil {
  4213  		w.c.werr = err
  4214  		w.c.cancelCtx()
  4215  	}
  4216  	return
  4217  }
  4218  
  4219  func numLeadingCRorLF(v []byte) (n int) {
  4220  	for _, b := range v {
  4221  		if b == '\r' || b == '\n' {
  4222  			n++
  4223  			continue
  4224  		}
  4225  		break
  4226  	}
  4227  	return
  4228  }
  4229  
  4230  // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
  4231  // looks like it might've been a misdirected plaintext HTTP request.
  4232  func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
  4233  	switch string(hdr[:]) {
  4234  	case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
  4235  		return true
  4236  	}
  4237  	return false
  4238  }
  4239  
  4240  // MaxBytesHandler returns a [Handler] that runs h with its [ResponseWriter] and [Request.Body] wrapped by a MaxBytesReader.
  4241  func MaxBytesHandler(h Handler, n int64) Handler {
  4242  	return HandlerFunc(func(w ResponseWriter, r *Request) {
  4243  		r2 := *r
  4244  		r2.Body = MaxBytesReader(w, r.Body, n)
  4245  		h.ServeHTTP(w, &r2)
  4246  	})
  4247  }
  4248  

View as plain text