• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1// Copyright 2014 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// TODO: turn off the serve goroutine when idle, so
6// an idle conn only has the readFrames goroutine active. (which could
7// also be optimized probably to pin less memory in crypto/tls). This
8// would involve tracking when the serve goroutine is active (atomic
9// int32 read/CAS probably?) and starting it up when frames arrive,
10// and shutting it down when all handlers exit. the occasional PING
11// packets could use time.AfterFunc to call sc.wakeStartServeLoop()
12// (which is a no-op if already running) and then queue the PING write
13// as normal. The serve loop would then exit in most cases (if no
14// Handlers running) and not be woken up again until the PING packet
15// returns.
16
17// TODO (maybe): add a mechanism for Handlers to going into
18// half-closed-local mode (rw.(io.Closer) test?) but not exit their
19// handler, and continue to be able to read from the
20// Request.Body. This would be a somewhat semantic change from HTTP/1
21// (or at least what we expose in net/http), so I'd probably want to
22// add it there too. For now, this package says that returning from
23// the Handler ServeHTTP function means you're both done reading and
24// done writing, without a way to stop just one or the other.
25
26package http2
27
28import (
29	"bufio"
30	"bytes"
31	"crypto/tls"
32	"errors"
33	"fmt"
34	"io"
35	"log"
36	"math"
37	"net"
38	"net/http"
39	"net/textproto"
40	"net/url"
41	"os"
42	"reflect"
43	"runtime"
44	"strconv"
45	"strings"
46	"sync"
47	"time"
48
49	"golang.org/x/net/http/httpguts"
50	"golang.org/x/net/http2/hpack"
51)
52
53const (
54	prefaceTimeout        = 10 * time.Second
55	firstSettingsTimeout  = 2 * time.Second // should be in-flight with preface anyway
56	handlerChunkWriteSize = 4 << 10
57	defaultMaxStreams     = 250 // TODO: make this 100 as the GFE seems to?
58)
59
60var (
61	errClientDisconnected = errors.New("client disconnected")
62	errClosedBody         = errors.New("body closed by handler")
63	errHandlerComplete    = errors.New("http2: request body closed due to handler exiting")
64	errStreamClosed       = errors.New("http2: stream closed")
65)
66
67var responseWriterStatePool = sync.Pool{
68	New: func() interface{} {
69		rws := &responseWriterState{}
70		rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
71		return rws
72	},
73}
74
75// Test hooks.
76var (
77	testHookOnConn        func()
78	testHookGetServerConn func(*serverConn)
79	testHookOnPanicMu     *sync.Mutex // nil except in tests
80	testHookOnPanic       func(sc *serverConn, panicVal interface{}) (rePanic bool)
81)
82
83// Server is an HTTP/2 server.
84type Server struct {
85	// MaxHandlers limits the number of http.Handler ServeHTTP goroutines
86	// which may run at a time over all connections.
87	// Negative or zero no limit.
88	// TODO: implement
89	MaxHandlers int
90
91	// MaxConcurrentStreams optionally specifies the number of
92	// concurrent streams that each client may have open at a
93	// time. This is unrelated to the number of http.Handler goroutines
94	// which may be active globally, which is MaxHandlers.
95	// If zero, MaxConcurrentStreams defaults to at least 100, per
96	// the HTTP/2 spec's recommendations.
97	MaxConcurrentStreams uint32
98
99	// MaxReadFrameSize optionally specifies the largest frame
100	// this server is willing to read. A valid value is between
101	// 16k and 16M, inclusive. If zero or otherwise invalid, a
102	// default value is used.
103	MaxReadFrameSize uint32
104
105	// PermitProhibitedCipherSuites, if true, permits the use of
106	// cipher suites prohibited by the HTTP/2 spec.
107	PermitProhibitedCipherSuites bool
108
109	// IdleTimeout specifies how long until idle clients should be
110	// closed with a GOAWAY frame. PING frames are not considered
111	// activity for the purposes of IdleTimeout.
112	IdleTimeout time.Duration
113
114	// MaxUploadBufferPerConnection is the size of the initial flow
115	// control window for each connections. The HTTP/2 spec does not
116	// allow this to be smaller than 65535 or larger than 2^32-1.
117	// If the value is outside this range, a default value will be
118	// used instead.
119	MaxUploadBufferPerConnection int32
120
121	// MaxUploadBufferPerStream is the size of the initial flow control
122	// window for each stream. The HTTP/2 spec does not allow this to
123	// be larger than 2^32-1. If the value is zero or larger than the
124	// maximum, a default value will be used instead.
125	MaxUploadBufferPerStream int32
126
127	// NewWriteScheduler constructs a write scheduler for a connection.
128	// If nil, a default scheduler is chosen.
129	NewWriteScheduler func() WriteScheduler
130
131	// Internal state. This is a pointer (rather than embedded directly)
132	// so that we don't embed a Mutex in this struct, which will make the
133	// struct non-copyable, which might break some callers.
134	state *serverInternalState
135}
136
137func (s *Server) initialConnRecvWindowSize() int32 {
138	if s.MaxUploadBufferPerConnection > initialWindowSize {
139		return s.MaxUploadBufferPerConnection
140	}
141	return 1 << 20
142}
143
144func (s *Server) initialStreamRecvWindowSize() int32 {
145	if s.MaxUploadBufferPerStream > 0 {
146		return s.MaxUploadBufferPerStream
147	}
148	return 1 << 20
149}
150
151func (s *Server) maxReadFrameSize() uint32 {
152	if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
153		return v
154	}
155	return defaultMaxReadFrameSize
156}
157
158func (s *Server) maxConcurrentStreams() uint32 {
159	if v := s.MaxConcurrentStreams; v > 0 {
160		return v
161	}
162	return defaultMaxStreams
163}
164
165type serverInternalState struct {
166	mu          sync.Mutex
167	activeConns map[*serverConn]struct{}
168}
169
170func (s *serverInternalState) registerConn(sc *serverConn) {
171	if s == nil {
172		return // if the Server was used without calling ConfigureServer
173	}
174	s.mu.Lock()
175	s.activeConns[sc] = struct{}{}
176	s.mu.Unlock()
177}
178
179func (s *serverInternalState) unregisterConn(sc *serverConn) {
180	if s == nil {
181		return // if the Server was used without calling ConfigureServer
182	}
183	s.mu.Lock()
184	delete(s.activeConns, sc)
185	s.mu.Unlock()
186}
187
188func (s *serverInternalState) startGracefulShutdown() {
189	if s == nil {
190		return // if the Server was used without calling ConfigureServer
191	}
192	s.mu.Lock()
193	for sc := range s.activeConns {
194		sc.startGracefulShutdown()
195	}
196	s.mu.Unlock()
197}
198
199// ConfigureServer adds HTTP/2 support to a net/http Server.
200//
201// The configuration conf may be nil.
202//
203// ConfigureServer must be called before s begins serving.
204func ConfigureServer(s *http.Server, conf *Server) error {
205	if s == nil {
206		panic("nil *http.Server")
207	}
208	if conf == nil {
209		conf = new(Server)
210	}
211	conf.state = &serverInternalState{activeConns: make(map[*serverConn]struct{})}
212	if err := configureServer18(s, conf); err != nil {
213		return err
214	}
215	if err := configureServer19(s, conf); err != nil {
216		return err
217	}
218
219	if s.TLSConfig == nil {
220		s.TLSConfig = new(tls.Config)
221	} else if s.TLSConfig.CipherSuites != nil {
222		// If they already provided a CipherSuite list, return
223		// an error if it has a bad order or is missing
224		// ECDHE_RSA_WITH_AES_128_GCM_SHA256 or ECDHE_ECDSA_WITH_AES_128_GCM_SHA256.
225		haveRequired := false
226		sawBad := false
227		for i, cs := range s.TLSConfig.CipherSuites {
228			switch cs {
229			case tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256,
230				// Alternative MTI cipher to not discourage ECDSA-only servers.
231				// See http://golang.org/cl/30721 for further information.
232				tls.TLS_ECDHE_ECDSA_WITH_AES_128_GCM_SHA256:
233				haveRequired = true
234			}
235			if isBadCipher(cs) {
236				sawBad = true
237			} else if sawBad {
238				return fmt.Errorf("http2: TLSConfig.CipherSuites index %d contains an HTTP/2-approved cipher suite (%#04x), but it comes after unapproved cipher suites. With this configuration, clients that don't support previous, approved cipher suites may be given an unapproved one and reject the connection.", i, cs)
239			}
240		}
241		if !haveRequired {
242			return fmt.Errorf("http2: TLSConfig.CipherSuites is missing an HTTP/2-required AES_128_GCM_SHA256 cipher.")
243		}
244	}
245
246	// Note: not setting MinVersion to tls.VersionTLS12,
247	// as we don't want to interfere with HTTP/1.1 traffic
248	// on the user's server. We enforce TLS 1.2 later once
249	// we accept a connection. Ideally this should be done
250	// during next-proto selection, but using TLS <1.2 with
251	// HTTP/2 is still the client's bug.
252
253	s.TLSConfig.PreferServerCipherSuites = true
254
255	haveNPN := false
256	for _, p := range s.TLSConfig.NextProtos {
257		if p == NextProtoTLS {
258			haveNPN = true
259			break
260		}
261	}
262	if !haveNPN {
263		s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
264	}
265
266	if s.TLSNextProto == nil {
267		s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
268	}
269	protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
270		if testHookOnConn != nil {
271			testHookOnConn()
272		}
273		conf.ServeConn(c, &ServeConnOpts{
274			Handler:    h,
275			BaseConfig: hs,
276		})
277	}
278	s.TLSNextProto[NextProtoTLS] = protoHandler
279	return nil
280}
281
282// ServeConnOpts are options for the Server.ServeConn method.
283type ServeConnOpts struct {
284	// BaseConfig optionally sets the base configuration
285	// for values. If nil, defaults are used.
286	BaseConfig *http.Server
287
288	// Handler specifies which handler to use for processing
289	// requests. If nil, BaseConfig.Handler is used. If BaseConfig
290	// or BaseConfig.Handler is nil, http.DefaultServeMux is used.
291	Handler http.Handler
292}
293
294func (o *ServeConnOpts) baseConfig() *http.Server {
295	if o != nil && o.BaseConfig != nil {
296		return o.BaseConfig
297	}
298	return new(http.Server)
299}
300
301func (o *ServeConnOpts) handler() http.Handler {
302	if o != nil {
303		if o.Handler != nil {
304			return o.Handler
305		}
306		if o.BaseConfig != nil && o.BaseConfig.Handler != nil {
307			return o.BaseConfig.Handler
308		}
309	}
310	return http.DefaultServeMux
311}
312
313// ServeConn serves HTTP/2 requests on the provided connection and
314// blocks until the connection is no longer readable.
315//
316// ServeConn starts speaking HTTP/2 assuming that c has not had any
317// reads or writes. It writes its initial settings frame and expects
318// to be able to read the preface and settings frame from the
319// client. If c has a ConnectionState method like a *tls.Conn, the
320// ConnectionState is used to verify the TLS ciphersuite and to set
321// the Request.TLS field in Handlers.
322//
323// ServeConn does not support h2c by itself. Any h2c support must be
324// implemented in terms of providing a suitably-behaving net.Conn.
325//
326// The opts parameter is optional. If nil, default values are used.
327func (s *Server) ServeConn(c net.Conn, opts *ServeConnOpts) {
328	baseCtx, cancel := serverConnBaseContext(c, opts)
329	defer cancel()
330
331	sc := &serverConn{
332		srv:                         s,
333		hs:                          opts.baseConfig(),
334		conn:                        c,
335		baseCtx:                     baseCtx,
336		remoteAddrStr:               c.RemoteAddr().String(),
337		bw:                          newBufferedWriter(c),
338		handler:                     opts.handler(),
339		streams:                     make(map[uint32]*stream),
340		readFrameCh:                 make(chan readFrameResult),
341		wantWriteFrameCh:            make(chan FrameWriteRequest, 8),
342		serveMsgCh:                  make(chan interface{}, 8),
343		wroteFrameCh:                make(chan frameWriteResult, 1), // buffered; one send in writeFrameAsync
344		bodyReadCh:                  make(chan bodyReadMsg),         // buffering doesn't matter either way
345		doneServing:                 make(chan struct{}),
346		clientMaxStreams:            math.MaxUint32, // Section 6.5.2: "Initially, there is no limit to this value"
347		advMaxStreams:               s.maxConcurrentStreams(),
348		initialStreamSendWindowSize: initialWindowSize,
349		maxFrameSize:                initialMaxFrameSize,
350		headerTableSize:             initialHeaderTableSize,
351		serveG:                      newGoroutineLock(),
352		pushEnabled:                 true,
353	}
354
355	s.state.registerConn(sc)
356	defer s.state.unregisterConn(sc)
357
358	// The net/http package sets the write deadline from the
359	// http.Server.WriteTimeout during the TLS handshake, but then
360	// passes the connection off to us with the deadline already set.
361	// Write deadlines are set per stream in serverConn.newStream.
362	// Disarm the net.Conn write deadline here.
363	if sc.hs.WriteTimeout != 0 {
364		sc.conn.SetWriteDeadline(time.Time{})
365	}
366
367	if s.NewWriteScheduler != nil {
368		sc.writeSched = s.NewWriteScheduler()
369	} else {
370		sc.writeSched = NewRandomWriteScheduler()
371	}
372
373	// These start at the RFC-specified defaults. If there is a higher
374	// configured value for inflow, that will be updated when we send a
375	// WINDOW_UPDATE shortly after sending SETTINGS.
376	sc.flow.add(initialWindowSize)
377	sc.inflow.add(initialWindowSize)
378	sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
379
380	fr := NewFramer(sc.bw, c)
381	fr.ReadMetaHeaders = hpack.NewDecoder(initialHeaderTableSize, nil)
382	fr.MaxHeaderListSize = sc.maxHeaderListSize()
383	fr.SetMaxReadFrameSize(s.maxReadFrameSize())
384	sc.framer = fr
385
386	if tc, ok := c.(connectionStater); ok {
387		sc.tlsState = new(tls.ConnectionState)
388		*sc.tlsState = tc.ConnectionState()
389		// 9.2 Use of TLS Features
390		// An implementation of HTTP/2 over TLS MUST use TLS
391		// 1.2 or higher with the restrictions on feature set
392		// and cipher suite described in this section. Due to
393		// implementation limitations, it might not be
394		// possible to fail TLS negotiation. An endpoint MUST
395		// immediately terminate an HTTP/2 connection that
396		// does not meet the TLS requirements described in
397		// this section with a connection error (Section
398		// 5.4.1) of type INADEQUATE_SECURITY.
399		if sc.tlsState.Version < tls.VersionTLS12 {
400			sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
401			return
402		}
403
404		if sc.tlsState.ServerName == "" {
405			// Client must use SNI, but we don't enforce that anymore,
406			// since it was causing problems when connecting to bare IP
407			// addresses during development.
408			//
409			// TODO: optionally enforce? Or enforce at the time we receive
410			// a new request, and verify the ServerName matches the :authority?
411			// But that precludes proxy situations, perhaps.
412			//
413			// So for now, do nothing here again.
414		}
415
416		if !s.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
417			// "Endpoints MAY choose to generate a connection error
418			// (Section 5.4.1) of type INADEQUATE_SECURITY if one of
419			// the prohibited cipher suites are negotiated."
420			//
421			// We choose that. In my opinion, the spec is weak
422			// here. It also says both parties must support at least
423			// TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
424			// excuses here. If we really must, we could allow an
425			// "AllowInsecureWeakCiphers" option on the server later.
426			// Let's see how it plays out first.
427			sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
428			return
429		}
430	}
431
432	if hook := testHookGetServerConn; hook != nil {
433		hook(sc)
434	}
435	sc.serve()
436}
437
438func (sc *serverConn) rejectConn(err ErrCode, debug string) {
439	sc.vlogf("http2: server rejecting conn: %v, %s", err, debug)
440	// ignoring errors. hanging up anyway.
441	sc.framer.WriteGoAway(0, err, []byte(debug))
442	sc.bw.Flush()
443	sc.conn.Close()
444}
445
446type serverConn struct {
447	// Immutable:
448	srv              *Server
449	hs               *http.Server
450	conn             net.Conn
451	bw               *bufferedWriter // writing to conn
452	handler          http.Handler
453	baseCtx          contextContext
454	framer           *Framer
455	doneServing      chan struct{}          // closed when serverConn.serve ends
456	readFrameCh      chan readFrameResult   // written by serverConn.readFrames
457	wantWriteFrameCh chan FrameWriteRequest // from handlers -> serve
458	wroteFrameCh     chan frameWriteResult  // from writeFrameAsync -> serve, tickles more frame writes
459	bodyReadCh       chan bodyReadMsg       // from handlers -> serve
460	serveMsgCh       chan interface{}       // misc messages & code to send to / run on the serve loop
461	flow             flow                   // conn-wide (not stream-specific) outbound flow control
462	inflow           flow                   // conn-wide inbound flow control
463	tlsState         *tls.ConnectionState   // shared by all handlers, like net/http
464	remoteAddrStr    string
465	writeSched       WriteScheduler
466
467	// Everything following is owned by the serve loop; use serveG.check():
468	serveG                      goroutineLock // used to verify funcs are on serve()
469	pushEnabled                 bool
470	sawFirstSettings            bool // got the initial SETTINGS frame after the preface
471	needToSendSettingsAck       bool
472	unackedSettings             int    // how many SETTINGS have we sent without ACKs?
473	clientMaxStreams            uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
474	advMaxStreams               uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
475	curClientStreams            uint32 // number of open streams initiated by the client
476	curPushedStreams            uint32 // number of open streams initiated by server push
477	maxClientStreamID           uint32 // max ever seen from client (odd), or 0 if there have been no client requests
478	maxPushPromiseID            uint32 // ID of the last push promise (even), or 0 if there have been no pushes
479	streams                     map[uint32]*stream
480	initialStreamSendWindowSize int32
481	maxFrameSize                int32
482	headerTableSize             uint32
483	peerMaxHeaderListSize       uint32            // zero means unknown (default)
484	canonHeader                 map[string]string // http2-lower-case -> Go-Canonical-Case
485	writingFrame                bool              // started writing a frame (on serve goroutine or separate)
486	writingFrameAsync           bool              // started a frame on its own goroutine but haven't heard back on wroteFrameCh
487	needsFrameFlush             bool              // last frame write wasn't a flush
488	inGoAway                    bool              // we've started to or sent GOAWAY
489	inFrameScheduleLoop         bool              // whether we're in the scheduleFrameWrite loop
490	needToSendGoAway            bool              // we need to schedule a GOAWAY frame write
491	goAwayCode                  ErrCode
492	shutdownTimer               *time.Timer // nil until used
493	idleTimer                   *time.Timer // nil if unused
494
495	// Owned by the writeFrameAsync goroutine:
496	headerWriteBuf bytes.Buffer
497	hpackEncoder   *hpack.Encoder
498
499	// Used by startGracefulShutdown.
500	shutdownOnce sync.Once
501}
502
503func (sc *serverConn) maxHeaderListSize() uint32 {
504	n := sc.hs.MaxHeaderBytes
505	if n <= 0 {
506		n = http.DefaultMaxHeaderBytes
507	}
508	// http2's count is in a slightly different unit and includes 32 bytes per pair.
509	// So, take the net/http.Server value and pad it up a bit, assuming 10 headers.
510	const perFieldOverhead = 32 // per http2 spec
511	const typicalHeaders = 10   // conservative
512	return uint32(n + typicalHeaders*perFieldOverhead)
513}
514
515func (sc *serverConn) curOpenStreams() uint32 {
516	sc.serveG.check()
517	return sc.curClientStreams + sc.curPushedStreams
518}
519
520// stream represents a stream. This is the minimal metadata needed by
521// the serve goroutine. Most of the actual stream state is owned by
522// the http.Handler's goroutine in the responseWriter. Because the
523// responseWriter's responseWriterState is recycled at the end of a
524// handler, this struct intentionally has no pointer to the
525// *responseWriter{,State} itself, as the Handler ending nils out the
526// responseWriter's state field.
527type stream struct {
528	// immutable:
529	sc        *serverConn
530	id        uint32
531	body      *pipe       // non-nil if expecting DATA frames
532	cw        closeWaiter // closed wait stream transitions to closed state
533	ctx       contextContext
534	cancelCtx func()
535
536	// owned by serverConn's serve loop:
537	bodyBytes        int64   // body bytes seen so far
538	declBodyBytes    int64   // or -1 if undeclared
539	flow             flow    // limits writing from Handler to client
540	inflow           flow    // what the client is allowed to POST/etc to us
541	parent           *stream // or nil
542	numTrailerValues int64
543	weight           uint8
544	state            streamState
545	resetQueued      bool        // RST_STREAM queued for write; set by sc.resetStream
546	gotTrailerHeader bool        // HEADER frame for trailers was seen
547	wroteHeaders     bool        // whether we wrote headers (not status 100)
548	writeDeadline    *time.Timer // nil if unused
549
550	trailer    http.Header // accumulated trailers
551	reqTrailer http.Header // handler's Request.Trailer
552}
553
554func (sc *serverConn) Framer() *Framer  { return sc.framer }
555func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
556func (sc *serverConn) Flush() error     { return sc.bw.Flush() }
557func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
558	return sc.hpackEncoder, &sc.headerWriteBuf
559}
560
561func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
562	sc.serveG.check()
563	// http://tools.ietf.org/html/rfc7540#section-5.1
564	if st, ok := sc.streams[streamID]; ok {
565		return st.state, st
566	}
567	// "The first use of a new stream identifier implicitly closes all
568	// streams in the "idle" state that might have been initiated by
569	// that peer with a lower-valued stream identifier. For example, if
570	// a client sends a HEADERS frame on stream 7 without ever sending a
571	// frame on stream 5, then stream 5 transitions to the "closed"
572	// state when the first frame for stream 7 is sent or received."
573	if streamID%2 == 1 {
574		if streamID <= sc.maxClientStreamID {
575			return stateClosed, nil
576		}
577	} else {
578		if streamID <= sc.maxPushPromiseID {
579			return stateClosed, nil
580		}
581	}
582	return stateIdle, nil
583}
584
585// setConnState calls the net/http ConnState hook for this connection, if configured.
586// Note that the net/http package does StateNew and StateClosed for us.
587// There is currently no plan for StateHijacked or hijacking HTTP/2 connections.
588func (sc *serverConn) setConnState(state http.ConnState) {
589	if sc.hs.ConnState != nil {
590		sc.hs.ConnState(sc.conn, state)
591	}
592}
593
594func (sc *serverConn) vlogf(format string, args ...interface{}) {
595	if VerboseLogs {
596		sc.logf(format, args...)
597	}
598}
599
600func (sc *serverConn) logf(format string, args ...interface{}) {
601	if lg := sc.hs.ErrorLog; lg != nil {
602		lg.Printf(format, args...)
603	} else {
604		log.Printf(format, args...)
605	}
606}
607
608// errno returns v's underlying uintptr, else 0.
609//
610// TODO: remove this helper function once http2 can use build
611// tags. See comment in isClosedConnError.
612func errno(v error) uintptr {
613	if rv := reflect.ValueOf(v); rv.Kind() == reflect.Uintptr {
614		return uintptr(rv.Uint())
615	}
616	return 0
617}
618
619// isClosedConnError reports whether err is an error from use of a closed
620// network connection.
621func isClosedConnError(err error) bool {
622	if err == nil {
623		return false
624	}
625
626	// TODO: remove this string search and be more like the Windows
627	// case below. That might involve modifying the standard library
628	// to return better error types.
629	str := err.Error()
630	if strings.Contains(str, "use of closed network connection") {
631		return true
632	}
633
634	// TODO(bradfitz): x/tools/cmd/bundle doesn't really support
635	// build tags, so I can't make an http2_windows.go file with
636	// Windows-specific stuff. Fix that and move this, once we
637	// have a way to bundle this into std's net/http somehow.
638	if runtime.GOOS == "windows" {
639		if oe, ok := err.(*net.OpError); ok && oe.Op == "read" {
640			if se, ok := oe.Err.(*os.SyscallError); ok && se.Syscall == "wsarecv" {
641				const WSAECONNABORTED = 10053
642				const WSAECONNRESET = 10054
643				if n := errno(se.Err); n == WSAECONNRESET || n == WSAECONNABORTED {
644					return true
645				}
646			}
647		}
648	}
649	return false
650}
651
652func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
653	if err == nil {
654		return
655	}
656	if err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err) || err == errPrefaceTimeout {
657		// Boring, expected errors.
658		sc.vlogf(format, args...)
659	} else {
660		sc.logf(format, args...)
661	}
662}
663
664func (sc *serverConn) canonicalHeader(v string) string {
665	sc.serveG.check()
666	cv, ok := commonCanonHeader[v]
667	if ok {
668		return cv
669	}
670	cv, ok = sc.canonHeader[v]
671	if ok {
672		return cv
673	}
674	if sc.canonHeader == nil {
675		sc.canonHeader = make(map[string]string)
676	}
677	cv = http.CanonicalHeaderKey(v)
678	sc.canonHeader[v] = cv
679	return cv
680}
681
682type readFrameResult struct {
683	f   Frame // valid until readMore is called
684	err error
685
686	// readMore should be called once the consumer no longer needs or
687	// retains f. After readMore, f is invalid and more frames can be
688	// read.
689	readMore func()
690}
691
692// readFrames is the loop that reads incoming frames.
693// It takes care to only read one frame at a time, blocking until the
694// consumer is done with the frame.
695// It's run on its own goroutine.
696func (sc *serverConn) readFrames() {
697	gate := make(gate)
698	gateDone := gate.Done
699	for {
700		f, err := sc.framer.ReadFrame()
701		select {
702		case sc.readFrameCh <- readFrameResult{f, err, gateDone}:
703		case <-sc.doneServing:
704			return
705		}
706		select {
707		case <-gate:
708		case <-sc.doneServing:
709			return
710		}
711		if terminalReadFrameError(err) {
712			return
713		}
714	}
715}
716
717// frameWriteResult is the message passed from writeFrameAsync to the serve goroutine.
718type frameWriteResult struct {
719	wr  FrameWriteRequest // what was written (or attempted)
720	err error             // result of the writeFrame call
721}
722
723// writeFrameAsync runs in its own goroutine and writes a single frame
724// and then reports when it's done.
725// At most one goroutine can be running writeFrameAsync at a time per
726// serverConn.
727func (sc *serverConn) writeFrameAsync(wr FrameWriteRequest) {
728	err := wr.write.writeFrame(sc)
729	sc.wroteFrameCh <- frameWriteResult{wr, err}
730}
731
732func (sc *serverConn) closeAllStreamsOnConnClose() {
733	sc.serveG.check()
734	for _, st := range sc.streams {
735		sc.closeStream(st, errClientDisconnected)
736	}
737}
738
739func (sc *serverConn) stopShutdownTimer() {
740	sc.serveG.check()
741	if t := sc.shutdownTimer; t != nil {
742		t.Stop()
743	}
744}
745
746func (sc *serverConn) notePanic() {
747	// Note: this is for serverConn.serve panicking, not http.Handler code.
748	if testHookOnPanicMu != nil {
749		testHookOnPanicMu.Lock()
750		defer testHookOnPanicMu.Unlock()
751	}
752	if testHookOnPanic != nil {
753		if e := recover(); e != nil {
754			if testHookOnPanic(sc, e) {
755				panic(e)
756			}
757		}
758	}
759}
760
761func (sc *serverConn) serve() {
762	sc.serveG.check()
763	defer sc.notePanic()
764	defer sc.conn.Close()
765	defer sc.closeAllStreamsOnConnClose()
766	defer sc.stopShutdownTimer()
767	defer close(sc.doneServing) // unblocks handlers trying to send
768
769	if VerboseLogs {
770		sc.vlogf("http2: server connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
771	}
772
773	sc.writeFrame(FrameWriteRequest{
774		write: writeSettings{
775			{SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
776			{SettingMaxConcurrentStreams, sc.advMaxStreams},
777			{SettingMaxHeaderListSize, sc.maxHeaderListSize()},
778			{SettingInitialWindowSize, uint32(sc.srv.initialStreamRecvWindowSize())},
779		},
780	})
781	sc.unackedSettings++
782
783	// Each connection starts with intialWindowSize inflow tokens.
784	// If a higher value is configured, we add more tokens.
785	if diff := sc.srv.initialConnRecvWindowSize() - initialWindowSize; diff > 0 {
786		sc.sendWindowUpdate(nil, int(diff))
787	}
788
789	if err := sc.readPreface(); err != nil {
790		sc.condlogf(err, "http2: server: error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
791		return
792	}
793	// Now that we've got the preface, get us out of the
794	// "StateNew" state. We can't go directly to idle, though.
795	// Active means we read some data and anticipate a request. We'll
796	// do another Active when we get a HEADERS frame.
797	sc.setConnState(http.StateActive)
798	sc.setConnState(http.StateIdle)
799
800	if sc.srv.IdleTimeout != 0 {
801		sc.idleTimer = time.AfterFunc(sc.srv.IdleTimeout, sc.onIdleTimer)
802		defer sc.idleTimer.Stop()
803	}
804
805	go sc.readFrames() // closed by defer sc.conn.Close above
806
807	settingsTimer := time.AfterFunc(firstSettingsTimeout, sc.onSettingsTimer)
808	defer settingsTimer.Stop()
809
810	loopNum := 0
811	for {
812		loopNum++
813		select {
814		case wr := <-sc.wantWriteFrameCh:
815			if se, ok := wr.write.(StreamError); ok {
816				sc.resetStream(se)
817				break
818			}
819			sc.writeFrame(wr)
820		case res := <-sc.wroteFrameCh:
821			sc.wroteFrame(res)
822		case res := <-sc.readFrameCh:
823			if !sc.processFrameFromReader(res) {
824				return
825			}
826			res.readMore()
827			if settingsTimer != nil {
828				settingsTimer.Stop()
829				settingsTimer = nil
830			}
831		case m := <-sc.bodyReadCh:
832			sc.noteBodyRead(m.st, m.n)
833		case msg := <-sc.serveMsgCh:
834			switch v := msg.(type) {
835			case func(int):
836				v(loopNum) // for testing
837			case *serverMessage:
838				switch v {
839				case settingsTimerMsg:
840					sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
841					return
842				case idleTimerMsg:
843					sc.vlogf("connection is idle")
844					sc.goAway(ErrCodeNo)
845				case shutdownTimerMsg:
846					sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
847					return
848				case gracefulShutdownMsg:
849					sc.startGracefulShutdownInternal()
850				default:
851					panic("unknown timer")
852				}
853			case *startPushRequest:
854				sc.startPush(v)
855			default:
856				panic(fmt.Sprintf("unexpected type %T", v))
857			}
858		}
859
860		// Start the shutdown timer after sending a GOAWAY. When sending GOAWAY
861		// with no error code (graceful shutdown), don't start the timer until
862		// all open streams have been completed.
863		sentGoAway := sc.inGoAway && !sc.needToSendGoAway && !sc.writingFrame
864		gracefulShutdownComplete := sc.goAwayCode == ErrCodeNo && sc.curOpenStreams() == 0
865		if sentGoAway && sc.shutdownTimer == nil && (sc.goAwayCode != ErrCodeNo || gracefulShutdownComplete) {
866			sc.shutDownIn(goAwayTimeout)
867		}
868	}
869}
870
871func (sc *serverConn) awaitGracefulShutdown(sharedCh <-chan struct{}, privateCh chan struct{}) {
872	select {
873	case <-sc.doneServing:
874	case <-sharedCh:
875		close(privateCh)
876	}
877}
878
879type serverMessage int
880
881// Message values sent to serveMsgCh.
882var (
883	settingsTimerMsg    = new(serverMessage)
884	idleTimerMsg        = new(serverMessage)
885	shutdownTimerMsg    = new(serverMessage)
886	gracefulShutdownMsg = new(serverMessage)
887)
888
889func (sc *serverConn) onSettingsTimer() { sc.sendServeMsg(settingsTimerMsg) }
890func (sc *serverConn) onIdleTimer()     { sc.sendServeMsg(idleTimerMsg) }
891func (sc *serverConn) onShutdownTimer() { sc.sendServeMsg(shutdownTimerMsg) }
892
893func (sc *serverConn) sendServeMsg(msg interface{}) {
894	sc.serveG.checkNotOn() // NOT
895	select {
896	case sc.serveMsgCh <- msg:
897	case <-sc.doneServing:
898	}
899}
900
901var errPrefaceTimeout = errors.New("timeout waiting for client preface")
902
903// readPreface reads the ClientPreface greeting from the peer or
904// returns errPrefaceTimeout on timeout, or an error if the greeting
905// is invalid.
906func (sc *serverConn) readPreface() error {
907	errc := make(chan error, 1)
908	go func() {
909		// Read the client preface
910		buf := make([]byte, len(ClientPreface))
911		if _, err := io.ReadFull(sc.conn, buf); err != nil {
912			errc <- err
913		} else if !bytes.Equal(buf, clientPreface) {
914			errc <- fmt.Errorf("bogus greeting %q", buf)
915		} else {
916			errc <- nil
917		}
918	}()
919	timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
920	defer timer.Stop()
921	select {
922	case <-timer.C:
923		return errPrefaceTimeout
924	case err := <-errc:
925		if err == nil {
926			if VerboseLogs {
927				sc.vlogf("http2: server: client %v said hello", sc.conn.RemoteAddr())
928			}
929		}
930		return err
931	}
932}
933
934var errChanPool = sync.Pool{
935	New: func() interface{} { return make(chan error, 1) },
936}
937
938var writeDataPool = sync.Pool{
939	New: func() interface{} { return new(writeData) },
940}
941
942// writeDataFromHandler writes DATA response frames from a handler on
943// the given stream.
944func (sc *serverConn) writeDataFromHandler(stream *stream, data []byte, endStream bool) error {
945	ch := errChanPool.Get().(chan error)
946	writeArg := writeDataPool.Get().(*writeData)
947	*writeArg = writeData{stream.id, data, endStream}
948	err := sc.writeFrameFromHandler(FrameWriteRequest{
949		write:  writeArg,
950		stream: stream,
951		done:   ch,
952	})
953	if err != nil {
954		return err
955	}
956	var frameWriteDone bool // the frame write is done (successfully or not)
957	select {
958	case err = <-ch:
959		frameWriteDone = true
960	case <-sc.doneServing:
961		return errClientDisconnected
962	case <-stream.cw:
963		// If both ch and stream.cw were ready (as might
964		// happen on the final Write after an http.Handler
965		// ends), prefer the write result. Otherwise this
966		// might just be us successfully closing the stream.
967		// The writeFrameAsync and serve goroutines guarantee
968		// that the ch send will happen before the stream.cw
969		// close.
970		select {
971		case err = <-ch:
972			frameWriteDone = true
973		default:
974			return errStreamClosed
975		}
976	}
977	errChanPool.Put(ch)
978	if frameWriteDone {
979		writeDataPool.Put(writeArg)
980	}
981	return err
982}
983
984// writeFrameFromHandler sends wr to sc.wantWriteFrameCh, but aborts
985// if the connection has gone away.
986//
987// This must not be run from the serve goroutine itself, else it might
988// deadlock writing to sc.wantWriteFrameCh (which is only mildly
989// buffered and is read by serve itself). If you're on the serve
990// goroutine, call writeFrame instead.
991func (sc *serverConn) writeFrameFromHandler(wr FrameWriteRequest) error {
992	sc.serveG.checkNotOn() // NOT
993	select {
994	case sc.wantWriteFrameCh <- wr:
995		return nil
996	case <-sc.doneServing:
997		// Serve loop is gone.
998		// Client has closed their connection to the server.
999		return errClientDisconnected
1000	}
1001}
1002
1003// writeFrame schedules a frame to write and sends it if there's nothing
1004// already being written.
1005//
1006// There is no pushback here (the serve goroutine never blocks). It's
1007// the http.Handlers that block, waiting for their previous frames to
1008// make it onto the wire
1009//
1010// If you're not on the serve goroutine, use writeFrameFromHandler instead.
1011func (sc *serverConn) writeFrame(wr FrameWriteRequest) {
1012	sc.serveG.check()
1013
1014	// If true, wr will not be written and wr.done will not be signaled.
1015	var ignoreWrite bool
1016
1017	// We are not allowed to write frames on closed streams. RFC 7540 Section
1018	// 5.1.1 says: "An endpoint MUST NOT send frames other than PRIORITY on
1019	// a closed stream." Our server never sends PRIORITY, so that exception
1020	// does not apply.
1021	//
1022	// The serverConn might close an open stream while the stream's handler
1023	// is still running. For example, the server might close a stream when it
1024	// receives bad data from the client. If this happens, the handler might
1025	// attempt to write a frame after the stream has been closed (since the
1026	// handler hasn't yet been notified of the close). In this case, we simply
1027	// ignore the frame. The handler will notice that the stream is closed when
1028	// it waits for the frame to be written.
1029	//
1030	// As an exception to this rule, we allow sending RST_STREAM after close.
1031	// This allows us to immediately reject new streams without tracking any
1032	// state for those streams (except for the queued RST_STREAM frame). This
1033	// may result in duplicate RST_STREAMs in some cases, but the client should
1034	// ignore those.
1035	if wr.StreamID() != 0 {
1036		_, isReset := wr.write.(StreamError)
1037		if state, _ := sc.state(wr.StreamID()); state == stateClosed && !isReset {
1038			ignoreWrite = true
1039		}
1040	}
1041
1042	// Don't send a 100-continue response if we've already sent headers.
1043	// See golang.org/issue/14030.
1044	switch wr.write.(type) {
1045	case *writeResHeaders:
1046		wr.stream.wroteHeaders = true
1047	case write100ContinueHeadersFrame:
1048		if wr.stream.wroteHeaders {
1049			// We do not need to notify wr.done because this frame is
1050			// never written with wr.done != nil.
1051			if wr.done != nil {
1052				panic("wr.done != nil for write100ContinueHeadersFrame")
1053			}
1054			ignoreWrite = true
1055		}
1056	}
1057
1058	if !ignoreWrite {
1059		sc.writeSched.Push(wr)
1060	}
1061	sc.scheduleFrameWrite()
1062}
1063
1064// startFrameWrite starts a goroutine to write wr (in a separate
1065// goroutine since that might block on the network), and updates the
1066// serve goroutine's state about the world, updated from info in wr.
1067func (sc *serverConn) startFrameWrite(wr FrameWriteRequest) {
1068	sc.serveG.check()
1069	if sc.writingFrame {
1070		panic("internal error: can only be writing one frame at a time")
1071	}
1072
1073	st := wr.stream
1074	if st != nil {
1075		switch st.state {
1076		case stateHalfClosedLocal:
1077			switch wr.write.(type) {
1078			case StreamError, handlerPanicRST, writeWindowUpdate:
1079				// RFC 7540 Section 5.1 allows sending RST_STREAM, PRIORITY, and WINDOW_UPDATE
1080				// in this state. (We never send PRIORITY from the server, so that is not checked.)
1081			default:
1082				panic(fmt.Sprintf("internal error: attempt to send frame on a half-closed-local stream: %v", wr))
1083			}
1084		case stateClosed:
1085			panic(fmt.Sprintf("internal error: attempt to send frame on a closed stream: %v", wr))
1086		}
1087	}
1088	if wpp, ok := wr.write.(*writePushPromise); ok {
1089		var err error
1090		wpp.promisedID, err = wpp.allocatePromisedID()
1091		if err != nil {
1092			sc.writingFrameAsync = false
1093			wr.replyToWriter(err)
1094			return
1095		}
1096	}
1097
1098	sc.writingFrame = true
1099	sc.needsFrameFlush = true
1100	if wr.write.staysWithinBuffer(sc.bw.Available()) {
1101		sc.writingFrameAsync = false
1102		err := wr.write.writeFrame(sc)
1103		sc.wroteFrame(frameWriteResult{wr, err})
1104	} else {
1105		sc.writingFrameAsync = true
1106		go sc.writeFrameAsync(wr)
1107	}
1108}
1109
1110// errHandlerPanicked is the error given to any callers blocked in a read from
1111// Request.Body when the main goroutine panics. Since most handlers read in the
1112// the main ServeHTTP goroutine, this will show up rarely.
1113var errHandlerPanicked = errors.New("http2: handler panicked")
1114
1115// wroteFrame is called on the serve goroutine with the result of
1116// whatever happened on writeFrameAsync.
1117func (sc *serverConn) wroteFrame(res frameWriteResult) {
1118	sc.serveG.check()
1119	if !sc.writingFrame {
1120		panic("internal error: expected to be already writing a frame")
1121	}
1122	sc.writingFrame = false
1123	sc.writingFrameAsync = false
1124
1125	wr := res.wr
1126
1127	if writeEndsStream(wr.write) {
1128		st := wr.stream
1129		if st == nil {
1130			panic("internal error: expecting non-nil stream")
1131		}
1132		switch st.state {
1133		case stateOpen:
1134			// Here we would go to stateHalfClosedLocal in
1135			// theory, but since our handler is done and
1136			// the net/http package provides no mechanism
1137			// for closing a ResponseWriter while still
1138			// reading data (see possible TODO at top of
1139			// this file), we go into closed state here
1140			// anyway, after telling the peer we're
1141			// hanging up on them. We'll transition to
1142			// stateClosed after the RST_STREAM frame is
1143			// written.
1144			st.state = stateHalfClosedLocal
1145			// Section 8.1: a server MAY request that the client abort
1146			// transmission of a request without error by sending a
1147			// RST_STREAM with an error code of NO_ERROR after sending
1148			// a complete response.
1149			sc.resetStream(streamError(st.id, ErrCodeNo))
1150		case stateHalfClosedRemote:
1151			sc.closeStream(st, errHandlerComplete)
1152		}
1153	} else {
1154		switch v := wr.write.(type) {
1155		case StreamError:
1156			// st may be unknown if the RST_STREAM was generated to reject bad input.
1157			if st, ok := sc.streams[v.StreamID]; ok {
1158				sc.closeStream(st, v)
1159			}
1160		case handlerPanicRST:
1161			sc.closeStream(wr.stream, errHandlerPanicked)
1162		}
1163	}
1164
1165	// Reply (if requested) to unblock the ServeHTTP goroutine.
1166	wr.replyToWriter(res.err)
1167
1168	sc.scheduleFrameWrite()
1169}
1170
1171// scheduleFrameWrite tickles the frame writing scheduler.
1172//
1173// If a frame is already being written, nothing happens. This will be called again
1174// when the frame is done being written.
1175//
1176// If a frame isn't being written we need to send one, the best frame
1177// to send is selected, preferring first things that aren't
1178// stream-specific (e.g. ACKing settings), and then finding the
1179// highest priority stream.
1180//
1181// If a frame isn't being written and there's nothing else to send, we
1182// flush the write buffer.
1183func (sc *serverConn) scheduleFrameWrite() {
1184	sc.serveG.check()
1185	if sc.writingFrame || sc.inFrameScheduleLoop {
1186		return
1187	}
1188	sc.inFrameScheduleLoop = true
1189	for !sc.writingFrameAsync {
1190		if sc.needToSendGoAway {
1191			sc.needToSendGoAway = false
1192			sc.startFrameWrite(FrameWriteRequest{
1193				write: &writeGoAway{
1194					maxStreamID: sc.maxClientStreamID,
1195					code:        sc.goAwayCode,
1196				},
1197			})
1198			continue
1199		}
1200		if sc.needToSendSettingsAck {
1201			sc.needToSendSettingsAck = false
1202			sc.startFrameWrite(FrameWriteRequest{write: writeSettingsAck{}})
1203			continue
1204		}
1205		if !sc.inGoAway || sc.goAwayCode == ErrCodeNo {
1206			if wr, ok := sc.writeSched.Pop(); ok {
1207				sc.startFrameWrite(wr)
1208				continue
1209			}
1210		}
1211		if sc.needsFrameFlush {
1212			sc.startFrameWrite(FrameWriteRequest{write: flushFrameWriter{}})
1213			sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
1214			continue
1215		}
1216		break
1217	}
1218	sc.inFrameScheduleLoop = false
1219}
1220
1221// startGracefulShutdown gracefully shuts down a connection. This
1222// sends GOAWAY with ErrCodeNo to tell the client we're gracefully
1223// shutting down. The connection isn't closed until all current
1224// streams are done.
1225//
1226// startGracefulShutdown returns immediately; it does not wait until
1227// the connection has shut down.
1228func (sc *serverConn) startGracefulShutdown() {
1229	sc.serveG.checkNotOn() // NOT
1230	sc.shutdownOnce.Do(func() { sc.sendServeMsg(gracefulShutdownMsg) })
1231}
1232
1233// After sending GOAWAY, the connection will close after goAwayTimeout.
1234// If we close the connection immediately after sending GOAWAY, there may
1235// be unsent data in our kernel receive buffer, which will cause the kernel
1236// to send a TCP RST on close() instead of a FIN. This RST will abort the
1237// connection immediately, whether or not the client had received the GOAWAY.
1238//
1239// Ideally we should delay for at least 1 RTT + epsilon so the client has
1240// a chance to read the GOAWAY and stop sending messages. Measuring RTT
1241// is hard, so we approximate with 1 second. See golang.org/issue/18701.
1242//
1243// This is a var so it can be shorter in tests, where all requests uses the
1244// loopback interface making the expected RTT very small.
1245//
1246// TODO: configurable?
1247var goAwayTimeout = 1 * time.Second
1248
1249func (sc *serverConn) startGracefulShutdownInternal() {
1250	sc.goAway(ErrCodeNo)
1251}
1252
1253func (sc *serverConn) goAway(code ErrCode) {
1254	sc.serveG.check()
1255	if sc.inGoAway {
1256		return
1257	}
1258	sc.inGoAway = true
1259	sc.needToSendGoAway = true
1260	sc.goAwayCode = code
1261	sc.scheduleFrameWrite()
1262}
1263
1264func (sc *serverConn) shutDownIn(d time.Duration) {
1265	sc.serveG.check()
1266	sc.shutdownTimer = time.AfterFunc(d, sc.onShutdownTimer)
1267}
1268
1269func (sc *serverConn) resetStream(se StreamError) {
1270	sc.serveG.check()
1271	sc.writeFrame(FrameWriteRequest{write: se})
1272	if st, ok := sc.streams[se.StreamID]; ok {
1273		st.resetQueued = true
1274	}
1275}
1276
1277// processFrameFromReader processes the serve loop's read from readFrameCh from the
1278// frame-reading goroutine.
1279// processFrameFromReader returns whether the connection should be kept open.
1280func (sc *serverConn) processFrameFromReader(res readFrameResult) bool {
1281	sc.serveG.check()
1282	err := res.err
1283	if err != nil {
1284		if err == ErrFrameTooLarge {
1285			sc.goAway(ErrCodeFrameSize)
1286			return true // goAway will close the loop
1287		}
1288		clientGone := err == io.EOF || err == io.ErrUnexpectedEOF || isClosedConnError(err)
1289		if clientGone {
1290			// TODO: could we also get into this state if
1291			// the peer does a half close
1292			// (e.g. CloseWrite) because they're done
1293			// sending frames but they're still wanting
1294			// our open replies?  Investigate.
1295			// TODO: add CloseWrite to crypto/tls.Conn first
1296			// so we have a way to test this? I suppose
1297			// just for testing we could have a non-TLS mode.
1298			return false
1299		}
1300	} else {
1301		f := res.f
1302		if VerboseLogs {
1303			sc.vlogf("http2: server read frame %v", summarizeFrame(f))
1304		}
1305		err = sc.processFrame(f)
1306		if err == nil {
1307			return true
1308		}
1309	}
1310
1311	switch ev := err.(type) {
1312	case StreamError:
1313		sc.resetStream(ev)
1314		return true
1315	case goAwayFlowError:
1316		sc.goAway(ErrCodeFlowControl)
1317		return true
1318	case ConnectionError:
1319		sc.logf("http2: server connection error from %v: %v", sc.conn.RemoteAddr(), ev)
1320		sc.goAway(ErrCode(ev))
1321		return true // goAway will handle shutdown
1322	default:
1323		if res.err != nil {
1324			sc.vlogf("http2: server closing client connection; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
1325		} else {
1326			sc.logf("http2: server closing client connection: %v", err)
1327		}
1328		return false
1329	}
1330}
1331
1332func (sc *serverConn) processFrame(f Frame) error {
1333	sc.serveG.check()
1334
1335	// First frame received must be SETTINGS.
1336	if !sc.sawFirstSettings {
1337		if _, ok := f.(*SettingsFrame); !ok {
1338			return ConnectionError(ErrCodeProtocol)
1339		}
1340		sc.sawFirstSettings = true
1341	}
1342
1343	switch f := f.(type) {
1344	case *SettingsFrame:
1345		return sc.processSettings(f)
1346	case *MetaHeadersFrame:
1347		return sc.processHeaders(f)
1348	case *WindowUpdateFrame:
1349		return sc.processWindowUpdate(f)
1350	case *PingFrame:
1351		return sc.processPing(f)
1352	case *DataFrame:
1353		return sc.processData(f)
1354	case *RSTStreamFrame:
1355		return sc.processResetStream(f)
1356	case *PriorityFrame:
1357		return sc.processPriority(f)
1358	case *GoAwayFrame:
1359		return sc.processGoAway(f)
1360	case *PushPromiseFrame:
1361		// A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
1362		// frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
1363		return ConnectionError(ErrCodeProtocol)
1364	default:
1365		sc.vlogf("http2: server ignoring frame: %v", f.Header())
1366		return nil
1367	}
1368}
1369
1370func (sc *serverConn) processPing(f *PingFrame) error {
1371	sc.serveG.check()
1372	if f.IsAck() {
1373		// 6.7 PING: " An endpoint MUST NOT respond to PING frames
1374		// containing this flag."
1375		return nil
1376	}
1377	if f.StreamID != 0 {
1378		// "PING frames are not associated with any individual
1379		// stream. If a PING frame is received with a stream
1380		// identifier field value other than 0x0, the recipient MUST
1381		// respond with a connection error (Section 5.4.1) of type
1382		// PROTOCOL_ERROR."
1383		return ConnectionError(ErrCodeProtocol)
1384	}
1385	if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
1386		return nil
1387	}
1388	sc.writeFrame(FrameWriteRequest{write: writePingAck{f}})
1389	return nil
1390}
1391
1392func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
1393	sc.serveG.check()
1394	switch {
1395	case f.StreamID != 0: // stream-level flow control
1396		state, st := sc.state(f.StreamID)
1397		if state == stateIdle {
1398			// Section 5.1: "Receiving any frame other than HEADERS
1399			// or PRIORITY on a stream in this state MUST be
1400			// treated as a connection error (Section 5.4.1) of
1401			// type PROTOCOL_ERROR."
1402			return ConnectionError(ErrCodeProtocol)
1403		}
1404		if st == nil {
1405			// "WINDOW_UPDATE can be sent by a peer that has sent a
1406			// frame bearing the END_STREAM flag. This means that a
1407			// receiver could receive a WINDOW_UPDATE frame on a "half
1408			// closed (remote)" or "closed" stream. A receiver MUST
1409			// NOT treat this as an error, see Section 5.1."
1410			return nil
1411		}
1412		if !st.flow.add(int32(f.Increment)) {
1413			return streamError(f.StreamID, ErrCodeFlowControl)
1414		}
1415	default: // connection-level flow control
1416		if !sc.flow.add(int32(f.Increment)) {
1417			return goAwayFlowError{}
1418		}
1419	}
1420	sc.scheduleFrameWrite()
1421	return nil
1422}
1423
1424func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
1425	sc.serveG.check()
1426
1427	state, st := sc.state(f.StreamID)
1428	if state == stateIdle {
1429		// 6.4 "RST_STREAM frames MUST NOT be sent for a
1430		// stream in the "idle" state. If a RST_STREAM frame
1431		// identifying an idle stream is received, the
1432		// recipient MUST treat this as a connection error
1433		// (Section 5.4.1) of type PROTOCOL_ERROR.
1434		return ConnectionError(ErrCodeProtocol)
1435	}
1436	if st != nil {
1437		st.cancelCtx()
1438		sc.closeStream(st, streamError(f.StreamID, f.ErrCode))
1439	}
1440	return nil
1441}
1442
1443func (sc *serverConn) closeStream(st *stream, err error) {
1444	sc.serveG.check()
1445	if st.state == stateIdle || st.state == stateClosed {
1446		panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
1447	}
1448	st.state = stateClosed
1449	if st.writeDeadline != nil {
1450		st.writeDeadline.Stop()
1451	}
1452	if st.isPushed() {
1453		sc.curPushedStreams--
1454	} else {
1455		sc.curClientStreams--
1456	}
1457	delete(sc.streams, st.id)
1458	if len(sc.streams) == 0 {
1459		sc.setConnState(http.StateIdle)
1460		if sc.srv.IdleTimeout != 0 {
1461			sc.idleTimer.Reset(sc.srv.IdleTimeout)
1462		}
1463		if h1ServerKeepAlivesDisabled(sc.hs) {
1464			sc.startGracefulShutdownInternal()
1465		}
1466	}
1467	if p := st.body; p != nil {
1468		// Return any buffered unread bytes worth of conn-level flow control.
1469		// See golang.org/issue/16481
1470		sc.sendWindowUpdate(nil, p.Len())
1471
1472		p.CloseWithError(err)
1473	}
1474	st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
1475	sc.writeSched.CloseStream(st.id)
1476}
1477
1478func (sc *serverConn) processSettings(f *SettingsFrame) error {
1479	sc.serveG.check()
1480	if f.IsAck() {
1481		sc.unackedSettings--
1482		if sc.unackedSettings < 0 {
1483			// Why is the peer ACKing settings we never sent?
1484			// The spec doesn't mention this case, but
1485			// hang up on them anyway.
1486			return ConnectionError(ErrCodeProtocol)
1487		}
1488		return nil
1489	}
1490	if err := f.ForeachSetting(sc.processSetting); err != nil {
1491		return err
1492	}
1493	sc.needToSendSettingsAck = true
1494	sc.scheduleFrameWrite()
1495	return nil
1496}
1497
1498func (sc *serverConn) processSetting(s Setting) error {
1499	sc.serveG.check()
1500	if err := s.Valid(); err != nil {
1501		return err
1502	}
1503	if VerboseLogs {
1504		sc.vlogf("http2: server processing setting %v", s)
1505	}
1506	switch s.ID {
1507	case SettingHeaderTableSize:
1508		sc.headerTableSize = s.Val
1509		sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
1510	case SettingEnablePush:
1511		sc.pushEnabled = s.Val != 0
1512	case SettingMaxConcurrentStreams:
1513		sc.clientMaxStreams = s.Val
1514	case SettingInitialWindowSize:
1515		return sc.processSettingInitialWindowSize(s.Val)
1516	case SettingMaxFrameSize:
1517		sc.maxFrameSize = int32(s.Val) // the maximum valid s.Val is < 2^31
1518	case SettingMaxHeaderListSize:
1519		sc.peerMaxHeaderListSize = s.Val
1520	default:
1521		// Unknown setting: "An endpoint that receives a SETTINGS
1522		// frame with any unknown or unsupported identifier MUST
1523		// ignore that setting."
1524		if VerboseLogs {
1525			sc.vlogf("http2: server ignoring unknown setting %v", s)
1526		}
1527	}
1528	return nil
1529}
1530
1531func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
1532	sc.serveG.check()
1533	// Note: val already validated to be within range by
1534	// processSetting's Valid call.
1535
1536	// "A SETTINGS frame can alter the initial flow control window
1537	// size for all current streams. When the value of
1538	// SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
1539	// adjust the size of all stream flow control windows that it
1540	// maintains by the difference between the new value and the
1541	// old value."
1542	old := sc.initialStreamSendWindowSize
1543	sc.initialStreamSendWindowSize = int32(val)
1544	growth := int32(val) - old // may be negative
1545	for _, st := range sc.streams {
1546		if !st.flow.add(growth) {
1547			// 6.9.2 Initial Flow Control Window Size
1548			// "An endpoint MUST treat a change to
1549			// SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
1550			// control window to exceed the maximum size as a
1551			// connection error (Section 5.4.1) of type
1552			// FLOW_CONTROL_ERROR."
1553			return ConnectionError(ErrCodeFlowControl)
1554		}
1555	}
1556	return nil
1557}
1558
1559func (sc *serverConn) processData(f *DataFrame) error {
1560	sc.serveG.check()
1561	if sc.inGoAway && sc.goAwayCode != ErrCodeNo {
1562		return nil
1563	}
1564	data := f.Data()
1565
1566	// "If a DATA frame is received whose stream is not in "open"
1567	// or "half closed (local)" state, the recipient MUST respond
1568	// with a stream error (Section 5.4.2) of type STREAM_CLOSED."
1569	id := f.Header().StreamID
1570	state, st := sc.state(id)
1571	if id == 0 || state == stateIdle {
1572		// Section 5.1: "Receiving any frame other than HEADERS
1573		// or PRIORITY on a stream in this state MUST be
1574		// treated as a connection error (Section 5.4.1) of
1575		// type PROTOCOL_ERROR."
1576		return ConnectionError(ErrCodeProtocol)
1577	}
1578	if st == nil || state != stateOpen || st.gotTrailerHeader || st.resetQueued {
1579		// This includes sending a RST_STREAM if the stream is
1580		// in stateHalfClosedLocal (which currently means that
1581		// the http.Handler returned, so it's done reading &
1582		// done writing). Try to stop the client from sending
1583		// more DATA.
1584
1585		// But still enforce their connection-level flow control,
1586		// and return any flow control bytes since we're not going
1587		// to consume them.
1588		if sc.inflow.available() < int32(f.Length) {
1589			return streamError(id, ErrCodeFlowControl)
1590		}
1591		// Deduct the flow control from inflow, since we're
1592		// going to immediately add it back in
1593		// sendWindowUpdate, which also schedules sending the
1594		// frames.
1595		sc.inflow.take(int32(f.Length))
1596		sc.sendWindowUpdate(nil, int(f.Length)) // conn-level
1597
1598		if st != nil && st.resetQueued {
1599			// Already have a stream error in flight. Don't send another.
1600			return nil
1601		}
1602		return streamError(id, ErrCodeStreamClosed)
1603	}
1604	if st.body == nil {
1605		panic("internal error: should have a body in this state")
1606	}
1607
1608	// Sender sending more than they'd declared?
1609	if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
1610		st.body.CloseWithError(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
1611		// RFC 7540, sec 8.1.2.6: A request or response is also malformed if the
1612		// value of a content-length header field does not equal the sum of the
1613		// DATA frame payload lengths that form the body.
1614		return streamError(id, ErrCodeProtocol)
1615	}
1616	if f.Length > 0 {
1617		// Check whether the client has flow control quota.
1618		if st.inflow.available() < int32(f.Length) {
1619			return streamError(id, ErrCodeFlowControl)
1620		}
1621		st.inflow.take(int32(f.Length))
1622
1623		if len(data) > 0 {
1624			wrote, err := st.body.Write(data)
1625			if err != nil {
1626				return streamError(id, ErrCodeStreamClosed)
1627			}
1628			if wrote != len(data) {
1629				panic("internal error: bad Writer")
1630			}
1631			st.bodyBytes += int64(len(data))
1632		}
1633
1634		// Return any padded flow control now, since we won't
1635		// refund it later on body reads.
1636		if pad := int32(f.Length) - int32(len(data)); pad > 0 {
1637			sc.sendWindowUpdate32(nil, pad)
1638			sc.sendWindowUpdate32(st, pad)
1639		}
1640	}
1641	if f.StreamEnded() {
1642		st.endStream()
1643	}
1644	return nil
1645}
1646
1647func (sc *serverConn) processGoAway(f *GoAwayFrame) error {
1648	sc.serveG.check()
1649	if f.ErrCode != ErrCodeNo {
1650		sc.logf("http2: received GOAWAY %+v, starting graceful shutdown", f)
1651	} else {
1652		sc.vlogf("http2: received GOAWAY %+v, starting graceful shutdown", f)
1653	}
1654	sc.startGracefulShutdownInternal()
1655	// http://tools.ietf.org/html/rfc7540#section-6.8
1656	// We should not create any new streams, which means we should disable push.
1657	sc.pushEnabled = false
1658	return nil
1659}
1660
1661// isPushed reports whether the stream is server-initiated.
1662func (st *stream) isPushed() bool {
1663	return st.id%2 == 0
1664}
1665
1666// endStream closes a Request.Body's pipe. It is called when a DATA
1667// frame says a request body is over (or after trailers).
1668func (st *stream) endStream() {
1669	sc := st.sc
1670	sc.serveG.check()
1671
1672	if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
1673		st.body.CloseWithError(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
1674			st.declBodyBytes, st.bodyBytes))
1675	} else {
1676		st.body.closeWithErrorAndCode(io.EOF, st.copyTrailersToHandlerRequest)
1677		st.body.CloseWithError(io.EOF)
1678	}
1679	st.state = stateHalfClosedRemote
1680}
1681
1682// copyTrailersToHandlerRequest is run in the Handler's goroutine in
1683// its Request.Body.Read just before it gets io.EOF.
1684func (st *stream) copyTrailersToHandlerRequest() {
1685	for k, vv := range st.trailer {
1686		if _, ok := st.reqTrailer[k]; ok {
1687			// Only copy it over it was pre-declared.
1688			st.reqTrailer[k] = vv
1689		}
1690	}
1691}
1692
1693// onWriteTimeout is run on its own goroutine (from time.AfterFunc)
1694// when the stream's WriteTimeout has fired.
1695func (st *stream) onWriteTimeout() {
1696	st.sc.writeFrameFromHandler(FrameWriteRequest{write: streamError(st.id, ErrCodeInternal)})
1697}
1698
1699func (sc *serverConn) processHeaders(f *MetaHeadersFrame) error {
1700	sc.serveG.check()
1701	id := f.StreamID
1702	if sc.inGoAway {
1703		// Ignore.
1704		return nil
1705	}
1706	// http://tools.ietf.org/html/rfc7540#section-5.1.1
1707	// Streams initiated by a client MUST use odd-numbered stream
1708	// identifiers. [...] An endpoint that receives an unexpected
1709	// stream identifier MUST respond with a connection error
1710	// (Section 5.4.1) of type PROTOCOL_ERROR.
1711	if id%2 != 1 {
1712		return ConnectionError(ErrCodeProtocol)
1713	}
1714	// A HEADERS frame can be used to create a new stream or
1715	// send a trailer for an open one. If we already have a stream
1716	// open, let it process its own HEADERS frame (trailers at this
1717	// point, if it's valid).
1718	if st := sc.streams[f.StreamID]; st != nil {
1719		if st.resetQueued {
1720			// We're sending RST_STREAM to close the stream, so don't bother
1721			// processing this frame.
1722			return nil
1723		}
1724		return st.processTrailerHeaders(f)
1725	}
1726
1727	// [...] The identifier of a newly established stream MUST be
1728	// numerically greater than all streams that the initiating
1729	// endpoint has opened or reserved. [...]  An endpoint that
1730	// receives an unexpected stream identifier MUST respond with
1731	// a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
1732	if id <= sc.maxClientStreamID {
1733		return ConnectionError(ErrCodeProtocol)
1734	}
1735	sc.maxClientStreamID = id
1736
1737	if sc.idleTimer != nil {
1738		sc.idleTimer.Stop()
1739	}
1740
1741	// http://tools.ietf.org/html/rfc7540#section-5.1.2
1742	// [...] Endpoints MUST NOT exceed the limit set by their peer. An
1743	// endpoint that receives a HEADERS frame that causes their
1744	// advertised concurrent stream limit to be exceeded MUST treat
1745	// this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR
1746	// or REFUSED_STREAM.
1747	if sc.curClientStreams+1 > sc.advMaxStreams {
1748		if sc.unackedSettings == 0 {
1749			// They should know better.
1750			return streamError(id, ErrCodeProtocol)
1751		}
1752		// Assume it's a network race, where they just haven't
1753		// received our last SETTINGS update. But actually
1754		// this can't happen yet, because we don't yet provide
1755		// a way for users to adjust server parameters at
1756		// runtime.
1757		return streamError(id, ErrCodeRefusedStream)
1758	}
1759
1760	initialState := stateOpen
1761	if f.StreamEnded() {
1762		initialState = stateHalfClosedRemote
1763	}
1764	st := sc.newStream(id, 0, initialState)
1765
1766	if f.HasPriority() {
1767		if err := checkPriority(f.StreamID, f.Priority); err != nil {
1768			return err
1769		}
1770		sc.writeSched.AdjustStream(st.id, f.Priority)
1771	}
1772
1773	rw, req, err := sc.newWriterAndRequest(st, f)
1774	if err != nil {
1775		return err
1776	}
1777	st.reqTrailer = req.Trailer
1778	if st.reqTrailer != nil {
1779		st.trailer = make(http.Header)
1780	}
1781	st.body = req.Body.(*requestBody).pipe // may be nil
1782	st.declBodyBytes = req.ContentLength
1783
1784	handler := sc.handler.ServeHTTP
1785	if f.Truncated {
1786		// Their header list was too long. Send a 431 error.
1787		handler = handleHeaderListTooLong
1788	} else if err := checkValidHTTP2RequestHeaders(req.Header); err != nil {
1789		handler = new400Handler(err)
1790	}
1791
1792	// The net/http package sets the read deadline from the
1793	// http.Server.ReadTimeout during the TLS handshake, but then
1794	// passes the connection off to us with the deadline already
1795	// set. Disarm it here after the request headers are read,
1796	// similar to how the http1 server works. Here it's
1797	// technically more like the http1 Server's ReadHeaderTimeout
1798	// (in Go 1.8), though. That's a more sane option anyway.
1799	if sc.hs.ReadTimeout != 0 {
1800		sc.conn.SetReadDeadline(time.Time{})
1801	}
1802
1803	go sc.runHandler(rw, req, handler)
1804	return nil
1805}
1806
1807func (st *stream) processTrailerHeaders(f *MetaHeadersFrame) error {
1808	sc := st.sc
1809	sc.serveG.check()
1810	if st.gotTrailerHeader {
1811		return ConnectionError(ErrCodeProtocol)
1812	}
1813	st.gotTrailerHeader = true
1814	if !f.StreamEnded() {
1815		return streamError(st.id, ErrCodeProtocol)
1816	}
1817
1818	if len(f.PseudoFields()) > 0 {
1819		return streamError(st.id, ErrCodeProtocol)
1820	}
1821	if st.trailer != nil {
1822		for _, hf := range f.RegularFields() {
1823			key := sc.canonicalHeader(hf.Name)
1824			if !httpguts.ValidTrailerHeader(key) {
1825				// TODO: send more details to the peer somehow. But http2 has
1826				// no way to send debug data at a stream level. Discuss with
1827				// HTTP folk.
1828				return streamError(st.id, ErrCodeProtocol)
1829			}
1830			st.trailer[key] = append(st.trailer[key], hf.Value)
1831		}
1832	}
1833	st.endStream()
1834	return nil
1835}
1836
1837func checkPriority(streamID uint32, p PriorityParam) error {
1838	if streamID == p.StreamDep {
1839		// Section 5.3.1: "A stream cannot depend on itself. An endpoint MUST treat
1840		// this as a stream error (Section 5.4.2) of type PROTOCOL_ERROR."
1841		// Section 5.3.3 says that a stream can depend on one of its dependencies,
1842		// so it's only self-dependencies that are forbidden.
1843		return streamError(streamID, ErrCodeProtocol)
1844	}
1845	return nil
1846}
1847
1848func (sc *serverConn) processPriority(f *PriorityFrame) error {
1849	if sc.inGoAway {
1850		return nil
1851	}
1852	if err := checkPriority(f.StreamID, f.PriorityParam); err != nil {
1853		return err
1854	}
1855	sc.writeSched.AdjustStream(f.StreamID, f.PriorityParam)
1856	return nil
1857}
1858
1859func (sc *serverConn) newStream(id, pusherID uint32, state streamState) *stream {
1860	sc.serveG.check()
1861	if id == 0 {
1862		panic("internal error: cannot create stream with id 0")
1863	}
1864
1865	ctx, cancelCtx := contextWithCancel(sc.baseCtx)
1866	st := &stream{
1867		sc:        sc,
1868		id:        id,
1869		state:     state,
1870		ctx:       ctx,
1871		cancelCtx: cancelCtx,
1872	}
1873	st.cw.Init()
1874	st.flow.conn = &sc.flow // link to conn-level counter
1875	st.flow.add(sc.initialStreamSendWindowSize)
1876	st.inflow.conn = &sc.inflow // link to conn-level counter
1877	st.inflow.add(sc.srv.initialStreamRecvWindowSize())
1878	if sc.hs.WriteTimeout != 0 {
1879		st.writeDeadline = time.AfterFunc(sc.hs.WriteTimeout, st.onWriteTimeout)
1880	}
1881
1882	sc.streams[id] = st
1883	sc.writeSched.OpenStream(st.id, OpenStreamOptions{PusherID: pusherID})
1884	if st.isPushed() {
1885		sc.curPushedStreams++
1886	} else {
1887		sc.curClientStreams++
1888	}
1889	if sc.curOpenStreams() == 1 {
1890		sc.setConnState(http.StateActive)
1891	}
1892
1893	return st
1894}
1895
1896func (sc *serverConn) newWriterAndRequest(st *stream, f *MetaHeadersFrame) (*responseWriter, *http.Request, error) {
1897	sc.serveG.check()
1898
1899	rp := requestParam{
1900		method:    f.PseudoValue("method"),
1901		scheme:    f.PseudoValue("scheme"),
1902		authority: f.PseudoValue("authority"),
1903		path:      f.PseudoValue("path"),
1904	}
1905
1906	isConnect := rp.method == "CONNECT"
1907	if isConnect {
1908		if rp.path != "" || rp.scheme != "" || rp.authority == "" {
1909			return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
1910		}
1911	} else if rp.method == "" || rp.path == "" || (rp.scheme != "https" && rp.scheme != "http") {
1912		// See 8.1.2.6 Malformed Requests and Responses:
1913		//
1914		// Malformed requests or responses that are detected
1915		// MUST be treated as a stream error (Section 5.4.2)
1916		// of type PROTOCOL_ERROR."
1917		//
1918		// 8.1.2.3 Request Pseudo-Header Fields
1919		// "All HTTP/2 requests MUST include exactly one valid
1920		// value for the :method, :scheme, and :path
1921		// pseudo-header fields"
1922		return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
1923	}
1924
1925	bodyOpen := !f.StreamEnded()
1926	if rp.method == "HEAD" && bodyOpen {
1927		// HEAD requests can't have bodies
1928		return nil, nil, streamError(f.StreamID, ErrCodeProtocol)
1929	}
1930
1931	rp.header = make(http.Header)
1932	for _, hf := range f.RegularFields() {
1933		rp.header.Add(sc.canonicalHeader(hf.Name), hf.Value)
1934	}
1935	if rp.authority == "" {
1936		rp.authority = rp.header.Get("Host")
1937	}
1938
1939	rw, req, err := sc.newWriterAndRequestNoBody(st, rp)
1940	if err != nil {
1941		return nil, nil, err
1942	}
1943	if bodyOpen {
1944		if vv, ok := rp.header["Content-Length"]; ok {
1945			req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
1946		} else {
1947			req.ContentLength = -1
1948		}
1949		req.Body.(*requestBody).pipe = &pipe{
1950			b: &dataBuffer{expected: req.ContentLength},
1951		}
1952	}
1953	return rw, req, nil
1954}
1955
1956type requestParam struct {
1957	method                  string
1958	scheme, authority, path string
1959	header                  http.Header
1960}
1961
1962func (sc *serverConn) newWriterAndRequestNoBody(st *stream, rp requestParam) (*responseWriter, *http.Request, error) {
1963	sc.serveG.check()
1964
1965	var tlsState *tls.ConnectionState // nil if not scheme https
1966	if rp.scheme == "https" {
1967		tlsState = sc.tlsState
1968	}
1969
1970	needsContinue := rp.header.Get("Expect") == "100-continue"
1971	if needsContinue {
1972		rp.header.Del("Expect")
1973	}
1974	// Merge Cookie headers into one "; "-delimited value.
1975	if cookies := rp.header["Cookie"]; len(cookies) > 1 {
1976		rp.header.Set("Cookie", strings.Join(cookies, "; "))
1977	}
1978
1979	// Setup Trailers
1980	var trailer http.Header
1981	for _, v := range rp.header["Trailer"] {
1982		for _, key := range strings.Split(v, ",") {
1983			key = http.CanonicalHeaderKey(strings.TrimSpace(key))
1984			switch key {
1985			case "Transfer-Encoding", "Trailer", "Content-Length":
1986				// Bogus. (copy of http1 rules)
1987				// Ignore.
1988			default:
1989				if trailer == nil {
1990					trailer = make(http.Header)
1991				}
1992				trailer[key] = nil
1993			}
1994		}
1995	}
1996	delete(rp.header, "Trailer")
1997
1998	var url_ *url.URL
1999	var requestURI string
2000	if rp.method == "CONNECT" {
2001		url_ = &url.URL{Host: rp.authority}
2002		requestURI = rp.authority // mimic HTTP/1 server behavior
2003	} else {
2004		var err error
2005		url_, err = url.ParseRequestURI(rp.path)
2006		if err != nil {
2007			return nil, nil, streamError(st.id, ErrCodeProtocol)
2008		}
2009		requestURI = rp.path
2010	}
2011
2012	body := &requestBody{
2013		conn:          sc,
2014		stream:        st,
2015		needsContinue: needsContinue,
2016	}
2017	req := &http.Request{
2018		Method:     rp.method,
2019		URL:        url_,
2020		RemoteAddr: sc.remoteAddrStr,
2021		Header:     rp.header,
2022		RequestURI: requestURI,
2023		Proto:      "HTTP/2.0",
2024		ProtoMajor: 2,
2025		ProtoMinor: 0,
2026		TLS:        tlsState,
2027		Host:       rp.authority,
2028		Body:       body,
2029		Trailer:    trailer,
2030	}
2031	req = requestWithContext(req, st.ctx)
2032
2033	rws := responseWriterStatePool.Get().(*responseWriterState)
2034	bwSave := rws.bw
2035	*rws = responseWriterState{} // zero all the fields
2036	rws.conn = sc
2037	rws.bw = bwSave
2038	rws.bw.Reset(chunkWriter{rws})
2039	rws.stream = st
2040	rws.req = req
2041	rws.body = body
2042
2043	rw := &responseWriter{rws: rws}
2044	return rw, req, nil
2045}
2046
2047// Run on its own goroutine.
2048func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request, handler func(http.ResponseWriter, *http.Request)) {
2049	didPanic := true
2050	defer func() {
2051		rw.rws.stream.cancelCtx()
2052		if didPanic {
2053			e := recover()
2054			sc.writeFrameFromHandler(FrameWriteRequest{
2055				write:  handlerPanicRST{rw.rws.stream.id},
2056				stream: rw.rws.stream,
2057			})
2058			// Same as net/http:
2059			if shouldLogPanic(e) {
2060				const size = 64 << 10
2061				buf := make([]byte, size)
2062				buf = buf[:runtime.Stack(buf, false)]
2063				sc.logf("http2: panic serving %v: %v\n%s", sc.conn.RemoteAddr(), e, buf)
2064			}
2065			return
2066		}
2067		rw.handlerDone()
2068	}()
2069	handler(rw, req)
2070	didPanic = false
2071}
2072
2073func handleHeaderListTooLong(w http.ResponseWriter, r *http.Request) {
2074	// 10.5.1 Limits on Header Block Size:
2075	// .. "A server that receives a larger header block than it is
2076	// willing to handle can send an HTTP 431 (Request Header Fields Too
2077	// Large) status code"
2078	const statusRequestHeaderFieldsTooLarge = 431 // only in Go 1.6+
2079	w.WriteHeader(statusRequestHeaderFieldsTooLarge)
2080	io.WriteString(w, "<h1>HTTP Error 431</h1><p>Request Header Field(s) Too Large</p>")
2081}
2082
2083// called from handler goroutines.
2084// h may be nil.
2085func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders) error {
2086	sc.serveG.checkNotOn() // NOT on
2087	var errc chan error
2088	if headerData.h != nil {
2089		// If there's a header map (which we don't own), so we have to block on
2090		// waiting for this frame to be written, so an http.Flush mid-handler
2091		// writes out the correct value of keys, before a handler later potentially
2092		// mutates it.
2093		errc = errChanPool.Get().(chan error)
2094	}
2095	if err := sc.writeFrameFromHandler(FrameWriteRequest{
2096		write:  headerData,
2097		stream: st,
2098		done:   errc,
2099	}); err != nil {
2100		return err
2101	}
2102	if errc != nil {
2103		select {
2104		case err := <-errc:
2105			errChanPool.Put(errc)
2106			return err
2107		case <-sc.doneServing:
2108			return errClientDisconnected
2109		case <-st.cw:
2110			return errStreamClosed
2111		}
2112	}
2113	return nil
2114}
2115
2116// called from handler goroutines.
2117func (sc *serverConn) write100ContinueHeaders(st *stream) {
2118	sc.writeFrameFromHandler(FrameWriteRequest{
2119		write:  write100ContinueHeadersFrame{st.id},
2120		stream: st,
2121	})
2122}
2123
2124// A bodyReadMsg tells the server loop that the http.Handler read n
2125// bytes of the DATA from the client on the given stream.
2126type bodyReadMsg struct {
2127	st *stream
2128	n  int
2129}
2130
2131// called from handler goroutines.
2132// Notes that the handler for the given stream ID read n bytes of its body
2133// and schedules flow control tokens to be sent.
2134func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int, err error) {
2135	sc.serveG.checkNotOn() // NOT on
2136	if n > 0 {
2137		select {
2138		case sc.bodyReadCh <- bodyReadMsg{st, n}:
2139		case <-sc.doneServing:
2140		}
2141	}
2142}
2143
2144func (sc *serverConn) noteBodyRead(st *stream, n int) {
2145	sc.serveG.check()
2146	sc.sendWindowUpdate(nil, n) // conn-level
2147	if st.state != stateHalfClosedRemote && st.state != stateClosed {
2148		// Don't send this WINDOW_UPDATE if the stream is closed
2149		// remotely.
2150		sc.sendWindowUpdate(st, n)
2151	}
2152}
2153
2154// st may be nil for conn-level
2155func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
2156	sc.serveG.check()
2157	// "The legal range for the increment to the flow control
2158	// window is 1 to 2^31-1 (2,147,483,647) octets."
2159	// A Go Read call on 64-bit machines could in theory read
2160	// a larger Read than this. Very unlikely, but we handle it here
2161	// rather than elsewhere for now.
2162	const maxUint31 = 1<<31 - 1
2163	for n >= maxUint31 {
2164		sc.sendWindowUpdate32(st, maxUint31)
2165		n -= maxUint31
2166	}
2167	sc.sendWindowUpdate32(st, int32(n))
2168}
2169
2170// st may be nil for conn-level
2171func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
2172	sc.serveG.check()
2173	if n == 0 {
2174		return
2175	}
2176	if n < 0 {
2177		panic("negative update")
2178	}
2179	var streamID uint32
2180	if st != nil {
2181		streamID = st.id
2182	}
2183	sc.writeFrame(FrameWriteRequest{
2184		write:  writeWindowUpdate{streamID: streamID, n: uint32(n)},
2185		stream: st,
2186	})
2187	var ok bool
2188	if st == nil {
2189		ok = sc.inflow.add(n)
2190	} else {
2191		ok = st.inflow.add(n)
2192	}
2193	if !ok {
2194		panic("internal error; sent too many window updates without decrements?")
2195	}
2196}
2197
2198// requestBody is the Handler's Request.Body type.
2199// Read and Close may be called concurrently.
2200type requestBody struct {
2201	stream        *stream
2202	conn          *serverConn
2203	closed        bool  // for use by Close only
2204	sawEOF        bool  // for use by Read only
2205	pipe          *pipe // non-nil if we have a HTTP entity message body
2206	needsContinue bool  // need to send a 100-continue
2207}
2208
2209func (b *requestBody) Close() error {
2210	if b.pipe != nil && !b.closed {
2211		b.pipe.BreakWithError(errClosedBody)
2212	}
2213	b.closed = true
2214	return nil
2215}
2216
2217func (b *requestBody) Read(p []byte) (n int, err error) {
2218	if b.needsContinue {
2219		b.needsContinue = false
2220		b.conn.write100ContinueHeaders(b.stream)
2221	}
2222	if b.pipe == nil || b.sawEOF {
2223		return 0, io.EOF
2224	}
2225	n, err = b.pipe.Read(p)
2226	if err == io.EOF {
2227		b.sawEOF = true
2228	}
2229	if b.conn == nil && inTests {
2230		return
2231	}
2232	b.conn.noteBodyReadFromHandler(b.stream, n, err)
2233	return
2234}
2235
2236// responseWriter is the http.ResponseWriter implementation. It's
2237// intentionally small (1 pointer wide) to minimize garbage. The
2238// responseWriterState pointer inside is zeroed at the end of a
2239// request (in handlerDone) and calls on the responseWriter thereafter
2240// simply crash (caller's mistake), but the much larger responseWriterState
2241// and buffers are reused between multiple requests.
2242type responseWriter struct {
2243	rws *responseWriterState
2244}
2245
2246// Optional http.ResponseWriter interfaces implemented.
2247var (
2248	_ http.CloseNotifier = (*responseWriter)(nil)
2249	_ http.Flusher       = (*responseWriter)(nil)
2250	_ stringWriter       = (*responseWriter)(nil)
2251)
2252
2253type responseWriterState struct {
2254	// immutable within a request:
2255	stream *stream
2256	req    *http.Request
2257	body   *requestBody // to close at end of request, if DATA frames didn't
2258	conn   *serverConn
2259
2260	// TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
2261	bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
2262
2263	// mutated by http.Handler goroutine:
2264	handlerHeader http.Header // nil until called
2265	snapHeader    http.Header // snapshot of handlerHeader at WriteHeader time
2266	trailers      []string    // set in writeChunk
2267	status        int         // status code passed to WriteHeader
2268	wroteHeader   bool        // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
2269	sentHeader    bool        // have we sent the header frame?
2270	handlerDone   bool        // handler has finished
2271	dirty         bool        // a Write failed; don't reuse this responseWriterState
2272
2273	sentContentLen int64 // non-zero if handler set a Content-Length header
2274	wroteBytes     int64
2275
2276	closeNotifierMu sync.Mutex // guards closeNotifierCh
2277	closeNotifierCh chan bool  // nil until first used
2278}
2279
2280type chunkWriter struct{ rws *responseWriterState }
2281
2282func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
2283
2284func (rws *responseWriterState) hasTrailers() bool { return len(rws.trailers) != 0 }
2285
2286// declareTrailer is called for each Trailer header when the
2287// response header is written. It notes that a header will need to be
2288// written in the trailers at the end of the response.
2289func (rws *responseWriterState) declareTrailer(k string) {
2290	k = http.CanonicalHeaderKey(k)
2291	if !httpguts.ValidTrailerHeader(k) {
2292		// Forbidden by RFC 7230, section 4.1.2.
2293		rws.conn.logf("ignoring invalid trailer %q", k)
2294		return
2295	}
2296	if !strSliceContains(rws.trailers, k) {
2297		rws.trailers = append(rws.trailers, k)
2298	}
2299}
2300
2301// writeChunk writes chunks from the bufio.Writer. But because
2302// bufio.Writer may bypass its chunking, sometimes p may be
2303// arbitrarily large.
2304//
2305// writeChunk is also responsible (on the first chunk) for sending the
2306// HEADER response.
2307func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
2308	if !rws.wroteHeader {
2309		rws.writeHeader(200)
2310	}
2311
2312	isHeadResp := rws.req.Method == "HEAD"
2313	if !rws.sentHeader {
2314		rws.sentHeader = true
2315		var ctype, clen string
2316		if clen = rws.snapHeader.Get("Content-Length"); clen != "" {
2317			rws.snapHeader.Del("Content-Length")
2318			clen64, err := strconv.ParseInt(clen, 10, 64)
2319			if err == nil && clen64 >= 0 {
2320				rws.sentContentLen = clen64
2321			} else {
2322				clen = ""
2323			}
2324		}
2325		if clen == "" && rws.handlerDone && bodyAllowedForStatus(rws.status) && (len(p) > 0 || !isHeadResp) {
2326			clen = strconv.Itoa(len(p))
2327		}
2328		_, hasContentType := rws.snapHeader["Content-Type"]
2329		if !hasContentType && bodyAllowedForStatus(rws.status) && len(p) > 0 {
2330			if cto := rws.snapHeader.Get("X-Content-Type-Options"); strings.EqualFold("nosniff", cto) {
2331				// nosniff is an explicit directive not to guess a content-type.
2332				// Content-sniffing is no less susceptible to polyglot attacks via
2333				// hosted content when done on the server.
2334				ctype = "application/octet-stream"
2335				rws.conn.logf("http2: WriteHeader called with X-Content-Type-Options:nosniff but no Content-Type")
2336			} else {
2337				ctype = http.DetectContentType(p)
2338			}
2339		}
2340		var date string
2341		if _, ok := rws.snapHeader["Date"]; !ok {
2342			// TODO(bradfitz): be faster here, like net/http? measure.
2343			date = time.Now().UTC().Format(http.TimeFormat)
2344		}
2345
2346		for _, v := range rws.snapHeader["Trailer"] {
2347			foreachHeaderElement(v, rws.declareTrailer)
2348		}
2349
2350		endStream := (rws.handlerDone && !rws.hasTrailers() && len(p) == 0) || isHeadResp
2351		err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2352			streamID:      rws.stream.id,
2353			httpResCode:   rws.status,
2354			h:             rws.snapHeader,
2355			endStream:     endStream,
2356			contentType:   ctype,
2357			contentLength: clen,
2358			date:          date,
2359		})
2360		if err != nil {
2361			rws.dirty = true
2362			return 0, err
2363		}
2364		if endStream {
2365			return 0, nil
2366		}
2367	}
2368	if isHeadResp {
2369		return len(p), nil
2370	}
2371	if len(p) == 0 && !rws.handlerDone {
2372		return 0, nil
2373	}
2374
2375	if rws.handlerDone {
2376		rws.promoteUndeclaredTrailers()
2377	}
2378
2379	endStream := rws.handlerDone && !rws.hasTrailers()
2380	if len(p) > 0 || endStream {
2381		// only send a 0 byte DATA frame if we're ending the stream.
2382		if err := rws.conn.writeDataFromHandler(rws.stream, p, endStream); err != nil {
2383			rws.dirty = true
2384			return 0, err
2385		}
2386	}
2387
2388	if rws.handlerDone && rws.hasTrailers() {
2389		err = rws.conn.writeHeaders(rws.stream, &writeResHeaders{
2390			streamID:  rws.stream.id,
2391			h:         rws.handlerHeader,
2392			trailers:  rws.trailers,
2393			endStream: true,
2394		})
2395		if err != nil {
2396			rws.dirty = true
2397		}
2398		return len(p), err
2399	}
2400	return len(p), nil
2401}
2402
2403// TrailerPrefix is a magic prefix for ResponseWriter.Header map keys
2404// that, if present, signals that the map entry is actually for
2405// the response trailers, and not the response headers. The prefix
2406// is stripped after the ServeHTTP call finishes and the values are
2407// sent in the trailers.
2408//
2409// This mechanism is intended only for trailers that are not known
2410// prior to the headers being written. If the set of trailers is fixed
2411// or known before the header is written, the normal Go trailers mechanism
2412// is preferred:
2413//    https://golang.org/pkg/net/http/#ResponseWriter
2414//    https://golang.org/pkg/net/http/#example_ResponseWriter_trailers
2415const TrailerPrefix = "Trailer:"
2416
2417// promoteUndeclaredTrailers permits http.Handlers to set trailers
2418// after the header has already been flushed. Because the Go
2419// ResponseWriter interface has no way to set Trailers (only the
2420// Header), and because we didn't want to expand the ResponseWriter
2421// interface, and because nobody used trailers, and because RFC 7230
2422// says you SHOULD (but not must) predeclare any trailers in the
2423// header, the official ResponseWriter rules said trailers in Go must
2424// be predeclared, and then we reuse the same ResponseWriter.Header()
2425// map to mean both Headers and Trailers. When it's time to write the
2426// Trailers, we pick out the fields of Headers that were declared as
2427// trailers. That worked for a while, until we found the first major
2428// user of Trailers in the wild: gRPC (using them only over http2),
2429// and gRPC libraries permit setting trailers mid-stream without
2430// predeclarnig them. So: change of plans. We still permit the old
2431// way, but we also permit this hack: if a Header() key begins with
2432// "Trailer:", the suffix of that key is a Trailer. Because ':' is an
2433// invalid token byte anyway, there is no ambiguity. (And it's already
2434// filtered out) It's mildly hacky, but not terrible.
2435//
2436// This method runs after the Handler is done and promotes any Header
2437// fields to be trailers.
2438func (rws *responseWriterState) promoteUndeclaredTrailers() {
2439	for k, vv := range rws.handlerHeader {
2440		if !strings.HasPrefix(k, TrailerPrefix) {
2441			continue
2442		}
2443		trailerKey := strings.TrimPrefix(k, TrailerPrefix)
2444		rws.declareTrailer(trailerKey)
2445		rws.handlerHeader[http.CanonicalHeaderKey(trailerKey)] = vv
2446	}
2447
2448	if len(rws.trailers) > 1 {
2449		sorter := sorterPool.Get().(*sorter)
2450		sorter.SortStrings(rws.trailers)
2451		sorterPool.Put(sorter)
2452	}
2453}
2454
2455func (w *responseWriter) Flush() {
2456	rws := w.rws
2457	if rws == nil {
2458		panic("Header called after Handler finished")
2459	}
2460	if rws.bw.Buffered() > 0 {
2461		if err := rws.bw.Flush(); err != nil {
2462			// Ignore the error. The frame writer already knows.
2463			return
2464		}
2465	} else {
2466		// The bufio.Writer won't call chunkWriter.Write
2467		// (writeChunk with zero bytes, so we have to do it
2468		// ourselves to force the HTTP response header and/or
2469		// final DATA frame (with END_STREAM) to be sent.
2470		rws.writeChunk(nil)
2471	}
2472}
2473
2474func (w *responseWriter) CloseNotify() <-chan bool {
2475	rws := w.rws
2476	if rws == nil {
2477		panic("CloseNotify called after Handler finished")
2478	}
2479	rws.closeNotifierMu.Lock()
2480	ch := rws.closeNotifierCh
2481	if ch == nil {
2482		ch = make(chan bool, 1)
2483		rws.closeNotifierCh = ch
2484		cw := rws.stream.cw
2485		go func() {
2486			cw.Wait() // wait for close
2487			ch <- true
2488		}()
2489	}
2490	rws.closeNotifierMu.Unlock()
2491	return ch
2492}
2493
2494func (w *responseWriter) Header() http.Header {
2495	rws := w.rws
2496	if rws == nil {
2497		panic("Header called after Handler finished")
2498	}
2499	if rws.handlerHeader == nil {
2500		rws.handlerHeader = make(http.Header)
2501	}
2502	return rws.handlerHeader
2503}
2504
2505// checkWriteHeaderCode is a copy of net/http's checkWriteHeaderCode.
2506func checkWriteHeaderCode(code int) {
2507	// Issue 22880: require valid WriteHeader status codes.
2508	// For now we only enforce that it's three digits.
2509	// In the future we might block things over 599 (600 and above aren't defined
2510	// at http://httpwg.org/specs/rfc7231.html#status.codes)
2511	// and we might block under 200 (once we have more mature 1xx support).
2512	// But for now any three digits.
2513	//
2514	// We used to send "HTTP/1.1 000 0" on the wire in responses but there's
2515	// no equivalent bogus thing we can realistically send in HTTP/2,
2516	// so we'll consistently panic instead and help people find their bugs
2517	// early. (We can't return an error from WriteHeader even if we wanted to.)
2518	if code < 100 || code > 999 {
2519		panic(fmt.Sprintf("invalid WriteHeader code %v", code))
2520	}
2521}
2522
2523func (w *responseWriter) WriteHeader(code int) {
2524	rws := w.rws
2525	if rws == nil {
2526		panic("WriteHeader called after Handler finished")
2527	}
2528	rws.writeHeader(code)
2529}
2530
2531func (rws *responseWriterState) writeHeader(code int) {
2532	if !rws.wroteHeader {
2533		checkWriteHeaderCode(code)
2534		rws.wroteHeader = true
2535		rws.status = code
2536		if len(rws.handlerHeader) > 0 {
2537			rws.snapHeader = cloneHeader(rws.handlerHeader)
2538		}
2539	}
2540}
2541
2542func cloneHeader(h http.Header) http.Header {
2543	h2 := make(http.Header, len(h))
2544	for k, vv := range h {
2545		vv2 := make([]string, len(vv))
2546		copy(vv2, vv)
2547		h2[k] = vv2
2548	}
2549	return h2
2550}
2551
2552// The Life Of A Write is like this:
2553//
2554// * Handler calls w.Write or w.WriteString ->
2555// * -> rws.bw (*bufio.Writer) ->
2556// * (Handler might call Flush)
2557// * -> chunkWriter{rws}
2558// * -> responseWriterState.writeChunk(p []byte)
2559// * -> responseWriterState.writeChunk (most of the magic; see comment there)
2560func (w *responseWriter) Write(p []byte) (n int, err error) {
2561	return w.write(len(p), p, "")
2562}
2563
2564func (w *responseWriter) WriteString(s string) (n int, err error) {
2565	return w.write(len(s), nil, s)
2566}
2567
2568// either dataB or dataS is non-zero.
2569func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
2570	rws := w.rws
2571	if rws == nil {
2572		panic("Write called after Handler finished")
2573	}
2574	if !rws.wroteHeader {
2575		w.WriteHeader(200)
2576	}
2577	if !bodyAllowedForStatus(rws.status) {
2578		return 0, http.ErrBodyNotAllowed
2579	}
2580	rws.wroteBytes += int64(len(dataB)) + int64(len(dataS)) // only one can be set
2581	if rws.sentContentLen != 0 && rws.wroteBytes > rws.sentContentLen {
2582		// TODO: send a RST_STREAM
2583		return 0, errors.New("http2: handler wrote more than declared Content-Length")
2584	}
2585
2586	if dataB != nil {
2587		return rws.bw.Write(dataB)
2588	} else {
2589		return rws.bw.WriteString(dataS)
2590	}
2591}
2592
2593func (w *responseWriter) handlerDone() {
2594	rws := w.rws
2595	dirty := rws.dirty
2596	rws.handlerDone = true
2597	w.Flush()
2598	w.rws = nil
2599	if !dirty {
2600		// Only recycle the pool if all prior Write calls to
2601		// the serverConn goroutine completed successfully. If
2602		// they returned earlier due to resets from the peer
2603		// there might still be write goroutines outstanding
2604		// from the serverConn referencing the rws memory. See
2605		// issue 20704.
2606		responseWriterStatePool.Put(rws)
2607	}
2608}
2609
2610// Push errors.
2611var (
2612	ErrRecursivePush    = errors.New("http2: recursive push not allowed")
2613	ErrPushLimitReached = errors.New("http2: push would exceed peer's SETTINGS_MAX_CONCURRENT_STREAMS")
2614)
2615
2616// pushOptions is the internal version of http.PushOptions, which we
2617// cannot include here because it's only defined in Go 1.8 and later.
2618type pushOptions struct {
2619	Method string
2620	Header http.Header
2621}
2622
2623func (w *responseWriter) push(target string, opts pushOptions) error {
2624	st := w.rws.stream
2625	sc := st.sc
2626	sc.serveG.checkNotOn()
2627
2628	// No recursive pushes: "PUSH_PROMISE frames MUST only be sent on a peer-initiated stream."
2629	// http://tools.ietf.org/html/rfc7540#section-6.6
2630	if st.isPushed() {
2631		return ErrRecursivePush
2632	}
2633
2634	// Default options.
2635	if opts.Method == "" {
2636		opts.Method = "GET"
2637	}
2638	if opts.Header == nil {
2639		opts.Header = http.Header{}
2640	}
2641	wantScheme := "http"
2642	if w.rws.req.TLS != nil {
2643		wantScheme = "https"
2644	}
2645
2646	// Validate the request.
2647	u, err := url.Parse(target)
2648	if err != nil {
2649		return err
2650	}
2651	if u.Scheme == "" {
2652		if !strings.HasPrefix(target, "/") {
2653			return fmt.Errorf("target must be an absolute URL or an absolute path: %q", target)
2654		}
2655		u.Scheme = wantScheme
2656		u.Host = w.rws.req.Host
2657	} else {
2658		if u.Scheme != wantScheme {
2659			return fmt.Errorf("cannot push URL with scheme %q from request with scheme %q", u.Scheme, wantScheme)
2660		}
2661		if u.Host == "" {
2662			return errors.New("URL must have a host")
2663		}
2664	}
2665	for k := range opts.Header {
2666		if strings.HasPrefix(k, ":") {
2667			return fmt.Errorf("promised request headers cannot include pseudo header %q", k)
2668		}
2669		// These headers are meaningful only if the request has a body,
2670		// but PUSH_PROMISE requests cannot have a body.
2671		// http://tools.ietf.org/html/rfc7540#section-8.2
2672		// Also disallow Host, since the promised URL must be absolute.
2673		switch strings.ToLower(k) {
2674		case "content-length", "content-encoding", "trailer", "te", "expect", "host":
2675			return fmt.Errorf("promised request headers cannot include %q", k)
2676		}
2677	}
2678	if err := checkValidHTTP2RequestHeaders(opts.Header); err != nil {
2679		return err
2680	}
2681
2682	// The RFC effectively limits promised requests to GET and HEAD:
2683	// "Promised requests MUST be cacheable [GET, HEAD, or POST], and MUST be safe [GET or HEAD]"
2684	// http://tools.ietf.org/html/rfc7540#section-8.2
2685	if opts.Method != "GET" && opts.Method != "HEAD" {
2686		return fmt.Errorf("method %q must be GET or HEAD", opts.Method)
2687	}
2688
2689	msg := &startPushRequest{
2690		parent: st,
2691		method: opts.Method,
2692		url:    u,
2693		header: cloneHeader(opts.Header),
2694		done:   errChanPool.Get().(chan error),
2695	}
2696
2697	select {
2698	case <-sc.doneServing:
2699		return errClientDisconnected
2700	case <-st.cw:
2701		return errStreamClosed
2702	case sc.serveMsgCh <- msg:
2703	}
2704
2705	select {
2706	case <-sc.doneServing:
2707		return errClientDisconnected
2708	case <-st.cw:
2709		return errStreamClosed
2710	case err := <-msg.done:
2711		errChanPool.Put(msg.done)
2712		return err
2713	}
2714}
2715
2716type startPushRequest struct {
2717	parent *stream
2718	method string
2719	url    *url.URL
2720	header http.Header
2721	done   chan error
2722}
2723
2724func (sc *serverConn) startPush(msg *startPushRequest) {
2725	sc.serveG.check()
2726
2727	// http://tools.ietf.org/html/rfc7540#section-6.6.
2728	// PUSH_PROMISE frames MUST only be sent on a peer-initiated stream that
2729	// is in either the "open" or "half-closed (remote)" state.
2730	if msg.parent.state != stateOpen && msg.parent.state != stateHalfClosedRemote {
2731		// responseWriter.Push checks that the stream is peer-initiaed.
2732		msg.done <- errStreamClosed
2733		return
2734	}
2735
2736	// http://tools.ietf.org/html/rfc7540#section-6.6.
2737	if !sc.pushEnabled {
2738		msg.done <- http.ErrNotSupported
2739		return
2740	}
2741
2742	// PUSH_PROMISE frames must be sent in increasing order by stream ID, so
2743	// we allocate an ID for the promised stream lazily, when the PUSH_PROMISE
2744	// is written. Once the ID is allocated, we start the request handler.
2745	allocatePromisedID := func() (uint32, error) {
2746		sc.serveG.check()
2747
2748		// Check this again, just in case. Technically, we might have received
2749		// an updated SETTINGS by the time we got around to writing this frame.
2750		if !sc.pushEnabled {
2751			return 0, http.ErrNotSupported
2752		}
2753		// http://tools.ietf.org/html/rfc7540#section-6.5.2.
2754		if sc.curPushedStreams+1 > sc.clientMaxStreams {
2755			return 0, ErrPushLimitReached
2756		}
2757
2758		// http://tools.ietf.org/html/rfc7540#section-5.1.1.
2759		// Streams initiated by the server MUST use even-numbered identifiers.
2760		// A server that is unable to establish a new stream identifier can send a GOAWAY
2761		// frame so that the client is forced to open a new connection for new streams.
2762		if sc.maxPushPromiseID+2 >= 1<<31 {
2763			sc.startGracefulShutdownInternal()
2764			return 0, ErrPushLimitReached
2765		}
2766		sc.maxPushPromiseID += 2
2767		promisedID := sc.maxPushPromiseID
2768
2769		// http://tools.ietf.org/html/rfc7540#section-8.2.
2770		// Strictly speaking, the new stream should start in "reserved (local)", then
2771		// transition to "half closed (remote)" after sending the initial HEADERS, but
2772		// we start in "half closed (remote)" for simplicity.
2773		// See further comments at the definition of stateHalfClosedRemote.
2774		promised := sc.newStream(promisedID, msg.parent.id, stateHalfClosedRemote)
2775		rw, req, err := sc.newWriterAndRequestNoBody(promised, requestParam{
2776			method:    msg.method,
2777			scheme:    msg.url.Scheme,
2778			authority: msg.url.Host,
2779			path:      msg.url.RequestURI(),
2780			header:    cloneHeader(msg.header), // clone since handler runs concurrently with writing the PUSH_PROMISE
2781		})
2782		if err != nil {
2783			// Should not happen, since we've already validated msg.url.
2784			panic(fmt.Sprintf("newWriterAndRequestNoBody(%+v): %v", msg.url, err))
2785		}
2786
2787		go sc.runHandler(rw, req, sc.handler.ServeHTTP)
2788		return promisedID, nil
2789	}
2790
2791	sc.writeFrame(FrameWriteRequest{
2792		write: &writePushPromise{
2793			streamID:           msg.parent.id,
2794			method:             msg.method,
2795			url:                msg.url,
2796			h:                  msg.header,
2797			allocatePromisedID: allocatePromisedID,
2798		},
2799		stream: msg.parent,
2800		done:   msg.done,
2801	})
2802}
2803
2804// foreachHeaderElement splits v according to the "#rule" construction
2805// in RFC 7230 section 7 and calls fn for each non-empty element.
2806func foreachHeaderElement(v string, fn func(string)) {
2807	v = textproto.TrimString(v)
2808	if v == "" {
2809		return
2810	}
2811	if !strings.Contains(v, ",") {
2812		fn(v)
2813		return
2814	}
2815	for _, f := range strings.Split(v, ",") {
2816		if f = textproto.TrimString(f); f != "" {
2817			fn(f)
2818		}
2819	}
2820}
2821
2822// From http://httpwg.org/specs/rfc7540.html#rfc.section.8.1.2.2
2823var connHeaders = []string{
2824	"Connection",
2825	"Keep-Alive",
2826	"Proxy-Connection",
2827	"Transfer-Encoding",
2828	"Upgrade",
2829}
2830
2831// checkValidHTTP2RequestHeaders checks whether h is a valid HTTP/2 request,
2832// per RFC 7540 Section 8.1.2.2.
2833// The returned error is reported to users.
2834func checkValidHTTP2RequestHeaders(h http.Header) error {
2835	for _, k := range connHeaders {
2836		if _, ok := h[k]; ok {
2837			return fmt.Errorf("request header %q is not valid in HTTP/2", k)
2838		}
2839	}
2840	te := h["Te"]
2841	if len(te) > 0 && (len(te) > 1 || (te[0] != "trailers" && te[0] != "")) {
2842		return errors.New(`request header "TE" may only be "trailers" in HTTP/2`)
2843	}
2844	return nil
2845}
2846
2847func new400Handler(err error) http.HandlerFunc {
2848	return func(w http.ResponseWriter, r *http.Request) {
2849		http.Error(w, err.Error(), http.StatusBadRequest)
2850	}
2851}
2852
2853// h1ServerKeepAlivesDisabled reports whether hs has its keep-alives
2854// disabled. See comments on h1ServerShutdownChan above for why
2855// the code is written this way.
2856func h1ServerKeepAlivesDisabled(hs *http.Server) bool {
2857	var x interface{} = hs
2858	type I interface {
2859		doKeepAlives() bool
2860	}
2861	if hs, ok := x.(I); ok {
2862		return !hs.doKeepAlives()
2863	}
2864	return false
2865}
2866