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

View as plain text