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