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