github.com/d4l3k/go@v0.0.0-20151015000803-65fc379daeda/src/net/http/server.go (about)

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