You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

2759 lines
84 KiB

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