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