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