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

View as plain text