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

View as plain text