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 if code == StatusSwitchingProtocols { 1644 // Don't continue using a connection after sending 101 Switching Protocols. 1645 w.closeAfterReply = true 1646 } 1647 1648 // Only override the Connection header if it is not a successful 1649 // protocol switch response and if KeepAlives are not enabled. 1650 // See https://golang.org/issue/36381. 1651 delConnectionHeader := w.closeAfterReply && 1652 (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) && 1653 !isProtocolSwitchResponse(w.status, header) 1654 if delConnectionHeader { 1655 delHeader("Connection") 1656 // Don't set Connection: close on a 2xx CONNECT response, 1657 // even though we will close the connection if the handler doesn't hijack it. 1658 // If the handler does hijack the connection, the Connection: close is confusing. 1659 if w.req.ProtoAtLeast(1, 1) && !isSuccessfulCONNECT { 1660 setHeader.connection = "close" 1661 } else { 1662 setHeader.connection = "" 1663 } 1664 } 1665 1666 writeStatusLine(w.conn.bufw, w.req.ProtoAtLeast(1, 1), code, w.statusBuf[:]) 1667 cw.header.WriteSubset(w.conn.bufw, excludeHeader) 1668 setHeader.Write(w.conn.bufw) 1669 w.conn.bufw.Write(crlf) 1670 } 1671 1672 // foreachHeaderElement splits v according to the "#rule" construction 1673 // in RFC 7230 section 7 and calls fn for each non-empty element. 1674 func foreachHeaderElement(v string, fn func(string)) { 1675 v = textproto.TrimString(v) 1676 if v == "" { 1677 return 1678 } 1679 if !strings.Contains(v, ",") { 1680 fn(v) 1681 return 1682 } 1683 for f := range strings.SplitSeq(v, ",") { 1684 if f = textproto.TrimString(f); f != "" { 1685 fn(f) 1686 } 1687 } 1688 } 1689 1690 // writeStatusLine writes an HTTP/1.x Status-Line (RFC 7230 Section 3.1.2) 1691 // to bw. is11 is whether the HTTP request is HTTP/1.1. false means HTTP/1.0. 1692 // code is the response status code. 1693 // scratch is an optional scratch buffer. If it has at least capacity 3, it's used. 1694 func writeStatusLine(bw *bufio.Writer, is11 bool, code int, scratch []byte) { 1695 if is11 { 1696 bw.WriteString("HTTP/1.1 ") 1697 } else { 1698 bw.WriteString("HTTP/1.0 ") 1699 } 1700 if text := StatusText(code); text != "" { 1701 bw.Write(strconv.AppendInt(scratch[:0], int64(code), 10)) 1702 bw.WriteByte(' ') 1703 bw.WriteString(text) 1704 bw.WriteString("\r\n") 1705 } else { 1706 // don't worry about performance 1707 fmt.Fprintf(bw, "%03d status code %d\r\n", code, code) 1708 } 1709 } 1710 1711 // bodyAllowed reports whether a Write is allowed for this response type. 1712 // It's illegal to call this before the header has been flushed. 1713 func (w *response) bodyAllowed() bool { 1714 if !w.wroteHeader { 1715 panic("net/http: bodyAllowed called before the header was written") 1716 } 1717 return bodyAllowedForStatus(w.status) 1718 } 1719 1720 // The Life Of A Write is like this: 1721 // 1722 // Handler starts. No header has been sent. The handler can either 1723 // write a header, or just start writing. Writing before sending a header 1724 // sends an implicitly empty 200 OK header. 1725 // 1726 // If the handler didn't declare a Content-Length up front, we either 1727 // go into chunking mode or, if the handler finishes running before 1728 // the chunking buffer size, we compute a Content-Length and send that 1729 // in the header instead. 1730 // 1731 // Likewise, if the handler didn't set a Content-Type, we sniff that 1732 // from the initial chunk of output. 1733 // 1734 // The Writers are wired together like: 1735 // 1736 // 1. *response (the ResponseWriter) -> 1737 // 2. (*response).w, a [*bufio.Writer] of bufferBeforeChunkingSize bytes -> 1738 // 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type) 1739 // and which writes the chunk headers, if needed -> 1740 // 4. conn.bufw, a *bufio.Writer of default (4kB) bytes, writing to -> 1741 // 5. checkConnErrorWriter{c}, which notes any non-nil error on Write 1742 // and populates c.werr with it if so, but otherwise writes to -> 1743 // 6. the rwc, the [net.Conn]. 1744 // 1745 // TODO(bradfitz): short-circuit some of the buffering when the 1746 // initial header contains both a Content-Type and Content-Length. 1747 // Also short-circuit in (1) when the header's been sent and not in 1748 // chunking mode, writing directly to (4) instead, if (2) has no 1749 // buffered data. More generally, we could short-circuit from (1) to 1750 // (3) even in chunking mode if the write size from (1) is over some 1751 // threshold and nothing is in (2). The answer might be mostly making 1752 // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal 1753 // with this instead. 1754 func (w *response) Write(data []byte) (n int, err error) { 1755 return w.write(len(data), data, "") 1756 } 1757 1758 func (w *response) WriteString(data string) (n int, err error) { 1759 return w.write(len(data), nil, data) 1760 } 1761 1762 // either dataB or dataS is non-zero. 1763 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) { 1764 if w.conn.hijacked() { 1765 if lenData > 0 { 1766 caller := relevantCaller() 1767 w.conn.server.logf("http: response.Write on hijacked connection from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line) 1768 } 1769 return 0, ErrHijacked 1770 } 1771 1772 if w.canWriteContinue.Load() { 1773 // Body reader wants to write 100 Continue but hasn't yet. Tell it not to. 1774 w.disableWriteContinue(true) 1775 } 1776 1777 if !w.wroteHeader { 1778 w.WriteHeader(StatusOK) 1779 } 1780 if lenData == 0 { 1781 return 0, nil 1782 } 1783 if !w.bodyAllowed() { 1784 return 0, ErrBodyNotAllowed 1785 } 1786 1787 w.written += int64(lenData) // ignoring errors, for errorKludge 1788 if w.contentLength != -1 && w.written > w.contentLength { 1789 return 0, ErrContentLength 1790 } 1791 if dataB != nil { 1792 return w.w.Write(dataB) 1793 } else { 1794 return w.w.WriteString(dataS) 1795 } 1796 } 1797 1798 func (w *response) finishRequest() { 1799 w.handlerDone.Store(true) 1800 1801 if !w.wroteHeader { 1802 w.WriteHeader(StatusOK) 1803 } 1804 1805 w.w.Flush() 1806 putBufioWriter(w.w) 1807 w.cw.close() 1808 w.conn.bufw.Flush() 1809 1810 w.conn.r.abortPendingRead() 1811 w.reqBody.registerOnHitEOF(nil) // prevent new background read from starting 1812 1813 if w.canWriteContinue.Load() { 1814 w.disableWriteContinue(true) 1815 } 1816 1817 // Close the body (regardless of w.closeAfterReply) so we can 1818 // re-use its bufio.Reader later safely. 1819 // 1820 // In full-duplex mode, this may also drain the remaining request body. 1821 w.reqBody.Close() 1822 } 1823 1824 // shouldReuseConnection reports whether the underlying TCP connection can be reused. 1825 // It must only be called after the handler is done executing. 1826 func (w *response) shouldReuseConnection() bool { 1827 if w.closeAfterReply { 1828 // The request or something set while executing the 1829 // handler indicated we shouldn't reuse this 1830 // connection. 1831 return false 1832 } 1833 1834 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written { 1835 // Did not write enough. Avoid getting out of sync. 1836 return false 1837 } 1838 1839 // There was some error writing to the underlying connection 1840 // during the request, so don't re-use this conn. 1841 if w.conn.werr != nil { 1842 return false 1843 } 1844 1845 // We haven't read the entire request body, so we can't reuse the connection. 1846 if !w.reqBody.consumedEntireBody() { 1847 return false 1848 } 1849 1850 return true 1851 } 1852 1853 func (w *response) Flush() { 1854 w.FlushError() 1855 } 1856 1857 func (w *response) FlushError() error { 1858 if !w.wroteHeader { 1859 w.WriteHeader(StatusOK) 1860 } 1861 err := w.w.Flush() 1862 e2 := w.cw.flush() 1863 if err == nil { 1864 err = e2 1865 } 1866 return err 1867 } 1868 1869 func (c *conn) finalFlush() { 1870 if c.bufr != nil { 1871 // Steal the bufio.Reader (~4KB worth of memory) and its associated 1872 // reader for a future connection. 1873 putBufioReader(c.bufr) 1874 c.bufr = nil 1875 } 1876 1877 if c.bufw != nil { 1878 c.bufw.Flush() 1879 // Steal the bufio.Writer (~4KB worth of memory) and its associated 1880 // writer for a future connection. 1881 putBufioWriter(c.bufw) 1882 c.bufw = nil 1883 } 1884 } 1885 1886 // Close the connection. 1887 func (c *conn) close() { 1888 c.finalFlush() 1889 c.rwc.Close() 1890 } 1891 1892 // rstAvoidanceDelay is the amount of time we sleep after closing the 1893 // write side of a TCP connection before closing the entire socket. 1894 // By sleeping, we increase the chances that the client sees our FIN 1895 // and processes its final data before they process the subsequent RST 1896 // from closing a connection with known unread data. 1897 // This RST seems to occur mostly on BSD systems. (And Windows?) 1898 // This timeout is somewhat arbitrary (~latency around the planet), 1899 // and may be modified by tests. 1900 // 1901 // TODO(bcmills): This should arguably be a server configuration parameter, 1902 // not a hard-coded value. 1903 var rstAvoidanceDelay = 500 * time.Millisecond 1904 1905 type closeWriter interface { 1906 CloseWrite() error 1907 } 1908 1909 var _ closeWriter = (*net.TCPConn)(nil) 1910 1911 // closeWriteAndWait flushes any outstanding data and sends a FIN packet (if 1912 // client is connected via TCP), signaling that we're done. We then 1913 // pause for a bit, hoping the client processes it before any 1914 // subsequent RST. 1915 // 1916 // See https://golang.org/issue/3595 1917 func (c *conn) closeWriteAndWait() { 1918 c.finalFlush() 1919 if tcp, ok := c.rwc.(closeWriter); ok { 1920 tcp.CloseWrite() 1921 } 1922 1923 // When we return from closeWriteAndWait, the caller will fully close the 1924 // connection. If client is still writing to the connection, this will cause 1925 // the write to fail with ECONNRESET or similar. Unfortunately, many TCP 1926 // implementations will also drop unread packets from the client's read buffer 1927 // when a write fails, causing our final response to be truncated away too. 1928 // 1929 // As a result, https://www.rfc-editor.org/rfc/rfc7230#section-6.6 recommends 1930 // that “[t]he server … continues to read from the connection until it 1931 // receives a corresponding close by the client, or until the server is 1932 // reasonably certain that its own TCP stack has received the client's 1933 // acknowledgement of the packet(s) containing the server's last response.” 1934 // 1935 // Unfortunately, we have no straightforward way to be “reasonably certain” 1936 // that we have received the client's ACK, and at any rate we don't want to 1937 // allow a misbehaving client to soak up server connections indefinitely by 1938 // withholding an ACK, nor do we want to go through the complexity or overhead 1939 // of using low-level APIs to figure out when a TCP round-trip has completed. 1940 // 1941 // Instead, we declare that we are “reasonably certain” that we received the 1942 // ACK if maxRSTAvoidanceDelay has elapsed. 1943 time.Sleep(rstAvoidanceDelay) 1944 } 1945 1946 // validNextProto reports whether the proto is a valid ALPN protocol name. 1947 // Everything is valid except the empty string and built-in protocol types, 1948 // so that those can't be overridden with alternate implementations. 1949 func validNextProto(proto string) bool { 1950 switch proto { 1951 case "", "http/1.1", "http/1.0": 1952 return false 1953 } 1954 return true 1955 } 1956 1957 const ( 1958 runHooks = true 1959 skipHooks = false 1960 ) 1961 1962 func (c *conn) setState(nc net.Conn, state ConnState, runHook bool) { 1963 srv := c.server 1964 switch state { 1965 case StateNew: 1966 srv.trackConn(c, true) 1967 case StateHijacked, StateClosed: 1968 srv.trackConn(c, false) 1969 } 1970 if state > 0xff || state < 0 { 1971 panic("internal error") 1972 } 1973 packedState := uint64(time.Now().Unix()<<8) | uint64(state) 1974 c.curState.Store(packedState) 1975 if !runHook { 1976 return 1977 } 1978 if hook := srv.ConnState; hook != nil { 1979 hook(nc, state) 1980 } 1981 } 1982 1983 func (c *conn) getState() (state ConnState, unixSec int64) { 1984 packedState := c.curState.Load() 1985 return ConnState(packedState & 0xff), int64(packedState >> 8) 1986 } 1987 1988 // badRequestError is a literal string (used by in the server in HTML, 1989 // unescaped) to tell the user why their request was bad. It should 1990 // be plain text without user info or other embedded errors. 1991 func badRequestError(e string) error { return statusError{StatusBadRequest, e} } 1992 1993 // statusError is an error used to respond to a request with an HTTP status. 1994 // The text should be plain text without user info or other embedded errors. 1995 type statusError struct { 1996 code int 1997 text string 1998 } 1999 2000 func (e statusError) Error() string { return StatusText(e.code) + ": " + e.text } 2001 2002 // ErrAbortHandler is a sentinel panic value to abort a handler. 2003 // While any panic from ServeHTTP aborts the response to the client, 2004 // panicking with ErrAbortHandler also suppresses logging of a stack 2005 // trace to the server's error log. 2006 var ErrAbortHandler = internal.ErrAbortHandler 2007 2008 // isCommonNetReadError reports whether err is a common error 2009 // encountered during reading a request off the network when the 2010 // client has gone away or had its read fail somehow. This is used to 2011 // determine which logs are interesting enough to log about. 2012 func isCommonNetReadError(err error) bool { 2013 if err == io.EOF { 2014 return true 2015 } 2016 if neterr, ok := err.(net.Error); ok && neterr.Timeout() { 2017 return true 2018 } 2019 if oe, ok := err.(*net.OpError); ok && oe.Op == "read" { 2020 return true 2021 } 2022 return false 2023 } 2024 2025 // Serve a new connection. 2026 func (c *conn) serve(ctx context.Context) { 2027 if ra := c.rwc.RemoteAddr(); ra != nil { 2028 c.remoteAddr = ra.String() 2029 } 2030 ctx = context.WithValue(ctx, LocalAddrContextKey, c.rwc.LocalAddr()) 2031 var inFlightResponse *response 2032 defer func() { 2033 if inFlightResponse != nil { 2034 inFlightResponse.cancelCtx() 2035 inFlightResponse.disableWriteContinue(true) 2036 } 2037 if !c.hijacked() && !c.http2HandedOff { 2038 if inFlightResponse != nil { 2039 inFlightResponse.conn.r.abortPendingRead() 2040 inFlightResponse.reqBody.Close() 2041 } 2042 c.close() 2043 c.setState(c.rwc, StateClosed, runHooks) 2044 } 2045 }() 2046 2047 type connectionStater interface { 2048 ConnectionState() tls.ConnectionState 2049 } 2050 type handshakeContexter interface { 2051 HandshakeContext(ctx context.Context) error 2052 } 2053 if connStater, ok := c.rwc.(connectionStater); ok { 2054 tlsTO := c.server.tlsHandshakeTimeout() 2055 if tlsTO > 0 { 2056 dl := time.Now().Add(tlsTO) 2057 c.rwc.SetReadDeadline(dl) 2058 c.rwc.SetWriteDeadline(dl) 2059 } 2060 var err error 2061 if handshaker, ok := c.rwc.(handshakeContexter); ok { 2062 err = handshaker.HandshakeContext(ctx) 2063 } 2064 if err != nil { 2065 // If the handshake failed due to the client not speaking 2066 // TLS, assume they're speaking plaintext HTTP and write a 2067 // 400 response on the TLS conn's underlying net.Conn. 2068 var reason string 2069 if re, ok := err.(tls.RecordHeaderError); ok && re.Conn != nil && tlsRecordHeaderLooksLikeHTTP(re.RecordHeader) { 2070 io.WriteString(re.Conn, "HTTP/1.0 400 Bad Request\r\n\r\nClient sent an HTTP request to an HTTPS server.\n") 2071 re.Conn.Close() 2072 reason = "client sent an HTTP request to an HTTPS server" 2073 } else { 2074 reason = err.Error() 2075 } 2076 c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), reason) 2077 return 2078 } 2079 // Restore Conn-level deadlines. 2080 if tlsTO > 0 { 2081 c.rwc.SetReadDeadline(time.Time{}) 2082 c.rwc.SetWriteDeadline(time.Time{}) 2083 } 2084 c.tlsState = new(tls.ConnectionState) 2085 *c.tlsState = connStater.ConnectionState() 2086 proto := c.tlsState.NegotiatedProtocol 2087 if proto == "h2" && c.server.h2 != nil { 2088 // net/http/internal/http2 path. 2089 // 2090 // Mark freshly created HTTP/2 as active and prevent any server state hooks 2091 // from being run on these connections. This prevents closeIdleConns from 2092 // closing such connections. See issue https://golang.org/issue/39776. 2093 c.setState(c.rwc, StateActive, skipHooks) 2094 const sawClientPreface = false 2095 c.serveHTTP2(ctx, sawClientPreface) 2096 return 2097 } 2098 tlsConn, tlsConnOK := c.rwc.(*tls.Conn) 2099 if validNextProto(proto) && tlsConnOK { 2100 // Legacy TLSNextProto path. 2101 if fn := c.server.TLSNextProto[proto]; fn != nil { 2102 h := initALPNRequest{ctx, tlsConn, c.server} 2103 // Mark freshly created HTTP/2 as active (see above). 2104 c.setState(c.rwc, StateActive, skipHooks) 2105 fn(c.server, tlsConn, h) 2106 } 2107 return 2108 } 2109 } 2110 2111 // HTTP/1.x or unencrypted HTTP/2. 2112 2113 // Set Request.TLS if the conn is not a *tls.Conn, but implements ConnectionState. 2114 if c.tlsState == nil { 2115 if tc, ok := c.rwc.(connectionStater); ok { 2116 c.tlsState = new(tls.ConnectionState) 2117 *c.tlsState = tc.ConnectionState() 2118 } 2119 } 2120 2121 // HTTP/2 may outlive this goroutine, so it gets the uncancelable ctx. 2122 connCtx := ctx 2123 2124 ctx, cancelCtx := context.WithCancel(ctx) 2125 c.cancelCtx = cancelCtx 2126 defer cancelCtx() 2127 2128 c.r = &connReader{conn: c, rwc: c.rwc} 2129 c.bufr = newBufioReader(c.r) 2130 2131 if d := c.server.readHeaderTimeout(); d > 0 { 2132 c.rwc.SetReadDeadline(time.Now().Add(d)) 2133 } 2134 2135 protos := c.server.protocols() 2136 if c.tlsState == nil && protos.UnencryptedHTTP2() { 2137 if c.maybeServeUnencryptedHTTP2(connCtx) { 2138 return 2139 } 2140 } 2141 if !protos.HTTP1() { 2142 return 2143 } 2144 2145 // HTTP/1.x from here on. 2146 2147 c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10) 2148 2149 for { 2150 w, err := c.readRequest(ctx) 2151 if c.r.remain != c.server.initialReadLimitSize() { 2152 // If we read any bytes off the wire, we're active. 2153 c.setState(c.rwc, StateActive, runHooks) 2154 } 2155 if c.server.shuttingDown() { 2156 return 2157 } 2158 if err != nil { 2159 const errorHeaders = "\r\nContent-Type: text/plain; charset=utf-8\r\nConnection: close\r\n\r\n" 2160 2161 switch { 2162 case err == errTooLarge: 2163 // Their HTTP client may or may not be 2164 // able to read this if we're 2165 // responding to them and hanging up 2166 // while they're still writing their 2167 // request. Undefined behavior. 2168 const publicErr = "431 Request Header Fields Too Large" 2169 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr) 2170 c.closeWriteAndWait() 2171 return 2172 2173 case isUnsupportedTEError(err): 2174 // Respond as per RFC 7230 Section 3.3.1 which says, 2175 // A server that receives a request message with a 2176 // transfer coding it does not understand SHOULD 2177 // respond with 501 (Unimplemented). 2178 code := StatusNotImplemented 2179 2180 // We purposefully aren't echoing back the transfer-encoding's value, 2181 // so as to mitigate the risk of cross side scripting by an attacker. 2182 fmt.Fprintf(c.rwc, "HTTP/1.1 %d %s%sUnsupported transfer encoding", code, StatusText(code), errorHeaders) 2183 return 2184 2185 case isCommonNetReadError(err): 2186 return // don't reply 2187 2188 default: 2189 if v, ok := err.(statusError); ok { 2190 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) 2191 return 2192 } 2193 const publicErr = "400 Bad Request" 2194 fmt.Fprintf(c.rwc, "HTTP/1.1 "+publicErr+errorHeaders+publicErr) 2195 return 2196 } 2197 } 2198 2199 // Expect 100 Continue support 2200 req := w.req 2201 if req.expectsContinue() { 2202 if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 { 2203 // Wrap the Body reader with one that replies on the connection 2204 w.ecReader = &expectContinueReader{readCloser: req.Body, resp: w} 2205 w.canWriteContinue.Store(true) 2206 req.Body = w.ecReader 2207 } 2208 } else if req.Header.get("Expect") != "" { 2209 w.sendExpectationFailed() 2210 return 2211 } 2212 2213 c.curReq.Store(w) 2214 2215 // Start background read, which detects when a client has closed its connection 2216 // while a request handler is still running. When the request has a body, we 2217 // start the background read only after the entire body has been consumed. 2218 if w.reqBody.bodyRemains() { 2219 w.reqBody.registerOnHitEOF(w.conn.r.startBackgroundRead) 2220 } else { 2221 w.conn.r.startBackgroundRead() 2222 } 2223 2224 // HTTP cannot have multiple simultaneous active requests.[*] 2225 // Until the server replies to this request, it can't read another, 2226 // so we might as well run the handler in this goroutine. 2227 // [*] Not strictly true: HTTP pipelining. We could let them all process 2228 // in parallel even if their responses need to be serialized. 2229 // But we're not going to implement HTTP pipelining because it 2230 // was never deployed in the wild and the answer is HTTP/2. 2231 inFlightResponse = w 2232 if err := c.server.HandleRequest(w, w.req); err != nil { 2233 return 2234 } 2235 inFlightResponse = nil 2236 w.cancelCtx() 2237 if c.hijacked() { 2238 c.r.releaseConn() 2239 return 2240 } 2241 w.finishRequest() 2242 c.rwc.SetWriteDeadline(time.Time{}) 2243 if !w.shouldReuseConnection() { 2244 // On some platforms, closing a socket with data in the read buffer 2245 // sends a RST. If we do this with data sent by us in flight, the client 2246 // might read the RST before reading what we sent. So if we might still 2247 // have bytes in our read buffer, CloseWrite the connection (to send a FIN) 2248 // and wait a short while before closing it entirely. 2249 if w.requestBodyLimitHit || !w.reqBody.consumedEntireBody() { 2250 c.closeWriteAndWait() 2251 } 2252 return 2253 } 2254 c.setState(c.rwc, StateIdle, runHooks) 2255 c.curReq.Store(nil) 2256 2257 if !w.conn.server.doKeepAlives() { 2258 // We're in shutdown mode. We might've replied 2259 // to the user without "Connection: close" and 2260 // they might think they can send another 2261 // request, but such is life with HTTP/1.1. 2262 return 2263 } 2264 2265 var idleDeadline time.Time 2266 if d := c.server.idleTimeout(); d > 0 { 2267 idleDeadline = time.Now().Add(d) 2268 } 2269 2270 // Wait for the connection to become readable again before trying to 2271 // read the next request. This prevents a ReadHeaderTimeout or 2272 // ReadTimeout from starting until the first bytes of the next request 2273 // have been received. 2274 // 2275 // The wait runs in two phases. First wait briefly with the 2276 // connection's bufio buffers still attached: on a busy 2277 // connection the next request typically arrives almost 2278 // immediately, and this keeps the buffer release below off the 2279 // hot path. If the connection then still has nothing buffered, 2280 // it has gone idle, possibly for a long time, so release its 2281 // bufio.Reader and Writer (~8 kB of per-connection memory 2282 // holding no data) to their pools for the rest of the wait. 2283 // The byte read by waitReadable is stashed in the connReader 2284 // and yielded by its next Read after fresh buffers are 2285 // acquired. 2286 shortDeadline := time.Now().Add(idleBufsReleaseDelay) 2287 if !idleDeadline.IsZero() && idleDeadline.Before(shortDeadline) { 2288 shortDeadline = idleDeadline 2289 } 2290 c.rwc.SetReadDeadline(shortDeadline) 2291 c.r.setProbing(true) 2292 _, peekErr := c.bufr.Peek(4) 2293 c.r.setProbing(false) 2294 if isNetTimeoutError(peekErr) && (idleDeadline.IsZero() || time.Now().Before(idleDeadline)) { 2295 c.rwc.SetReadDeadline(idleDeadline) 2296 if c.bufr.Buffered() == 0 && c.bufw.Buffered() == 0 { 2297 putBufioReader(c.bufr) 2298 c.bufr = nil 2299 putBufioWriter(c.bufw) 2300 c.bufw = nil 2301 if !c.r.waitReadable() { 2302 return 2303 } 2304 c.bufr = newBufioReader(c.r) 2305 c.bufw = newBufioWriterSize(checkConnErrorWriter{c}, 4<<10) 2306 } 2307 _, peekErr = c.bufr.Peek(4) 2308 } 2309 if peekErr != nil { 2310 return 2311 } 2312 2313 if d := c.server.readHeaderTimeout(); d > 0 { 2314 c.rwc.SetReadDeadline(time.Now().Add(d)) 2315 } else { 2316 c.rwc.SetReadDeadline(time.Time{}) 2317 } 2318 } 2319 } 2320 2321 // unencryptedHTTP2Request is an HTTP handler that initializes 2322 // certain uninitialized fields in its *Request. 2323 // 2324 // It's the unencrypted version of initALPNRequest. 2325 type unencryptedHTTP2Request struct { 2326 ctx context.Context 2327 c net.Conn 2328 srv *Server 2329 } 2330 2331 func (h unencryptedHTTP2Request) BaseContext() context.Context { return h.ctx } 2332 2333 func (h unencryptedHTTP2Request) ServeHTTP(rw ResponseWriter, req *Request) { 2334 if req.Body == nil { 2335 req.Body = NoBody 2336 } 2337 if req.RemoteAddr == "" { 2338 req.RemoteAddr = h.c.RemoteAddr().String() 2339 } 2340 h.srv.serveHTTP(rw, req, h.srv.Handler) 2341 } 2342 2343 // unencryptedNetConnInTLSConn is used to pass an unencrypted net.Conn to 2344 // functions that only accept a *tls.Conn. 2345 type unencryptedNetConnInTLSConn struct { 2346 net.Conn // panic on all net.Conn methods 2347 conn net.Conn 2348 } 2349 2350 func (c unencryptedNetConnInTLSConn) UnencryptedNetConn() net.Conn { 2351 return c.conn 2352 } 2353 2354 func unencryptedTLSConn(c net.Conn) *tls.Conn { 2355 return tls.Client(unencryptedNetConnInTLSConn{conn: c}, nil) 2356 } 2357 2358 // TLSNextProto key to use for unencrypted HTTP/2 connections. 2359 // Not actually a TLS-negotiated protocol. 2360 const nextProtoUnencryptedHTTP2 = "unencrypted_http2" 2361 2362 func (c *conn) maybeServeUnencryptedHTTP2(ctx context.Context) bool { 2363 var nextFunc func(*Server, *tls.Conn, Handler) 2364 if c.server.h2 == nil { 2365 var ok bool 2366 nextFunc, ok = c.server.TLSNextProto[nextProtoUnencryptedHTTP2] 2367 if !ok { 2368 return false 2369 } 2370 } 2371 hasPreface := func(c *conn, preface []byte) bool { 2372 c.r.setReadLimit(int64(len(preface)) - int64(c.bufr.Buffered())) 2373 got, err := c.bufr.Peek(len(preface)) 2374 c.r.setInfiniteReadLimit() 2375 return err == nil && bytes.Equal(got, preface) 2376 } 2377 if !hasPreface(c, []byte("PRI * HTTP/2.0")) { 2378 return false 2379 } 2380 if !hasPreface(c, []byte("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")) { 2381 return false 2382 } 2383 c.setState(c.rwc, StateActive, skipHooks) 2384 if c.server.h2 != nil { 2385 const sawClientPreface = true 2386 c.serveHTTP2(ctx, sawClientPreface) 2387 } else { 2388 c.rwc.SetReadDeadline(time.Time{}) 2389 c.rwc.SetWriteDeadline(time.Time{}) 2390 h := unencryptedHTTP2Request{ctx, c.rwc, c.server} 2391 nextFunc(c.server, unencryptedTLSConn(c.rwc), h) 2392 } 2393 return true 2394 } 2395 2396 // serveHTTP2 hands the connection off to the HTTP/2 server, which owns 2397 // the connection from here on: it closes the connection and runs the 2398 // final ConnState hook when it's done, possibly after this function has 2399 // returned, since an idle HTTP/2 connection doesn't hold onto a 2400 // goroutine. 2401 func (c *conn) serveHTTP2(ctx context.Context, sawClientPreface bool) { 2402 c.http2HandedOff = true 2403 2404 // HTTP/2 only uses c.rwc, so release the bufio.Reader if we have one. 2405 if c.bufr != nil { 2406 putBufioReader(c.bufr) 2407 c.bufr = nil 2408 } 2409 2410 c.server.serveHTTP2Conn(ctx, c.rwc, c.server.Handler, sawClientPreface, nil, nil, func() { 2411 c.close() 2412 c.setState(c.rwc, StateClosed, runHooks) 2413 }) 2414 } 2415 2416 func (w *response) sendExpectationFailed() { 2417 // TODO(bradfitz): let ServeHTTP handlers handle 2418 // requests with non-standard expectation[s]? Seems 2419 // theoretical at best, and doesn't fit into the 2420 // current ServeHTTP model anyway. We'd need to 2421 // make the ResponseWriter an optional 2422 // "ExpectReplier" interface or something. 2423 // 2424 // For now we'll just obey RFC 7231 5.1.1 which says 2425 // "A server that receives an Expect field-value other 2426 // than 100-continue MAY respond with a 417 (Expectation 2427 // Failed) status code to indicate that the unexpected 2428 // expectation cannot be met." 2429 w.Header().Set("Connection", "close") 2430 w.WriteHeader(StatusExpectationFailed) 2431 w.finishRequest() 2432 } 2433 2434 // Hijack implements the [Hijacker.Hijack] method. Our response is both a [ResponseWriter] 2435 // and a [Hijacker]. 2436 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) { 2437 if w.handlerDone.Load() { 2438 panic("net/http: Hijack called after ServeHTTP finished") 2439 } 2440 w.disableWriteContinue(false) 2441 if w.wroteHeader { 2442 w.cw.flush() 2443 } 2444 2445 c := w.conn 2446 c.mu.Lock() 2447 defer c.mu.Unlock() 2448 2449 // Release the bufioWriter that writes to the chunk writer, it is not 2450 // used after a connection has been hijacked. 2451 rwc, buf, err = c.hijackLocked() 2452 if err == nil { 2453 putBufioWriter(w.w) 2454 w.w = nil 2455 } 2456 return rwc, buf, err 2457 } 2458 2459 func (w *response) CloseNotify() <-chan bool { 2460 w.lazyCloseNotifyMu.Lock() 2461 defer w.lazyCloseNotifyMu.Unlock() 2462 if w.handlerDone.Load() { 2463 panic("net/http: CloseNotify called after ServeHTTP finished") 2464 } 2465 if w.closeNotifyCh == nil { 2466 w.closeNotifyCh = make(chan bool, 1) 2467 if w.closeNotifyTriggered { 2468 w.closeNotifyCh <- true // action prior closeNotify call 2469 } 2470 } 2471 return w.closeNotifyCh 2472 } 2473 2474 func (w *response) closeNotify() { 2475 w.lazyCloseNotifyMu.Lock() 2476 defer w.lazyCloseNotifyMu.Unlock() 2477 if w.closeNotifyTriggered { 2478 return // already triggered 2479 } 2480 w.closeNotifyTriggered = true 2481 if w.closeNotifyCh != nil { 2482 w.closeNotifyCh <- true 2483 } 2484 } 2485 2486 // The HandlerFunc type is an adapter to allow the use of 2487 // ordinary functions as HTTP handlers. If f is a function 2488 // with the appropriate signature, HandlerFunc(f) is a 2489 // [Handler] that calls f. 2490 type HandlerFunc func(ResponseWriter, *Request) 2491 2492 // ServeHTTP calls f(w, r). 2493 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { 2494 f(w, r) 2495 } 2496 2497 // Helper handlers 2498 2499 // Error replies to the request with the specified error message and HTTP code. 2500 // It does not otherwise end the request; the caller should ensure no further 2501 // writes are done to w. 2502 // The error message should be plain text. 2503 // 2504 // Error deletes the Content-Length header, 2505 // sets Content-Type to “text/plain; charset=utf-8”, 2506 // and sets X-Content-Type-Options to “nosniff”. 2507 // This configures the header properly for the error message, 2508 // in case the caller had set it up expecting a successful output. 2509 func Error(w ResponseWriter, error string, code int) { 2510 h := w.Header() 2511 2512 // Delete the Content-Length header, which might be for some other content. 2513 // Assuming the error string fits in the writer's buffer, we'll figure 2514 // out the correct Content-Length for it later. 2515 // 2516 // We don't delete Content-Encoding, because some middleware sets 2517 // Content-Encoding: gzip and wraps the ResponseWriter to compress on-the-fly. 2518 // See https://go.dev/issue/66343. 2519 h.Del("Content-Length") 2520 2521 // There might be content type already set, but we reset it to 2522 // text/plain for the error message. 2523 h.Set("Content-Type", "text/plain; charset=utf-8") 2524 h.Set("X-Content-Type-Options", "nosniff") 2525 w.WriteHeader(code) 2526 fmt.Fprintln(w, error) 2527 } 2528 2529 // NotFound replies to the request with an HTTP 404 not found error. 2530 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) } 2531 2532 // NotFoundHandler returns a simple request handler 2533 // that replies to each request with a “404 page not found” reply. 2534 func NotFoundHandler() Handler { return HandlerFunc(NotFound) } 2535 2536 // StripPrefix returns a handler that serves HTTP requests by removing the 2537 // given prefix from the request URL's Path (and RawPath if set) and invoking 2538 // the handler h. StripPrefix handles a request for a path that doesn't begin 2539 // with prefix by replying with an HTTP 404 not found error. The prefix must 2540 // match exactly: if the prefix in the request contains escaped characters 2541 // the reply is also an HTTP 404 not found error. 2542 func StripPrefix(prefix string, h Handler) Handler { 2543 if prefix == "" { 2544 return h 2545 } 2546 return HandlerFunc(func(w ResponseWriter, r *Request) { 2547 p := strings.TrimPrefix(r.URL.Path, prefix) 2548 rp := strings.TrimPrefix(r.URL.RawPath, prefix) 2549 if len(p) < len(r.URL.Path) && (r.URL.RawPath == "" || len(rp) < len(r.URL.RawPath)) { 2550 r2 := new(Request) 2551 *r2 = *r 2552 r2.URL = new(url.URL) 2553 *r2.URL = *r.URL 2554 r2.URL.Path = p 2555 r2.URL.RawPath = rp 2556 h.ServeHTTP(w, r2) 2557 } else { 2558 NotFound(w, r) 2559 } 2560 }) 2561 } 2562 2563 // Redirect replies to the request with a redirect to url, 2564 // which may be a path relative to the request path. 2565 // Any non-ASCII characters in url will be percent-encoded, 2566 // but existing percent encodings will not be changed. 2567 // 2568 // The provided code should be in the 3xx range and is usually 2569 // [StatusMovedPermanently], [StatusFound] or [StatusSeeOther]. 2570 // 2571 // If the Content-Type header has not been set, [Redirect] sets it 2572 // to "text/html; charset=utf-8" and writes a small HTML body. 2573 // Setting the Content-Type header to any value, including nil, 2574 // disables that behavior. 2575 func Redirect(w ResponseWriter, r *Request, url string, code int) { 2576 if u, err := urlpkg.Parse(url); err == nil { 2577 // If url was relative, make its path absolute by 2578 // combining with request path. 2579 // The client would probably do this for us, 2580 // but doing it ourselves is more reliable. 2581 // See RFC 7231, section 7.1.2 2582 if u.Scheme == "" && u.Host == "" { 2583 oldpath := r.URL.EscapedPath() 2584 if oldpath == "" { // should not happen, but avoid a crash if it does 2585 oldpath = "/" 2586 } 2587 2588 // no leading http://server 2589 if url == "" || url[0] != '/' { 2590 // make relative path absolute 2591 olddir, _ := path.Split(oldpath) 2592 url = olddir + url 2593 } 2594 2595 var query string 2596 if i := strings.Index(url, "?"); i != -1 { 2597 url, query = url[:i], url[i:] 2598 } 2599 2600 // clean up but preserve trailing slash 2601 trailing := strings.HasSuffix(url, "/") 2602 url = path.Clean(url) 2603 if trailing && !strings.HasSuffix(url, "/") { 2604 url += "/" 2605 } 2606 url += query 2607 } 2608 } 2609 2610 h := w.Header() 2611 2612 // RFC 7231 notes that a short HTML body is usually included in 2613 // the response because older user agents may not understand 301/307. 2614 // Do it only if the request didn't already have a Content-Type header. 2615 _, hadCT := h["Content-Type"] 2616 2617 h.Set("Location", hexEscapeNonASCII(url)) 2618 if !hadCT && (r.Method == "GET" || r.Method == "HEAD") { 2619 h.Set("Content-Type", "text/html; charset=utf-8") 2620 } 2621 w.WriteHeader(code) 2622 2623 // Shouldn't send the body for POST or HEAD; that leaves GET. 2624 if !hadCT && r.Method == "GET" { 2625 body := "<a href=\"" + htmlEscape(url) + "\">" + StatusText(code) + "</a>.\n" 2626 fmt.Fprintln(w, body) 2627 } 2628 } 2629 2630 var htmlReplacer = strings.NewReplacer( 2631 "&", "&", 2632 "<", "<", 2633 ">", ">", 2634 // """ is shorter than """. 2635 `"`, """, 2636 // "'" is shorter than "'" and apos was not in HTML until HTML5. 2637 "'", "'", 2638 ) 2639 2640 func htmlEscape(s string) string { 2641 return htmlReplacer.Replace(s) 2642 } 2643 2644 // Redirect to a fixed URL 2645 type redirectHandler struct { 2646 url string 2647 code int 2648 } 2649 2650 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) { 2651 Redirect(w, r, rh.url, rh.code) 2652 } 2653 2654 // RedirectHandler returns a request handler that redirects 2655 // each request it receives to the given url using the given 2656 // status code. 2657 // 2658 // The provided code should be in the 3xx range and is usually 2659 // [StatusMovedPermanently], [StatusFound] or [StatusSeeOther]. 2660 func RedirectHandler(url string, code int) Handler { 2661 return &redirectHandler{url, code} 2662 } 2663 2664 // ServeMux is an HTTP request multiplexer. 2665 // It matches the URL of each incoming request against a list of registered 2666 // patterns and calls the handler for the pattern that 2667 // most closely matches the URL. 2668 // 2669 // # Patterns 2670 // 2671 // Patterns can match the method, host and path of a request. 2672 // Some examples: 2673 // 2674 // - "/index.html" matches the path "/index.html" for any host and method. 2675 // - "GET /static/" matches a GET request whose path begins with "/static/". 2676 // - "example.com/" matches any request to the host "example.com". 2677 // - "example.com/{$}" matches requests with host "example.com" and path "/". 2678 // - "/b/{bucket}/o/{objectname...}" matches paths whose first segment is "b" 2679 // and whose third segment is "o". The name "bucket" denotes the second 2680 // segment and "objectname" denotes the remainder of the path. 2681 // 2682 // In general, a pattern looks like 2683 // 2684 // [METHOD ][HOST]/[PATH] 2685 // 2686 // All three parts are optional; "/" is a valid pattern. 2687 // If METHOD is present, it must be followed by at least one space or tab. 2688 // 2689 // Literal (that is, non-wildcard) parts of a pattern match 2690 // the corresponding parts of a request case-sensitively. 2691 // 2692 // A pattern with no method matches every method. A pattern 2693 // with the method GET matches both GET and HEAD requests. 2694 // Otherwise, the method must match exactly. 2695 // 2696 // A pattern with no host matches every host. 2697 // A pattern with a host matches URLs on that host only. 2698 // 2699 // A path can include wildcard segments of the form {NAME} or {NAME...}. 2700 // For example, "/b/{bucket}/o/{objectname...}". 2701 // The wildcard name must be a valid Go identifier. 2702 // Wildcards must be full path segments: they must be preceded by a slash and followed by 2703 // either a slash or the end of the string. 2704 // For example, "/b_{bucket}" is not a valid pattern. 2705 // 2706 // Normally a wildcard matches only a single path segment, 2707 // ending at the next literal slash (not %2F) in the request URL. 2708 // But if the "..." is present, then the wildcard matches the remainder of the URL path, including slashes. 2709 // (Therefore it is invalid for a "..." wildcard to appear anywhere but at the end of a pattern.) 2710 // The match for a wildcard can be obtained by calling [Request.PathValue] with the wildcard's name. 2711 // A trailing slash in a path acts as an anonymous "..." wildcard. 2712 // 2713 // The special wildcard {$} matches only the end of the URL. 2714 // For example, the pattern "/{$}" matches only the path "/", 2715 // whereas the pattern "/" matches every path. 2716 // 2717 // For matching, both pattern paths and incoming request paths are unescaped segment by segment. 2718 // So, for example, the path "/a%2Fb/100%25" is treated as having two segments, "a/b" and "100%". 2719 // The pattern "/a%2fb/" matches it, but the pattern "/a/b/" does not. 2720 // 2721 // # Precedence 2722 // 2723 // If two or more patterns match a request, then the most specific pattern takes precedence. 2724 // A pattern P1 is more specific than P2 if P1 matches a strict subset of P2’s requests; 2725 // that is, if P2 matches all the requests of P1 and more. 2726 // If neither is more specific, then the patterns conflict. 2727 // There is one exception to this rule, for backwards compatibility: 2728 // if two patterns would otherwise conflict and one has a host while the other does not, 2729 // then the pattern with the host takes precedence. 2730 // If a pattern passed to [ServeMux.Handle] or [ServeMux.HandleFunc] conflicts with 2731 // another pattern that is already registered, those functions panic. 2732 // 2733 // As an example of the general rule, "/images/thumbnails/" is more specific than "/images/", 2734 // so both can be registered. 2735 // The former matches paths beginning with "/images/thumbnails/" 2736 // and the latter will match any other path in the "/images/" subtree. 2737 // 2738 // As another example, consider the patterns "GET /" and "/index.html": 2739 // both match a GET request for "/index.html", but the former pattern 2740 // matches all other GET and HEAD requests, while the latter matches any 2741 // request for "/index.html" that uses a different method. 2742 // The patterns conflict. 2743 // 2744 // # Trailing-slash redirection 2745 // 2746 // Consider a [ServeMux] with a handler for a subtree, registered using a trailing slash or "..." wildcard. 2747 // If the ServeMux receives a request for the subtree root without a trailing slash, 2748 // it redirects the request by adding the trailing slash. 2749 // This behavior can be overridden with a separate registration for the path without 2750 // the trailing slash or "..." wildcard. For example, registering "/images/" causes ServeMux 2751 // to redirect a request for "/images" to "/images/", unless "/images" has 2752 // been registered separately. 2753 // 2754 // # Request sanitizing 2755 // 2756 // ServeMux also takes care of sanitizing the URL request path and the Host 2757 // header, stripping the port number and redirecting any request containing . or 2758 // .. segments or repeated slashes to an equivalent, cleaner URL. 2759 // Escaped path elements such as "%2e" for "." and "%2f" for "/" are preserved 2760 // and aren't considered separators for request routing. 2761 // 2762 // # Compatibility 2763 // 2764 // The pattern syntax and matching behavior of ServeMux changed significantly 2765 // in Go 1.22. To restore the old behavior, set the GODEBUG environment variable 2766 // to "httpmuxgo121=1". This setting is read once, at program startup; changes 2767 // during execution will be ignored. 2768 // 2769 // The backwards-incompatible changes include: 2770 // - Wildcards are just ordinary literal path segments in 1.21. 2771 // For example, the pattern "/{x}" will match only that path in 1.21, 2772 // but will match any one-segment path in 1.22. 2773 // - In 1.21, no pattern was rejected, unless it was empty or conflicted with an existing pattern. 2774 // In 1.22, syntactically invalid patterns will cause [ServeMux.Handle] and [ServeMux.HandleFunc] to panic. 2775 // For example, in 1.21, the patterns "/{" and "/a{x}" match themselves, 2776 // but in 1.22 they are invalid and will cause a panic when registered. 2777 // - In 1.22, each segment of a pattern is unescaped; this was not done in 1.21. 2778 // For example, in 1.22 the pattern "/%61" matches the path "/a" ("%61" being the URL escape sequence for "a"), 2779 // but in 1.21 it would match only the path "/%2561" (where "%25" is the escape for the percent sign). 2780 // - When matching patterns to paths, in 1.22 each segment of the path is unescaped; in 1.21, the entire path is unescaped. 2781 // This change mostly affects how paths with %2F escapes adjacent to slashes are treated. 2782 // See https://go.dev/issue/21955 for details. 2783 type ServeMux struct { 2784 mu sync.RWMutex 2785 tree routingNode 2786 index routingIndex 2787 mux121 serveMux121 // used only when GODEBUG=httpmuxgo121=1 2788 } 2789 2790 // NewServeMux allocates and returns a new [ServeMux]. 2791 func NewServeMux() *ServeMux { 2792 return &ServeMux{} 2793 } 2794 2795 // DefaultServeMux is the default [ServeMux] used by [Serve]. 2796 var DefaultServeMux = &defaultServeMux 2797 2798 var defaultServeMux ServeMux 2799 2800 // cleanPath returns the canonical path for p, eliminating . and .. elements. 2801 func cleanPath(p string) string { 2802 if p == "" { 2803 return "/" 2804 } 2805 if p[0] != '/' { 2806 p = "/" + p 2807 } 2808 np := path.Clean(p) 2809 // path.Clean removes trailing slash except for root; 2810 // put the trailing slash back if necessary. 2811 if p[len(p)-1] == '/' && np != "/" { 2812 // Fast path for common case of p being the string we want: 2813 if len(p) == len(np)+1 && strings.HasPrefix(p, np) { 2814 np = p 2815 } else { 2816 np += "/" 2817 } 2818 } 2819 return np 2820 } 2821 2822 // stripHostPort returns h without any trailing ":<port>". 2823 func stripHostPort(h string) string { 2824 // If no port on host, return unchanged 2825 if !strings.Contains(h, ":") { 2826 return h 2827 } 2828 host, _, err := net.SplitHostPort(h) 2829 if err != nil { 2830 return h // on error, return unchanged 2831 } 2832 return host 2833 } 2834 2835 // Handler returns the handler to use for the given request, 2836 // consulting r.Method, r.Host, and r.URL.Path. It always returns 2837 // a non-nil handler. If the path is not in its canonical form, the 2838 // handler will be an internally-generated handler that redirects 2839 // to the canonical path. If the host contains a port, it is ignored 2840 // when matching handlers. 2841 // 2842 // The path and host are used unchanged for CONNECT requests. 2843 // 2844 // Handler also returns the registered pattern that matches the 2845 // request or, in the case of internally-generated redirects, 2846 // the path that will match after following the redirect. 2847 // 2848 // If there is no registered handler that applies to the request, 2849 // Handler returns a “page not found” or “method not supported” 2850 // handler and an empty pattern. 2851 // 2852 // Handler does not modify its argument. In particular, it does not 2853 // populate named path wildcards, so r.PathValue will always return 2854 // the empty string. 2855 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) { 2856 if use121 { 2857 return mux.mux121.findHandler(r) 2858 } 2859 h, p, _, _ := mux.findHandler(r) 2860 return h, p 2861 } 2862 2863 // findHandler finds a handler for a request. 2864 // If there is a matching handler, it returns it and the pattern that matched. 2865 // Otherwise it returns a Redirect or NotFound handler with the path that would match 2866 // after the redirect. 2867 func (mux *ServeMux) findHandler(r *Request) (h Handler, patStr string, _ *pattern, matches []string) { 2868 var n *routingNode 2869 host := r.URL.Host 2870 escapedPath := r.URL.EscapedPath() 2871 path := escapedPath 2872 // CONNECT requests are not canonicalized. 2873 if r.Method == "CONNECT" { 2874 // If r.URL.Path is /tree and its handler is not registered, 2875 // the /tree -> /tree/ redirect applies to CONNECT requests 2876 // but the path canonicalization does not. 2877 _, _, u := mux.matchOrRedirect(host, r.Method, path, r.URL) 2878 if u != nil { 2879 return RedirectHandler(u.String(), StatusTemporaryRedirect), u.Path, nil, nil 2880 } 2881 // Redo the match, this time with r.Host instead of r.URL.Host. 2882 // Pass a nil URL to skip the trailing-slash redirect logic. 2883 n, matches, _ = mux.matchOrRedirect(r.Host, r.Method, path, nil) 2884 } else { 2885 // All other requests have any port stripped and path cleaned 2886 // before passing to mux.handler. 2887 host = stripHostPort(r.Host) 2888 path = cleanPath(path) 2889 2890 // If the given path is /tree and its handler is not registered, 2891 // redirect for /tree/. 2892 var u *url.URL 2893 n, matches, u = mux.matchOrRedirect(host, r.Method, path, r.URL) 2894 if u != nil { 2895 return RedirectHandler(u.String(), StatusTemporaryRedirect), n.pattern.String(), nil, nil 2896 } 2897 if path != escapedPath { 2898 // Redirect to cleaned path. 2899 patStr := "" 2900 if n != nil { 2901 patStr = n.pattern.String() 2902 } 2903 u := urlFromEscaped(path, r.URL.RawQuery) 2904 return RedirectHandler(u.String(), StatusTemporaryRedirect), patStr, nil, nil 2905 } 2906 } 2907 if n == nil { 2908 // We didn't find a match with the request method. To distinguish between 2909 // Not Found and Method Not Allowed, see if there is another pattern that 2910 // matches except for the method. 2911 allowedMethods := mux.matchingMethods(host, path) 2912 if len(allowedMethods) > 0 { 2913 return HandlerFunc(func(w ResponseWriter, r *Request) { 2914 w.Header().Set("Allow", strings.Join(allowedMethods, ", ")) 2915 Error(w, StatusText(StatusMethodNotAllowed), StatusMethodNotAllowed) 2916 }), "", nil, nil 2917 } 2918 return NotFoundHandler(), "", nil, nil 2919 } 2920 return n.handler, n.pattern.String(), n.pattern, matches 2921 } 2922 2923 // matchOrRedirect looks up a node in the tree that matches the host, method and path. 2924 // 2925 // If the url argument is non-nil, handler also deals with trailing-slash 2926 // redirection: when a path doesn't match exactly, the match is tried again 2927 // after appending "/" to the path. If that second match succeeds, the last 2928 // return value is the URL to redirect to. 2929 func (mux *ServeMux) matchOrRedirect(host, method, path string, u *url.URL) (_ *routingNode, matches []string, redirectTo *url.URL) { 2930 mux.mu.RLock() 2931 defer mux.mu.RUnlock() 2932 2933 n, matches := mux.tree.match(host, method, path) 2934 // We can terminate here if any of the following is true: 2935 // - We have an exact match already. 2936 // - We were asked not to try trailing slash redirection. 2937 // - The URL already has a trailing slash. 2938 // - The URL is an empty string. 2939 if !exactMatch(n, path) && u != nil && !strings.HasSuffix(path, "/") && path != "" { 2940 // If there is an exact match with a trailing slash, then redirect. 2941 path += "/" 2942 n2, _ := mux.tree.match(host, method, path) 2943 if exactMatch(n2, path) { 2944 // It is safe to return n2 here: it is used only in the second RedirectHandler case 2945 // of findHandler, and that method returns before it does the "n == nil" check where 2946 // the first return value matters. We return it here only to make the pattern available 2947 // to findHandler. 2948 return n2, nil, urlFromEscaped(path, u.RawQuery) 2949 } 2950 } 2951 return n, matches, nil 2952 } 2953 2954 // urlFromEscaped returns a url.URL constructed from an escaped path and a raw 2955 // query. 2956 // 2957 // It ensures that the Path and RawPath fields are in sync by unescaping the 2958 // escaped path. Populating only the Path field and leaving RawPath empty (or 2959 // failing to keep them in sync) can cause url.URL.String to produce a URL with 2960 // either unexpected escaping (e.g., double-escaping "%" into "%25" in an 2961 // already escaped path) or a lack thereof (e.g., losing the escaping of "%2f" 2962 // and turning it into a literal path separator "/"). 2963 func urlFromEscaped(escaped, rawQuery string) *url.URL { 2964 unescaped, err := url.PathUnescape(escaped) 2965 // Should be impossible, since ServeMux will reject unparsable URLs way 2966 // earlier. 2967 if err != nil { 2968 unescaped = escaped 2969 } 2970 return &url.URL{ 2971 Path: unescaped, 2972 RawPath: escaped, 2973 RawQuery: rawQuery, 2974 } 2975 } 2976 2977 // exactMatch reports whether the node's pattern exactly matches the path. 2978 // As a special case, if the node is nil, exactMatch return false. 2979 // 2980 // Before wildcards were introduced, it was clear that an exact match meant 2981 // that the pattern and path were the same string. The only other possibility 2982 // was that a trailing-slash pattern, like "/", matched a path longer than 2983 // it, like "/a". 2984 // 2985 // With wildcards, we define an inexact match as any one where a multi wildcard 2986 // matches a non-empty string. All other matches are exact. 2987 // For example, these are all exact matches: 2988 // 2989 // pattern path 2990 // /a /a 2991 // /{x} /a 2992 // /a/{$} /a/ 2993 // /a/ /a/ 2994 // 2995 // The last case has a multi wildcard (implicitly), but the match is exact because 2996 // the wildcard matches the empty string. 2997 // 2998 // Examples of matches that are not exact: 2999 // 3000 // pattern path 3001 // / /a 3002 // /a/{x...} /a/b 3003 func exactMatch(n *routingNode, path string) bool { 3004 if n == nil { 3005 return false 3006 } 3007 // We can't directly implement the definition (empty match for multi 3008 // wildcard) because we don't record a match for anonymous multis. 3009 3010 // If there is no multi, the match is exact. 3011 if !n.pattern.lastSegment().multi { 3012 return true 3013 } 3014 3015 // If the path doesn't end in a trailing slash, then the multi match 3016 // is non-empty. 3017 if len(path) > 0 && path[len(path)-1] != '/' { 3018 return false 3019 } 3020 // Only patterns ending in {$} or a multi wildcard can 3021 // match a path with a trailing slash. 3022 // For the match to be exact, the number of pattern 3023 // segments should be the same as the number of slashes in the path. 3024 // E.g. "/a/b/{$}" and "/a/b/{...}" exactly match "/a/b/", but "/a/" does not. 3025 return len(n.pattern.segments) == strings.Count(path, "/") 3026 } 3027 3028 // matchingMethods return a sorted list of all methods that would match with the given host and path. 3029 func (mux *ServeMux) matchingMethods(host, path string) []string { 3030 // Hold the read lock for the entire method so that the two matches are done 3031 // on the same set of registered patterns. 3032 mux.mu.RLock() 3033 defer mux.mu.RUnlock() 3034 ms := map[string]bool{} 3035 mux.tree.matchingMethods(host, path, ms) 3036 // matchOrRedirect will try appending a trailing slash if there is no match. 3037 if !strings.HasSuffix(path, "/") { 3038 mux.tree.matchingMethods(host, path+"/", ms) 3039 } 3040 return slices.Sorted(maps.Keys(ms)) 3041 } 3042 3043 // ServeHTTP dispatches the request to the handler whose 3044 // pattern most closely matches the request URL. 3045 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) { 3046 if r.RequestURI == "*" { 3047 if r.ProtoAtLeast(1, 1) { 3048 w.Header().Set("Connection", "close") 3049 } 3050 w.WriteHeader(StatusBadRequest) 3051 return 3052 } 3053 var h Handler 3054 if use121 { 3055 h, _ = mux.mux121.findHandler(r) 3056 } else { 3057 h, r.Pattern, r.pat, r.matches = mux.findHandler(r) 3058 } 3059 h.ServeHTTP(w, r) 3060 } 3061 3062 // The four functions below all call ServeMux.register so that callerLocation 3063 // always refers to user code. 3064 3065 // Handle registers the handler for the given pattern. 3066 // If the given pattern conflicts with one that is already registered 3067 // or if the pattern is invalid, Handle panics. 3068 // 3069 // See [ServeMux] for details on valid patterns and conflict rules. 3070 func (mux *ServeMux) Handle(pattern string, handler Handler) { 3071 if use121 { 3072 mux.mux121.handle(pattern, handler) 3073 } else { 3074 mux.register(pattern, handler) 3075 } 3076 } 3077 3078 // HandleFunc registers the handler function for the given pattern. 3079 // If the given pattern conflicts with one that is already registered 3080 // or if the pattern is invalid, HandleFunc panics. 3081 // 3082 // See [ServeMux] for details on valid patterns and conflict rules. 3083 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { 3084 if use121 { 3085 mux.mux121.handleFunc(pattern, handler) 3086 } else { 3087 mux.register(pattern, HandlerFunc(handler)) 3088 } 3089 } 3090 3091 // Handle registers the handler for the given pattern in [DefaultServeMux]. 3092 // The documentation for [ServeMux] explains how patterns are matched. 3093 func Handle(pattern string, handler Handler) { 3094 if use121 { 3095 DefaultServeMux.mux121.handle(pattern, handler) 3096 } else { 3097 DefaultServeMux.register(pattern, handler) 3098 } 3099 } 3100 3101 // HandleFunc registers the handler function for the given pattern in [DefaultServeMux]. 3102 // The documentation for [ServeMux] explains how patterns are matched. 3103 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { 3104 if use121 { 3105 DefaultServeMux.mux121.handleFunc(pattern, handler) 3106 } else { 3107 DefaultServeMux.register(pattern, HandlerFunc(handler)) 3108 } 3109 } 3110 3111 func (mux *ServeMux) register(pattern string, handler Handler) { 3112 if err := mux.registerErr(pattern, handler); err != nil { 3113 panic(err) 3114 } 3115 } 3116 3117 func (mux *ServeMux) registerErr(patstr string, handler Handler) error { 3118 if patstr == "" { 3119 return errors.New("http: invalid pattern") 3120 } 3121 if handler == nil { 3122 return errors.New("http: nil handler") 3123 } 3124 if f, ok := handler.(HandlerFunc); ok && f == nil { 3125 return errors.New("http: nil handler") 3126 } 3127 3128 pat, err := parsePattern(patstr) 3129 if err != nil { 3130 return fmt.Errorf("parsing %q: %w", patstr, err) 3131 } 3132 3133 // Get the caller's location, for better conflict error messages. 3134 // Skip register and whatever calls it. 3135 _, file, line, ok := runtime.Caller(3) 3136 if !ok { 3137 pat.loc = "unknown location" 3138 } else { 3139 pat.loc = fmt.Sprintf("%s:%d", file, line) 3140 } 3141 3142 mux.mu.Lock() 3143 defer mux.mu.Unlock() 3144 // Check for conflict. 3145 if err := mux.index.possiblyConflictingPatterns(pat, func(pat2 *pattern) error { 3146 if pat.conflictsWith(pat2) { 3147 d := describeConflict(pat, pat2) 3148 return fmt.Errorf("pattern %q (registered at %s) conflicts with pattern %q (registered at %s):\n%s", 3149 pat, pat.loc, pat2, pat2.loc, d) 3150 } 3151 return nil 3152 }); err != nil { 3153 return err 3154 } 3155 mux.tree.addPattern(pat, handler) 3156 mux.index.addPattern(pat) 3157 return nil 3158 } 3159 3160 // Serve accepts incoming HTTP connections on the listener l, 3161 // creating a new service goroutine for each. The service goroutines 3162 // read requests and then call handler to reply to them. 3163 // 3164 // The handler is typically nil, in which case [DefaultServeMux] is used. 3165 // 3166 // HTTP/2 support is only enabled if the Listener returns [*tls.Conn] 3167 // connections or connections which implement the same ConnectionState 3168 // method as *tls.Conn, and the connection state indicates that the "h2" 3169 // protocol was negotiated by ALPN. 3170 // 3171 // Serve always returns a non-nil error. 3172 func Serve(l net.Listener, handler Handler) error { 3173 srv := &Server{Handler: handler} 3174 return srv.Serve(l) 3175 } 3176 3177 // ServeTLS accepts incoming HTTPS connections on the listener l, 3178 // creating a new service goroutine for each. The service goroutines 3179 // read requests and then call handler to reply to them. 3180 // 3181 // The handler is typically nil, in which case [DefaultServeMux] is used. 3182 // 3183 // Additionally, files containing a certificate and matching private key 3184 // for the server must be provided. If the certificate is signed by a 3185 // certificate authority, the certFile should be the concatenation 3186 // of the server's certificate, any intermediates, and the CA's certificate. 3187 // 3188 // ServeTLS always returns a non-nil error. 3189 func ServeTLS(l net.Listener, handler Handler, certFile, keyFile string) error { 3190 srv := &Server{Handler: handler} 3191 return srv.ServeTLS(l, certFile, keyFile) 3192 } 3193 3194 // A Server defines parameters for running an HTTP server. 3195 // The zero value for Server is a valid configuration. 3196 type Server struct { 3197 // Addr optionally specifies the TCP address for the server to listen on, 3198 // in the form "host:port". If empty, ":http" (port 80) is used. 3199 // The service names are defined in RFC 6335 and assigned by IANA. 3200 // See net.Dial for details of the address format. 3201 Addr string 3202 3203 Handler Handler // handler to invoke, http.DefaultServeMux if nil 3204 3205 // DisableGeneralOptionsHandler, if true, passes "OPTIONS *" requests to the Handler, 3206 // otherwise responds with 200 OK and Content-Length: 0. 3207 DisableGeneralOptionsHandler bool 3208 3209 // TLSConfig optionally provides a TLS configuration for use 3210 // by ServeTLS and ListenAndServeTLS. Note that this value is 3211 // cloned by ServeTLS and ListenAndServeTLS, so it's not 3212 // possible to modify the configuration with methods like 3213 // tls.Config.SetSessionTicketKeys. To use 3214 // SetSessionTicketKeys, use Server.Serve with a TLS Listener 3215 // instead. 3216 TLSConfig *tls.Config 3217 3218 // ReadTimeout is the maximum duration for reading the entire 3219 // request, including the body. A zero or negative value means 3220 // there will be no timeout. 3221 // 3222 // Because ReadTimeout does not let Handlers make per-request 3223 // decisions on each request body's acceptable deadline or 3224 // upload rate, most users will prefer to use 3225 // ReadHeaderTimeout. It is valid to use them both. 3226 ReadTimeout time.Duration 3227 3228 // ReadHeaderTimeout is the amount of time allowed to read 3229 // request headers. The connection's read deadline is reset 3230 // after reading the headers and the Handler can decide what 3231 // is considered too slow for the body. If zero, the value of 3232 // ReadTimeout is used. If negative, or if zero and ReadTimeout 3233 // is zero or negative, there is no timeout. 3234 ReadHeaderTimeout time.Duration 3235 3236 // WriteTimeout is the maximum duration before timing out 3237 // writes of the response. It is reset whenever a new 3238 // request's header is read. Like ReadTimeout, it does not 3239 // let Handlers make decisions on a per-request basis. 3240 // A zero or negative value means there will be no timeout. 3241 WriteTimeout time.Duration 3242 3243 // IdleTimeout is the maximum amount of time to wait for the 3244 // next request when keep-alives are enabled. If zero, the value 3245 // of ReadTimeout is used. If negative, or if zero and ReadTimeout 3246 // is zero or negative, there is no timeout. 3247 IdleTimeout time.Duration 3248 3249 // MaxHeaderBytes controls the maximum number of bytes the 3250 // server will read parsing the request header's keys and 3251 // values, including the request line. It does not limit the 3252 // size of the request body. 3253 // If zero, DefaultMaxHeaderBytes is used. 3254 MaxHeaderBytes int 3255 3256 // MaxHeaderValueCount controls the maximum number of header 3257 // values that the server is willing to parse from a request. 3258 // If zero, DefaultMaxHeaderValueCount is used. 3259 // Comma-separated values in a single header line are counted 3260 // once, while values sent as multiple header lines are 3261 // counted multiple times. An exception to this is the Trailer 3262 // header, whose comma-separated values are counted separately, 3263 // as each of them is expected to be received later as an 3264 // individual trailer header line. 3265 MaxHeaderValueCount int 3266 3267 // TLSNextProto optionally specifies a function to take over 3268 // ownership of the provided TLS connection when an ALPN 3269 // protocol upgrade has occurred. The map key is the protocol 3270 // name negotiated. The Handler argument should be used to 3271 // handle HTTP requests and will initialize the Request's TLS 3272 // and RemoteAddr if not already set. The connection is 3273 // automatically closed when the function returns. 3274 // If TLSNextProto is not nil, HTTP/2 support is not enabled 3275 // automatically. 3276 // 3277 // Historically, TLSNextProto was used to disable HTTP/2 support. 3278 // The Server.Protocols field now provides a simpler way to do this. 3279 TLSNextProto map[string]func(*Server, *tls.Conn, Handler) 3280 3281 // ConnState specifies an optional callback function that is 3282 // called when a client connection changes state. See the 3283 // ConnState type and associated constants for details. 3284 ConnState func(net.Conn, ConnState) 3285 3286 // ErrorLog specifies an optional logger for errors accepting 3287 // connections, unexpected behavior from handlers, and 3288 // underlying FileSystem errors. 3289 // If nil, logging is done via the log package's standard logger. 3290 ErrorLog *log.Logger 3291 3292 // BaseContext optionally specifies a function that returns 3293 // the base context for incoming requests on this server. 3294 // The provided Listener is the specific Listener that's 3295 // about to start accepting requests. 3296 // If BaseContext is nil, the default is context.Background(). 3297 // If non-nil, it must return a non-nil context. 3298 BaseContext func(net.Listener) context.Context 3299 3300 // ConnContext optionally specifies a function that modifies 3301 // the context used for a new connection c. The provided ctx 3302 // is derived from the base context and has a ServerContextKey 3303 // value. 3304 ConnContext func(ctx context.Context, c net.Conn) context.Context 3305 3306 // HTTP2 configures HTTP/2 connections. 3307 HTTP2 *HTTP2Config 3308 3309 // Protocols is the set of protocols accepted by the server. 3310 // 3311 // If Protocols includes UnencryptedHTTP2, the server will accept 3312 // unencrypted HTTP/2 connections. The server can serve both 3313 // HTTP/1 and unencrypted HTTP/2 on the same address and port. 3314 // 3315 // If Protocols is nil, the default is usually HTTP/1 and HTTP/2. 3316 // If TLSNextProto is non-nil and does not contain an "h2" entry, 3317 // the default is HTTP/1 only. 3318 Protocols *Protocols 3319 3320 // DisableClientPriority specifies whether client-specified priority, as 3321 // specified in RFC 9218, should be respected or not. 3322 // 3323 // This field only takes effect if using HTTP/2, and if no custom write 3324 // scheduler is defined for the HTTP/2 server. Otherwise, this field is a 3325 // no-op. 3326 // 3327 // If set to true, requests will be served in a round-robin manner, without 3328 // prioritization. 3329 DisableClientPriority bool 3330 3331 inShutdown atomic.Bool // true when server is in shutdown 3332 3333 disableKeepAlives atomic.Bool 3334 nextProtoOnce sync.Once // guards setupHTTP2_* init 3335 nextProtoErr error // result of http2.ConfigureServer if used 3336 3337 mu sync.Mutex 3338 listeners map[*net.Listener]struct{} 3339 activeConn map[*conn]struct{} 3340 onShutdown []func() 3341 h2 *http2Server 3342 h2Config http2ExternalServerConfig 3343 h2IdleTimeout time.Duration 3344 h3Server http3Server 3345 3346 listenerGroup sync.WaitGroup 3347 } 3348 3349 // Close immediately closes all active net.Listeners and any 3350 // connections in state [StateNew], [StateActive], or [StateIdle]. For a 3351 // graceful shutdown, use [Server.Shutdown]. 3352 // 3353 // Close does not attempt to close (and does not even know about) 3354 // any hijacked connections, such as WebSockets. 3355 // 3356 // Close returns any error returned from closing the [Server]'s 3357 // underlying Listener(s). 3358 func (s *Server) Close() error { 3359 s.inShutdown.Store(true) 3360 s.mu.Lock() 3361 defer s.mu.Unlock() 3362 err := s.closeListenersLocked() 3363 if s.h3Server != nil { 3364 ctx, cancel := context.WithCancel(context.Background()) 3365 cancel() 3366 go s.h3Server.Shutdown(ctx) 3367 } 3368 3369 // Unlock s.mu while waiting for listenerGroup. 3370 // The group Add and Done calls are made with s.mu held, 3371 // to avoid adding a new listener in the window between 3372 // us setting inShutdown above and waiting here. 3373 s.mu.Unlock() 3374 s.listenerGroup.Wait() 3375 s.mu.Lock() 3376 3377 for c := range s.activeConn { 3378 c.rwc.Close() 3379 delete(s.activeConn, c) 3380 } 3381 return err 3382 } 3383 3384 // shutdownPollIntervalMax is the max polling interval when checking 3385 // quiescence during Server.Shutdown. Polling starts with a small 3386 // interval and backs off to the max. 3387 // Ideally we could find a solution that doesn't involve polling, 3388 // but which also doesn't have a high runtime cost (and doesn't 3389 // involve any contentious mutexes), but that is left as an 3390 // exercise for the reader. 3391 const shutdownPollIntervalMax = 500 * time.Millisecond 3392 3393 // Shutdown gracefully shuts down the server without interrupting any 3394 // active connections. Shutdown works by first closing all open 3395 // listeners, then closing all idle connections, and then waiting 3396 // indefinitely for connections to return to idle and then shut down. 3397 // If the provided context expires before the shutdown is complete, 3398 // Shutdown returns the context's error, otherwise it returns any 3399 // error returned from closing the [Server]'s underlying Listener(s). 3400 // 3401 // When Shutdown is called, [Serve], [ServeTLS], [ListenAndServe], and 3402 // [ListenAndServeTLS] immediately return [ErrServerClosed]. Make sure the 3403 // program doesn't exit and waits instead for Shutdown to return. 3404 // 3405 // Shutdown does not attempt to close nor wait for hijacked 3406 // connections such as WebSockets. The caller of Shutdown should 3407 // separately notify such long-lived connections of shutdown and wait 3408 // for them to close, if desired. See [Server.RegisterOnShutdown] for a way to 3409 // register shutdown notification functions. 3410 // 3411 // Once Shutdown has been called on a server, it may not be reused; 3412 // future calls to methods such as Serve will return ErrServerClosed. 3413 func (s *Server) Shutdown(ctx context.Context) error { 3414 s.inShutdown.Store(true) 3415 3416 s.mu.Lock() 3417 lnerr := s.closeListenersLocked() 3418 for _, f := range s.onShutdown { 3419 go f() 3420 } 3421 if s.h3Server != nil { 3422 go s.h3Server.Shutdown(ctx) 3423 } 3424 s.mu.Unlock() 3425 s.listenerGroup.Wait() 3426 3427 pollIntervalBase := time.Millisecond 3428 nextPollInterval := func() time.Duration { 3429 // Add 10% jitter. 3430 interval := pollIntervalBase + time.Duration(rand.IntN(int(pollIntervalBase/10))) 3431 // Double and clamp for next time. 3432 pollIntervalBase *= 2 3433 if pollIntervalBase > shutdownPollIntervalMax { 3434 pollIntervalBase = shutdownPollIntervalMax 3435 } 3436 return interval 3437 } 3438 3439 timer := time.NewTimer(nextPollInterval()) 3440 defer timer.Stop() 3441 for { 3442 if s.closeIdleConns() { 3443 return lnerr 3444 } 3445 select { 3446 case <-ctx.Done(): 3447 return ctx.Err() 3448 case <-timer.C: 3449 timer.Reset(nextPollInterval()) 3450 } 3451 } 3452 } 3453 3454 // RegisterOnShutdown registers a function to call on [Server.Shutdown]. 3455 // This can be used to gracefully shutdown connections that have 3456 // undergone ALPN protocol upgrade or that have been hijacked. 3457 // This function should start protocol-specific graceful shutdown, 3458 // but should not wait for shutdown to complete. 3459 func (s *Server) RegisterOnShutdown(f func()) { 3460 s.mu.Lock() 3461 s.onShutdown = append(s.onShutdown, f) 3462 s.mu.Unlock() 3463 } 3464 3465 // closeIdleConns closes all idle connections and reports whether the 3466 // server is quiescent. 3467 func (s *Server) closeIdleConns() bool { 3468 s.mu.Lock() 3469 defer s.mu.Unlock() 3470 quiescent := true 3471 for c := range s.activeConn { 3472 st, unixSec := c.getState() 3473 // Issue 22682: treat StateNew connections as if 3474 // they're idle if we haven't read the first request's 3475 // header in over 5 seconds. 3476 if st == StateNew && unixSec < time.Now().Unix()-5 { 3477 st = StateIdle 3478 } 3479 if st != StateIdle || unixSec == 0 { 3480 // Assume unixSec == 0 means it's a very new 3481 // connection, without state set yet. 3482 quiescent = false 3483 continue 3484 } 3485 c.rwc.Close() 3486 delete(s.activeConn, c) 3487 } 3488 return quiescent 3489 } 3490 3491 func (s *Server) closeListenersLocked() error { 3492 var err error 3493 for ln := range s.listeners { 3494 if cerr := (*ln).Close(); cerr != nil && err == nil { 3495 err = cerr 3496 } 3497 } 3498 return err 3499 } 3500 3501 // A ConnState represents the state of a client connection to a server. 3502 // It's used by the optional [Server.ConnState] hook. 3503 type ConnState int 3504 3505 const ( 3506 // StateNew represents a new connection that is expected to 3507 // send a request immediately. Connections begin at this 3508 // state and then transition to either StateActive or 3509 // StateClosed. 3510 StateNew ConnState = iota 3511 3512 // StateActive represents a connection that has read 1 or more 3513 // bytes of a request. The Server.ConnState hook for 3514 // StateActive fires before the request has entered a handler 3515 // and doesn't fire again until the request has been 3516 // handled. After the request is handled, the state 3517 // transitions to StateClosed, StateHijacked, or StateIdle. 3518 // For HTTP/2, StateActive fires on the transition from zero 3519 // to one active request, and only transitions away once all 3520 // active requests are complete. That means that ConnState 3521 // cannot be used to do per-request work; ConnState only notes 3522 // the overall state of the connection. 3523 StateActive 3524 3525 // StateIdle represents a connection that has finished 3526 // handling a request and is in the keep-alive state, waiting 3527 // for a new request. Connections transition from StateIdle 3528 // to either StateActive or StateClosed. 3529 StateIdle 3530 3531 // StateHijacked represents a hijacked connection. 3532 // This is a terminal state. It does not transition to StateClosed. 3533 StateHijacked 3534 3535 // StateClosed represents a closed connection. 3536 // This is a terminal state. Hijacked connections do not 3537 // transition to StateClosed. 3538 StateClosed 3539 ) 3540 3541 var stateName = map[ConnState]string{ 3542 StateNew: "new", 3543 StateActive: "active", 3544 StateIdle: "idle", 3545 StateHijacked: "hijacked", 3546 StateClosed: "closed", 3547 } 3548 3549 func (c ConnState) String() string { 3550 return stateName[c] 3551 } 3552 3553 // badServeHTTP should be an internal detail, 3554 // but widely used packages access it using linkname. 3555 // Notable members of the hall of shame include: 3556 // - github.com/erda-project/erda-infra 3557 // 3558 // Do not remove or change the type signature. 3559 // See go.dev/issue/67401. 3560 // 3561 //go:linkname badServeHTTP net/http.serverHandler.ServeHTTP 3562 func badServeHTTP(srv *Server, rw ResponseWriter, req *Request) { 3563 srv.serveHTTP(rw, req, srv.Handler) 3564 } 3565 3566 // AllowQuerySemicolons returns a handler that serves requests by converting any 3567 // unescaped semicolons in the URL query to ampersands, and invoking the handler h. 3568 // 3569 // This restores the pre-Go 1.17 behavior of splitting query parameters on both 3570 // semicolons and ampersands. (See golang.org/issue/25192). Note that this 3571 // behavior doesn't match that of many proxies, and the mismatch can lead to 3572 // security issues. 3573 // 3574 // AllowQuerySemicolons should be invoked before [Request.ParseForm] is called. 3575 func AllowQuerySemicolons(h Handler) Handler { 3576 return HandlerFunc(func(w ResponseWriter, r *Request) { 3577 if strings.Contains(r.URL.RawQuery, ";") { 3578 r2 := new(Request) 3579 *r2 = *r 3580 r2.URL = new(url.URL) 3581 *r2.URL = *r.URL 3582 r2.URL.RawQuery = strings.ReplaceAll(r.URL.RawQuery, ";", "&") 3583 h.ServeHTTP(w, r2) 3584 } else { 3585 h.ServeHTTP(w, r) 3586 } 3587 }) 3588 } 3589 3590 // ListenAndServe listens on the TCP network address s.Addr and then 3591 // calls [Serve] to handle requests on incoming connections. 3592 // Accepted connections are configured to enable TCP keep-alives. 3593 // 3594 // If s.Addr is blank, ":http" is used. 3595 // 3596 // ListenAndServe always returns a non-nil error. After [Server.Shutdown] or [Server.Close], 3597 // the returned error is [ErrServerClosed]. 3598 func (s *Server) ListenAndServe() error { 3599 if s.shuttingDown() { 3600 return ErrServerClosed 3601 } 3602 addr := s.Addr 3603 if addr == "" { 3604 addr = ":http" 3605 } 3606 ln, err := net.Listen("tcp", addr) 3607 if err != nil { 3608 return err 3609 } 3610 return s.Serve(ln) 3611 } 3612 3613 var testHookServerServe func(*Server, net.Listener) // used if non-nil 3614 3615 // shouldConfigureHTTP2ForServe reports whether Server.Serve should configure 3616 // automatic HTTP/2. (which sets up the s.TLSNextProto map) 3617 func (s *Server) shouldConfigureHTTP2ForServe() bool { 3618 if s.TLSConfig == nil { 3619 // Compatibility with Go 1.6: 3620 // If there's no TLSConfig, it's possible that the user just 3621 // didn't set it on the http.Server, but did pass it to 3622 // tls.NewListener and passed that listener to Serve. 3623 // So we should configure HTTP/2 (to set up s.TLSNextProto) 3624 // in case the listener returns an "h2" *tls.Conn. 3625 return true 3626 } 3627 if s.protocols().UnencryptedHTTP2() { 3628 return true 3629 } 3630 // The user specified a TLSConfig on their http.Server. 3631 // In this, case, only configure HTTP/2 if their tls.Config 3632 // explicitly mentions "h2". Otherwise http2.ConfigureServer 3633 // would modify the tls.Config to add it, but they probably already 3634 // passed this tls.Config to tls.NewListener. And if they did, 3635 // it's too late anyway to fix it. It would only be potentially racy. 3636 // See Issue 15908. 3637 return slices.Contains(s.TLSConfig.NextProtos, "h2") 3638 } 3639 3640 // ErrServerClosed is returned by the [Server.Serve], [ServeTLS], [ListenAndServe], 3641 // and [ListenAndServeTLS] methods after a call to [Server.Shutdown] or [Server.Close]. 3642 var ErrServerClosed = errors.New("http: Server closed") 3643 3644 // Serve accepts incoming connections on the Listener l, creating a 3645 // new service goroutine for each. The service goroutines read requests and 3646 // then call s.Handler to reply to them. 3647 // 3648 // HTTP/2 support is only enabled if the Listener returns [*tls.Conn] 3649 // connections and they were configured with "h2" in the TLS 3650 // Config.NextProtos. 3651 // 3652 // Serve always returns a non-nil error and closes l. 3653 // After [Server.Shutdown] or [Server.Close], the returned error is [ErrServerClosed]. 3654 func (s *Server) Serve(l net.Listener) error { 3655 // This is the sneaky path we use to let x/net/http2 wrap an http.Server 3656 // and net/http/internal/http3 install an HTTP/3 implementation: 3657 // http2.ConfigureServer calls http.Server.Serve with a net.Listener that 3658 // implements a certain interface, which we recognize here as an attempt 3659 // to associate an http2.Server with us. 3660 // 3661 // (This is about as principled as the way we (ab)use Transport.RegisterProtocol, 3662 // which is to say not at all. It's worth it.) 3663 // 3664 // Server.Serve never returns a nil error under normal circumstances. 3665 // Returning nil on success informs our caller that we support this 3666 // sneaky registration mechanism. 3667 switch conf := l.(type) { 3668 case http2ExternalServerConfig: 3669 s.setHTTP2Config(conf) 3670 return nil 3671 case http3Server: 3672 s.setHTTP3Server(conf) 3673 return nil 3674 } 3675 3676 if fn := testHookServerServe; fn != nil { 3677 fn(s, l) // call hook with unwrapped listener 3678 } 3679 3680 origListener := l 3681 l = &onceCloseListener{Listener: l} 3682 defer l.Close() 3683 3684 if err := s.setupHTTP2_Serve(); err != nil { 3685 return err 3686 } 3687 3688 if !s.trackListener(&l, true) { 3689 return ErrServerClosed 3690 } 3691 defer s.trackListener(&l, false) 3692 3693 baseCtx := context.Background() 3694 if s.BaseContext != nil { 3695 baseCtx = s.BaseContext(origListener) 3696 if baseCtx == nil { 3697 panic("BaseContext returned a nil context") 3698 } 3699 } 3700 3701 var tempDelay time.Duration // how long to sleep on accept failure 3702 3703 ctx := context.WithValue(baseCtx, ServerContextKey, s) 3704 for { 3705 rw, err := l.Accept() 3706 if err != nil { 3707 if s.shuttingDown() { 3708 return ErrServerClosed 3709 } 3710 if ne, ok := err.(net.Error); ok && ne.Temporary() { 3711 if tempDelay == 0 { 3712 tempDelay = 5 * time.Millisecond 3713 } else { 3714 tempDelay *= 2 3715 } 3716 if max := 1 * time.Second; tempDelay > max { 3717 tempDelay = max 3718 } 3719 s.logf("http: Accept error: %v; retrying in %v", err, tempDelay) 3720 time.Sleep(tempDelay) 3721 continue 3722 } 3723 return err 3724 } 3725 connCtx := ctx 3726 if cc := s.ConnContext; cc != nil { 3727 connCtx = cc(connCtx, rw) 3728 if connCtx == nil { 3729 panic("ConnContext returned nil") 3730 } 3731 } 3732 tempDelay = 0 3733 c := s.newConn(rw) 3734 c.setState(c.rwc, StateNew, runHooks) // before Serve can return 3735 go c.serve(connCtx) 3736 } 3737 } 3738 3739 func (s *Server) setupTLSConfig(certFile, keyFile string, nextProtos []string) (*tls.Config, error) { 3740 config := cloneTLSConfig(s.TLSConfig) 3741 config.NextProtos = nextProtos 3742 3743 configHasCert := len(config.Certificates) > 0 || config.GetCertificate != nil || config.GetConfigForClient != nil 3744 if !configHasCert || certFile != "" || keyFile != "" { 3745 var err error 3746 config.Certificates = make([]tls.Certificate, 1) 3747 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) 3748 if err != nil { 3749 return nil, err 3750 } 3751 } 3752 return config, nil 3753 } 3754 3755 // ServeTLS accepts incoming connections on the Listener l, creating a 3756 // new service goroutine for each. The service goroutines perform TLS 3757 // setup and then read requests, calling s.Handler to reply to them. 3758 // 3759 // Files containing a certificate and matching private key for the 3760 // server must be provided if neither the [Server]'s 3761 // TLSConfig.Certificates, TLSConfig.GetCertificate nor 3762 // config.GetConfigForClient are populated. 3763 // If the certificate is signed by a certificate authority, the 3764 // certFile should be the concatenation of the server's certificate, 3765 // any intermediates, and the CA's certificate. 3766 // 3767 // ServeTLS always returns a non-nil error. After [Server.Shutdown] or [Server.Close], the 3768 // returned error is [ErrServerClosed]. 3769 func (s *Server) ServeTLS(l net.Listener, certFile, keyFile string) error { 3770 // Setup HTTP/2 before s.Serve, to initialize s.TLSConfig 3771 // before we clone it and create the TLS Listener. 3772 if err := s.setupHTTP2_ServeTLS(); err != nil { 3773 return err 3774 } 3775 if s.h3Server != nil { 3776 // Temporary, test-only way to serve HTTP/3 from a PacketConn: 3777 // Pass it to ServeTLS wrapped in a net.Listener. 3778 // The caller should pass a net.Listener that immediately returns an error 3779 // if passed to a Server that doesn't support this path. 3780 if x, ok := l.(interface { 3781 HTTP3PacketConn() net.PacketConn 3782 }); ok { 3783 return s.serveHTTP3(x.HTTP3PacketConn(), certFile, keyFile) 3784 } 3785 } 3786 3787 var nextProtos []string 3788 if s.TLSConfig != nil { 3789 nextProtos = s.TLSConfig.NextProtos 3790 } 3791 config, err := s.setupTLSConfig(certFile, keyFile, adjustNextProtos(nextProtos, s.protocols())) 3792 if err != nil { 3793 return err 3794 } 3795 3796 tlsListener := tls.NewListener(l, config) 3797 return s.Serve(tlsListener) 3798 } 3799 3800 // HandleRequest handles a request as if it was received by the server. 3801 // 3802 // - If Server.DisableGeneralOptionsHandler is not true, 3803 // it responds to "OPTIONS *" requests with 200 OK and Content-Length: 0. 3804 // - If Server.Handler is nil, it uses [DefaultServeMux]. 3805 // - Panics in the handler are recovered. 3806 // If the panic is not [ErrAbortHandler], the panic is logged. 3807 // 3808 // HandleRequest returns a non-nil error if the handler panics. 3809 // It returns [ErrAbortHandler] if the handler panicked with that value. 3810 func (s *Server) HandleRequest(w ResponseWriter, req *Request) error { 3811 return s.handleRequest(w, req, s.Handler) 3812 } 3813 3814 func (s *Server) handleRequest(w ResponseWriter, req *Request, h Handler) (err error) { 3815 didPanic := true 3816 defer func() { 3817 if !didPanic { 3818 return 3819 } 3820 e := recover() 3821 if e == ErrAbortHandler { 3822 err = ErrAbortHandler 3823 return 3824 } 3825 if e != nil { 3826 const size = 64 << 10 3827 buf := make([]byte, size) 3828 buf = buf[:runtime.Stack(buf, false)] 3829 s.logf("http: panic serving %v: %v\n%s", req.RemoteAddr, e, buf) 3830 } 3831 err = fmt.Errorf("http: panic serving %v: %v", req.RemoteAddr, e) 3832 }() 3833 s.serveHTTP(w, req, h) 3834 didPanic = false 3835 return nil 3836 } 3837 3838 func (s *Server) serveHTTP(rw ResponseWriter, req *Request, handler Handler) { 3839 if handler == nil { 3840 handler = DefaultServeMux 3841 } 3842 if !s.DisableGeneralOptionsHandler && req.RequestURI == "*" && req.Method == "OPTIONS" { 3843 handler = globalOptionsHandler{} 3844 } 3845 3846 defer func() { 3847 if req.MultipartForm != nil { 3848 req.MultipartForm.RemoveAll() 3849 } 3850 }() 3851 handler.ServeHTTP(rw, req) 3852 } 3853 3854 func (s *Server) protocols() Protocols { 3855 if s.Protocols != nil { 3856 // Historically, even when Protocols for a Server was set to be empty, 3857 // the Server can still run normally with just HTTP/1. 3858 // To keep backward-compatibility, the zero value of Protocols is 3859 // defined as having only HTTP/1 enabled. 3860 if s.Protocols.empty() { 3861 var p Protocols 3862 p.SetHTTP1(true) 3863 return p 3864 } 3865 return *s.Protocols // user-configured set 3866 } 3867 3868 // The historic way of disabling HTTP/2 is to set TLSNextProto to 3869 // a non-nil map with no "h2" entry. 3870 _, hasH2 := s.TLSNextProto["h2"] 3871 http2Disabled := s.TLSNextProto != nil && !hasH2 3872 3873 // If GODEBUG=http2server=0, then HTTP/2 is disabled unless 3874 // the user has manually added an "h2" entry to TLSNextProto 3875 // (probably by using x/net/http2 directly). 3876 if http2server.Value() == "0" && !hasH2 { 3877 http2Disabled = true 3878 } 3879 3880 var p Protocols 3881 p.SetHTTP1(true) // default always includes HTTP/1 3882 if !http2Disabled { 3883 p.SetHTTP2(true) 3884 } 3885 return p 3886 } 3887 3888 // adjustNextProtos adds or removes "http/1.1" and "h2" entries from 3889 // a tls.Config.NextProtos list, according to the set of protocols in protos. 3890 func adjustNextProtos(nextProtos []string, protos Protocols) []string { 3891 // Make a copy of NextProtos since it might be shared with some other tls.Config. 3892 // (tls.Config.Clone doesn't do a deep copy.) 3893 // 3894 // We could avoid an allocation in the common case by checking to see if the slice 3895 // is already in order, but this is just one small allocation per connection. 3896 nextProtos = slices.Clone(nextProtos) 3897 var have Protocols 3898 nextProtos = slices.DeleteFunc(nextProtos, func(s string) bool { 3899 switch s { 3900 case "http/1.1": 3901 if !protos.HTTP1() { 3902 return true 3903 } 3904 have.SetHTTP1(true) 3905 case "h2": 3906 if !protos.HTTP2() { 3907 return true 3908 } 3909 have.SetHTTP2(true) 3910 } 3911 return false 3912 }) 3913 if protos.HTTP2() && !have.HTTP2() { 3914 nextProtos = append(nextProtos, "h2") 3915 } 3916 if protos.HTTP1() && !have.HTTP1() { 3917 nextProtos = append(nextProtos, "http/1.1") 3918 } 3919 return nextProtos 3920 } 3921 3922 // trackListener adds or removes a net.Listener to the set of tracked 3923 // listeners. 3924 // 3925 // We store a pointer to interface in the map set, in case the 3926 // net.Listener is not comparable. This is safe because we only call 3927 // trackListener via Serve and can track+defer untrack the same 3928 // pointer to local variable there. We never need to compare a 3929 // Listener from another caller. 3930 // 3931 // It reports whether the server is still up (not Shutdown or Closed). 3932 func (s *Server) trackListener(ln *net.Listener, add bool) bool { 3933 s.mu.Lock() 3934 defer s.mu.Unlock() 3935 if s.listeners == nil { 3936 s.listeners = make(map[*net.Listener]struct{}) 3937 } 3938 if add { 3939 if s.shuttingDown() { 3940 return false 3941 } 3942 s.listeners[ln] = struct{}{} 3943 s.listenerGroup.Add(1) 3944 } else { 3945 delete(s.listeners, ln) 3946 s.listenerGroup.Done() 3947 } 3948 return true 3949 } 3950 3951 func (s *Server) trackConn(c *conn, add bool) { 3952 s.mu.Lock() 3953 defer s.mu.Unlock() 3954 if s.activeConn == nil { 3955 s.activeConn = make(map[*conn]struct{}) 3956 } 3957 if add { 3958 s.activeConn[c] = struct{}{} 3959 } else { 3960 delete(s.activeConn, c) 3961 } 3962 } 3963 3964 func (s *Server) idleTimeout() time.Duration { 3965 if s.IdleTimeout != 0 { 3966 return s.IdleTimeout 3967 } 3968 return s.ReadTimeout 3969 } 3970 3971 func (s *Server) readHeaderTimeout() time.Duration { 3972 if s.ReadHeaderTimeout != 0 { 3973 return s.ReadHeaderTimeout 3974 } 3975 return s.ReadTimeout 3976 } 3977 3978 func (s *Server) doKeepAlives() bool { 3979 return !s.disableKeepAlives.Load() && !s.shuttingDown() 3980 } 3981 3982 func (s *Server) shuttingDown() bool { 3983 return s.inShutdown.Load() 3984 } 3985 3986 // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. 3987 // By default, keep-alives are always enabled. Only very 3988 // resource-constrained environments or servers in the process of 3989 // shutting down should disable them. 3990 func (s *Server) SetKeepAlivesEnabled(v bool) { 3991 if v { 3992 s.disableKeepAlives.Store(false) 3993 return 3994 } 3995 s.disableKeepAlives.Store(true) 3996 3997 // Close idle HTTP/1 conns: 3998 s.closeIdleConns() 3999 4000 // TODO: Issue 26303: close HTTP/2 conns as soon as they become idle. 4001 } 4002 4003 func (s *Server) logf(format string, args ...any) { 4004 if s.ErrorLog != nil { 4005 s.ErrorLog.Printf(format, args...) 4006 } else { 4007 log.Printf(format, args...) 4008 } 4009 } 4010 4011 // logf prints to the ErrorLog of the *Server associated with request r 4012 // via ServerContextKey. If there's no associated server, or if ErrorLog 4013 // is nil, logging is done via the log package's standard logger. 4014 func logf(r *Request, format string, args ...any) { 4015 s, _ := r.Context().Value(ServerContextKey).(*Server) 4016 if s != nil && s.ErrorLog != nil { 4017 s.ErrorLog.Printf(format, args...) 4018 } else { 4019 log.Printf(format, args...) 4020 } 4021 } 4022 4023 // ListenAndServe listens on the TCP network address addr and then calls 4024 // [Serve] with handler to handle requests on incoming connections. 4025 // Accepted connections are configured to enable TCP keep-alives. 4026 // 4027 // The handler is typically nil, in which case [DefaultServeMux] is used. 4028 // 4029 // ListenAndServe always returns a non-nil error. 4030 func ListenAndServe(addr string, handler Handler) error { 4031 server := &Server{Addr: addr, Handler: handler} 4032 return server.ListenAndServe() 4033 } 4034 4035 // ListenAndServeTLS acts identically to [ListenAndServe], except that it 4036 // expects HTTPS connections. Additionally, files containing a certificate and 4037 // matching private key for the server must be provided. If the certificate 4038 // is signed by a certificate authority, the certFile should be the concatenation 4039 // of the server's certificate, any intermediates, and the CA's certificate. 4040 func ListenAndServeTLS(addr, certFile, keyFile string, handler Handler) error { 4041 server := &Server{Addr: addr, Handler: handler} 4042 return server.ListenAndServeTLS(certFile, keyFile) 4043 } 4044 4045 // http3ServerHandler implements an interface in an external library that 4046 // supports HTTP/3, allowing an external implementation of HTTP/3 to be used 4047 // via net/http. See https://go.dev/issue/77440 for details. 4048 // 4049 // This is currently only used with net/http/internal/http3, to allow us to 4050 // test our HTTP/3 implementation against tests in net/http. HTTP/3 is not yet 4051 // accessible to end-users. 4052 type http3ServerHandler struct { 4053 srv *Server 4054 tlsConfig *tls.Config 4055 baseCtx context.Context 4056 errc chan error 4057 shutdownCtx context.Context 4058 } 4059 4060 // ServeHTTP ensures that http3ServerHandler implements the Handler interface, 4061 // and gives an HTTP/3 server implementation access to the net/http handler. 4062 func (h *http3ServerHandler) ServeHTTP(w ResponseWriter, r *Request) { 4063 h.srv.serveHTTP(w, r, h.srv.Handler) 4064 } 4065 4066 // Addr gives an HTTP/3 server implementation the address that it should listen 4067 // on. 4068 func (h *http3ServerHandler) Addr() string { 4069 return h.srv.Addr 4070 } 4071 4072 // TLSConfig gives an HTTP/3 server implementation the *tls.Config that it 4073 // should use. 4074 func (h *http3ServerHandler) TLSConfig() *tls.Config { 4075 return h.tlsConfig 4076 } 4077 4078 // BaseContext gives an HTTP/3 server implementation the base context to use 4079 // for server requests. 4080 func (h *http3ServerHandler) BaseContext() context.Context { 4081 return h.baseCtx 4082 } 4083 4084 // ListenErrHook should be called by an HTTP/3 server implementation to 4085 // propagate any error it encounters when trying to listen, if any, to 4086 // net/http. 4087 func (h *http3ServerHandler) ListenErrHook(err error) { 4088 h.errc <- err 4089 } 4090 4091 // ShutdownContext gives an HTTP/3 server implementation the context that is 4092 // used when [Server.Shutdown] is called. This allows an HTTP/3 server 4093 // implementation to know how long it can take to gracefully shutdown in the 4094 // function it registers with [Server.RegisterOnShutdown]. Callers must not use 4095 // this method for any other purpose. 4096 func (h *http3ServerHandler) ShutdownContext() context.Context { 4097 return h.shutdownCtx 4098 } 4099 4100 // ListenAndServeTLS listens on the TCP network address s.Addr and 4101 // then calls [ServeTLS] to handle requests on incoming TLS connections. 4102 // Accepted connections are configured to enable TCP keep-alives. 4103 // 4104 // Filenames containing a certificate and matching private key for the 4105 // server must be provided if neither the [Server]'s TLSConfig.Certificates 4106 // nor TLSConfig.GetCertificate are populated. If the certificate is 4107 // signed by a certificate authority, the certFile should be the 4108 // concatenation of the server's certificate, any intermediates, and 4109 // the CA's certificate. 4110 // 4111 // If s.Addr is blank, ":https" is used. 4112 // 4113 // ListenAndServeTLS always returns a non-nil error. After [Server.Shutdown] or 4114 // [Server.Close], the returned error is [ErrServerClosed]. 4115 func (s *Server) ListenAndServeTLS(certFile, keyFile string) error { 4116 if s.shuttingDown() { 4117 return ErrServerClosed 4118 } 4119 addr := s.Addr 4120 if addr == "" { 4121 addr = ":https" 4122 } 4123 4124 p := s.protocols() 4125 if p.http3() { 4126 // TODO: Support HTTP/3 here. 4127 // For now, tests use Server.ServeTLS. 4128 return errors.New("http: Server.Protocols contains HTTP3, but Server does not support HTTP/3") 4129 } 4130 // Only start a TCP listener if HTTP/1 or HTTP/2 is used. 4131 if !p.HTTP1() && !p.HTTP2() && !p.UnencryptedHTTP2() { 4132 return errors.New("http: no protocols configured") 4133 } 4134 4135 ln, err := net.Listen("tcp", addr) 4136 if err != nil { 4137 return err 4138 } 4139 defer ln.Close() 4140 return s.ServeTLS(ln, certFile, keyFile) 4141 } 4142 4143 // setupHTTP2_ServeTLS conditionally configures HTTP/2 on 4144 // s and reports whether there was an error setting it up. If it is 4145 // not configured for policy reasons, nil is returned. 4146 func (s *Server) setupHTTP2_ServeTLS() error { 4147 s.nextProtoOnce.Do(s.onceSetNextProtoDefaults) 4148 return s.nextProtoErr 4149 } 4150 4151 // setupHTTP2_Serve is called from (*Server).Serve and conditionally 4152 // configures HTTP/2 on s using a more conservative policy than 4153 // setupHTTP2_ServeTLS because Serve is called after tls.Listen, 4154 // and may be called concurrently. See shouldConfigureHTTP2ForServe. 4155 // 4156 // The tests named TestTransportAutomaticHTTP2* and 4157 // TestConcurrentServerServe in server_test.go demonstrate some 4158 // of the supported use cases and motivations. 4159 func (s *Server) setupHTTP2_Serve() error { 4160 s.nextProtoOnce.Do(s.onceSetNextProtoDefaults_Serve) 4161 return s.nextProtoErr 4162 } 4163 4164 func (s *Server) onceSetNextProtoDefaults_Serve() { 4165 if s.shouldConfigureHTTP2ForServe() { 4166 s.onceSetNextProtoDefaults() 4167 } 4168 } 4169 4170 var http2server = godebug.New("http2server") 4171 4172 // onceSetNextProtoDefaults configures HTTP/2, if the user hasn't 4173 // configured otherwise. (by setting s.TLSNextProto non-nil) 4174 // It must only be called via s.nextProtoOnce (use s.setupHTTP2_*). 4175 func (s *Server) onceSetNextProtoDefaults() { 4176 if omitHTTP2Server { 4177 return 4178 } 4179 p := s.protocols() 4180 if !p.HTTP2() && !p.UnencryptedHTTP2() { 4181 return 4182 } 4183 if http2server.Value() == "0" { 4184 http2server.IncNonDefault() 4185 return 4186 } 4187 if _, ok := s.TLSNextProto["h2"]; ok { 4188 // TLSNextProto already contains an HTTP/2 implementation. 4189 // The user probably called golang.org/x/net/http2.ConfigureServer 4190 // to add it. 4191 return 4192 } 4193 s.configureHTTP2() 4194 } 4195 4196 // TimeoutHandler returns a [Handler] that runs h with the given time limit. 4197 // 4198 // The new Handler calls h.ServeHTTP to handle each request, but if a 4199 // call runs for longer than its time limit, the handler responds with 4200 // a 503 Service Unavailable error and the given message in its body. 4201 // (If msg is empty, a suitable default message will be sent.) 4202 // After such a timeout, writes by h to its [ResponseWriter] will return 4203 // [ErrHandlerTimeout]. 4204 // 4205 // TimeoutHandler supports the [Pusher] interface but does not support 4206 // the [Hijacker] or [Flusher] interfaces. 4207 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler { 4208 return &timeoutHandler{ 4209 handler: h, 4210 body: msg, 4211 dt: dt, 4212 } 4213 } 4214 4215 // ErrHandlerTimeout is returned on [ResponseWriter] Write calls 4216 // in handlers which have timed out. 4217 var ErrHandlerTimeout = errors.New("http: Handler timeout") 4218 4219 type timeoutHandler struct { 4220 handler Handler 4221 body string 4222 dt time.Duration 4223 4224 // When set, no context will be created and this context will 4225 // be used instead. 4226 testContext context.Context 4227 } 4228 4229 func (h *timeoutHandler) errorBody() string { 4230 if h.body != "" { 4231 return h.body 4232 } 4233 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>" 4234 } 4235 4236 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) { 4237 ctx := h.testContext 4238 if ctx == nil { 4239 var cancelCtx context.CancelFunc 4240 ctx, cancelCtx = context.WithTimeout(r.Context(), h.dt) 4241 defer cancelCtx() 4242 } 4243 r = r.WithContext(ctx) 4244 done := make(chan struct{}) 4245 tw := &timeoutWriter{ 4246 w: w, 4247 h: make(Header), 4248 req: r, 4249 } 4250 panicChan := make(chan any, 1) 4251 go func() { 4252 defer func() { 4253 if p := recover(); p != nil { 4254 panicChan <- p 4255 } 4256 }() 4257 h.handler.ServeHTTP(tw, r) 4258 close(done) 4259 }() 4260 select { 4261 case p := <-panicChan: 4262 panic(p) 4263 case <-done: 4264 tw.mu.Lock() 4265 defer tw.mu.Unlock() 4266 dst := w.Header() 4267 maps.Copy(dst, tw.h) 4268 if !tw.wroteHeader { 4269 tw.code = StatusOK 4270 } 4271 w.WriteHeader(tw.code) 4272 w.Write(tw.wbuf.Bytes()) 4273 case <-ctx.Done(): 4274 tw.mu.Lock() 4275 defer tw.mu.Unlock() 4276 switch err := ctx.Err(); err { 4277 case context.DeadlineExceeded: 4278 w.WriteHeader(StatusServiceUnavailable) 4279 io.WriteString(w, h.errorBody()) 4280 tw.err = ErrHandlerTimeout 4281 default: 4282 w.WriteHeader(StatusServiceUnavailable) 4283 tw.err = err 4284 } 4285 } 4286 } 4287 4288 type timeoutWriter struct { 4289 w ResponseWriter 4290 h Header 4291 wbuf bytes.Buffer 4292 req *Request 4293 4294 mu sync.Mutex 4295 err error 4296 wroteHeader bool 4297 code int 4298 } 4299 4300 var _ Pusher = (*timeoutWriter)(nil) 4301 4302 // Push implements the [Pusher] interface. 4303 func (tw *timeoutWriter) Push(target string, opts *PushOptions) error { 4304 if pusher, ok := tw.w.(Pusher); ok { 4305 return pusher.Push(target, opts) 4306 } 4307 return ErrNotSupported 4308 } 4309 4310 func (tw *timeoutWriter) Header() Header { return tw.h } 4311 4312 func (tw *timeoutWriter) Write(p []byte) (int, error) { 4313 tw.mu.Lock() 4314 defer tw.mu.Unlock() 4315 if tw.err != nil { 4316 return 0, tw.err 4317 } 4318 if !tw.wroteHeader { 4319 tw.writeHeaderLocked(StatusOK) 4320 } 4321 return tw.wbuf.Write(p) 4322 } 4323 4324 func (tw *timeoutWriter) writeHeaderLocked(code int) { 4325 checkWriteHeaderCode(code) 4326 4327 switch { 4328 case tw.err != nil: 4329 return 4330 case tw.wroteHeader: 4331 if tw.req != nil { 4332 caller := relevantCaller() 4333 logf(tw.req, "http: superfluous response.WriteHeader call from %s (%s:%d)", caller.Function, path.Base(caller.File), caller.Line) 4334 } 4335 default: 4336 tw.wroteHeader = true 4337 tw.code = code 4338 } 4339 } 4340 4341 func (tw *timeoutWriter) WriteHeader(code int) { 4342 tw.mu.Lock() 4343 defer tw.mu.Unlock() 4344 tw.writeHeaderLocked(code) 4345 } 4346 4347 // onceCloseListener wraps a net.Listener, protecting it from 4348 // multiple Close calls. 4349 type onceCloseListener struct { 4350 net.Listener 4351 once sync.Once 4352 closeErr error 4353 } 4354 4355 func (oc *onceCloseListener) Close() error { 4356 oc.once.Do(oc.close) 4357 return oc.closeErr 4358 } 4359 4360 func (oc *onceCloseListener) close() { oc.closeErr = oc.Listener.Close() } 4361 4362 // globalOptionsHandler responds to "OPTIONS *" requests. 4363 type globalOptionsHandler struct{} 4364 4365 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) { 4366 w.Header().Set("Content-Length", "0") 4367 if r.ContentLength != 0 { 4368 // Read up to 4KB of OPTIONS body (as mentioned in the 4369 // spec as being reserved for future use), but anything 4370 // over that is considered a waste of server resources 4371 // (or an attack) and we abort and close the connection, 4372 // courtesy of MaxBytesReader's EOF behavior. 4373 mb := MaxBytesReader(w, r.Body, 4<<10) 4374 io.Copy(io.Discard, mb) 4375 } 4376 } 4377 4378 // initALPNRequest is an HTTP handler that initializes certain 4379 // uninitialized fields in its *Request. Such partially-initialized 4380 // Requests come from ALPN protocol handlers. 4381 type initALPNRequest struct { 4382 ctx context.Context 4383 c *tls.Conn 4384 srv *Server 4385 } 4386 4387 // BaseContext is an exported but unadvertised [http.Handler] method 4388 // recognized by x/net/http2 to pass down a context; the TLSNextProto 4389 // API predates context support so we shoehorn through the only 4390 // interface we have available. 4391 func (h initALPNRequest) BaseContext() context.Context { return h.ctx } 4392 4393 func (h initALPNRequest) ServeHTTP(rw ResponseWriter, req *Request) { 4394 if req.TLS == nil { 4395 req.TLS = &tls.ConnectionState{} 4396 *req.TLS = h.c.ConnectionState() 4397 } 4398 if req.Body == nil { 4399 req.Body = NoBody 4400 } 4401 if req.RemoteAddr == "" { 4402 req.RemoteAddr = h.c.RemoteAddr().String() 4403 } 4404 h.srv.serveHTTP(rw, req, h.srv.Handler) 4405 } 4406 4407 // loggingConn is used for debugging. 4408 type loggingConn struct { 4409 name string 4410 net.Conn 4411 } 4412 4413 var ( 4414 uniqNameMu sync.Mutex 4415 uniqNameNext = make(map[string]int) 4416 ) 4417 4418 func newLoggingConn(baseName string, c net.Conn) net.Conn { 4419 uniqNameMu.Lock() 4420 defer uniqNameMu.Unlock() 4421 uniqNameNext[baseName]++ 4422 return &loggingConn{ 4423 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]), 4424 Conn: c, 4425 } 4426 } 4427 4428 func (c *loggingConn) Write(p []byte) (n int, err error) { 4429 log.Printf("%s.Write(%d) = ....", c.name, len(p)) 4430 n, err = c.Conn.Write(p) 4431 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err) 4432 return 4433 } 4434 4435 func (c *loggingConn) Read(p []byte) (n int, err error) { 4436 log.Printf("%s.Read(%d) = ....", c.name, len(p)) 4437 n, err = c.Conn.Read(p) 4438 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err) 4439 return 4440 } 4441 4442 func (c *loggingConn) Close() (err error) { 4443 log.Printf("%s.Close() = ...", c.name) 4444 err = c.Conn.Close() 4445 log.Printf("%s.Close() = %v", c.name, err) 4446 return 4447 } 4448 4449 // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr. 4450 // It only contains one field (and a pointer field at that), so it 4451 // fits in an interface value without an extra allocation. 4452 type checkConnErrorWriter struct { 4453 c *conn 4454 } 4455 4456 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) { 4457 n, err = w.c.rwc.Write(p) 4458 if err != nil && w.c.werr == nil { 4459 w.c.werr = err 4460 w.c.cancelCtx() 4461 } 4462 return 4463 } 4464 4465 func numLeadingCRorLF(v []byte) (n int) { 4466 for _, b := range v { 4467 if b == '\r' || b == '\n' { 4468 n++ 4469 continue 4470 } 4471 break 4472 } 4473 return 4474 } 4475 4476 // tlsRecordHeaderLooksLikeHTTP reports whether a TLS record header 4477 // looks like it might've been a misdirected plaintext HTTP request. 4478 func tlsRecordHeaderLooksLikeHTTP(hdr [5]byte) bool { 4479 switch string(hdr[:]) { 4480 case "GET /", "HEAD ", "POST ", "PUT /", "OPTIO": 4481 return true 4482 } 4483 return false 4484 } 4485 4486 // MaxBytesHandler returns a [Handler] that runs h with its [ResponseWriter] and [Request.Body] wrapped by a MaxBytesReader. 4487 func MaxBytesHandler(h Handler, n int64) Handler { 4488 return HandlerFunc(func(w ResponseWriter, r *Request) { 4489 r2 := *r 4490 r2.Body = MaxBytesReader(w, r.Body, n) 4491 h.ServeHTTP(w, &r2) 4492 }) 4493 } 4494