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