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