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