...
Run Format

Source file src/net/http/server.go

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

View as plain text