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