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