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