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() {
   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 (srv *Server) newConn(rwc net.Conn) *conn {
   632  	c := &conn{
   633  		server: srv,
   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 (srv *Server) maxHeaderBytes() int {
   919  	if srv.MaxHeaderBytes > 0 {
   920  		return srv.MaxHeaderBytes
   921  	}
   922  	return DefaultMaxHeaderBytes
   923  }
   924  
   925  func (srv *Server) initialReadLimitSize() int64 {
   926  	return int64(srv.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 (srv *Server) tlsHandshakeTimeout() time.Duration {
   935  	var ret time.Duration
   936  	for _, v := range [...]time.Duration{
   937  		srv.ReadHeaderTimeout,
   938  		srv.ReadTimeout,
   939  		srv.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  //
  2484  // # Compatibility
  2485  //
  2486  // The pattern syntax and matching behavior of ServeMux changed significantly
  2487  // in Go 1.22. To restore the old behavior, set the GODEBUG environment variable
  2488  // to "httpmuxgo121=1". This setting is read once, at program startup; changes
  2489  // during execution will be ignored.
  2490  //
  2491  // The backwards-incompatible changes include:
  2492  //   - Wildcards are just ordinary literal path segments in 1.21.
  2493  //     For example, the pattern "/{x}" will match only that path in 1.21,
  2494  //     but will match any one-segment path in 1.22.
  2495  //   - In 1.21, no pattern was rejected, unless it was empty or conflicted with an existing pattern.
  2496  //     In 1.22, syntactically invalid patterns will cause [ServeMux.Handle] and [ServeMux.HandleFunc] to panic.
  2497  //     For example, in 1.21, the patterns "/{"  and "/a{x}" match themselves,
  2498  //     but in 1.22 they are invalid and will cause a panic when registered.
  2499  //   - In 1.22, each segment of a pattern is unescaped; this was not done in 1.21.
  2500  //     For example, in 1.22 the pattern "/%61" matches the path "/a" ("%61" being the URL escape sequence for "a"),
  2501  //     but in 1.21 it would match only the path "/%2561" (where "%25" is the escape for the percent sign).
  2502  //   - When matching patterns to paths, in 1.22 each segment of the path is unescaped; in 1.21, the entire path is unescaped.
  2503  //     This change mostly affects how paths with %2F escapes adjacent to slashes are treated.
  2504  //     See https://go.dev/issue/21955 for details.
  2505  type ServeMux struct {
  2506  	mu       sync.RWMutex
  2507  	tree     routingNode
  2508  	index    routingIndex
  2509  	patterns []*pattern  // TODO(jba): remove if possible
  2510  	mux121   serveMux121 // used only when GODEBUG=httpmuxgo121=1
  2511  }
  2512  
  2513  // NewServeMux allocates and returns a new [ServeMux].
  2514  func NewServeMux() *ServeMux {
  2515  	return &ServeMux{}
  2516  }
  2517  
  2518  // DefaultServeMux is the default [ServeMux] used by [Serve].
  2519  var DefaultServeMux = &defaultServeMux
  2520  
  2521  var defaultServeMux ServeMux
  2522  
  2523  // cleanPath returns the canonical path for p, eliminating . and .. elements.
  2524  func cleanPath(p string) string {
  2525  	if p == "" {
  2526  		return "/"
  2527  	}
  2528  	if p[0] != '/' {
  2529  		p = "/" + p
  2530  	}
  2531  	np := path.Clean(p)
  2532  	// path.Clean removes trailing slash except for root;
  2533  	// put the trailing slash back if necessary.
  2534  	if p[len(p)-1] == '/' && np != "/" {
  2535  		// Fast path for common case of p being the string we want:
  2536  		if len(p) == len(np)+1 && strings.HasPrefix(p, np) {
  2537  			np = p
  2538  		} else {
  2539  			np += "/"
  2540  		}
  2541  	}
  2542  	return np
  2543  }
  2544  
  2545  // stripHostPort returns h without any trailing ":<port>".
  2546  func stripHostPort(h string) string {
  2547  	// If no port on host, return unchanged
  2548  	if !strings.Contains(h, ":") {
  2549  		return h
  2550  	}
  2551  	host, _, err := net.SplitHostPort(h)
  2552  	if err != nil {
  2553  		return h // on error, return unchanged
  2554  	}
  2555  	return host
  2556  }
  2557  
  2558  // Handler returns the handler to use for the given request,
  2559  // consulting r.Method, r.Host, and r.URL.Path. It always returns
  2560  // a non-nil handler. If the path is not in its canonical form, the
  2561  // handler will be an internally-generated handler that redirects
  2562  // to the canonical path. If the host contains a port, it is ignored
  2563  // when matching handlers.
  2564  //
  2565  // The path and host are used unchanged for CONNECT requests.
  2566  //
  2567  // Handler also returns the registered pattern that matches the
  2568  // request or, in the case of internally-generated redirects,
  2569  // the path that will match after following the redirect.
  2570  //
  2571  // If there is no registered handler that applies to the request,
  2572  // Handler returns a “page not found” handler and an empty pattern.
  2573  func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) {
  2574  	if use121 {
  2575  		return mux.mux121.findHandler(r)
  2576  	}
  2577  	h, p, _, _ := mux.findHandler(r)
  2578  	return h, p
  2579  }
  2580  
  2581  // findHandler finds a handler for a request.
  2582  // If there is a matching handler, it returns it and the pattern that matched.
  2583  // Otherwise it returns a Redirect or NotFound handler with the path that would match
  2584  // after the redirect.
  2585  func (mux *ServeMux) findHandler(r *Request) (h Handler, patStr string, _ *pattern, matches []string) {
  2586  	var n *routingNode
  2587  	host := r.URL.Host
  2588  	escapedPath := r.URL.EscapedPath()
  2589  	path := escapedPath
  2590  	// CONNECT requests are not canonicalized.
  2591  	if r.Method == "CONNECT" {
  2592  		// If r.URL.Path is /tree and its handler is not registered,
  2593  		// the /tree -> /tree/ redirect applies to CONNECT requests
  2594  		// but the path canonicalization does not.
  2595  		_, _, u := mux.matchOrRedirect(host, r.Method, path, r.URL)
  2596  		if u != nil {
  2597  			return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
  2598  		}
  2599  		// Redo the match, this time with r.Host instead of r.URL.Host.
  2600  		// Pass a nil URL to skip the trailing-slash redirect logic.
  2601  		n, matches, _ = mux.matchOrRedirect(r.Host, r.Method, path, nil)
  2602  	} else {
  2603  		// All other requests have any port stripped and path cleaned
  2604  		// before passing to mux.handler.
  2605  		host = stripHostPort(r.Host)
  2606  		path = cleanPath(path)
  2607  
  2608  		// If the given path is /tree and its handler is not registered,
  2609  		// redirect for /tree/.
  2610  		var u *url.URL
  2611  		n, matches, u = mux.matchOrRedirect(host, r.Method, path, r.URL)
  2612  		if u != nil {
  2613  			return RedirectHandler(u.String(), StatusMovedPermanently), u.Path, nil, nil
  2614  		}
  2615  		if path != escapedPath {
  2616  			// Redirect to cleaned path.
  2617  			patStr := ""
  2618  			if n != nil {
  2619  				patStr = n.pattern.String()
  2620  			}
  2621  			u := &url.URL{Path: path, RawQuery: r.URL.RawQuery}
  2622  			return RedirectHandler(u.String(), StatusMovedPermanently), patStr, nil, nil
  2623  		}
  2624  	}
  2625  	if n == nil {
  2626  		// We didn't find a match with the request method. To distinguish between
  2627  		// Not Found and Method Not Allowed, see if there is another pattern that
  2628  		// matches except for the method.
  2629  		allowedMethods := mux.matchingMethods(host, path)
  2630  		if len(allowedMethods) > 0 {
  2631  			return HandlerFunc(func(w ResponseWriter, r *Request) {
  2632  				w.Header().Set("Allow", strings.Join(allowedMethods, ", "))
  2633  				Error(w, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed)
  2634  			}), "", nil, nil
  2635  		}
  2636  		return NotFoundHandler(), "", nil, nil
  2637  	}
  2638  	return n.handler, n.pattern.String(), n.pattern, matches
  2639  }
  2640  
  2641  // matchOrRedirect looks up a node in the tree that matches the host, method and path.
  2642  //
  2643  // If the url argument is non-nil, handler also deals with trailing-slash
  2644  // redirection: when a path doesn't match exactly, the match is tried again
  2645  // after appending "/" to the path. If that second match succeeds, the last
  2646  // return value is the URL to redirect to.
  2647  func (mux *ServeMux) matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL) {
  2648  	mux.mu.RLock()
  2649  	defer mux.mu.RUnlock()
  2650  
  2651  	n, matches := mux.tree.match(host, method, path)
  2652  	// If we have an exact match, or we were asked not to try trailing-slash redirection,
  2653  	// or the URL already has a trailing slash, then we're done.
  2654  	if !exactMatch(n, path) && u != nil && !strings.HasSuffix(path, "/") {
  2655  		// If there is an exact match with a trailing slash, then redirect.
  2656  		path += "/"
  2657  		n2, _ := mux.tree.match(host, method, path)
  2658  		if exactMatch(n2, path) {
  2659  			return nil, nil, &url.URL{Path: cleanPath(u.Path) + "/", RawQuery: u.RawQuery}
  2660  		}
  2661  	}
  2662  	return n, matches, nil
  2663  }
  2664  
  2665  // exactMatch reports whether the node's pattern exactly matches the path.
  2666  // As a special case, if the node is nil, exactMatch return false.
  2667  //
  2668  // Before wildcards were introduced, it was clear that an exact match meant
  2669  // that the pattern and path were the same string. The only other possibility
  2670  // was that a trailing-slash pattern, like "/", matched a path longer than
  2671  // it, like "/a".
  2672  //
  2673  // With wildcards, we define an inexact match as any one where a multi wildcard
  2674  // matches a non-empty string. All other matches are exact.
  2675  // For example, these are all exact matches:
  2676  //
  2677  //	pattern   path
  2678  //	/a        /a
  2679  //	/{x}      /a
  2680  //	/a/{$}    /a/
  2681  //	/a/       /a/
  2682  //
  2683  // The last case has a multi wildcard (implicitly), but the match is exact because
  2684  // the wildcard matches the empty string.
  2685  //
  2686  // Examples of matches that are not exact:
  2687  //
  2688  //	pattern   path
  2689  //	/         /a
  2690  //	/a/{x...} /a/b
  2691  func exactMatch(n *routingNode, path string) bool {
  2692  	if n == nil {
  2693  		return false
  2694  	}
  2695  	// We can't directly implement the definition (empty match for multi
  2696  	// wildcard) because we don't record a match for anonymous multis.
  2697  
  2698  	// If there is no multi, the match is exact.
  2699  	if !n.pattern.lastSegment().multi {
  2700  		return true
  2701  	}
  2702  
  2703  	// If the path doesn't end in a trailing slash, then the multi match
  2704  	// is non-empty.
  2705  	if len(path) > 0 && path[len(path)-1] != '/' {
  2706  		return false
  2707  	}
  2708  	// Only patterns ending in {$} or a multi wildcard can
  2709  	// match a path with a trailing slash.
  2710  	// For the match to be exact, the number of pattern
  2711  	// segments should be the same as the number of slashes in the path.
  2712  	// E.g. "/a/b/{$}" and "/a/b/{...}" exactly match "/a/b/", but "/a/" does not.
  2713  	return len(n.pattern.segments) == strings.Count(path, "/")
  2714  }
  2715  
  2716  // matchingMethods return a sorted list of all methods that would match with the given host and path.
  2717  func (mux *ServeMux) matchingMethods(host, path string) []string {
  2718  	// Hold the read lock for the entire method so that the two matches are done
  2719  	// on the same set of registered patterns.
  2720  	mux.mu.RLock()
  2721  	defer mux.mu.RUnlock()
  2722  	ms := map[string]bool{}
  2723  	mux.tree.matchingMethods(host, path, ms)
  2724  	// matchOrRedirect will try appending a trailing slash if there is no match.
  2725  	if !strings.HasSuffix(path, "/") {
  2726  		mux.tree.matchingMethods(host, path+"/", ms)
  2727  	}
  2728  	return slices.Sorted(maps.Keys(ms))
  2729  }
  2730  
  2731  // ServeHTTP dispatches the request to the handler whose
  2732  // pattern most closely matches the request URL.
  2733  func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) {
  2734  	if r.RequestURI == "*" {
  2735  		if r.ProtoAtLeast(1, 1) {
  2736  			w.Header().Set("Connection", "close")
  2737  		}
  2738  		w.WriteHeader(StatusBadRequest)
  2739  		return
  2740  	}
  2741  	var h Handler
  2742  	if use121 {
  2743  		h, _ = mux.mux121.findHandler(r)
  2744  	} else {
  2745  		h, r.Pattern, r.pat, r.matches = mux.findHandler(r)
  2746  	}
  2747  	h.ServeHTTP(w, r)
  2748  }
  2749  
  2750  // The four functions below all call ServeMux.register so that callerLocation
  2751  // always refers to user code.
  2752  
  2753  // Handle registers the handler for the given pattern.
  2754  // If the given pattern conflicts, with one that is already registered, Handle
  2755  // panics.
  2756  func (mux *ServeMux) Handle(pattern string, handler Handler) {
  2757  	if use121 {
  2758  		mux.mux121.handle(pattern, handler)
  2759  	} else {
  2760  		mux.register(pattern, handler)
  2761  	}
  2762  }
  2763  
  2764  // HandleFunc registers the handler function for the given pattern.
  2765  // If the given pattern conflicts, with one that is already registered, HandleFunc
  2766  // panics.
  2767  func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  2768  	if use121 {
  2769  		mux.mux121.handleFunc(pattern, handler)
  2770  	} else {
  2771  		mux.register(pattern, HandlerFunc(handler))
  2772  	}
  2773  }
  2774  
  2775  // Handle registers the handler for the given pattern in [DefaultServeMux].
  2776  // The documentation for [ServeMux] explains how patterns are matched.
  2777  func Handle(pattern string, handler Handler) {
  2778  	if use121 {
  2779  		DefaultServeMux.mux121.handle(pattern, handler)
  2780  	} else {
  2781  		DefaultServeMux.register(pattern, handler)
  2782  	}
  2783  }
  2784  
  2785  // HandleFunc registers the handler function for the given pattern in [DefaultServeMux].
  2786  // The documentation for [ServeMux] explains how patterns are matched.
  2787  func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) {
  2788  	if use121 {
  2789  		DefaultServeMux.mux121.handleFunc(pattern, handler)
  2790  	} else {
  2791  		DefaultServeMux.register(pattern, HandlerFunc(handler))
  2792  	}
  2793  }
  2794  
  2795  func (mux *ServeMux) register(pattern string, handler Handler) {
  2796  	if err := mux.registerErr(pattern, handler); err != nil {
  2797  		panic(err)
  2798  	}
  2799  }
  2800  
  2801  func (mux *ServeMux) registerErr(patstr string, handler Handler) error {
  2802  	if patstr == "" {
  2803  		return errors.New("http: invalid pattern")
  2804  	}
  2805  	if handler == nil {
  2806  		return errors.New("http: nil handler")
  2807  	}
  2808  	if f, ok := handler.(HandlerFunc); ok && f == nil {
  2809  		return errors.New("http: nil handler")
  2810  	}
  2811  
  2812  	pat, err := parsePattern(patstr)
  2813  	if err != nil {
  2814  		return fmt.Errorf("parsing %q: %w", patstr, err)
  2815  	}
  2816  
  2817  	// Get the caller's location, for better conflict error messages.
  2818  	// Skip register and whatever calls it.
  2819  	_, file, line, ok := runtime.Caller(3)
  2820  	if !ok {
  2821  		pat.loc = "unknown location"
  2822  	} else {
  2823  		pat.loc = fmt.Sprintf("%s:%d", file, line)
  2824  	}
  2825  
  2826  	mux.mu.Lock()
  2827  	defer mux.mu.Unlock()
  2828  	// Check for conflict.
  2829  	if err := mux.index.possiblyConflictingPatterns(pat, func(pat2 *pattern) error {
  2830  		if pat.conflictsWith(pat2) {
  2831  			d := describeConflict(pat, pat2)
  2832  			return fmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s):\n%s",
  2833  				pat, pat.loc, pat2, pat2.loc, d)
  2834  		}
  2835  		return nil
  2836  	}); err != nil {
  2837  		return err
  2838  	}
  2839  	mux.tree.addPattern(pat, handler)
  2840  	mux.index.addPattern(pat)
  2841  	mux.patterns = append(mux.patterns, 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  	inShutdown atomic.Bool // true when server is in shutdown
  2977  
  2978  	disableKeepAlives atomic.Bool
  2979  	nextProtoOnce     sync.Once // guards setupHTTP2_* init
  2980  	nextProtoErr      error     // result of http2.ConfigureServer if used
  2981  
  2982  	mu         sync.Mutex
  2983  	listeners  map[*net.Listener]struct{}
  2984  	activeConn map[*conn]struct{}
  2985  	onShutdown []func()
  2986  
  2987  	listenerGroup sync.WaitGroup
  2988  }
  2989  
  2990  // Close immediately closes all active net.Listeners and any
  2991  // connections in state [StateNew], [StateActive], or [StateIdle]. For a
  2992  // graceful shutdown, use [Server.Shutdown].
  2993  //
  2994  // Close does not attempt to close (and does not even know about)
  2995  // any hijacked connections, such as WebSockets.
  2996  //
  2997  // Close returns any error returned from closing the [Server]'s
  2998  // underlying Listener(s).
  2999  func (srv *Server) Close() error {
  3000  	srv.inShutdown.Store(true)
  3001  	srv.mu.Lock()
  3002  	defer srv.mu.Unlock()
  3003  	err := srv.closeListenersLocked()
  3004  
  3005  	// Unlock srv.mu while waiting for listenerGroup.
  3006  	// The group Add and Done calls are made with srv.mu held,
  3007  	// to avoid adding a new listener in the window between
  3008  	// us setting inShutdown above and waiting here.
  3009  	srv.mu.Unlock()
  3010  	srv.listenerGroup.Wait()
  3011  	srv.mu.Lock()
  3012  
  3013  	for c := range srv.activeConn {
  3014  		c.rwc.Close()
  3015  		delete(srv.activeConn, c)
  3016  	}
  3017  	return err
  3018  }
  3019  
  3020  // shutdownPollIntervalMax is the max polling interval when checking
  3021  // quiescence during Server.Shutdown. Polling starts with a small
  3022  // interval and backs off to the max.
  3023  // Ideally we could find a solution that doesn't involve polling,
  3024  // but which also doesn't have a high runtime cost (and doesn't
  3025  // involve any contentious mutexes), but that is left as an
  3026  // exercise for the reader.
  3027  const shutdownPollIntervalMax = 500 * time.Millisecond
  3028  
  3029  // Shutdown gracefully shuts down the server without interrupting any
  3030  // active connections. Shutdown works by first closing all open
  3031  // listeners, then closing all idle connections, and then waiting
  3032  // indefinitely for connections to return to idle and then shut down.
  3033  // If the provided context expires before the shutdown is complete,
  3034  // Shutdown returns the context's error, otherwise it returns any
  3035  // error returned from closing the [Server]'s underlying Listener(s).
  3036  //
  3037  // When Shutdown is called, [Serve], [ListenAndServe], and
  3038  // [ListenAndServeTLS] immediately return [ErrServerClosed]. Make sure the
  3039  // program doesn't exit and waits instead for Shutdown to return.
  3040  //
  3041  // Shutdown does not attempt to close nor wait for hijacked
  3042  // connections such as WebSockets. The caller of Shutdown should
  3043  // separately notify such long-lived connections of shutdown and wait
  3044  // for them to close, if desired. See [Server.RegisterOnShutdown] for a way to
  3045  // register shutdown notification functions.
  3046  //
  3047  // Once Shutdown has been called on a server, it may not be reused;
  3048  // future calls to methods such as Serve will return ErrServerClosed.
  3049  func (srv *Server) Shutdown(ctx context.Context) error {
  3050  	srv.inShutdown.Store(true)
  3051  
  3052  	srv.mu.Lock()
  3053  	lnerr := srv.closeListenersLocked()
  3054  	for _, f := range srv.onShutdown {
  3055  		go f()
  3056  	}
  3057  	srv.mu.Unlock()
  3058  	srv.listenerGroup.Wait()
  3059  
  3060  	pollIntervalBase := time.Millisecond
  3061  	nextPollInterval := func() time.Duration {
  3062  		// Add 10% jitter.
  3063  		interval := pollIntervalBase + time.Duration(rand.Intn(int(pollIntervalBase/10)))
  3064  		// Double and clamp for next time.
  3065  		pollIntervalBase *= 2
  3066  		if pollIntervalBase > shutdownPollIntervalMax {
  3067  			pollIntervalBase = shutdownPollIntervalMax
  3068  		}
  3069  		return interval
  3070  	}
  3071  
  3072  	timer := time.NewTimer(nextPollInterval())
  3073  	defer timer.Stop()
  3074  	for {
  3075  		if srv.closeIdleConns() {
  3076  			return lnerr
  3077  		}
  3078  		select {
  3079  		case <-ctx.Done():
  3080  			return ctx.Err()
  3081  		case <-timer.C:
  3082  			timer.Reset(nextPollInterval())
  3083  		}
  3084  	}
  3085  }
  3086  
  3087  // RegisterOnShutdown registers a function to call on [Server.Shutdown].
  3088  // This can be used to gracefully shutdown connections that have
  3089  // undergone ALPN protocol upgrade or that have been hijacked.
  3090  // This function should start protocol-specific graceful shutdown,
  3091  // but should not wait for shutdown to complete.
  3092  func (srv *Server) RegisterOnShutdown(f func()) {
  3093  	srv.mu.Lock()
  3094  	srv.onShutdown = append(srv.onShutdown, f)
  3095  	srv.mu.Unlock()
  3096  }
  3097  
  3098  // closeIdleConns closes all idle connections and reports whether the
  3099  // server is quiescent.
  3100  func (s *Server) closeIdleConns() bool {
  3101  	s.mu.Lock()
  3102  	defer s.mu.Unlock()
  3103  	quiescent := true
  3104  	for c := range s.activeConn {
  3105  		st, unixSec := c.getState()
  3106  		// Issue 22682: treat StateNew connections as if
  3107  		// they're idle if we haven't read the first request's
  3108  		// header in over 5 seconds.
  3109  		if st == StateNew && unixSec < time.Now().Unix()-5 {
  3110  			st = StateIdle
  3111  		}
  3112  		if st != StateIdle || unixSec == 0 {
  3113  			// Assume unixSec == 0 means it's a very new
  3114  			// connection, without state set yet.
  3115  			quiescent = false
  3116  			continue
  3117  		}
  3118  		c.rwc.Close()
  3119  		delete(s.activeConn, c)
  3120  	}
  3121  	return quiescent
  3122  }
  3123  
  3124  func (s *Server) closeListenersLocked() error {
  3125  	var err error
  3126  	for ln := range s.listeners {
  3127  		if cerr := (*ln).Close(); cerr != nil && err == nil {
  3128  			err = cerr
  3129  		}
  3130  	}
  3131  	return err
  3132  }
  3133  
  3134  // A ConnState represents the state of a client connection to a server.
  3135  // It's used by the optional [Server.ConnState] hook.
  3136  type ConnState int
  3137  
  3138  const (
  3139  	// StateNew represents a new connection that is expected to
  3140  	// send a request immediately. Connections begin at this
  3141  	// state and then transition to either StateActive or
  3142  	// StateClosed.
  3143  	StateNew ConnState = iota
  3144  
  3145  	// StateActive represents a connection that has read 1 or more
  3146  	// bytes of a request. The Server.ConnState hook for
  3147  	// StateActive fires before the request has entered a handler
  3148  	// and doesn't fire again until the request has been
  3149  	// handled. After the request is handled, the state
  3150  	// transitions to StateClosed, StateHijacked, or StateIdle.
  3151  	// For HTTP/2, StateActive fires on the transition from zero
  3152  	// to one active request, and only transitions away once all
  3153  	// active requests are complete. That means that ConnState
  3154  	// cannot be used to do per-request work; ConnState only notes
  3155  	// the overall state of the connection.
  3156  	StateActive
  3157  
  3158  	// StateIdle represents a connection that has finished
  3159  	// handling a request and is in the keep-alive state, waiting
  3160  	// for a new request. Connections transition from StateIdle
  3161  	// to either StateActive or StateClosed.
  3162  	StateIdle
  3163  
  3164  	// StateHijacked represents a hijacked connection.
  3165  	// This is a terminal state. It does not transition to StateClosed.
  3166  	StateHijacked
  3167  
  3168  	// StateClosed represents a closed connection.
  3169  	// This is a terminal state. Hijacked connections do not
  3170  	// transition to StateClosed.
  3171  	StateClosed
  3172  )
  3173  
  3174  var stateName = map[ConnState]string{
  3175  	StateNew:      "new",
  3176  	StateActive:   "active",
  3177  	StateIdle:     "idle",
  3178  	StateHijacked: "hijacked",
  3179  	StateClosed:   "closed",
  3180  }
  3181  
  3182  func (c ConnState) String() string {
  3183  	return stateName[c]
  3184  }
  3185  
  3186  // serverHandler delegates to either the server's Handler or
  3187  // DefaultServeMux and also handles "OPTIONS *" requests.
  3188  type serverHandler struct {
  3189  	srv *Server
  3190  }
  3191  
  3192  // ServeHTTP should be an internal detail,
  3193  // but widely used packages access it using linkname.
  3194  // Notable members of the hall of shame include:
  3195  //   - github.com/erda-project/erda-infra
  3196  //
  3197  // Do not remove or change the type signature.
  3198  // See go.dev/issue/67401.
  3199  //
  3200  //go:linkname badServeHTTP net/http.serverHandler.ServeHTTP
  3201  func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) {
  3202  	handler := sh.srv.Handler
  3203  	if handler == nil {
  3204  		handler = DefaultServeMux
  3205  	}
  3206  	if !sh.srv.DisableGeneralOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" {
  3207  		handler = globalOptionsHandler{}
  3208  	}
  3209  
  3210  	handler.ServeHTTP(rw, req)
  3211  }
  3212  
  3213  func badServeHTTP(serverHandler, ResponseWriter, *Request)
  3214  
  3215  // AllowQuerySemicolons returns a handler that serves requests by converting any
  3216  // unescaped semicolons in the URL query to ampersands, and invoking the handler h.
  3217  //
  3218  // This restores the pre-Go 1.17 behavior of splitting query parameters on both
  3219  // semicolons and ampersands. (See golang.org/issue/25192). Note that this
  3220  // behavior doesn't match that of many proxies, and the mismatch can lead to
  3221  // security issues.
  3222  //
  3223  // AllowQuerySemicolons should be invoked before [Request.ParseForm] is called.
  3224  func AllowQuerySemicolons(h Handler) Handler {
  3225  	return HandlerFunc(func(w ResponseWriter, r *Request) {
  3226  		if strings.Contains(r.URL.RawQuery, ";") {
  3227  			r2 := new(Request)
  3228  			*r2 = *r
  3229  			r2.URL = new(url.URL)
  3230  			*r2.URL = *r.URL
  3231  			r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&")
  3232  			h.ServeHTTP(w, r2)
  3233  		} else {
  3234  			h.ServeHTTP(w, r)
  3235  		}
  3236  	})
  3237  }
  3238  
  3239  // ListenAndServe listens on the TCP network address srv.Addr and then
  3240  // calls [Serve] to handle requests on incoming connections.
  3241  // Accepted connections are configured to enable TCP keep-alives.
  3242  //
  3243  // If srv.Addr is blank, ":http" is used.
  3244  //
  3245  // ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close],
  3246  // the returned error is [ErrServerClosed].
  3247  func (srv *Server) ListenAndServe() error {
  3248  	if srv.shuttingDown() {
  3249  		return ErrServerClosed
  3250  	}
  3251  	addr := srv.Addr
  3252  	if addr == "" {
  3253  		addr = ":http"
  3254  	}
  3255  	ln, err := net.Listen("tcp", addr)
  3256  	if err != nil {
  3257  		return err
  3258  	}
  3259  	return srv.Serve(ln)
  3260  }
  3261  
  3262  var testHookServerServe func(*Server, net.Listener) // used if non-nil
  3263  
  3264  // shouldConfigureHTTP2ForServe reports whether Server.Serve should configure
  3265  // automatic HTTP/2. (which sets up the srv.TLSNextProto map)
  3266  func (srv *Server) shouldConfigureHTTP2ForServe() bool {
  3267  	if srv.TLSConfig == nil {
  3268  		// Compatibility with Go 1.6:
  3269  		// If there's no TLSConfig, it's possible that the user just
  3270  		// didn't set it on the http.Server, but did pass it to
  3271  		// tls.NewListener and passed that listener to Serve.
  3272  		// So we should configure HTTP/2 (to set up srv.TLSNextProto)
  3273  		// in case the listener returns an "h2" *tls.Conn.
  3274  		return true
  3275  	}
  3276  	// The user specified a TLSConfig on their http.Server.
  3277  	// In this, case, only configure HTTP/2 if their tls.Config
  3278  	// explicitly mentions "h2". Otherwise http2.ConfigureServer
  3279  	// would modify the tls.Config to add it, but they probably already
  3280  	// passed this tls.Config to tls.NewListener. And if they did,
  3281  	// it's too late anyway to fix it. It would only be potentially racy.
  3282  	// See Issue 15908.
  3283  	return slices.Contains(srv.TLSConfig.NextProtos, http2NextProtoTLS)
  3284  }
  3285  
  3286  // ErrServerClosed is returned by the [Server.Serve], [ServeTLS], [ListenAndServe],
  3287  // and [ListenAndServeTLS] methods after a call to [Server.Shutdown] or [Server.Close].
  3288  var ErrServerClosed = errors.New("http: Server closed")
  3289  
  3290  // Serve accepts incoming connections on the Listener l, creating a
  3291  // new service goroutine for each. The service goroutines read requests and
  3292  // then call srv.Handler to reply to them.
  3293  //
  3294  // HTTP/2 support is only enabled if the Listener returns [*tls.Conn]
  3295  // connections and they were configured with "h2" in the TLS
  3296  // Config.NextProtos.
  3297  //
  3298  // Serve always returns a non-nil error and closes l.
  3299  // After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed].
  3300  func (srv *Server) Serve(l net.Listener) error {
  3301  	if fn := testHookServerServe; fn != nil {
  3302  		fn(srv, l) // call hook with unwrapped listener
  3303  	}
  3304  
  3305  	origListener := l
  3306  	l = &onceCloseListener{Listener: l}
  3307  	defer l.Close()
  3308  
  3309  	if err := srv.setupHTTP2_Serve(); err != nil {
  3310  		return err
  3311  	}
  3312  
  3313  	if !srv.trackListener(&l, true) {
  3314  		return ErrServerClosed
  3315  	}
  3316  	defer srv.trackListener(&l, false)
  3317  
  3318  	baseCtx := context.Background()
  3319  	if srv.BaseContext != nil {
  3320  		baseCtx = srv.BaseContext(origListener)
  3321  		if baseCtx == nil {
  3322  			panic("BaseContext returned a nil context")
  3323  		}
  3324  	}
  3325  
  3326  	var tempDelay time.Duration // how long to sleep on accept failure
  3327  
  3328  	ctx := context.WithValue(baseCtx, ServerContextKey, srv)
  3329  	for {
  3330  		rw, err := l.Accept()
  3331  		if err != nil {
  3332  			if srv.shuttingDown() {
  3333  				return ErrServerClosed
  3334  			}
  3335  			if ne, ok := err.(net.Error); ok && ne.Temporary() {
  3336  				if tempDelay == 0 {
  3337  					tempDelay = 5 * time.Millisecond
  3338  				} else {
  3339  					tempDelay *= 2
  3340  				}
  3341  				if max := 1 * time.Second; tempDelay > max {
  3342  					tempDelay = max
  3343  				}
  3344  				srv.logf("http: Accept error: %v; retrying in %v", err, tempDelay)
  3345  				time.Sleep(tempDelay)
  3346  				continue
  3347  			}
  3348  			return err
  3349  		}
  3350  		connCtx := ctx
  3351  		if cc := srv.ConnContext; cc != nil {
  3352  			connCtx = cc(connCtx, rw)
  3353  			if connCtx == nil {
  3354  				panic("ConnContext returned nil")
  3355  			}
  3356  		}
  3357  		tempDelay = 0
  3358  		c := srv.newConn(rw)
  3359  		c.setState(c.rwc, StateNew, runHooks) // before Serve can return
  3360  		go c.serve(connCtx)
  3361  	}
  3362  }
  3363  
  3364  // ServeTLS accepts incoming connections on the Listener l, creating a
  3365  // new service goroutine for each. The service goroutines perform TLS
  3366  // setup and then read requests, calling srv.Handler to reply to them.
  3367  //
  3368  // Files containing a certificate and matching private key for the
  3369  // server must be provided if neither the [Server]'s
  3370  // TLSConfig.Certificates, TLSConfig.GetCertificate nor
  3371  // config.GetConfigForClient are populated.
  3372  // If the certificate is signed by a certificate authority, the
  3373  // certFile should be the concatenation of the server's certificate,
  3374  // any intermediates, and the CA's certificate.
  3375  //
  3376  // ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the
  3377  // returned error is [ErrServerClosed].
  3378  func (srv *Server) ServeTLS(l net.Listener, certFile, keyFile string) error {
  3379  	// Setup HTTP/2 before srv.Serve, to initialize srv.TLSConfig
  3380  	// before we clone it and create the TLS Listener.
  3381  	if err := srv.setupHTTP2_ServeTLS(); err != nil {
  3382  		return err
  3383  	}
  3384  
  3385  	config := cloneTLSConfig(srv.TLSConfig)
  3386  	if !slices.Contains(config.NextProtos, "http/1.1") {
  3387  		config.NextProtos = append(config.NextProtos, "http/1.1")
  3388  	}
  3389  
  3390  	configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil || config.GetConfigForClient != nil
  3391  	if !configHasCert || certFile != "" || keyFile != "" {
  3392  		var err error
  3393  		config.Certificates = make([]tls.Certificate, 1)
  3394  		config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile)
  3395  		if err != nil {
  3396  			return err
  3397  		}
  3398  	}
  3399  
  3400  	tlsListener := tls.NewListener(l, config)
  3401  	return srv.Serve(tlsListener)
  3402  }
  3403  
  3404  // trackListener adds or removes a net.Listener to the set of tracked
  3405  // listeners.
  3406  //
  3407  // We store a pointer to interface in the map set, in case the
  3408  // net.Listener is not comparable. This is safe because we only call
  3409  // trackListener via Serve and can track+defer untrack the same
  3410  // pointer to local variable there. We never need to compare a
  3411  // Listener from another caller.
  3412  //
  3413  // It reports whether the server is still up (not Shutdown or Closed).
  3414  func (s *Server) trackListener(ln *net.Listener, add bool) bool {
  3415  	s.mu.Lock()
  3416  	defer s.mu.Unlock()
  3417  	if s.listeners == nil {
  3418  		s.listeners = make(map[*net.Listener]struct{})
  3419  	}
  3420  	if add {
  3421  		if s.shuttingDown() {
  3422  			return false
  3423  		}
  3424  		s.listeners[ln] = struct{}{}
  3425  		s.listenerGroup.Add(1)
  3426  	} else {
  3427  		delete(s.listeners, ln)
  3428  		s.listenerGroup.Done()
  3429  	}
  3430  	return true
  3431  }
  3432  
  3433  func (s *Server) trackConn(c *conn, add bool) {
  3434  	s.mu.Lock()
  3435  	defer s.mu.Unlock()
  3436  	if s.activeConn == nil {
  3437  		s.activeConn = make(map[*conn]struct{})
  3438  	}
  3439  	if add {
  3440  		s.activeConn[c] = struct{}{}
  3441  	} else {
  3442  		delete(s.activeConn, c)
  3443  	}
  3444  }
  3445  
  3446  func (s *Server) idleTimeout() time.Duration {
  3447  	if s.IdleTimeout != 0 {
  3448  		return s.IdleTimeout
  3449  	}
  3450  	return s.ReadTimeout
  3451  }
  3452  
  3453  func (s *Server) readHeaderTimeout() time.Duration {
  3454  	if s.ReadHeaderTimeout != 0 {
  3455  		return s.ReadHeaderTimeout
  3456  	}
  3457  	return s.ReadTimeout
  3458  }
  3459  
  3460  func (s *Server) doKeepAlives() bool {
  3461  	return !s.disableKeepAlives.Load() && !s.shuttingDown()
  3462  }
  3463  
  3464  func (s *Server) shuttingDown() bool {
  3465  	return s.inShutdown.Load()
  3466  }
  3467  
  3468  // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled.
  3469  // By default, keep-alives are always enabled. Only very
  3470  // resource-constrained environments or servers in the process of
  3471  // shutting down should disable them.
  3472  func (srv *Server) SetKeepAlivesEnabled(v bool) {
  3473  	if v {
  3474  		srv.disableKeepAlives.Store(false)
  3475  		return
  3476  	}
  3477  	srv.disableKeepAlives.Store(true)
  3478  
  3479  	// Close idle HTTP/1 conns:
  3480  	srv.closeIdleConns()
  3481  
  3482  	// TODO: Issue 26303: close HTTP/2 conns as soon as they become idle.
  3483  }
  3484  
  3485  func (s *Server) logf(format string, args ...any) {
  3486  	if s.ErrorLog != nil {
  3487  		s.ErrorLog.Printf(format, args...)
  3488  	} else {
  3489  		log.Printf(format, args...)
  3490  	}
  3491  }
  3492  
  3493  // logf prints to the ErrorLog of the *Server associated with request r
  3494  // via ServerContextKey. If there's no associated server, or if ErrorLog
  3495  // is nil, logging is done via the log package's standard logger.
  3496  func logf(r *Request, format string, args ...any) {
  3497  	s, _ := r.Context().Value(ServerContextKey).(*Server)
  3498  	if s != nil && s.ErrorLog != nil {
  3499  		s.ErrorLog.Printf(format, args...)
  3500  	} else {
  3501  		log.Printf(format, args...)
  3502  	}
  3503  }
  3504  
  3505  // ListenAndServe listens on the TCP network address addr and then calls
  3506  // [Serve] with handler to handle requests on incoming connections.
  3507  // Accepted connections are configured to enable TCP keep-alives.
  3508  //
  3509  // The handler is typically nil, in which case [DefaultServeMux] is used.
  3510  //
  3511  // ListenAndServe always returns a non-nil error.
  3512  func ListenAndServe(addr string, handler Handler) error {
  3513  	server := &Server{Addr: addr, Handler: handler}
  3514  	return server.ListenAndServe()
  3515  }
  3516  
  3517  // ListenAndServeTLS acts identically to [ListenAndServe], except that it
  3518  // expects HTTPS connections. Additionally, files containing a certificate and
  3519  // matching private key for the server must be provided. If the certificate
  3520  // is signed by a certificate authority, the certFile should be the concatenation
  3521  // of the server's certificate, any intermediates, and the CA's certificate.
  3522  func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error {
  3523  	server := &Server{Addr: addr, Handler: handler}
  3524  	return server.ListenAndServeTLS(certFile, keyFile)
  3525  }
  3526  
  3527  // ListenAndServeTLS listens on the TCP network address srv.Addr and
  3528  // then calls [ServeTLS] to handle requests on incoming TLS connections.
  3529  // Accepted connections are configured to enable TCP keep-alives.
  3530  //
  3531  // Filenames containing a certificate and matching private key for the
  3532  // server must be provided if neither the [Server]'s TLSConfig.Certificates
  3533  // nor TLSConfig.GetCertificate are populated. If the certificate is
  3534  // signed by a certificate authority, the certFile should be the
  3535  // concatenation of the server's certificate, any intermediates, and
  3536  // the CA's certificate.
  3537  //
  3538  // If srv.Addr is blank, ":https" is used.
  3539  //
  3540  // ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or
  3541  // [Server.Close], the returned error is [ErrServerClosed].
  3542  func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error {
  3543  	if srv.shuttingDown() {
  3544  		return ErrServerClosed
  3545  	}
  3546  	addr := srv.Addr
  3547  	if addr == "" {
  3548  		addr = ":https"
  3549  	}
  3550  
  3551  	ln, err := net.Listen("tcp", addr)
  3552  	if err != nil {
  3553  		return err
  3554  	}
  3555  
  3556  	defer ln.Close()
  3557  
  3558  	return srv.ServeTLS(ln, certFile, keyFile)
  3559  }
  3560  
  3561  // setupHTTP2_ServeTLS conditionally configures HTTP/2 on
  3562  // srv and reports whether there was an error setting it up. If it is
  3563  // not configured for policy reasons, nil is returned.
  3564  func (srv *Server) setupHTTP2_ServeTLS() error {
  3565  	srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults)
  3566  	return srv.nextProtoErr
  3567  }
  3568  
  3569  // setupHTTP2_Serve is called from (*Server).Serve and conditionally
  3570  // configures HTTP/2 on srv using a more conservative policy than
  3571  // setupHTTP2_ServeTLS because Serve is called after tls.Listen,
  3572  // and may be called concurrently. See shouldConfigureHTTP2ForServe.
  3573  //
  3574  // The tests named TestTransportAutomaticHTTP2* and
  3575  // TestConcurrentServerServe in server_test.go demonstrate some
  3576  // of the supported use cases and motivations.
  3577  func (srv *Server) setupHTTP2_Serve() error {
  3578  	srv.nextProtoOnce.Do(srv.onceSetNextProtoDefaults_Serve)
  3579  	return srv.nextProtoErr
  3580  }
  3581  
  3582  func (srv *Server) onceSetNextProtoDefaults_Serve() {
  3583  	if srv.shouldConfigureHTTP2ForServe() {
  3584  		srv.onceSetNextProtoDefaults()
  3585  	}
  3586  }
  3587  
  3588  var http2server = godebug.New("http2server")
  3589  
  3590  // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't
  3591  // configured otherwise. (by setting srv.TLSNextProto non-nil)
  3592  // It must only be called via srv.nextProtoOnce (use srv.setupHTTP2_*).
  3593  func (srv *Server) onceSetNextProtoDefaults() {
  3594  	if omitBundledHTTP2 {
  3595  		return
  3596  	}
  3597  	if http2server.Value() == "0" {
  3598  		http2server.IncNonDefault()
  3599  		return
  3600  	}
  3601  	// Enable HTTP/2 by default if the user hasn't otherwise
  3602  	// configured their TLSNextProto map.
  3603  	if srv.TLSNextProto == nil {
  3604  		conf := &http2Server{}
  3605  		srv.nextProtoErr = http2ConfigureServer(srv, conf)
  3606  	}
  3607  }
  3608  
  3609  // TimeoutHandler returns a [Handler] that runs h with the given time limit.
  3610  //
  3611  // The new Handler calls h.ServeHTTP to handle each request, but if a
  3612  // call runs for longer than its time limit, the handler responds with
  3613  // a 503 Service Unavailable error and the given message in its body.
  3614  // (If msg is empty, a suitable default message will be sent.)
  3615  // After such a timeout, writes by h to its [ResponseWriter] will return
  3616  // [ErrHandlerTimeout].
  3617  //
  3618  // TimeoutHandler supports the [Pusher] interface but does not support
  3619  // the [Hijacker] or [Flusher] interfaces.
  3620  func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler {
  3621  	return &timeoutHandler{
  3622  		handler: h,
  3623  		body:    msg,
  3624  		dt:      dt,
  3625  	}
  3626  }
  3627  
  3628  // ErrHandlerTimeout is returned on [ResponseWriter] Write calls
  3629  // in handlers which have timed out.
  3630  var ErrHandlerTimeout = errors.New("http: Handler timeout")
  3631  
  3632  type timeoutHandler struct {
  3633  	handler Handler
  3634  	body    string
  3635  	dt      time.Duration
  3636  
  3637  	// When set, no context will be created and this context will
  3638  	// be used instead.
  3639  	testContext context.Context
  3640  }
  3641  
  3642  func (h *timeoutHandler) errorBody() string {
  3643  	if h.body != "" {
  3644  		return h.body
  3645  	}
  3646  	return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>"
  3647  }
  3648  
  3649  func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) {
  3650  	ctx := h.testContext
  3651  	if ctx == nil {
  3652  		var cancelCtx context.CancelFunc
  3653  		ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt)
  3654  		defer cancelCtx()
  3655  	}
  3656  	r = r.WithContext(ctx)
  3657  	done := make(chan struct{})
  3658  	tw := &timeoutWriter{
  3659  		w:   w,
  3660  		h:   make(Header),
  3661  		req: r,
  3662  	}
  3663  	panicChan := make(chan any, 1)
  3664  	go func() {
  3665  		defer func() {
  3666  			if p := recover(); p != nil {
  3667  				panicChan <- p
  3668  			}
  3669  		}()
  3670  		h.handler.ServeHTTP(tw, r)
  3671  		close(done)
  3672  	}()
  3673  	select {
  3674  	case p := <-panicChan:
  3675  		panic(p)
  3676  	case <-done:
  3677  		tw.mu.Lock()
  3678  		defer tw.mu.Unlock()
  3679  		dst := w.Header()
  3680  		for k, vv := range tw.h {
  3681  			dst[k] = vv
  3682  		}
  3683  		if !tw.wroteHeader {
  3684  			tw.code = StatusOK
  3685  		}
  3686  		w.WriteHeader(tw.code)
  3687  		w.Write(tw.wbuf.Bytes())
  3688  	case <-ctx.Done():
  3689  		tw.mu.Lock()
  3690  		defer tw.mu.Unlock()
  3691  		switch err := ctx.Err(); err {
  3692  		case context.DeadlineExceeded:
  3693  			w.WriteHeader(StatusServiceUnavailable)
  3694  			io.WriteString(w, h.errorBody())
  3695  			tw.err = ErrHandlerTimeout
  3696  		default:
  3697  			w.WriteHeader(StatusServiceUnavailable)
  3698  			tw.err = err
  3699  		}
  3700  	}
  3701  }
  3702  
  3703  type timeoutWriter struct {
  3704  	w    ResponseWriter
  3705  	h    Header
  3706  	wbuf bytes.Buffer
  3707  	req  *Request
  3708  
  3709  	mu          sync.Mutex
  3710  	err         error
  3711  	wroteHeader bool
  3712  	code        int
  3713  }
  3714  
  3715  var _ Pusher = (*timeoutWriter)(nil)
  3716  
  3717  // Push implements the [Pusher] interface.
  3718  func (tw *timeoutWriter) Push(target string, opts *PushOptions) error {
  3719  	if pusher, ok := tw.w.(Pusher); ok {
  3720  		return pusher.Push(target, opts)
  3721  	}
  3722  	return ErrNotSupported
  3723  }
  3724  
  3725  func (tw *timeoutWriter) Header() Header { return tw.h }
  3726  
  3727  func (tw *timeoutWriter) Write(p []byte) (int, error) {
  3728  	tw.mu.Lock()
  3729  	defer tw.mu.Unlock()
  3730  	if tw.err != nil {
  3731  		return 0, tw.err
  3732  	}
  3733  	if !tw.wroteHeader {
  3734  		tw.writeHeaderLocked(StatusOK)
  3735  	}
  3736  	return tw.wbuf.Write(p)
  3737  }
  3738  
  3739  func (tw *timeoutWriter) writeHeaderLocked(code int) {
  3740  	checkWriteHeaderCode(code)
  3741  
  3742  	switch {
  3743  	case tw.err != nil:
  3744  		return
  3745  	case tw.wroteHeader:
  3746  		if tw.req != nil {
  3747  			caller := relevantCaller()
  3748  			logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line)
  3749  		}
  3750  	default:
  3751  		tw.wroteHeader = true
  3752  		tw.code = code
  3753  	}
  3754  }
  3755  
  3756  func (tw *timeoutWriter) WriteHeader(code int) {
  3757  	tw.mu.Lock()
  3758  	defer tw.mu.Unlock()
  3759  	tw.writeHeaderLocked(code)
  3760  }
  3761  
  3762  // onceCloseListener wraps a net.Listener, protecting it from
  3763  // multiple Close calls.
  3764  type onceCloseListener struct {
  3765  	net.Listener
  3766  	once     sync.Once
  3767  	closeErr error
  3768  }
  3769  
  3770  func (oc *onceCloseListener) Close() error {
  3771  	oc.once.Do(oc.close)
  3772  	return oc.closeErr
  3773  }
  3774  
  3775  func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() }
  3776  
  3777  // globalOptionsHandler responds to "OPTIONS *" requests.
  3778  type globalOptionsHandler struct{}
  3779  
  3780  func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) {
  3781  	w.Header().Set("Content-Length", "0")
  3782  	if r.ContentLength != 0 {
  3783  		// Read up to 4KB of OPTIONS body (as mentioned in the
  3784  		// spec as being reserved for future use), but anything
  3785  		// over that is considered a waste of server resources
  3786  		// (or an attack) and we abort and close the connection,
  3787  		// courtesy of MaxBytesReader's EOF behavior.
  3788  		mb := MaxBytesReader(w, r.Body, 4<<10)
  3789  		io.Copy(io.Discard, mb)
  3790  	}
  3791  }
  3792  
  3793  // initALPNRequest is an HTTP handler that initializes certain
  3794  // uninitialized fields in its *Request. Such partially-initialized
  3795  // Requests come from ALPN protocol handlers.
  3796  type initALPNRequest struct {
  3797  	ctx context.Context
  3798  	c   *tls.Conn
  3799  	h   serverHandler
  3800  }
  3801  
  3802  // BaseContext is an exported but unadvertised [http.Handler] method
  3803  // recognized by x/net/http2 to pass down a context; the TLSNextProto
  3804  // API predates context support so we shoehorn through the only
  3805  // interface we have available.
  3806  func (h initALPNRequest) BaseContext() context.Context { return h.ctx }
  3807  
  3808  func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) {
  3809  	if req.TLS == nil {
  3810  		req.TLS = &tls.ConnectionState{}
  3811  		*req.TLS = h.c.ConnectionState()
  3812  	}
  3813  	if req.Body == nil {
  3814  		req.Body = NoBody
  3815  	}
  3816  	if req.RemoteAddr == "" {
  3817  		req.RemoteAddr = h.c.RemoteAddr().String()
  3818  	}
  3819  	h.h.ServeHTTP(rw, req)
  3820  }
  3821  
  3822  // loggingConn is used for debugging.
  3823  type loggingConn struct {
  3824  	name string
  3825  	net.Conn
  3826  }
  3827  
  3828  var (
  3829  	uniqNameMu   sync.Mutex
  3830  	uniqNameNext = make(map[string]int)
  3831  )
  3832  
  3833  func newLoggingConn(baseName string, c net.Conn) net.Conn {
  3834  	uniqNameMu.Lock()
  3835  	defer uniqNameMu.Unlock()
  3836  	uniqNameNext[baseName]++
  3837  	return &loggingConn{
  3838  		name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]),
  3839  		Conn: c,
  3840  	}
  3841  }
  3842  
  3843  func (c *loggingConn) Write(p []byte) (n int, err error) {
  3844  	log.Printf("%s.Write(%d) = ....", c.name, len(p))
  3845  	n, err = c.Conn.Write(p)
  3846  	log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err)
  3847  	return
  3848  }
  3849  
  3850  func (c *loggingConn) Read(p []byte) (n int, err error) {
  3851  	log.Printf("%s.Read(%d) = ....", c.name, len(p))
  3852  	n, err = c.Conn.Read(p)
  3853  	log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err)
  3854  	return
  3855  }
  3856  
  3857  func (c *loggingConn) Close() (err error) {
  3858  	log.Printf("%s.Close() = ...", c.name)
  3859  	err = c.Conn.Close()
  3860  	log.Printf("%s.Close() = %v", c.name, err)
  3861  	return
  3862  }
  3863  
  3864  // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr.
  3865  // It only contains one field (and a pointer field at that), so it
  3866  // fits in an interface value without an extra allocation.
  3867  type checkConnErrorWriter struct {
  3868  	c *conn
  3869  }
  3870  
  3871  func (w checkConnErrorWriter) Write(p []byte) (n int, err error) {
  3872  	n, err = w.c.rwc.Write(p)
  3873  	if err != nil && w.c.werr == nil {
  3874  		w.c.werr = err
  3875  		w.c.cancelCtx()
  3876  	}
  3877  	return
  3878  }
  3879  
  3880  func numLeadingCRorLF(v []byte) (n int) {
  3881  	for _, b := range v {
  3882  		if b == '\r' || b == '\n' {
  3883  			n++
  3884  			continue
  3885  		}
  3886  		break
  3887  	}
  3888  	return
  3889  }
  3890  
  3891  // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header
  3892  // looks like it might've been a misdirected plaintext HTTP request.
  3893  func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool {
  3894  	switch string(hdr[:]) {
  3895  	case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO":
  3896  		return true
  3897  	}
  3898  	return false
  3899  }
  3900  
  3901  // MaxBytesHandler returns a [Handler] that runs h with its [ResponseWriter] and [Request.Body] wrapped by a MaxBytesReader.
  3902  func MaxBytesHandler(h Handler, n int64) Handler {
  3903  	return HandlerFunc(func(w ResponseWriter, r *Request) {
  3904  		r2 := *r
  3905  		r2.Body = MaxBytesReader(w, r.Body, n)
  3906  		h.ServeHTTP(w, &r2)
  3907  	})
  3908  }
  3909  

View as plain text