PageRenderTime 30ms CodeModel.GetById 21ms RepoModel.GetById 1ms app.codeStats 1ms

/vendor/golang.org/x/net/http2/server.go

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