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

View as plain text