github.com/rsc/go@v0.0.0-20150416155037-e040fd465409/src/net/http/server.go (about)

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