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