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