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