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