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