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