github.com/jonasi/go@v0.0.0-20150930005915-e78e654c1de0/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 "crypto/tls" 12 "errors" 13 "fmt" 14 "io" 15 "io/ioutil" 16 "log" 17 "net" 18 "net/textproto" 19 "net/url" 20 "os" 21 "path" 22 "runtime" 23 "strconv" 24 "strings" 25 "sync" 26 "sync/atomic" 27 "time" 28 ) 29 30 // Errors introduced by the HTTP server. 31 var ( 32 ErrWriteAfterFlush = errors.New("Conn.Write called after Flush") 33 ErrBodyNotAllowed = errors.New("http: request method or response status code does not allow body") 34 ErrHijacked = errors.New("Conn has been hijacked") 35 ErrContentLength = errors.New("Conn.Write wrote more than the declared Content-Length") 36 ) 37 38 // Objects implementing the Handler interface can be 39 // registered to serve a particular path or subtree 40 // in the HTTP server. 41 // 42 // ServeHTTP should write reply headers and data to the ResponseWriter 43 // and then return. Returning signals that the request is finished 44 // and that the HTTP server can move on to the next request on 45 // the connection. 46 // 47 // If ServeHTTP panics, the server (the caller of ServeHTTP) assumes 48 // that the effect of the panic was isolated to the active request. 49 // It recovers the panic, logs a stack trace to the server error log, 50 // and hangs up the connection. 51 // 52 type Handler interface { 53 ServeHTTP(ResponseWriter, *Request) 54 } 55 56 // A ResponseWriter interface is used by an HTTP handler to 57 // construct an HTTP response. 58 type ResponseWriter interface { 59 // Header returns the header map that will be sent by 60 // WriteHeader. Changing the header after a call to 61 // WriteHeader (or Write) has no effect unless the modified 62 // headers were declared as trailers by setting the 63 // "Trailer" header before the call to WriteHeader (see example). 64 // To suppress implicit response headers, set their value to nil. 65 Header() Header 66 67 // Write writes the data to the connection as part of an HTTP reply. 68 // If WriteHeader has not yet been called, Write calls WriteHeader(http.StatusOK) 69 // before writing the data. If the Header does not contain a 70 // Content-Type line, Write adds a Content-Type set to the result of passing 71 // the initial 512 bytes of written data to DetectContentType. 72 Write([]byte) (int, error) 73 74 // WriteHeader sends an HTTP response header with status code. 75 // If WriteHeader is not called explicitly, the first call to Write 76 // will trigger an implicit WriteHeader(http.StatusOK). 77 // Thus explicit calls to WriteHeader are mainly used to 78 // send error codes. 79 WriteHeader(int) 80 } 81 82 // The Flusher interface is implemented by ResponseWriters that allow 83 // an HTTP handler to flush buffered data to the client. 84 // 85 // Note that even for ResponseWriters that support Flush, 86 // if the client is connected through an HTTP proxy, 87 // the buffered data may not reach the client until the response 88 // completes. 89 type Flusher interface { 90 // Flush sends any buffered data to the client. 91 Flush() 92 } 93 94 // The Hijacker interface is implemented by ResponseWriters that allow 95 // an HTTP handler to take over the connection. 96 type Hijacker interface { 97 // Hijack lets the caller take over the connection. 98 // After a call to Hijack(), the HTTP server library 99 // will not do anything else with the connection. 100 // 101 // It becomes the caller's responsibility to manage 102 // and close the connection. 103 // 104 // The returned net.Conn may have read or write deadlines 105 // already set, depending on the configuration of the 106 // Server. It is the caller's responsibility to set 107 // or clear those deadlines as needed. 108 Hijack() (net.Conn, *bufio.ReadWriter, error) 109 } 110 111 // The CloseNotifier interface is implemented by ResponseWriters which 112 // allow detecting when the underlying connection has gone away. 113 // 114 // This mechanism can be used to cancel long operations on the server 115 // if the client has disconnected before the response is ready. 116 type CloseNotifier interface { 117 // CloseNotify returns a channel that receives a single value 118 // when the client connection has gone away. 119 CloseNotify() <-chan bool 120 } 121 122 // A conn represents the server side of an HTTP connection. 123 type conn struct { 124 remoteAddr string // network address of remote side 125 server *Server // the Server on which the connection arrived 126 rwc net.Conn // i/o connection 127 w io.Writer // checkConnErrorWriter's copy of wrc, not zeroed on Hijack 128 werr error // any errors writing to w 129 sr liveSwitchReader // where the LimitReader reads from; usually the rwc 130 lr *io.LimitedReader // io.LimitReader(sr) 131 buf *bufio.ReadWriter // buffered(lr,rwc), reading from bufio->limitReader->sr->rwc 132 tlsState *tls.ConnectionState // or nil when not using TLS 133 lastMethod string // method of previous request, or "" 134 135 mu sync.Mutex // guards the following 136 clientGone bool // if client has disconnected mid-request 137 closeNotifyc chan bool // made lazily 138 hijackedv bool // connection has been hijacked by handler 139 } 140 141 func (c *conn) hijacked() bool { 142 c.mu.Lock() 143 defer c.mu.Unlock() 144 return c.hijackedv 145 } 146 147 func (c *conn) hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) { 148 c.mu.Lock() 149 defer c.mu.Unlock() 150 if c.hijackedv { 151 return nil, nil, ErrHijacked 152 } 153 if c.closeNotifyc != nil { 154 return nil, nil, errors.New("http: Hijack is incompatible with use of CloseNotifier") 155 } 156 c.hijackedv = true 157 rwc = c.rwc 158 buf = c.buf 159 c.rwc = nil 160 c.buf = nil 161 c.setState(rwc, StateHijacked) 162 return 163 } 164 165 func (c *conn) closeNotify() <-chan bool { 166 c.mu.Lock() 167 defer c.mu.Unlock() 168 if c.closeNotifyc == nil { 169 c.closeNotifyc = make(chan bool, 1) 170 if c.hijackedv { 171 // to obey the function signature, even though 172 // it'll never receive a value. 173 return c.closeNotifyc 174 } 175 pr, pw := io.Pipe() 176 177 readSource := c.sr.r 178 c.sr.Lock() 179 c.sr.r = pr 180 c.sr.Unlock() 181 go func() { 182 bufp := copyBufPool.Get().(*[]byte) 183 defer copyBufPool.Put(bufp) 184 _, err := io.CopyBuffer(pw, readSource, *bufp) 185 if err == nil { 186 err = io.EOF 187 } 188 pw.CloseWithError(err) 189 c.noteClientGone() 190 }() 191 } 192 return c.closeNotifyc 193 } 194 195 func (c *conn) noteClientGone() { 196 c.mu.Lock() 197 defer c.mu.Unlock() 198 if c.closeNotifyc != nil && !c.clientGone { 199 c.closeNotifyc <- true 200 } 201 c.clientGone = true 202 } 203 204 // A switchWriter can have its Writer changed at runtime. 205 // It's not safe for concurrent Writes and switches. 206 type switchWriter struct { 207 io.Writer 208 } 209 210 // A liveSwitchReader can have its Reader changed at runtime. It's 211 // safe for concurrent reads and switches, if its mutex is held. 212 type liveSwitchReader struct { 213 sync.Mutex 214 r io.Reader 215 } 216 217 func (sr *liveSwitchReader) Read(p []byte) (n int, err error) { 218 sr.Lock() 219 r := sr.r 220 sr.Unlock() 221 return r.Read(p) 222 } 223 224 // This should be >= 512 bytes for DetectContentType, 225 // but otherwise it's somewhat arbitrary. 226 const bufferBeforeChunkingSize = 2048 227 228 // chunkWriter writes to a response's conn buffer, and is the writer 229 // wrapped by the response.bufw buffered writer. 230 // 231 // chunkWriter also is responsible for finalizing the Header, including 232 // conditionally setting the Content-Type and setting a Content-Length 233 // in cases where the handler's final output is smaller than the buffer 234 // size. It also conditionally adds chunk headers, when in chunking mode. 235 // 236 // See the comment above (*response).Write for the entire write flow. 237 type chunkWriter struct { 238 res *response 239 240 // header is either nil or a deep clone of res.handlerHeader 241 // at the time of res.WriteHeader, if res.WriteHeader is 242 // called and extra buffering is being done to calculate 243 // Content-Type and/or Content-Length. 244 header Header 245 246 // wroteHeader tells whether the header's been written to "the 247 // wire" (or rather: w.conn.buf). this is unlike 248 // (*response).wroteHeader, which tells only whether it was 249 // logically written. 250 wroteHeader bool 251 252 // set by the writeHeader method: 253 chunking bool // using chunked transfer encoding for reply body 254 } 255 256 var ( 257 crlf = []byte("\r\n") 258 colonSpace = []byte(": ") 259 ) 260 261 func (cw *chunkWriter) Write(p []byte) (n int, err error) { 262 if !cw.wroteHeader { 263 cw.writeHeader(p) 264 } 265 if cw.res.req.Method == "HEAD" { 266 // Eat writes. 267 return len(p), nil 268 } 269 if cw.chunking { 270 _, err = fmt.Fprintf(cw.res.conn.buf, "%x\r\n", len(p)) 271 if err != nil { 272 cw.res.conn.rwc.Close() 273 return 274 } 275 } 276 n, err = cw.res.conn.buf.Write(p) 277 if cw.chunking && err == nil { 278 _, err = cw.res.conn.buf.Write(crlf) 279 } 280 if err != nil { 281 cw.res.conn.rwc.Close() 282 } 283 return 284 } 285 286 func (cw *chunkWriter) flush() { 287 if !cw.wroteHeader { 288 cw.writeHeader(nil) 289 } 290 cw.res.conn.buf.Flush() 291 } 292 293 func (cw *chunkWriter) close() { 294 if !cw.wroteHeader { 295 cw.writeHeader(nil) 296 } 297 if cw.chunking { 298 bw := cw.res.conn.buf // conn's bufio writer 299 // zero chunk to mark EOF 300 bw.WriteString("0\r\n") 301 if len(cw.res.trailers) > 0 { 302 trailers := make(Header) 303 for _, h := range cw.res.trailers { 304 if vv := cw.res.handlerHeader[h]; len(vv) > 0 { 305 trailers[h] = vv 306 } 307 } 308 trailers.Write(bw) // the writer handles noting errors 309 } 310 // final blank line after the trailers (whether 311 // present or not) 312 bw.WriteString("\r\n") 313 } 314 } 315 316 // A response represents the server side of an HTTP response. 317 type response struct { 318 conn *conn 319 req *Request // request for this response 320 wroteHeader bool // reply header has been (logically) written 321 wroteContinue bool // 100 Continue response was written 322 323 w *bufio.Writer // buffers output in chunks to chunkWriter 324 cw chunkWriter 325 sw *switchWriter // of the bufio.Writer, for return to putBufioWriter 326 327 // handlerHeader is the Header that Handlers get access to, 328 // which may be retained and mutated even after WriteHeader. 329 // handlerHeader is copied into cw.header at WriteHeader 330 // time, and privately mutated thereafter. 331 handlerHeader Header 332 calledHeader bool // handler accessed handlerHeader via Header 333 334 written int64 // number of bytes written in body 335 contentLength int64 // explicitly-declared Content-Length; or -1 336 status int // status code passed to WriteHeader 337 338 // close connection after this reply. set on request and 339 // updated after response from handler if there's a 340 // "Connection: keep-alive" response header and a 341 // Content-Length. 342 closeAfterReply bool 343 344 // requestBodyLimitHit is set by requestTooLarge when 345 // maxBytesReader hits its max size. It is checked in 346 // WriteHeader, to make sure we don't consume the 347 // remaining request body to try to advance to the next HTTP 348 // request. Instead, when this is set, we stop reading 349 // subsequent requests on this connection and stop reading 350 // input from it. 351 requestBodyLimitHit bool 352 353 // trailers are the headers to be sent after the handler 354 // finishes writing the body. This field is initialized from 355 // the Trailer response header when the response header is 356 // written. 357 trailers []string 358 359 handlerDone bool // set true when the handler exits 360 361 // Buffers for Date and Content-Length 362 dateBuf [len(TimeFormat)]byte 363 clenBuf [10]byte 364 } 365 366 // declareTrailer is called for each Trailer header when the 367 // response header is written. It notes that a header will need to be 368 // written in the trailers at the end of the response. 369 func (w *response) declareTrailer(k string) { 370 k = CanonicalHeaderKey(k) 371 switch k { 372 case "Transfer-Encoding", "Content-Length", "Trailer": 373 // Forbidden by RFC 2616 14.40. 374 return 375 } 376 w.trailers = append(w.trailers, k) 377 } 378 379 // requestTooLarge is called by maxBytesReader when too much input has 380 // been read from the client. 381 func (w *response) requestTooLarge() { 382 w.closeAfterReply = true 383 w.requestBodyLimitHit = true 384 if !w.wroteHeader { 385 w.Header().Set("Connection", "close") 386 } 387 } 388 389 // needsSniff reports whether a Content-Type still needs to be sniffed. 390 func (w *response) needsSniff() bool { 391 _, haveType := w.handlerHeader["Content-Type"] 392 return !w.cw.wroteHeader && !haveType && w.written < sniffLen 393 } 394 395 // writerOnly hides an io.Writer value's optional ReadFrom method 396 // from io.Copy. 397 type writerOnly struct { 398 io.Writer 399 } 400 401 func srcIsRegularFile(src io.Reader) (isRegular bool, err error) { 402 switch v := src.(type) { 403 case *os.File: 404 fi, err := v.Stat() 405 if err != nil { 406 return false, err 407 } 408 return fi.Mode().IsRegular(), nil 409 case *io.LimitedReader: 410 return srcIsRegularFile(v.R) 411 default: 412 return 413 } 414 } 415 416 // ReadFrom is here to optimize copying from an *os.File regular file 417 // to a *net.TCPConn with sendfile. 418 func (w *response) ReadFrom(src io.Reader) (n int64, err error) { 419 // Our underlying w.conn.rwc is usually a *TCPConn (with its 420 // own ReadFrom method). If not, or if our src isn't a regular 421 // file, just fall back to the normal copy method. 422 rf, ok := w.conn.rwc.(io.ReaderFrom) 423 regFile, err := srcIsRegularFile(src) 424 if err != nil { 425 return 0, err 426 } 427 if !ok || !regFile { 428 bufp := copyBufPool.Get().(*[]byte) 429 defer copyBufPool.Put(bufp) 430 return io.CopyBuffer(writerOnly{w}, src, *bufp) 431 } 432 433 // sendfile path: 434 435 if !w.wroteHeader { 436 w.WriteHeader(StatusOK) 437 } 438 439 if w.needsSniff() { 440 n0, err := io.Copy(writerOnly{w}, io.LimitReader(src, sniffLen)) 441 n += n0 442 if err != nil { 443 return n, err 444 } 445 } 446 447 w.w.Flush() // get rid of any previous writes 448 w.cw.flush() // make sure Header is written; flush data to rwc 449 450 // Now that cw has been flushed, its chunking field is guaranteed initialized. 451 if !w.cw.chunking && w.bodyAllowed() { 452 n0, err := rf.ReadFrom(src) 453 n += n0 454 w.written += n0 455 return n, err 456 } 457 458 n0, err := io.Copy(writerOnly{w}, src) 459 n += n0 460 return n, err 461 } 462 463 // noLimit is an effective infinite upper bound for io.LimitedReader 464 const noLimit int64 = (1 << 63) - 1 465 466 // debugServerConnections controls whether all server connections are wrapped 467 // with a verbose logging wrapper. 468 const debugServerConnections = false 469 470 // Create new connection from rwc. 471 func (srv *Server) newConn(rwc net.Conn) (c *conn, err error) { 472 c = new(conn) 473 c.remoteAddr = rwc.RemoteAddr().String() 474 c.server = srv 475 c.rwc = rwc 476 c.w = rwc 477 if debugServerConnections { 478 c.rwc = newLoggingConn("server", c.rwc) 479 } 480 c.sr.r = c.rwc 481 c.lr = io.LimitReader(&c.sr, noLimit).(*io.LimitedReader) 482 br := newBufioReader(c.lr) 483 bw := newBufioWriterSize(checkConnErrorWriter{c}, 4<<10) 484 c.buf = bufio.NewReadWriter(br, bw) 485 return c, nil 486 } 487 488 var ( 489 bufioReaderPool sync.Pool 490 bufioWriter2kPool sync.Pool 491 bufioWriter4kPool sync.Pool 492 ) 493 494 var copyBufPool = sync.Pool{ 495 New: func() interface{} { 496 b := make([]byte, 32*1024) 497 return &b 498 }, 499 } 500 501 func bufioWriterPool(size int) *sync.Pool { 502 switch size { 503 case 2 << 10: 504 return &bufioWriter2kPool 505 case 4 << 10: 506 return &bufioWriter4kPool 507 } 508 return nil 509 } 510 511 func newBufioReader(r io.Reader) *bufio.Reader { 512 if v := bufioReaderPool.Get(); v != nil { 513 br := v.(*bufio.Reader) 514 br.Reset(r) 515 return br 516 } 517 // Note: if this reader size is every changed, update 518 // TestHandlerBodyClose's assumptions. 519 return bufio.NewReader(r) 520 } 521 522 func putBufioReader(br *bufio.Reader) { 523 br.Reset(nil) 524 bufioReaderPool.Put(br) 525 } 526 527 func newBufioWriterSize(w io.Writer, size int) *bufio.Writer { 528 pool := bufioWriterPool(size) 529 if pool != nil { 530 if v := pool.Get(); v != nil { 531 bw := v.(*bufio.Writer) 532 bw.Reset(w) 533 return bw 534 } 535 } 536 return bufio.NewWriterSize(w, size) 537 } 538 539 func putBufioWriter(bw *bufio.Writer) { 540 bw.Reset(nil) 541 if pool := bufioWriterPool(bw.Available()); pool != nil { 542 pool.Put(bw) 543 } 544 } 545 546 // DefaultMaxHeaderBytes is the maximum permitted size of the headers 547 // in an HTTP request. 548 // This can be overridden by setting Server.MaxHeaderBytes. 549 const DefaultMaxHeaderBytes = 1 << 20 // 1 MB 550 551 func (srv *Server) maxHeaderBytes() int { 552 if srv.MaxHeaderBytes > 0 { 553 return srv.MaxHeaderBytes 554 } 555 return DefaultMaxHeaderBytes 556 } 557 558 func (srv *Server) initialLimitedReaderSize() int64 { 559 return int64(srv.maxHeaderBytes()) + 4096 // bufio slop 560 } 561 562 // wrapper around io.ReaderCloser which on first read, sends an 563 // HTTP/1.1 100 Continue header 564 type expectContinueReader struct { 565 resp *response 566 readCloser io.ReadCloser 567 closed bool 568 sawEOF bool 569 } 570 571 func (ecr *expectContinueReader) Read(p []byte) (n int, err error) { 572 if ecr.closed { 573 return 0, ErrBodyReadAfterClose 574 } 575 if !ecr.resp.wroteContinue && !ecr.resp.conn.hijacked() { 576 ecr.resp.wroteContinue = true 577 ecr.resp.conn.buf.WriteString("HTTP/1.1 100 Continue\r\n\r\n") 578 ecr.resp.conn.buf.Flush() 579 } 580 n, err = ecr.readCloser.Read(p) 581 if err == io.EOF { 582 ecr.sawEOF = true 583 } 584 return 585 } 586 587 func (ecr *expectContinueReader) Close() error { 588 ecr.closed = true 589 return ecr.readCloser.Close() 590 } 591 592 // TimeFormat is the time format to use with 593 // time.Parse and time.Time.Format when parsing 594 // or generating times in HTTP headers. 595 // It is like time.RFC1123 but hard codes GMT as the time zone. 596 const TimeFormat = "Mon, 02 Jan 2006 15:04:05 GMT" 597 598 // appendTime is a non-allocating version of []byte(t.UTC().Format(TimeFormat)) 599 func appendTime(b []byte, t time.Time) []byte { 600 const days = "SunMonTueWedThuFriSat" 601 const months = "JanFebMarAprMayJunJulAugSepOctNovDec" 602 603 t = t.UTC() 604 yy, mm, dd := t.Date() 605 hh, mn, ss := t.Clock() 606 day := days[3*t.Weekday():] 607 mon := months[3*(mm-1):] 608 609 return append(b, 610 day[0], day[1], day[2], ',', ' ', 611 byte('0'+dd/10), byte('0'+dd%10), ' ', 612 mon[0], mon[1], mon[2], ' ', 613 byte('0'+yy/1000), byte('0'+(yy/100)%10), byte('0'+(yy/10)%10), byte('0'+yy%10), ' ', 614 byte('0'+hh/10), byte('0'+hh%10), ':', 615 byte('0'+mn/10), byte('0'+mn%10), ':', 616 byte('0'+ss/10), byte('0'+ss%10), ' ', 617 'G', 'M', 'T') 618 } 619 620 var errTooLarge = errors.New("http: request too large") 621 622 // Read next request from connection. 623 func (c *conn) readRequest() (w *response, err error) { 624 if c.hijacked() { 625 return nil, ErrHijacked 626 } 627 628 if d := c.server.ReadTimeout; d != 0 { 629 c.rwc.SetReadDeadline(time.Now().Add(d)) 630 } 631 if d := c.server.WriteTimeout; d != 0 { 632 defer func() { 633 c.rwc.SetWriteDeadline(time.Now().Add(d)) 634 }() 635 } 636 637 c.lr.N = c.server.initialLimitedReaderSize() 638 if c.lastMethod == "POST" { 639 // RFC 2616 section 4.1 tolerance for old buggy clients. 640 peek, _ := c.buf.Reader.Peek(4) // ReadRequest will get err below 641 c.buf.Reader.Discard(numLeadingCRorLF(peek)) 642 } 643 var req *Request 644 if req, err = ReadRequest(c.buf.Reader); err != nil { 645 if c.lr.N == 0 { 646 return nil, errTooLarge 647 } 648 return nil, err 649 } 650 c.lr.N = noLimit 651 c.lastMethod = req.Method 652 653 req.RemoteAddr = c.remoteAddr 654 req.TLS = c.tlsState 655 if body, ok := req.Body.(*body); ok { 656 body.doEarlyClose = true 657 } 658 659 w = &response{ 660 conn: c, 661 req: req, 662 handlerHeader: make(Header), 663 contentLength: -1, 664 } 665 w.cw.res = w 666 w.w = newBufioWriterSize(&w.cw, bufferBeforeChunkingSize) 667 return w, nil 668 } 669 670 func (w *response) Header() Header { 671 if w.cw.header == nil && w.wroteHeader && !w.cw.wroteHeader { 672 // Accessing the header between logically writing it 673 // and physically writing it means we need to allocate 674 // a clone to snapshot the logically written state. 675 w.cw.header = w.handlerHeader.clone() 676 } 677 w.calledHeader = true 678 return w.handlerHeader 679 } 680 681 // maxPostHandlerReadBytes is the max number of Request.Body bytes not 682 // consumed by a handler that the server will read from the client 683 // in order to keep a connection alive. If there are more bytes than 684 // this then the server to be paranoid instead sends a "Connection: 685 // close" response. 686 // 687 // This number is approximately what a typical machine's TCP buffer 688 // size is anyway. (if we have the bytes on the machine, we might as 689 // well read them) 690 const maxPostHandlerReadBytes = 256 << 10 691 692 func (w *response) WriteHeader(code int) { 693 if w.conn.hijacked() { 694 w.conn.server.logf("http: response.WriteHeader on hijacked connection") 695 return 696 } 697 if w.wroteHeader { 698 w.conn.server.logf("http: multiple response.WriteHeader calls") 699 return 700 } 701 w.wroteHeader = true 702 w.status = code 703 704 if w.calledHeader && w.cw.header == nil { 705 w.cw.header = w.handlerHeader.clone() 706 } 707 708 if cl := w.handlerHeader.get("Content-Length"); cl != "" { 709 v, err := strconv.ParseInt(cl, 10, 64) 710 if err == nil && v >= 0 { 711 w.contentLength = v 712 } else { 713 w.conn.server.logf("http: invalid Content-Length of %q", cl) 714 w.handlerHeader.Del("Content-Length") 715 } 716 } 717 } 718 719 // extraHeader is the set of headers sometimes added by chunkWriter.writeHeader. 720 // This type is used to avoid extra allocations from cloning and/or populating 721 // the response Header map and all its 1-element slices. 722 type extraHeader struct { 723 contentType string 724 connection string 725 transferEncoding string 726 date []byte // written if not nil 727 contentLength []byte // written if not nil 728 } 729 730 // Sorted the same as extraHeader.Write's loop. 731 var extraHeaderKeys = [][]byte{ 732 []byte("Content-Type"), 733 []byte("Connection"), 734 []byte("Transfer-Encoding"), 735 } 736 737 var ( 738 headerContentLength = []byte("Content-Length: ") 739 headerDate = []byte("Date: ") 740 ) 741 742 // Write writes the headers described in h to w. 743 // 744 // This method has a value receiver, despite the somewhat large size 745 // of h, because it prevents an allocation. The escape analysis isn't 746 // smart enough to realize this function doesn't mutate h. 747 func (h extraHeader) Write(w *bufio.Writer) { 748 if h.date != nil { 749 w.Write(headerDate) 750 w.Write(h.date) 751 w.Write(crlf) 752 } 753 if h.contentLength != nil { 754 w.Write(headerContentLength) 755 w.Write(h.contentLength) 756 w.Write(crlf) 757 } 758 for i, v := range []string{h.contentType, h.connection, h.transferEncoding} { 759 if v != "" { 760 w.Write(extraHeaderKeys[i]) 761 w.Write(colonSpace) 762 w.WriteString(v) 763 w.Write(crlf) 764 } 765 } 766 } 767 768 // writeHeader finalizes the header sent to the client and writes it 769 // to cw.res.conn.buf. 770 // 771 // p is not written by writeHeader, but is the first chunk of the body 772 // that will be written. It is sniffed for a Content-Type if none is 773 // set explicitly. It's also used to set the Content-Length, if the 774 // total body size was small and the handler has already finished 775 // running. 776 func (cw *chunkWriter) writeHeader(p []byte) { 777 if cw.wroteHeader { 778 return 779 } 780 cw.wroteHeader = true 781 782 w := cw.res 783 keepAlivesEnabled := w.conn.server.doKeepAlives() 784 isHEAD := w.req.Method == "HEAD" 785 786 // header is written out to w.conn.buf below. Depending on the 787 // state of the handler, we either own the map or not. If we 788 // don't own it, the exclude map is created lazily for 789 // WriteSubset to remove headers. The setHeader struct holds 790 // headers we need to add. 791 header := cw.header 792 owned := header != nil 793 if !owned { 794 header = w.handlerHeader 795 } 796 var excludeHeader map[string]bool 797 delHeader := func(key string) { 798 if owned { 799 header.Del(key) 800 return 801 } 802 if _, ok := header[key]; !ok { 803 return 804 } 805 if excludeHeader == nil { 806 excludeHeader = make(map[string]bool) 807 } 808 excludeHeader[key] = true 809 } 810 var setHeader extraHeader 811 812 trailers := false 813 for _, v := range cw.header["Trailer"] { 814 trailers = true 815 foreachHeaderElement(v, cw.res.declareTrailer) 816 } 817 818 te := header.get("Transfer-Encoding") 819 hasTE := te != "" 820 821 // If the handler is done but never sent a Content-Length 822 // response header and this is our first (and last) write, set 823 // it, even to zero. This helps HTTP/1.0 clients keep their 824 // "keep-alive" connections alive. 825 // Exceptions: 304/204/1xx responses never get Content-Length, and if 826 // it was a HEAD request, we don't know the difference between 827 // 0 actual bytes and 0 bytes because the handler noticed it 828 // was a HEAD request and chose not to write anything. So for 829 // HEAD, the handler should either write the Content-Length or 830 // write non-zero bytes. If it's actually 0 bytes and the 831 // handler never looked at the Request.Method, we just don't 832 // send a Content-Length header. 833 // Further, we don't send an automatic Content-Length if they 834 // set a Transfer-Encoding, because they're generally incompatible. 835 if w.handlerDone && !trailers && !hasTE && bodyAllowedForStatus(w.status) && header.get("Content-Length") == "" && (!isHEAD || len(p) > 0) { 836 w.contentLength = int64(len(p)) 837 setHeader.contentLength = strconv.AppendInt(cw.res.clenBuf[:0], int64(len(p)), 10) 838 } 839 840 // If this was an HTTP/1.0 request with keep-alive and we sent a 841 // Content-Length back, we can make this a keep-alive response ... 842 if w.req.wantsHttp10KeepAlive() && keepAlivesEnabled { 843 sentLength := header.get("Content-Length") != "" 844 if sentLength && header.get("Connection") == "keep-alive" { 845 w.closeAfterReply = false 846 } 847 } 848 849 // Check for a explicit (and valid) Content-Length header. 850 hasCL := w.contentLength != -1 851 852 if w.req.wantsHttp10KeepAlive() && (isHEAD || hasCL) { 853 _, connectionHeaderSet := header["Connection"] 854 if !connectionHeaderSet { 855 setHeader.connection = "keep-alive" 856 } 857 } else if !w.req.ProtoAtLeast(1, 1) || w.req.wantsClose() { 858 w.closeAfterReply = true 859 } 860 861 if header.get("Connection") == "close" || !keepAlivesEnabled { 862 w.closeAfterReply = true 863 } 864 865 // If the client wanted a 100-continue but we never sent it to 866 // them (or, more strictly: we never finished reading their 867 // request body), don't reuse this connection because it's now 868 // in an unknown state: we might be sending this response at 869 // the same time the client is now sending its request body 870 // after a timeout. (Some HTTP clients send Expect: 871 // 100-continue but knowing that some servers don't support 872 // it, the clients set a timer and send the body later anyway) 873 // If we haven't seen EOF, we can't skip over the unread body 874 // because we don't know if the next bytes on the wire will be 875 // the body-following-the-timer or the subsequent request. 876 // See Issue 11549. 877 if ecr, ok := w.req.Body.(*expectContinueReader); ok && !ecr.sawEOF { 878 w.closeAfterReply = true 879 } 880 881 // Per RFC 2616, we should consume the request body before 882 // replying, if the handler hasn't already done so. But we 883 // don't want to do an unbounded amount of reading here for 884 // DoS reasons, so we only try up to a threshold. 885 if w.req.ContentLength != 0 && !w.closeAfterReply { 886 var discard, tooBig bool 887 888 switch bdy := w.req.Body.(type) { 889 case *expectContinueReader: 890 if bdy.resp.wroteContinue { 891 discard = true 892 } 893 case *body: 894 bdy.mu.Lock() 895 switch { 896 case bdy.closed: 897 if !bdy.sawEOF { 898 // Body was closed in handler with non-EOF error. 899 w.closeAfterReply = true 900 } 901 case bdy.unreadDataSizeLocked() >= maxPostHandlerReadBytes: 902 tooBig = true 903 default: 904 discard = true 905 } 906 bdy.mu.Unlock() 907 default: 908 discard = true 909 } 910 911 if discard { 912 _, err := io.CopyN(ioutil.Discard, w.req.Body, maxPostHandlerReadBytes+1) 913 switch err { 914 case nil: 915 // There must be even more data left over. 916 tooBig = true 917 case ErrBodyReadAfterClose: 918 // Body was already consumed and closed. 919 case io.EOF: 920 // The remaining body was just consumed, close it. 921 err = w.req.Body.Close() 922 if err != nil { 923 w.closeAfterReply = true 924 } 925 default: 926 // Some other kind of error occured, like a read timeout, or 927 // corrupt chunked encoding. In any case, whatever remains 928 // on the wire must not be parsed as another HTTP request. 929 w.closeAfterReply = true 930 } 931 } 932 933 if tooBig { 934 w.requestTooLarge() 935 delHeader("Connection") 936 setHeader.connection = "close" 937 } 938 } 939 940 code := w.status 941 if bodyAllowedForStatus(code) { 942 // If no content type, apply sniffing algorithm to body. 943 _, haveType := header["Content-Type"] 944 if !haveType && !hasTE { 945 setHeader.contentType = DetectContentType(p) 946 } 947 } else { 948 for _, k := range suppressedHeaders(code) { 949 delHeader(k) 950 } 951 } 952 953 if _, ok := header["Date"]; !ok { 954 setHeader.date = appendTime(cw.res.dateBuf[:0], time.Now()) 955 } 956 957 if hasCL && hasTE && te != "identity" { 958 // TODO: return an error if WriteHeader gets a return parameter 959 // For now just ignore the Content-Length. 960 w.conn.server.logf("http: WriteHeader called with both Transfer-Encoding of %q and a Content-Length of %d", 961 te, w.contentLength) 962 delHeader("Content-Length") 963 hasCL = false 964 } 965 966 if w.req.Method == "HEAD" || !bodyAllowedForStatus(code) { 967 // do nothing 968 } else if code == StatusNoContent { 969 delHeader("Transfer-Encoding") 970 } else if hasCL { 971 delHeader("Transfer-Encoding") 972 } else if w.req.ProtoAtLeast(1, 1) { 973 // HTTP/1.1 or greater: Transfer-Encoding has been set to identity, and no 974 // content-length has been provided. The connection must be closed after the 975 // reply is written, and no chunking is to be done. This is the setup 976 // recommended in the Server-Sent Events candidate recommendation 11, 977 // section 8. 978 if hasTE && te == "identity" { 979 cw.chunking = false 980 w.closeAfterReply = true 981 } else { 982 // HTTP/1.1 or greater: use chunked transfer encoding 983 // to avoid closing the connection at EOF. 984 cw.chunking = true 985 setHeader.transferEncoding = "chunked" 986 } 987 } else { 988 // HTTP version < 1.1: cannot do chunked transfer 989 // encoding and we don't know the Content-Length so 990 // signal EOF by closing connection. 991 w.closeAfterReply = true 992 delHeader("Transfer-Encoding") // in case already set 993 } 994 995 // Cannot use Content-Length with non-identity Transfer-Encoding. 996 if cw.chunking { 997 delHeader("Content-Length") 998 } 999 if !w.req.ProtoAtLeast(1, 0) { 1000 return 1001 } 1002 1003 if w.closeAfterReply && (!keepAlivesEnabled || !hasToken(cw.header.get("Connection"), "close")) { 1004 delHeader("Connection") 1005 if w.req.ProtoAtLeast(1, 1) { 1006 setHeader.connection = "close" 1007 } 1008 } 1009 1010 w.conn.buf.WriteString(statusLine(w.req, code)) 1011 cw.header.WriteSubset(w.conn.buf, excludeHeader) 1012 setHeader.Write(w.conn.buf.Writer) 1013 w.conn.buf.Write(crlf) 1014 } 1015 1016 // foreachHeaderElement splits v according to the "#rule" construction 1017 // in RFC 2616 section 2.1 and calls fn for each non-empty element. 1018 func foreachHeaderElement(v string, fn func(string)) { 1019 v = textproto.TrimString(v) 1020 if v == "" { 1021 return 1022 } 1023 if !strings.Contains(v, ",") { 1024 fn(v) 1025 return 1026 } 1027 for _, f := range strings.Split(v, ",") { 1028 if f = textproto.TrimString(f); f != "" { 1029 fn(f) 1030 } 1031 } 1032 } 1033 1034 // statusLines is a cache of Status-Line strings, keyed by code (for 1035 // HTTP/1.1) or negative code (for HTTP/1.0). This is faster than a 1036 // map keyed by struct of two fields. This map's max size is bounded 1037 // by 2*len(statusText), two protocol types for each known official 1038 // status code in the statusText map. 1039 var ( 1040 statusMu sync.RWMutex 1041 statusLines = make(map[int]string) 1042 ) 1043 1044 // statusLine returns a response Status-Line (RFC 2616 Section 6.1) 1045 // for the given request and response status code. 1046 func statusLine(req *Request, code int) string { 1047 // Fast path: 1048 key := code 1049 proto11 := req.ProtoAtLeast(1, 1) 1050 if !proto11 { 1051 key = -key 1052 } 1053 statusMu.RLock() 1054 line, ok := statusLines[key] 1055 statusMu.RUnlock() 1056 if ok { 1057 return line 1058 } 1059 1060 // Slow path: 1061 proto := "HTTP/1.0" 1062 if proto11 { 1063 proto = "HTTP/1.1" 1064 } 1065 codestring := strconv.Itoa(code) 1066 text, ok := statusText[code] 1067 if !ok { 1068 text = "status code " + codestring 1069 } 1070 line = proto + " " + codestring + " " + text + "\r\n" 1071 if ok { 1072 statusMu.Lock() 1073 defer statusMu.Unlock() 1074 statusLines[key] = line 1075 } 1076 return line 1077 } 1078 1079 // bodyAllowed reports whether a Write is allowed for this response type. 1080 // It's illegal to call this before the header has been flushed. 1081 func (w *response) bodyAllowed() bool { 1082 if !w.wroteHeader { 1083 panic("") 1084 } 1085 return bodyAllowedForStatus(w.status) 1086 } 1087 1088 // The Life Of A Write is like this: 1089 // 1090 // Handler starts. No header has been sent. The handler can either 1091 // write a header, or just start writing. Writing before sending a header 1092 // sends an implicitly empty 200 OK header. 1093 // 1094 // If the handler didn't declare a Content-Length up front, we either 1095 // go into chunking mode or, if the handler finishes running before 1096 // the chunking buffer size, we compute a Content-Length and send that 1097 // in the header instead. 1098 // 1099 // Likewise, if the handler didn't set a Content-Type, we sniff that 1100 // from the initial chunk of output. 1101 // 1102 // The Writers are wired together like: 1103 // 1104 // 1. *response (the ResponseWriter) -> 1105 // 2. (*response).w, a *bufio.Writer of bufferBeforeChunkingSize bytes 1106 // 3. chunkWriter.Writer (whose writeHeader finalizes Content-Length/Type) 1107 // and which writes the chunk headers, if needed. 1108 // 4. conn.buf, a bufio.Writer of default (4kB) bytes, writing to -> 1109 // 5. checkConnErrorWriter{c}, which notes any non-nil error on Write 1110 // and populates c.werr with it if so. but otherwise writes to: 1111 // 6. the rwc, the net.Conn. 1112 // 1113 // TODO(bradfitz): short-circuit some of the buffering when the 1114 // initial header contains both a Content-Type and Content-Length. 1115 // Also short-circuit in (1) when the header's been sent and not in 1116 // chunking mode, writing directly to (4) instead, if (2) has no 1117 // buffered data. More generally, we could short-circuit from (1) to 1118 // (3) even in chunking mode if the write size from (1) is over some 1119 // threshold and nothing is in (2). The answer might be mostly making 1120 // bufferBeforeChunkingSize smaller and having bufio's fast-paths deal 1121 // with this instead. 1122 func (w *response) Write(data []byte) (n int, err error) { 1123 return w.write(len(data), data, "") 1124 } 1125 1126 func (w *response) WriteString(data string) (n int, err error) { 1127 return w.write(len(data), nil, data) 1128 } 1129 1130 // either dataB or dataS is non-zero. 1131 func (w *response) write(lenData int, dataB []byte, dataS string) (n int, err error) { 1132 if w.conn.hijacked() { 1133 w.conn.server.logf("http: response.Write on hijacked connection") 1134 return 0, ErrHijacked 1135 } 1136 if !w.wroteHeader { 1137 w.WriteHeader(StatusOK) 1138 } 1139 if lenData == 0 { 1140 return 0, nil 1141 } 1142 if !w.bodyAllowed() { 1143 return 0, ErrBodyNotAllowed 1144 } 1145 1146 w.written += int64(lenData) // ignoring errors, for errorKludge 1147 if w.contentLength != -1 && w.written > w.contentLength { 1148 return 0, ErrContentLength 1149 } 1150 if dataB != nil { 1151 return w.w.Write(dataB) 1152 } else { 1153 return w.w.WriteString(dataS) 1154 } 1155 } 1156 1157 func (w *response) finishRequest() { 1158 w.handlerDone = true 1159 1160 if !w.wroteHeader { 1161 w.WriteHeader(StatusOK) 1162 } 1163 1164 w.w.Flush() 1165 putBufioWriter(w.w) 1166 w.cw.close() 1167 w.conn.buf.Flush() 1168 1169 // Close the body (regardless of w.closeAfterReply) so we can 1170 // re-use its bufio.Reader later safely. 1171 w.req.Body.Close() 1172 1173 if w.req.MultipartForm != nil { 1174 w.req.MultipartForm.RemoveAll() 1175 } 1176 } 1177 1178 // shouldReuseConnection reports whether the underlying TCP connection can be reused. 1179 // It must only be called after the handler is done executing. 1180 func (w *response) shouldReuseConnection() bool { 1181 if w.closeAfterReply { 1182 // The request or something set while executing the 1183 // handler indicated we shouldn't reuse this 1184 // connection. 1185 return false 1186 } 1187 1188 if w.req.Method != "HEAD" && w.contentLength != -1 && w.bodyAllowed() && w.contentLength != w.written { 1189 // Did not write enough. Avoid getting out of sync. 1190 return false 1191 } 1192 1193 // There was some error writing to the underlying connection 1194 // during the request, so don't re-use this conn. 1195 if w.conn.werr != nil { 1196 return false 1197 } 1198 1199 if w.closedRequestBodyEarly() { 1200 return false 1201 } 1202 1203 return true 1204 } 1205 1206 func (w *response) closedRequestBodyEarly() bool { 1207 body, ok := w.req.Body.(*body) 1208 return ok && body.didEarlyClose() 1209 } 1210 1211 func (w *response) Flush() { 1212 if !w.wroteHeader { 1213 w.WriteHeader(StatusOK) 1214 } 1215 w.w.Flush() 1216 w.cw.flush() 1217 } 1218 1219 func (c *conn) finalFlush() { 1220 if c.buf != nil { 1221 c.buf.Flush() 1222 1223 // Steal the bufio.Reader (~4KB worth of memory) and its associated 1224 // reader for a future connection. 1225 putBufioReader(c.buf.Reader) 1226 1227 // Steal the bufio.Writer (~4KB worth of memory) and its associated 1228 // writer for a future connection. 1229 putBufioWriter(c.buf.Writer) 1230 1231 c.buf = nil 1232 } 1233 } 1234 1235 // Close the connection. 1236 func (c *conn) close() { 1237 c.finalFlush() 1238 if c.rwc != nil { 1239 c.rwc.Close() 1240 c.rwc = nil 1241 } 1242 } 1243 1244 // rstAvoidanceDelay is the amount of time we sleep after closing the 1245 // write side of a TCP connection before closing the entire socket. 1246 // By sleeping, we increase the chances that the client sees our FIN 1247 // and processes its final data before they process the subsequent RST 1248 // from closing a connection with known unread data. 1249 // This RST seems to occur mostly on BSD systems. (And Windows?) 1250 // This timeout is somewhat arbitrary (~latency around the planet). 1251 const rstAvoidanceDelay = 500 * time.Millisecond 1252 1253 type closeWriter interface { 1254 CloseWrite() error 1255 } 1256 1257 var _ closeWriter = (*net.TCPConn)(nil) 1258 1259 // closeWrite flushes any outstanding data and sends a FIN packet (if 1260 // client is connected via TCP), signalling that we're done. We then 1261 // pause for a bit, hoping the client processes it before any 1262 // subsequent RST. 1263 // 1264 // See https://golang.org/issue/3595 1265 func (c *conn) closeWriteAndWait() { 1266 c.finalFlush() 1267 if tcp, ok := c.rwc.(closeWriter); ok { 1268 tcp.CloseWrite() 1269 } 1270 time.Sleep(rstAvoidanceDelay) 1271 } 1272 1273 // validNPN reports whether the proto is not a blacklisted Next 1274 // Protocol Negotiation protocol. Empty and built-in protocol types 1275 // are blacklisted and can't be overridden with alternate 1276 // implementations. 1277 func validNPN(proto string) bool { 1278 switch proto { 1279 case "", "http/1.1", "http/1.0": 1280 return false 1281 } 1282 return true 1283 } 1284 1285 func (c *conn) setState(nc net.Conn, state ConnState) { 1286 if hook := c.server.ConnState; hook != nil { 1287 hook(nc, state) 1288 } 1289 } 1290 1291 // Serve a new connection. 1292 func (c *conn) serve() { 1293 origConn := c.rwc // copy it before it's set nil on Close or Hijack 1294 defer func() { 1295 if err := recover(); err != nil { 1296 const size = 64 << 10 1297 buf := make([]byte, size) 1298 buf = buf[:runtime.Stack(buf, false)] 1299 c.server.logf("http: panic serving %v: %v\n%s", c.remoteAddr, err, buf) 1300 } 1301 if !c.hijacked() { 1302 c.close() 1303 c.setState(origConn, StateClosed) 1304 } 1305 }() 1306 1307 if tlsConn, ok := c.rwc.(*tls.Conn); ok { 1308 if d := c.server.ReadTimeout; d != 0 { 1309 c.rwc.SetReadDeadline(time.Now().Add(d)) 1310 } 1311 if d := c.server.WriteTimeout; d != 0 { 1312 c.rwc.SetWriteDeadline(time.Now().Add(d)) 1313 } 1314 if err := tlsConn.Handshake(); err != nil { 1315 c.server.logf("http: TLS handshake error from %s: %v", c.rwc.RemoteAddr(), err) 1316 return 1317 } 1318 c.tlsState = new(tls.ConnectionState) 1319 *c.tlsState = tlsConn.ConnectionState() 1320 if proto := c.tlsState.NegotiatedProtocol; validNPN(proto) { 1321 if fn := c.server.TLSNextProto[proto]; fn != nil { 1322 h := initNPNRequest{tlsConn, serverHandler{c.server}} 1323 fn(c.server, tlsConn, h) 1324 } 1325 return 1326 } 1327 } 1328 1329 for { 1330 w, err := c.readRequest() 1331 if c.lr.N != c.server.initialLimitedReaderSize() { 1332 // If we read any bytes off the wire, we're active. 1333 c.setState(c.rwc, StateActive) 1334 } 1335 if err != nil { 1336 if err == errTooLarge { 1337 // Their HTTP client may or may not be 1338 // able to read this if we're 1339 // responding to them and hanging up 1340 // while they're still writing their 1341 // request. Undefined behavior. 1342 io.WriteString(c.rwc, "HTTP/1.1 413 Request Entity Too Large\r\n\r\n") 1343 c.closeWriteAndWait() 1344 break 1345 } else if err == io.EOF { 1346 break // Don't reply 1347 } else if neterr, ok := err.(net.Error); ok && neterr.Timeout() { 1348 break // Don't reply 1349 } 1350 io.WriteString(c.rwc, "HTTP/1.1 400 Bad Request\r\n\r\n") 1351 break 1352 } 1353 1354 // Expect 100 Continue support 1355 req := w.req 1356 if req.expectsContinue() { 1357 if req.ProtoAtLeast(1, 1) && req.ContentLength != 0 { 1358 // Wrap the Body reader with one that replies on the connection 1359 req.Body = &expectContinueReader{readCloser: req.Body, resp: w} 1360 } 1361 req.Header.Del("Expect") 1362 } else if req.Header.get("Expect") != "" { 1363 w.sendExpectationFailed() 1364 break 1365 } 1366 1367 // HTTP cannot have multiple simultaneous active requests.[*] 1368 // Until the server replies to this request, it can't read another, 1369 // so we might as well run the handler in this goroutine. 1370 // [*] Not strictly true: HTTP pipelining. We could let them all process 1371 // in parallel even if their responses need to be serialized. 1372 serverHandler{c.server}.ServeHTTP(w, w.req) 1373 if c.hijacked() { 1374 return 1375 } 1376 w.finishRequest() 1377 if !w.shouldReuseConnection() { 1378 if w.requestBodyLimitHit || w.closedRequestBodyEarly() { 1379 c.closeWriteAndWait() 1380 } 1381 break 1382 } 1383 c.setState(c.rwc, StateIdle) 1384 } 1385 } 1386 1387 func (w *response) sendExpectationFailed() { 1388 // TODO(bradfitz): let ServeHTTP handlers handle 1389 // requests with non-standard expectation[s]? Seems 1390 // theoretical at best, and doesn't fit into the 1391 // current ServeHTTP model anyway. We'd need to 1392 // make the ResponseWriter an optional 1393 // "ExpectReplier" interface or something. 1394 // 1395 // For now we'll just obey RFC 2616 14.20 which says 1396 // "If a server receives a request containing an 1397 // Expect field that includes an expectation- 1398 // extension that it does not support, it MUST 1399 // respond with a 417 (Expectation Failed) status." 1400 w.Header().Set("Connection", "close") 1401 w.WriteHeader(StatusExpectationFailed) 1402 w.finishRequest() 1403 } 1404 1405 // Hijack implements the Hijacker.Hijack method. Our response is both a ResponseWriter 1406 // and a Hijacker. 1407 func (w *response) Hijack() (rwc net.Conn, buf *bufio.ReadWriter, err error) { 1408 if w.wroteHeader { 1409 w.cw.flush() 1410 } 1411 // Release the bufioWriter that writes to the chunk writer, it is not 1412 // used after a connection has been hijacked. 1413 rwc, buf, err = w.conn.hijack() 1414 if err == nil { 1415 putBufioWriter(w.w) 1416 w.w = nil 1417 } 1418 return rwc, buf, err 1419 } 1420 1421 func (w *response) CloseNotify() <-chan bool { 1422 return w.conn.closeNotify() 1423 } 1424 1425 // The HandlerFunc type is an adapter to allow the use of 1426 // ordinary functions as HTTP handlers. If f is a function 1427 // with the appropriate signature, HandlerFunc(f) is a 1428 // Handler object that calls f. 1429 type HandlerFunc func(ResponseWriter, *Request) 1430 1431 // ServeHTTP calls f(w, r). 1432 func (f HandlerFunc) ServeHTTP(w ResponseWriter, r *Request) { 1433 f(w, r) 1434 } 1435 1436 // Helper handlers 1437 1438 // Error replies to the request with the specified error message and HTTP code. 1439 // The error message should be plain text. 1440 func Error(w ResponseWriter, error string, code int) { 1441 w.Header().Set("Content-Type", "text/plain; charset=utf-8") 1442 w.Header().Set("X-Content-Type-Options", "nosniff") 1443 w.WriteHeader(code) 1444 fmt.Fprintln(w, error) 1445 } 1446 1447 // NotFound replies to the request with an HTTP 404 not found error. 1448 func NotFound(w ResponseWriter, r *Request) { Error(w, "404 page not found", StatusNotFound) } 1449 1450 // NotFoundHandler returns a simple request handler 1451 // that replies to each request with a ``404 page not found'' reply. 1452 func NotFoundHandler() Handler { return HandlerFunc(NotFound) } 1453 1454 // StripPrefix returns a handler that serves HTTP requests 1455 // by removing the given prefix from the request URL's Path 1456 // and invoking the handler h. StripPrefix handles a 1457 // request for a path that doesn't begin with prefix by 1458 // replying with an HTTP 404 not found error. 1459 func StripPrefix(prefix string, h Handler) Handler { 1460 if prefix == "" { 1461 return h 1462 } 1463 return HandlerFunc(func(w ResponseWriter, r *Request) { 1464 if p := strings.TrimPrefix(r.URL.Path, prefix); len(p) < len(r.URL.Path) { 1465 r.URL.Path = p 1466 h.ServeHTTP(w, r) 1467 } else { 1468 NotFound(w, r) 1469 } 1470 }) 1471 } 1472 1473 // Redirect replies to the request with a redirect to url, 1474 // which may be a path relative to the request path. 1475 func Redirect(w ResponseWriter, r *Request, urlStr string, code int) { 1476 if u, err := url.Parse(urlStr); err == nil { 1477 // If url was relative, make absolute by 1478 // combining with request path. 1479 // The browser would probably do this for us, 1480 // but doing it ourselves is more reliable. 1481 1482 // NOTE(rsc): RFC 2616 says that the Location 1483 // line must be an absolute URI, like 1484 // "http://www.google.com/redirect/", 1485 // not a path like "/redirect/". 1486 // Unfortunately, we don't know what to 1487 // put in the host name section to get the 1488 // client to connect to us again, so we can't 1489 // know the right absolute URI to send back. 1490 // Because of this problem, no one pays attention 1491 // to the RFC; they all send back just a new path. 1492 // So do we. 1493 oldpath := r.URL.Path 1494 if oldpath == "" { // should not happen, but avoid a crash if it does 1495 oldpath = "/" 1496 } 1497 if u.Scheme == "" { 1498 // no leading http://server 1499 if urlStr == "" || urlStr[0] != '/' { 1500 // make relative path absolute 1501 olddir, _ := path.Split(oldpath) 1502 urlStr = olddir + urlStr 1503 } 1504 1505 var query string 1506 if i := strings.Index(urlStr, "?"); i != -1 { 1507 urlStr, query = urlStr[:i], urlStr[i:] 1508 } 1509 1510 // clean up but preserve trailing slash 1511 trailing := strings.HasSuffix(urlStr, "/") 1512 urlStr = path.Clean(urlStr) 1513 if trailing && !strings.HasSuffix(urlStr, "/") { 1514 urlStr += "/" 1515 } 1516 urlStr += query 1517 } 1518 } 1519 1520 w.Header().Set("Location", urlStr) 1521 w.WriteHeader(code) 1522 1523 // RFC2616 recommends that a short note "SHOULD" be included in the 1524 // response because older user agents may not understand 301/307. 1525 // Shouldn't send the response for POST or HEAD; that leaves GET. 1526 if r.Method == "GET" { 1527 note := "<a href=\"" + htmlEscape(urlStr) + "\">" + statusText[code] + "</a>.\n" 1528 fmt.Fprintln(w, note) 1529 } 1530 } 1531 1532 var htmlReplacer = strings.NewReplacer( 1533 "&", "&", 1534 "<", "<", 1535 ">", ">", 1536 // """ is shorter than """. 1537 `"`, """, 1538 // "'" is shorter than "'" and apos was not in HTML until HTML5. 1539 "'", "'", 1540 ) 1541 1542 func htmlEscape(s string) string { 1543 return htmlReplacer.Replace(s) 1544 } 1545 1546 // Redirect to a fixed URL 1547 type redirectHandler struct { 1548 url string 1549 code int 1550 } 1551 1552 func (rh *redirectHandler) ServeHTTP(w ResponseWriter, r *Request) { 1553 Redirect(w, r, rh.url, rh.code) 1554 } 1555 1556 // RedirectHandler returns a request handler that redirects 1557 // each request it receives to the given url using the given 1558 // status code. 1559 func RedirectHandler(url string, code int) Handler { 1560 return &redirectHandler{url, code} 1561 } 1562 1563 // ServeMux is an HTTP request multiplexer. 1564 // It matches the URL of each incoming request against a list of registered 1565 // patterns and calls the handler for the pattern that 1566 // most closely matches the URL. 1567 // 1568 // Patterns name fixed, rooted paths, like "/favicon.ico", 1569 // or rooted subtrees, like "/images/" (note the trailing slash). 1570 // Longer patterns take precedence over shorter ones, so that 1571 // if there are handlers registered for both "/images/" 1572 // and "/images/thumbnails/", the latter handler will be 1573 // called for paths beginning "/images/thumbnails/" and the 1574 // former will receive requests for any other paths in the 1575 // "/images/" subtree. 1576 // 1577 // Note that since a pattern ending in a slash names a rooted subtree, 1578 // the pattern "/" matches all paths not matched by other registered 1579 // patterns, not just the URL with Path == "/". 1580 // 1581 // Patterns may optionally begin with a host name, restricting matches to 1582 // URLs on that host only. Host-specific patterns take precedence over 1583 // general patterns, so that a handler might register for the two patterns 1584 // "/codesearch" and "codesearch.google.com/" without also taking over 1585 // requests for "http://www.google.com/". 1586 // 1587 // ServeMux also takes care of sanitizing the URL request path, 1588 // redirecting any request containing . or .. elements to an 1589 // equivalent .- and ..-free URL. 1590 type ServeMux struct { 1591 mu sync.RWMutex 1592 m map[string]muxEntry 1593 hosts bool // whether any patterns contain hostnames 1594 } 1595 1596 type muxEntry struct { 1597 explicit bool 1598 h Handler 1599 pattern string 1600 } 1601 1602 // NewServeMux allocates and returns a new ServeMux. 1603 func NewServeMux() *ServeMux { return &ServeMux{m: make(map[string]muxEntry)} } 1604 1605 // DefaultServeMux is the default ServeMux used by Serve. 1606 var DefaultServeMux = NewServeMux() 1607 1608 // Does path match pattern? 1609 func pathMatch(pattern, path string) bool { 1610 if len(pattern) == 0 { 1611 // should not happen 1612 return false 1613 } 1614 n := len(pattern) 1615 if pattern[n-1] != '/' { 1616 return pattern == path 1617 } 1618 return len(path) >= n && path[0:n] == pattern 1619 } 1620 1621 // Return the canonical path for p, eliminating . and .. elements. 1622 func cleanPath(p string) string { 1623 if p == "" { 1624 return "/" 1625 } 1626 if p[0] != '/' { 1627 p = "/" + p 1628 } 1629 np := path.Clean(p) 1630 // path.Clean removes trailing slash except for root; 1631 // put the trailing slash back if necessary. 1632 if p[len(p)-1] == '/' && np != "/" { 1633 np += "/" 1634 } 1635 return np 1636 } 1637 1638 // Find a handler on a handler map given a path string 1639 // Most-specific (longest) pattern wins 1640 func (mux *ServeMux) match(path string) (h Handler, pattern string) { 1641 var n = 0 1642 for k, v := range mux.m { 1643 if !pathMatch(k, path) { 1644 continue 1645 } 1646 if h == nil || len(k) > n { 1647 n = len(k) 1648 h = v.h 1649 pattern = v.pattern 1650 } 1651 } 1652 return 1653 } 1654 1655 // Handler returns the handler to use for the given request, 1656 // consulting r.Method, r.Host, and r.URL.Path. It always returns 1657 // a non-nil handler. If the path is not in its canonical form, the 1658 // handler will be an internally-generated handler that redirects 1659 // to the canonical path. 1660 // 1661 // Handler also returns the registered pattern that matches the 1662 // request or, in the case of internally-generated redirects, 1663 // the pattern that will match after following the redirect. 1664 // 1665 // If there is no registered handler that applies to the request, 1666 // Handler returns a ``page not found'' handler and an empty pattern. 1667 func (mux *ServeMux) Handler(r *Request) (h Handler, pattern string) { 1668 if r.Method != "CONNECT" { 1669 if p := cleanPath(r.URL.Path); p != r.URL.Path { 1670 _, pattern = mux.handler(r.Host, p) 1671 url := *r.URL 1672 url.Path = p 1673 return RedirectHandler(url.String(), StatusMovedPermanently), pattern 1674 } 1675 } 1676 1677 return mux.handler(r.Host, r.URL.Path) 1678 } 1679 1680 // handler is the main implementation of Handler. 1681 // The path is known to be in canonical form, except for CONNECT methods. 1682 func (mux *ServeMux) handler(host, path string) (h Handler, pattern string) { 1683 mux.mu.RLock() 1684 defer mux.mu.RUnlock() 1685 1686 // Host-specific pattern takes precedence over generic ones 1687 if mux.hosts { 1688 h, pattern = mux.match(host + path) 1689 } 1690 if h == nil { 1691 h, pattern = mux.match(path) 1692 } 1693 if h == nil { 1694 h, pattern = NotFoundHandler(), "" 1695 } 1696 return 1697 } 1698 1699 // ServeHTTP dispatches the request to the handler whose 1700 // pattern most closely matches the request URL. 1701 func (mux *ServeMux) ServeHTTP(w ResponseWriter, r *Request) { 1702 if r.RequestURI == "*" { 1703 if r.ProtoAtLeast(1, 1) { 1704 w.Header().Set("Connection", "close") 1705 } 1706 w.WriteHeader(StatusBadRequest) 1707 return 1708 } 1709 h, _ := mux.Handler(r) 1710 h.ServeHTTP(w, r) 1711 } 1712 1713 // Handle registers the handler for the given pattern. 1714 // If a handler already exists for pattern, Handle panics. 1715 func (mux *ServeMux) Handle(pattern string, handler Handler) { 1716 mux.mu.Lock() 1717 defer mux.mu.Unlock() 1718 1719 if pattern == "" { 1720 panic("http: invalid pattern " + pattern) 1721 } 1722 if handler == nil { 1723 panic("http: nil handler") 1724 } 1725 if mux.m[pattern].explicit { 1726 panic("http: multiple registrations for " + pattern) 1727 } 1728 1729 mux.m[pattern] = muxEntry{explicit: true, h: handler, pattern: pattern} 1730 1731 if pattern[0] != '/' { 1732 mux.hosts = true 1733 } 1734 1735 // Helpful behavior: 1736 // If pattern is /tree/, insert an implicit permanent redirect for /tree. 1737 // It can be overridden by an explicit registration. 1738 n := len(pattern) 1739 if n > 0 && pattern[n-1] == '/' && !mux.m[pattern[0:n-1]].explicit { 1740 // If pattern contains a host name, strip it and use remaining 1741 // path for redirect. 1742 path := pattern 1743 if pattern[0] != '/' { 1744 // In pattern, at least the last character is a '/', so 1745 // strings.Index can't be -1. 1746 path = pattern[strings.Index(pattern, "/"):] 1747 } 1748 url := &url.URL{Path: path} 1749 mux.m[pattern[0:n-1]] = muxEntry{h: RedirectHandler(url.String(), StatusMovedPermanently), pattern: pattern} 1750 } 1751 } 1752 1753 // HandleFunc registers the handler function for the given pattern. 1754 func (mux *ServeMux) HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { 1755 mux.Handle(pattern, HandlerFunc(handler)) 1756 } 1757 1758 // Handle registers the handler for the given pattern 1759 // in the DefaultServeMux. 1760 // The documentation for ServeMux explains how patterns are matched. 1761 func Handle(pattern string, handler Handler) { DefaultServeMux.Handle(pattern, handler) } 1762 1763 // HandleFunc registers the handler function for the given pattern 1764 // in the DefaultServeMux. 1765 // The documentation for ServeMux explains how patterns are matched. 1766 func HandleFunc(pattern string, handler func(ResponseWriter, *Request)) { 1767 DefaultServeMux.HandleFunc(pattern, handler) 1768 } 1769 1770 // Serve accepts incoming HTTP connections on the listener l, 1771 // creating a new service goroutine for each. The service goroutines 1772 // read requests and then call handler to reply to them. 1773 // Handler is typically nil, in which case the DefaultServeMux is used. 1774 func Serve(l net.Listener, handler Handler) error { 1775 srv := &Server{Handler: handler} 1776 return srv.Serve(l) 1777 } 1778 1779 // A Server defines parameters for running an HTTP server. 1780 // The zero value for Server is a valid configuration. 1781 type Server struct { 1782 Addr string // TCP address to listen on, ":http" if empty 1783 Handler Handler // handler to invoke, http.DefaultServeMux if nil 1784 ReadTimeout time.Duration // maximum duration before timing out read of the request 1785 WriteTimeout time.Duration // maximum duration before timing out write of the response 1786 MaxHeaderBytes int // maximum size of request headers, DefaultMaxHeaderBytes if 0 1787 TLSConfig *tls.Config // optional TLS config, used by ListenAndServeTLS 1788 1789 // TLSNextProto optionally specifies a function to take over 1790 // ownership of the provided TLS connection when an NPN 1791 // protocol upgrade has occurred. The map key is the protocol 1792 // name negotiated. The Handler argument should be used to 1793 // handle HTTP requests and will initialize the Request's TLS 1794 // and RemoteAddr if not already set. The connection is 1795 // automatically closed when the function returns. 1796 TLSNextProto map[string]func(*Server, *tls.Conn, Handler) 1797 1798 // ConnState specifies an optional callback function that is 1799 // called when a client connection changes state. See the 1800 // ConnState type and associated constants for details. 1801 ConnState func(net.Conn, ConnState) 1802 1803 // ErrorLog specifies an optional logger for errors accepting 1804 // connections and unexpected behavior from handlers. 1805 // If nil, logging goes to os.Stderr via the log package's 1806 // standard logger. 1807 ErrorLog *log.Logger 1808 1809 disableKeepAlives int32 // accessed atomically. 1810 } 1811 1812 // A ConnState represents the state of a client connection to a server. 1813 // It's used by the optional Server.ConnState hook. 1814 type ConnState int 1815 1816 const ( 1817 // StateNew represents a new connection that is expected to 1818 // send a request immediately. Connections begin at this 1819 // state and then transition to either StateActive or 1820 // StateClosed. 1821 StateNew ConnState = iota 1822 1823 // StateActive represents a connection that has read 1 or more 1824 // bytes of a request. The Server.ConnState hook for 1825 // StateActive fires before the request has entered a handler 1826 // and doesn't fire again until the request has been 1827 // handled. After the request is handled, the state 1828 // transitions to StateClosed, StateHijacked, or StateIdle. 1829 StateActive 1830 1831 // StateIdle represents a connection that has finished 1832 // handling a request and is in the keep-alive state, waiting 1833 // for a new request. Connections transition from StateIdle 1834 // to either StateActive or StateClosed. 1835 StateIdle 1836 1837 // StateHijacked represents a hijacked connection. 1838 // This is a terminal state. It does not transition to StateClosed. 1839 StateHijacked 1840 1841 // StateClosed represents a closed connection. 1842 // This is a terminal state. Hijacked connections do not 1843 // transition to StateClosed. 1844 StateClosed 1845 ) 1846 1847 var stateName = map[ConnState]string{ 1848 StateNew: "new", 1849 StateActive: "active", 1850 StateIdle: "idle", 1851 StateHijacked: "hijacked", 1852 StateClosed: "closed", 1853 } 1854 1855 func (c ConnState) String() string { 1856 return stateName[c] 1857 } 1858 1859 // serverHandler delegates to either the server's Handler or 1860 // DefaultServeMux and also handles "OPTIONS *" requests. 1861 type serverHandler struct { 1862 srv *Server 1863 } 1864 1865 func (sh serverHandler) ServeHTTP(rw ResponseWriter, req *Request) { 1866 handler := sh.srv.Handler 1867 if handler == nil { 1868 handler = DefaultServeMux 1869 } 1870 if req.RequestURI == "*" && req.Method == "OPTIONS" { 1871 handler = globalOptionsHandler{} 1872 } 1873 handler.ServeHTTP(rw, req) 1874 } 1875 1876 // ListenAndServe listens on the TCP network address srv.Addr and then 1877 // calls Serve to handle requests on incoming connections. 1878 // If srv.Addr is blank, ":http" is used. 1879 // ListenAndServe always returns a non-nil error. 1880 func (srv *Server) ListenAndServe() error { 1881 addr := srv.Addr 1882 if addr == "" { 1883 addr = ":http" 1884 } 1885 ln, err := net.Listen("tcp", addr) 1886 if err != nil { 1887 return err 1888 } 1889 return srv.Serve(tcpKeepAliveListener{ln.(*net.TCPListener)}) 1890 } 1891 1892 // Serve accepts incoming connections on the Listener l, creating a 1893 // new service goroutine for each. The service goroutines read requests and 1894 // then call srv.Handler to reply to them. 1895 // Serve always returns a non-nil error. 1896 func (srv *Server) Serve(l net.Listener) error { 1897 defer l.Close() 1898 var tempDelay time.Duration // how long to sleep on accept failure 1899 for { 1900 rw, e := l.Accept() 1901 if e != nil { 1902 if ne, ok := e.(net.Error); ok && ne.Temporary() { 1903 if tempDelay == 0 { 1904 tempDelay = 5 * time.Millisecond 1905 } else { 1906 tempDelay *= 2 1907 } 1908 if max := 1 * time.Second; tempDelay > max { 1909 tempDelay = max 1910 } 1911 srv.logf("http: Accept error: %v; retrying in %v", e, tempDelay) 1912 time.Sleep(tempDelay) 1913 continue 1914 } 1915 return e 1916 } 1917 tempDelay = 0 1918 c, err := srv.newConn(rw) 1919 if err != nil { 1920 continue 1921 } 1922 c.setState(c.rwc, StateNew) // before Serve can return 1923 go c.serve() 1924 } 1925 } 1926 1927 func (s *Server) doKeepAlives() bool { 1928 return atomic.LoadInt32(&s.disableKeepAlives) == 0 1929 } 1930 1931 // SetKeepAlivesEnabled controls whether HTTP keep-alives are enabled. 1932 // By default, keep-alives are always enabled. Only very 1933 // resource-constrained environments or servers in the process of 1934 // shutting down should disable them. 1935 func (srv *Server) SetKeepAlivesEnabled(v bool) { 1936 if v { 1937 atomic.StoreInt32(&srv.disableKeepAlives, 0) 1938 } else { 1939 atomic.StoreInt32(&srv.disableKeepAlives, 1) 1940 } 1941 } 1942 1943 func (s *Server) logf(format string, args ...interface{}) { 1944 if s.ErrorLog != nil { 1945 s.ErrorLog.Printf(format, args...) 1946 } else { 1947 log.Printf(format, args...) 1948 } 1949 } 1950 1951 // ListenAndServe listens on the TCP network address addr 1952 // and then calls Serve with handler to handle requests 1953 // on incoming connections. Handler is typically nil, 1954 // in which case the DefaultServeMux is used. 1955 // 1956 // A trivial example server is: 1957 // 1958 // package main 1959 // 1960 // import ( 1961 // "io" 1962 // "net/http" 1963 // "log" 1964 // ) 1965 // 1966 // // hello world, the web server 1967 // func HelloServer(w http.ResponseWriter, req *http.Request) { 1968 // io.WriteString(w, "hello, world!\n") 1969 // } 1970 // 1971 // func main() { 1972 // http.HandleFunc("/hello", HelloServer) 1973 // log.Fatal(http.ListenAndServe(":12345", nil)) 1974 // } 1975 // 1976 // ListenAndServe always returns a non-nil error. 1977 func ListenAndServe(addr string, handler Handler) error { 1978 server := &Server{Addr: addr, Handler: handler} 1979 return server.ListenAndServe() 1980 } 1981 1982 // ListenAndServeTLS acts identically to ListenAndServe, except that it 1983 // expects HTTPS connections. Additionally, files containing a certificate and 1984 // matching private key for the server must be provided. If the certificate 1985 // is signed by a certificate authority, the certFile should be the concatenation 1986 // of the server's certificate, any intermediates, and the CA's certificate. 1987 // 1988 // A trivial example server is: 1989 // 1990 // import ( 1991 // "log" 1992 // "net/http" 1993 // ) 1994 // 1995 // func handler(w http.ResponseWriter, req *http.Request) { 1996 // w.Header().Set("Content-Type", "text/plain") 1997 // w.Write([]byte("This is an example server.\n")) 1998 // } 1999 // 2000 // func main() { 2001 // http.HandleFunc("/", handler) 2002 // log.Printf("About to listen on 10443. Go to https://127.0.0.1:10443/") 2003 // err := http.ListenAndServeTLS(":10443", "cert.pem", "key.pem", nil) 2004 // log.Fatal(err) 2005 // } 2006 // 2007 // One can use generate_cert.go in crypto/tls to generate cert.pem and key.pem. 2008 // 2009 // ListenAndServeTLS always returns a non-nil error. 2010 func ListenAndServeTLS(addr string, certFile string, keyFile string, handler Handler) error { 2011 server := &Server{Addr: addr, Handler: handler} 2012 return server.ListenAndServeTLS(certFile, keyFile) 2013 } 2014 2015 // ListenAndServeTLS listens on the TCP network address srv.Addr and 2016 // then calls Serve to handle requests on incoming TLS connections. 2017 // 2018 // Filenames containing a certificate and matching private key for the 2019 // server must be provided if the Server's TLSConfig.Certificates is 2020 // not populated. If the certificate is signed by a certificate 2021 // authority, the certFile should be the concatenation of the server's 2022 // certificate, any intermediates, and the CA's certificate. 2023 // 2024 // If srv.Addr is blank, ":https" is used. 2025 // 2026 // ListenAndServeTLS always returns a non-nil error. 2027 func (srv *Server) ListenAndServeTLS(certFile, keyFile string) error { 2028 addr := srv.Addr 2029 if addr == "" { 2030 addr = ":https" 2031 } 2032 config := cloneTLSConfig(srv.TLSConfig) 2033 if config.NextProtos == nil { 2034 config.NextProtos = []string{"http/1.1"} 2035 } 2036 2037 if len(config.Certificates) == 0 || certFile != "" || keyFile != "" { 2038 var err error 2039 config.Certificates = make([]tls.Certificate, 1) 2040 config.Certificates[0], err = tls.LoadX509KeyPair(certFile, keyFile) 2041 if err != nil { 2042 return err 2043 } 2044 } 2045 2046 ln, err := net.Listen("tcp", addr) 2047 if err != nil { 2048 return err 2049 } 2050 2051 tlsListener := tls.NewListener(tcpKeepAliveListener{ln.(*net.TCPListener)}, config) 2052 return srv.Serve(tlsListener) 2053 } 2054 2055 // TimeoutHandler returns a Handler that runs h with the given time limit. 2056 // 2057 // The new Handler calls h.ServeHTTP to handle each request, but if a 2058 // call runs for longer than its time limit, the handler responds with 2059 // a 503 Service Unavailable error and the given message in its body. 2060 // (If msg is empty, a suitable default message will be sent.) 2061 // After such a timeout, writes by h to its ResponseWriter will return 2062 // ErrHandlerTimeout. 2063 func TimeoutHandler(h Handler, dt time.Duration, msg string) Handler { 2064 f := func() <-chan time.Time { 2065 return time.After(dt) 2066 } 2067 return &timeoutHandler{h, f, msg} 2068 } 2069 2070 // ErrHandlerTimeout is returned on ResponseWriter Write calls 2071 // in handlers which have timed out. 2072 var ErrHandlerTimeout = errors.New("http: Handler timeout") 2073 2074 type timeoutHandler struct { 2075 handler Handler 2076 timeout func() <-chan time.Time // returns channel producing a timeout 2077 body string 2078 } 2079 2080 func (h *timeoutHandler) errorBody() string { 2081 if h.body != "" { 2082 return h.body 2083 } 2084 return "<html><head><title>Timeout</title></head><body><h1>Timeout</h1></body></html>" 2085 } 2086 2087 func (h *timeoutHandler) ServeHTTP(w ResponseWriter, r *Request) { 2088 done := make(chan bool, 1) 2089 tw := &timeoutWriter{w: w} 2090 go func() { 2091 h.handler.ServeHTTP(tw, r) 2092 done <- true 2093 }() 2094 select { 2095 case <-done: 2096 return 2097 case <-h.timeout(): 2098 tw.mu.Lock() 2099 defer tw.mu.Unlock() 2100 if !tw.wroteHeader { 2101 tw.w.WriteHeader(StatusServiceUnavailable) 2102 tw.w.Write([]byte(h.errorBody())) 2103 } 2104 tw.timedOut = true 2105 } 2106 } 2107 2108 type timeoutWriter struct { 2109 w ResponseWriter 2110 2111 mu sync.Mutex 2112 timedOut bool 2113 wroteHeader bool 2114 } 2115 2116 func (tw *timeoutWriter) Header() Header { 2117 return tw.w.Header() 2118 } 2119 2120 func (tw *timeoutWriter) Write(p []byte) (int, error) { 2121 tw.mu.Lock() 2122 defer tw.mu.Unlock() 2123 tw.wroteHeader = true // implicitly at least 2124 if tw.timedOut { 2125 return 0, ErrHandlerTimeout 2126 } 2127 return tw.w.Write(p) 2128 } 2129 2130 func (tw *timeoutWriter) WriteHeader(code int) { 2131 tw.mu.Lock() 2132 defer tw.mu.Unlock() 2133 if tw.timedOut || tw.wroteHeader { 2134 return 2135 } 2136 tw.wroteHeader = true 2137 tw.w.WriteHeader(code) 2138 } 2139 2140 // tcpKeepAliveListener sets TCP keep-alive timeouts on accepted 2141 // connections. It's used by ListenAndServe and ListenAndServeTLS so 2142 // dead TCP connections (e.g. closing laptop mid-download) eventually 2143 // go away. 2144 type tcpKeepAliveListener struct { 2145 *net.TCPListener 2146 } 2147 2148 func (ln tcpKeepAliveListener) Accept() (c net.Conn, err error) { 2149 tc, err := ln.AcceptTCP() 2150 if err != nil { 2151 return 2152 } 2153 tc.SetKeepAlive(true) 2154 tc.SetKeepAlivePeriod(3 * time.Minute) 2155 return tc, nil 2156 } 2157 2158 // globalOptionsHandler responds to "OPTIONS *" requests. 2159 type globalOptionsHandler struct{} 2160 2161 func (globalOptionsHandler) ServeHTTP(w ResponseWriter, r *Request) { 2162 w.Header().Set("Content-Length", "0") 2163 if r.ContentLength != 0 { 2164 // Read up to 4KB of OPTIONS body (as mentioned in the 2165 // spec as being reserved for future use), but anything 2166 // over that is considered a waste of server resources 2167 // (or an attack) and we abort and close the connection, 2168 // courtesy of MaxBytesReader's EOF behavior. 2169 mb := MaxBytesReader(w, r.Body, 4<<10) 2170 io.Copy(ioutil.Discard, mb) 2171 } 2172 } 2173 2174 type eofReaderWithWriteTo struct{} 2175 2176 func (eofReaderWithWriteTo) WriteTo(io.Writer) (int64, error) { return 0, nil } 2177 func (eofReaderWithWriteTo) Read([]byte) (int, error) { return 0, io.EOF } 2178 2179 // eofReader is a non-nil io.ReadCloser that always returns EOF. 2180 // It has a WriteTo method so io.Copy won't need a buffer. 2181 var eofReader = &struct { 2182 eofReaderWithWriteTo 2183 io.Closer 2184 }{ 2185 eofReaderWithWriteTo{}, 2186 ioutil.NopCloser(nil), 2187 } 2188 2189 // Verify that an io.Copy from an eofReader won't require a buffer. 2190 var _ io.WriterTo = eofReader 2191 2192 // initNPNRequest is an HTTP handler that initializes certain 2193 // uninitialized fields in its *Request. Such partially-initialized 2194 // Requests come from NPN protocol handlers. 2195 type initNPNRequest struct { 2196 c *tls.Conn 2197 h serverHandler 2198 } 2199 2200 func (h initNPNRequest) ServeHTTP(rw ResponseWriter, req *Request) { 2201 if req.TLS == nil { 2202 req.TLS = &tls.ConnectionState{} 2203 *req.TLS = h.c.ConnectionState() 2204 } 2205 if req.Body == nil { 2206 req.Body = eofReader 2207 } 2208 if req.RemoteAddr == "" { 2209 req.RemoteAddr = h.c.RemoteAddr().String() 2210 } 2211 h.h.ServeHTTP(rw, req) 2212 } 2213 2214 // loggingConn is used for debugging. 2215 type loggingConn struct { 2216 name string 2217 net.Conn 2218 } 2219 2220 var ( 2221 uniqNameMu sync.Mutex 2222 uniqNameNext = make(map[string]int) 2223 ) 2224 2225 func newLoggingConn(baseName string, c net.Conn) net.Conn { 2226 uniqNameMu.Lock() 2227 defer uniqNameMu.Unlock() 2228 uniqNameNext[baseName]++ 2229 return &loggingConn{ 2230 name: fmt.Sprintf("%s-%d", baseName, uniqNameNext[baseName]), 2231 Conn: c, 2232 } 2233 } 2234 2235 func (c *loggingConn) Write(p []byte) (n int, err error) { 2236 log.Printf("%s.Write(%d) = ....", c.name, len(p)) 2237 n, err = c.Conn.Write(p) 2238 log.Printf("%s.Write(%d) = %d, %v", c.name, len(p), n, err) 2239 return 2240 } 2241 2242 func (c *loggingConn) Read(p []byte) (n int, err error) { 2243 log.Printf("%s.Read(%d) = ....", c.name, len(p)) 2244 n, err = c.Conn.Read(p) 2245 log.Printf("%s.Read(%d) = %d, %v", c.name, len(p), n, err) 2246 return 2247 } 2248 2249 func (c *loggingConn) Close() (err error) { 2250 log.Printf("%s.Close() = ...", c.name) 2251 err = c.Conn.Close() 2252 log.Printf("%s.Close() = %v", c.name, err) 2253 return 2254 } 2255 2256 // checkConnErrorWriter writes to c.rwc and records any write errors to c.werr. 2257 // It only contains one field (and a pointer field at that), so it 2258 // fits in an interface value without an extra allocation. 2259 type checkConnErrorWriter struct { 2260 c *conn 2261 } 2262 2263 func (w checkConnErrorWriter) Write(p []byte) (n int, err error) { 2264 n, err = w.c.w.Write(p) // c.w == c.rwc, except after a hijack, when rwc is nil. 2265 if err != nil && w.c.werr == nil { 2266 w.c.werr = err 2267 } 2268 return 2269 } 2270 2271 func numLeadingCRorLF(v []byte) (n int) { 2272 for _, b := range v { 2273 if b == '\r' || b == '\n' { 2274 n++ 2275 continue 2276 } 2277 break 2278 } 2279 return 2280 2281 }