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