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