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