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

View as plain text