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