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