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