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