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

View as plain text