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