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