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