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