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