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

View as plain text