server.go 53 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354135513561357135813591360136113621363136413651366136713681369137013711372137313741375137613771378137913801381138213831384138513861387138813891390139113921393139413951396139713981399140014011402140314041405140614071408140914101411141214131414141514161417141814191420142114221423142414251426142714281429143014311432143314341435143614371438143914401441144214431444144514461447144814491450145114521453145414551456145714581459146014611462146314641465146614671468146914701471147214731474147514761477147814791480148114821483148414851486148714881489149014911492149314941495149614971498149915001501150215031504150515061507150815091510151115121513151415151516151715181519152015211522152315241525152615271528152915301531153215331534153515361537153815391540154115421543154415451546154715481549155015511552155315541555155615571558155915601561156215631564156515661567156815691570157115721573157415751576157715781579158015811582158315841585158615871588158915901591159215931594159515961597159815991600160116021603160416051606160716081609161016111612161316141615161616171618161916201621162216231624162516261627162816291630163116321633163416351636163716381639164016411642164316441645164616471648164916501651165216531654165516561657165816591660166116621663166416651666166716681669167016711672167316741675167616771678167916801681168216831684168516861687168816891690169116921693169416951696169716981699170017011702170317041705170617071708170917101711171217131714171517161717171817191720172117221723172417251726172717281729173017311732173317341735173617371738173917401741174217431744174517461747174817491750175117521753175417551756175717581759176017611762176317641765176617671768176917701771177217731774177517761777177817791780
  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. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS
  5. // Licensed under the same terms as Go itself:
  6. // https://code.google.com/p/go/source/browse/LICENSE
  7. // TODO: replace all <-sc.doneServing with reads from the stream's cw
  8. // instead, and make sure that on close we close all open
  9. // streams. then remove doneServing?
  10. // TODO: finish GOAWAY support. Consider each incoming frame type and
  11. // whether it should be ignored during a shutdown race.
  12. // TODO: disconnect idle clients. GFE seems to do 4 minutes. make
  13. // configurable? or maximum number of idle clients and remove the
  14. // oldest?
  15. // TODO: turn off the serve goroutine when idle, so
  16. // an idle conn only has the readFrames goroutine active. (which could
  17. // also be optimized probably to pin less memory in crypto/tls). This
  18. // would involve tracking when the serve goroutine is active (atomic
  19. // int32 read/CAS probably?) and starting it up when frames arrive,
  20. // and shutting it down when all handlers exit. the occasional PING
  21. // packets could use time.AfterFunc to call sc.wakeStartServeLoop()
  22. // (which is a no-op if already running) and then queue the PING write
  23. // as normal. The serve loop would then exit in most cases (if no
  24. // Handlers running) and not be woken up again until the PING packet
  25. // returns.
  26. // TODO (maybe): add a mechanism for Handlers to going into
  27. // half-closed-local mode (rw.(io.Closer) test?) but not exit their
  28. // handler, and continue to be able to read from the
  29. // Request.Body. This would be a somewhat semantic change from HTTP/1
  30. // (or at least what we expose in net/http), so I'd probably want to
  31. // add it there too. For now, this package says that returning from
  32. // the Handler ServeHTTP function means you're both done reading and
  33. // done writing, without a way to stop just one or the other.
  34. package http2
  35. import (
  36. "bufio"
  37. "bytes"
  38. "crypto/tls"
  39. "errors"
  40. "fmt"
  41. "io"
  42. "log"
  43. "net"
  44. "net/http"
  45. "net/url"
  46. "strconv"
  47. "strings"
  48. "sync"
  49. "time"
  50. "golang.org/x/net/http2/hpack"
  51. )
  52. const (
  53. prefaceTimeout = 10 * time.Second
  54. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  55. handlerChunkWriteSize = 4 << 10
  56. defaultMaxStreams = 250 // TODO: make this 100 as the GFE seems to?
  57. )
  58. var (
  59. errClientDisconnected = errors.New("client disconnected")
  60. errClosedBody = errors.New("body closed by handler")
  61. errStreamBroken = errors.New("http2: stream broken")
  62. )
  63. var responseWriterStatePool = sync.Pool{
  64. New: func() interface{} {
  65. rws := &responseWriterState{}
  66. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  67. return rws
  68. },
  69. }
  70. // Test hooks.
  71. var (
  72. testHookOnConn func()
  73. testHookGetServerConn func(*serverConn)
  74. testHookOnPanicMu *sync.Mutex // nil except in tests
  75. testHookOnPanic func(sc *serverConn, panicVal interface{}) (rePanic bool)
  76. )
  77. // Server is an HTTP/2 server.
  78. type Server struct {
  79. // MaxHandlers limits the number of http.Handler ServeHTTP goroutines
  80. // which may run at a time over all connections.
  81. // Negative or zero no limit.
  82. // TODO: implement
  83. MaxHandlers int
  84. // MaxConcurrentStreams optionally specifies the number of
  85. // concurrent streams that each client may have open at a
  86. // time. This is unrelated to the number of http.Handler goroutines
  87. // which may be active globally, which is MaxHandlers.
  88. // If zero, MaxConcurrentStreams defaults to at least 100, per
  89. // the HTTP/2 spec's recommendations.
  90. MaxConcurrentStreams uint32
  91. // MaxReadFrameSize optionally specifies the largest frame
  92. // this server is willing to read. A valid value is between
  93. // 16k and 16M, inclusive. If zero or otherwise invalid, a
  94. // default value is used.
  95. MaxReadFrameSize uint32
  96. // PermitProhibitedCipherSuites, if true, permits the use of
  97. // cipher suites prohibited by the HTTP/2 spec.
  98. PermitProhibitedCipherSuites bool
  99. }
  100. func (s *Server) maxReadFrameSize() uint32 {
  101. if v := s.MaxReadFrameSize; v >= minMaxFrameSize && v <= maxFrameSize {
  102. return v
  103. }
  104. return defaultMaxReadFrameSize
  105. }
  106. func (s *Server) maxConcurrentStreams() uint32 {
  107. if v := s.MaxConcurrentStreams; v > 0 {
  108. return v
  109. }
  110. return defaultMaxStreams
  111. }
  112. // ConfigureServer adds HTTP/2 support to a net/http Server.
  113. //
  114. // The configuration conf may be nil.
  115. //
  116. // ConfigureServer must be called before s begins serving.
  117. func ConfigureServer(s *http.Server, conf *Server) {
  118. if conf == nil {
  119. conf = new(Server)
  120. }
  121. if s.TLSConfig == nil {
  122. s.TLSConfig = new(tls.Config)
  123. }
  124. // Note: not setting MinVersion to tls.VersionTLS12,
  125. // as we don't want to interfere with HTTP/1.1 traffic
  126. // on the user's server. We enforce TLS 1.2 later once
  127. // we accept a connection. Ideally this should be done
  128. // during next-proto selection, but using TLS <1.2 with
  129. // HTTP/2 is still the client's bug.
  130. // Be sure we advertise tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  131. // at least.
  132. // TODO: enable PreferServerCipherSuites?
  133. if s.TLSConfig.CipherSuites != nil {
  134. const requiredCipher = tls.TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256
  135. haveRequired := false
  136. for _, v := range s.TLSConfig.CipherSuites {
  137. if v == requiredCipher {
  138. haveRequired = true
  139. break
  140. }
  141. }
  142. if !haveRequired {
  143. s.TLSConfig.CipherSuites = append(s.TLSConfig.CipherSuites, requiredCipher)
  144. }
  145. }
  146. haveNPN := false
  147. for _, p := range s.TLSConfig.NextProtos {
  148. if p == NextProtoTLS {
  149. haveNPN = true
  150. break
  151. }
  152. }
  153. if !haveNPN {
  154. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, NextProtoTLS)
  155. }
  156. // h2-14 is temporary (as of 2015-03-05) while we wait for all browsers
  157. // to switch to "h2".
  158. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, "h2-14")
  159. if s.TLSNextProto == nil {
  160. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  161. }
  162. protoHandler := func(hs *http.Server, c *tls.Conn, h http.Handler) {
  163. if testHookOnConn != nil {
  164. testHookOnConn()
  165. }
  166. conf.handleConn(hs, c, h)
  167. }
  168. s.TLSNextProto[NextProtoTLS] = protoHandler
  169. s.TLSNextProto["h2-14"] = protoHandler // temporary; see above.
  170. }
  171. func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) {
  172. sc := &serverConn{
  173. srv: srv,
  174. hs: hs,
  175. conn: c,
  176. remoteAddrStr: c.RemoteAddr().String(),
  177. bw: newBufferedWriter(c),
  178. handler: h,
  179. streams: make(map[uint32]*stream),
  180. readFrameCh: make(chan frameAndGate),
  181. readFrameErrCh: make(chan error, 1), // must be buffered for 1
  182. wantWriteFrameCh: make(chan frameWriteMsg, 8),
  183. wroteFrameCh: make(chan struct{}, 1), // buffered; one send in reading goroutine
  184. bodyReadCh: make(chan bodyReadMsg), // buffering doesn't matter either way
  185. doneServing: make(chan struct{}),
  186. advMaxStreams: srv.maxConcurrentStreams(),
  187. writeSched: writeScheduler{
  188. maxFrameSize: initialMaxFrameSize,
  189. },
  190. initialWindowSize: initialWindowSize,
  191. headerTableSize: initialHeaderTableSize,
  192. serveG: newGoroutineLock(),
  193. pushEnabled: true,
  194. }
  195. sc.flow.add(initialWindowSize)
  196. sc.inflow.add(initialWindowSize)
  197. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  198. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField)
  199. fr := NewFramer(sc.bw, c)
  200. fr.SetMaxReadFrameSize(srv.maxReadFrameSize())
  201. sc.framer = fr
  202. if tc, ok := c.(*tls.Conn); ok {
  203. sc.tlsState = new(tls.ConnectionState)
  204. *sc.tlsState = tc.ConnectionState()
  205. // 9.2 Use of TLS Features
  206. // An implementation of HTTP/2 over TLS MUST use TLS
  207. // 1.2 or higher with the restrictions on feature set
  208. // and cipher suite described in this section. Due to
  209. // implementation limitations, it might not be
  210. // possible to fail TLS negotiation. An endpoint MUST
  211. // immediately terminate an HTTP/2 connection that
  212. // does not meet the TLS requirements described in
  213. // this section with a connection error (Section
  214. // 5.4.1) of type INADEQUATE_SECURITY.
  215. if sc.tlsState.Version < tls.VersionTLS12 {
  216. sc.rejectConn(ErrCodeInadequateSecurity, "TLS version too low")
  217. return
  218. }
  219. if sc.tlsState.ServerName == "" {
  220. // Client must use SNI, but we don't enforce that anymore,
  221. // since it was causing problems when connecting to bare IP
  222. // addresses during development.
  223. //
  224. // TODO: optionally enforce? Or enforce at the time we receive
  225. // a new request, and verify the the ServerName matches the :authority?
  226. // But that precludes proxy situations, perhaps.
  227. //
  228. // So for now, do nothing here again.
  229. }
  230. if !srv.PermitProhibitedCipherSuites && isBadCipher(sc.tlsState.CipherSuite) {
  231. // "Endpoints MAY choose to generate a connection error
  232. // (Section 5.4.1) of type INADEQUATE_SECURITY if one of
  233. // the prohibited cipher suites are negotiated."
  234. //
  235. // We choose that. In my opinion, the spec is weak
  236. // here. It also says both parties must support at least
  237. // TLS_ECDHE_RSA_WITH_AES_128_GCM_SHA256 so there's no
  238. // excuses here. If we really must, we could allow an
  239. // "AllowInsecureWeakCiphers" option on the server later.
  240. // Let's see how it plays out first.
  241. sc.rejectConn(ErrCodeInadequateSecurity, fmt.Sprintf("Prohibited TLS 1.2 Cipher Suite: %x", sc.tlsState.CipherSuite))
  242. return
  243. }
  244. }
  245. if hook := testHookGetServerConn; hook != nil {
  246. hook(sc)
  247. }
  248. sc.serve()
  249. }
  250. // isBadCipher reports whether the cipher is blacklisted by the HTTP/2 spec.
  251. func isBadCipher(cipher uint16) bool {
  252. switch cipher {
  253. case tls.TLS_RSA_WITH_RC4_128_SHA,
  254. tls.TLS_RSA_WITH_3DES_EDE_CBC_SHA,
  255. tls.TLS_RSA_WITH_AES_128_CBC_SHA,
  256. tls.TLS_RSA_WITH_AES_256_CBC_SHA,
  257. tls.TLS_ECDHE_ECDSA_WITH_RC4_128_SHA,
  258. tls.TLS_ECDHE_ECDSA_WITH_AES_128_CBC_SHA,
  259. tls.TLS_ECDHE_ECDSA_WITH_AES_256_CBC_SHA,
  260. tls.TLS_ECDHE_RSA_WITH_RC4_128_SHA,
  261. tls.TLS_ECDHE_RSA_WITH_3DES_EDE_CBC_SHA,
  262. tls.TLS_ECDHE_RSA_WITH_AES_128_CBC_SHA,
  263. tls.TLS_ECDHE_RSA_WITH_AES_256_CBC_SHA:
  264. // Reject cipher suites from Appendix A.
  265. // "This list includes those cipher suites that do not
  266. // offer an ephemeral key exchange and those that are
  267. // based on the TLS null, stream or block cipher type"
  268. return true
  269. default:
  270. return false
  271. }
  272. }
  273. func (sc *serverConn) rejectConn(err ErrCode, debug string) {
  274. log.Printf("REJECTING conn: %v, %s", err, debug)
  275. // ignoring errors. hanging up anyway.
  276. sc.framer.WriteGoAway(0, err, []byte(debug))
  277. sc.bw.Flush()
  278. sc.conn.Close()
  279. }
  280. // frameAndGates coordinates the readFrames and serve
  281. // goroutines. Because the Framer interface only permits the most
  282. // recently-read Frame from being accessed, the readFrames goroutine
  283. // blocks until it has a frame, passes it to serve, and then waits for
  284. // serve to be done with it before reading the next one.
  285. type frameAndGate struct {
  286. f Frame
  287. g gate
  288. }
  289. type serverConn struct {
  290. // Immutable:
  291. srv *Server
  292. hs *http.Server
  293. conn net.Conn
  294. bw *bufferedWriter // writing to conn
  295. handler http.Handler
  296. framer *Framer
  297. hpackDecoder *hpack.Decoder
  298. doneServing chan struct{} // closed when serverConn.serve ends
  299. readFrameCh chan frameAndGate // written by serverConn.readFrames
  300. readFrameErrCh chan error
  301. wantWriteFrameCh chan frameWriteMsg // from handlers -> serve
  302. wroteFrameCh chan struct{} // from writeFrameAsync -> serve, tickles more frame writes
  303. bodyReadCh chan bodyReadMsg // from handlers -> serve
  304. testHookCh chan func() // code to run on the serve loop
  305. flow flow // conn-wide (not stream-specific) outbound flow control
  306. inflow flow // conn-wide inbound flow control
  307. tlsState *tls.ConnectionState // shared by all handlers, like net/http
  308. remoteAddrStr string
  309. // Everything following is owned by the serve loop; use serveG.check():
  310. serveG goroutineLock // used to verify funcs are on serve()
  311. pushEnabled bool
  312. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  313. needToSendSettingsAck bool
  314. unackedSettings int // how many SETTINGS have we sent without ACKs?
  315. clientMaxStreams uint32 // SETTINGS_MAX_CONCURRENT_STREAMS from client (our PUSH_PROMISE limit)
  316. advMaxStreams uint32 // our SETTINGS_MAX_CONCURRENT_STREAMS advertised the client
  317. curOpenStreams uint32 // client's number of open streams
  318. maxStreamID uint32 // max ever seen
  319. streams map[uint32]*stream
  320. initialWindowSize int32
  321. headerTableSize uint32
  322. maxHeaderListSize uint32 // zero means unknown (default)
  323. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  324. req requestParam // non-zero while reading request headers
  325. writingFrame bool // started write goroutine but haven't heard back on wroteFrameCh
  326. needsFrameFlush bool // last frame write wasn't a flush
  327. writeSched writeScheduler
  328. inGoAway bool // we've started to or sent GOAWAY
  329. needToSendGoAway bool // we need to schedule a GOAWAY frame write
  330. goAwayCode ErrCode
  331. shutdownTimerCh <-chan time.Time // nil until used
  332. shutdownTimer *time.Timer // nil until used
  333. // Owned by the writeFrameAsync goroutine:
  334. headerWriteBuf bytes.Buffer
  335. hpackEncoder *hpack.Encoder
  336. }
  337. // requestParam is the state of the next request, initialized over
  338. // potentially several frames HEADERS + zero or more CONTINUATION
  339. // frames.
  340. type requestParam struct {
  341. // stream is non-nil if we're reading (HEADER or CONTINUATION)
  342. // frames for a request (but not DATA).
  343. stream *stream
  344. header http.Header
  345. method, path string
  346. scheme, authority string
  347. sawRegularHeader bool // saw a non-pseudo header already
  348. invalidHeader bool // an invalid header was seen
  349. }
  350. // stream represents a stream. This is the minimal metadata needed by
  351. // the serve goroutine. Most of the actual stream state is owned by
  352. // the http.Handler's goroutine in the responseWriter. Because the
  353. // responseWriter's responseWriterState is recycled at the end of a
  354. // handler, this struct intentionally has no pointer to the
  355. // *responseWriter{,State} itself, as the Handler ending nils out the
  356. // responseWriter's state field.
  357. type stream struct {
  358. // immutable:
  359. id uint32
  360. body *pipe // non-nil if expecting DATA frames
  361. cw closeWaiter // closed wait stream transitions to closed state
  362. // owned by serverConn's serve loop:
  363. bodyBytes int64 // body bytes seen so far
  364. declBodyBytes int64 // or -1 if undeclared
  365. flow flow // limits writing from Handler to client
  366. inflow flow // what the client is allowed to POST/etc to us
  367. parent *stream // or nil
  368. weight uint8
  369. state streamState
  370. sentReset bool // only true once detached from streams map
  371. gotReset bool // only true once detacted from streams map
  372. }
  373. func (sc *serverConn) Framer() *Framer { return sc.framer }
  374. func (sc *serverConn) CloseConn() error { return sc.conn.Close() }
  375. func (sc *serverConn) Flush() error { return sc.bw.Flush() }
  376. func (sc *serverConn) HeaderEncoder() (*hpack.Encoder, *bytes.Buffer) {
  377. return sc.hpackEncoder, &sc.headerWriteBuf
  378. }
  379. func (sc *serverConn) state(streamID uint32) (streamState, *stream) {
  380. sc.serveG.check()
  381. // http://http2.github.io/http2-spec/#rfc.section.5.1
  382. if st, ok := sc.streams[streamID]; ok {
  383. return st.state, st
  384. }
  385. // "The first use of a new stream identifier implicitly closes all
  386. // streams in the "idle" state that might have been initiated by
  387. // that peer with a lower-valued stream identifier. For example, if
  388. // a client sends a HEADERS frame on stream 7 without ever sending a
  389. // frame on stream 5, then stream 5 transitions to the "closed"
  390. // state when the first frame for stream 7 is sent or received."
  391. if streamID <= sc.maxStreamID {
  392. return stateClosed, nil
  393. }
  394. return stateIdle, nil
  395. }
  396. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  397. if VerboseLogs {
  398. sc.logf(format, args...)
  399. }
  400. }
  401. func (sc *serverConn) logf(format string, args ...interface{}) {
  402. if lg := sc.hs.ErrorLog; lg != nil {
  403. lg.Printf(format, args...)
  404. } else {
  405. log.Printf(format, args...)
  406. }
  407. }
  408. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  409. if err == nil {
  410. return
  411. }
  412. str := err.Error()
  413. if err == io.EOF || strings.Contains(str, "use of closed network connection") {
  414. // Boring, expected errors.
  415. sc.vlogf(format, args...)
  416. } else {
  417. sc.logf(format, args...)
  418. }
  419. }
  420. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  421. sc.serveG.check()
  422. sc.vlogf("got header field %+v", f)
  423. switch {
  424. case !validHeader(f.Name):
  425. sc.req.invalidHeader = true
  426. case strings.HasPrefix(f.Name, ":"):
  427. if sc.req.sawRegularHeader {
  428. sc.logf("pseudo-header after regular header")
  429. sc.req.invalidHeader = true
  430. return
  431. }
  432. var dst *string
  433. switch f.Name {
  434. case ":method":
  435. dst = &sc.req.method
  436. case ":path":
  437. dst = &sc.req.path
  438. case ":scheme":
  439. dst = &sc.req.scheme
  440. case ":authority":
  441. dst = &sc.req.authority
  442. default:
  443. // 8.1.2.1 Pseudo-Header Fields
  444. // "Endpoints MUST treat a request or response
  445. // that contains undefined or invalid
  446. // pseudo-header fields as malformed (Section
  447. // 8.1.2.6)."
  448. sc.logf("invalid pseudo-header %q", f.Name)
  449. sc.req.invalidHeader = true
  450. return
  451. }
  452. if *dst != "" {
  453. sc.logf("duplicate pseudo-header %q sent", f.Name)
  454. sc.req.invalidHeader = true
  455. return
  456. }
  457. *dst = f.Value
  458. case f.Name == "cookie":
  459. sc.req.sawRegularHeader = true
  460. if s, ok := sc.req.header["Cookie"]; ok && len(s) == 1 {
  461. s[0] = s[0] + "; " + f.Value
  462. } else {
  463. sc.req.header.Add("Cookie", f.Value)
  464. }
  465. default:
  466. sc.req.sawRegularHeader = true
  467. sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value)
  468. }
  469. }
  470. func (sc *serverConn) canonicalHeader(v string) string {
  471. sc.serveG.check()
  472. cv, ok := commonCanonHeader[v]
  473. if ok {
  474. return cv
  475. }
  476. cv, ok = sc.canonHeader[v]
  477. if ok {
  478. return cv
  479. }
  480. if sc.canonHeader == nil {
  481. sc.canonHeader = make(map[string]string)
  482. }
  483. cv = http.CanonicalHeaderKey(v)
  484. sc.canonHeader[v] = cv
  485. return cv
  486. }
  487. // readFrames is the loop that reads incoming frames.
  488. // It's run on its own goroutine.
  489. func (sc *serverConn) readFrames() {
  490. g := make(gate, 1)
  491. for {
  492. f, err := sc.framer.ReadFrame()
  493. if err != nil {
  494. sc.readFrameErrCh <- err
  495. close(sc.readFrameCh)
  496. return
  497. }
  498. sc.readFrameCh <- frameAndGate{f, g}
  499. // We can't read another frame until this one is
  500. // processed, as the ReadFrame interface doesn't copy
  501. // memory. The Frame accessor methods access the last
  502. // frame's (shared) buffer. So we wait for the
  503. // serve goroutine to tell us it's done:
  504. g.Wait()
  505. }
  506. }
  507. // writeFrameAsync runs in its own goroutine and writes a single frame
  508. // and then reports when it's done.
  509. // At most one goroutine can be running writeFrameAsync at a time per
  510. // serverConn.
  511. func (sc *serverConn) writeFrameAsync(wm frameWriteMsg) {
  512. err := wm.write.writeFrame(sc)
  513. if ch := wm.done; ch != nil {
  514. select {
  515. case ch <- err:
  516. default:
  517. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.write))
  518. }
  519. }
  520. sc.wroteFrameCh <- struct{}{} // tickle frame selection scheduler
  521. }
  522. func (sc *serverConn) closeAllStreamsOnConnClose() {
  523. sc.serveG.check()
  524. for _, st := range sc.streams {
  525. sc.closeStream(st, errClientDisconnected)
  526. }
  527. }
  528. func (sc *serverConn) stopShutdownTimer() {
  529. sc.serveG.check()
  530. if t := sc.shutdownTimer; t != nil {
  531. t.Stop()
  532. }
  533. }
  534. func (sc *serverConn) notePanic() {
  535. if testHookOnPanicMu != nil {
  536. testHookOnPanicMu.Lock()
  537. defer testHookOnPanicMu.Unlock()
  538. }
  539. if testHookOnPanic != nil {
  540. if e := recover(); e != nil {
  541. if testHookOnPanic(sc, e) {
  542. panic(e)
  543. }
  544. }
  545. }
  546. }
  547. func (sc *serverConn) serve() {
  548. sc.serveG.check()
  549. defer sc.notePanic()
  550. defer sc.conn.Close()
  551. defer sc.closeAllStreamsOnConnClose()
  552. defer sc.stopShutdownTimer()
  553. defer close(sc.doneServing) // unblocks handlers trying to send
  554. sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  555. sc.writeFrame(frameWriteMsg{
  556. write: writeSettings{
  557. {SettingMaxFrameSize, sc.srv.maxReadFrameSize()},
  558. {SettingMaxConcurrentStreams, sc.advMaxStreams},
  559. // TODO: more actual settings, notably
  560. // SettingInitialWindowSize, but then we also
  561. // want to bump up the conn window size the
  562. // same amount here right after the settings
  563. },
  564. })
  565. sc.unackedSettings++
  566. if err := sc.readPreface(); err != nil {
  567. sc.condlogf(err, "error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  568. return
  569. }
  570. go sc.readFrames() // closed by defer sc.conn.Close above
  571. settingsTimer := time.NewTimer(firstSettingsTimeout)
  572. for {
  573. select {
  574. case wm := <-sc.wantWriteFrameCh:
  575. sc.writeFrame(wm)
  576. case <-sc.wroteFrameCh:
  577. if sc.writingFrame != true {
  578. panic("internal error: expected to be already writing a frame")
  579. }
  580. sc.writingFrame = false
  581. sc.scheduleFrameWrite()
  582. case fg, ok := <-sc.readFrameCh:
  583. if !ok {
  584. sc.readFrameCh = nil
  585. }
  586. if !sc.processFrameFromReader(fg, ok) {
  587. return
  588. }
  589. if settingsTimer.C != nil {
  590. settingsTimer.Stop()
  591. settingsTimer.C = nil
  592. }
  593. case m := <-sc.bodyReadCh:
  594. sc.noteBodyRead(m.st, m.n)
  595. case <-settingsTimer.C:
  596. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  597. return
  598. case <-sc.shutdownTimerCh:
  599. sc.vlogf("GOAWAY close timer fired; closing conn from %v", sc.conn.RemoteAddr())
  600. return
  601. case fn := <-sc.testHookCh:
  602. fn()
  603. }
  604. }
  605. }
  606. // readPreface reads the ClientPreface greeting from the peer
  607. // or returns an error on timeout or an invalid greeting.
  608. func (sc *serverConn) readPreface() error {
  609. errc := make(chan error, 1)
  610. go func() {
  611. // Read the client preface
  612. buf := make([]byte, len(ClientPreface))
  613. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  614. errc <- err
  615. } else if !bytes.Equal(buf, clientPreface) {
  616. errc <- fmt.Errorf("bogus greeting %q", buf)
  617. } else {
  618. errc <- nil
  619. }
  620. }()
  621. timer := time.NewTimer(prefaceTimeout) // TODO: configurable on *Server?
  622. defer timer.Stop()
  623. select {
  624. case <-timer.C:
  625. return errors.New("timeout waiting for client preface")
  626. case err := <-errc:
  627. if err == nil {
  628. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  629. }
  630. return err
  631. }
  632. }
  633. // writeDataFromHandler writes the data described in req to stream.id.
  634. //
  635. // The provided ch is used to avoid allocating new channels for each
  636. // write operation. It's expected that the caller reuses writeData and ch
  637. // over time.
  638. //
  639. // The flow control currently happens in the Handler where it waits
  640. // for 1 or more bytes to be available to then write here. So at this
  641. // point we know that we have flow control. But this might have to
  642. // change when priority is implemented, so the serve goroutine knows
  643. // the total amount of bytes waiting to be sent and can can have more
  644. // scheduling decisions available.
  645. func (sc *serverConn) writeDataFromHandler(stream *stream, writeData *writeData, ch chan error) error {
  646. sc.writeFrameFromHandler(frameWriteMsg{
  647. write: writeData,
  648. stream: stream,
  649. done: ch,
  650. })
  651. select {
  652. case err := <-ch:
  653. return err
  654. case <-sc.doneServing:
  655. return errClientDisconnected
  656. case <-stream.cw:
  657. return errStreamBroken
  658. }
  659. }
  660. // writeFrameFromHandler sends wm to sc.wantWriteFrameCh, but aborts
  661. // if the connection has gone away.
  662. //
  663. // This must not be run from the serve goroutine itself, else it might
  664. // deadlock writing to sc.wantWriteFrameCh (which is only mildly
  665. // buffered and is read by serve itself). If you're on the serve
  666. // goroutine, call writeFrame instead.
  667. func (sc *serverConn) writeFrameFromHandler(wm frameWriteMsg) {
  668. sc.serveG.checkNotOn() // NOT
  669. select {
  670. case sc.wantWriteFrameCh <- wm:
  671. case <-sc.doneServing:
  672. // Client has closed their connection to the server.
  673. }
  674. }
  675. // writeFrame schedules a frame to write and sends it if there's nothing
  676. // already being written.
  677. //
  678. // There is no pushback here (the serve goroutine never blocks). It's
  679. // the http.Handlers that block, waiting for their previous frames to
  680. // make it onto the wire
  681. //
  682. // If you're not on the serve goroutine, use writeFrameFromHandler instead.
  683. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  684. sc.serveG.check()
  685. sc.writeSched.add(wm)
  686. sc.scheduleFrameWrite()
  687. }
  688. // startFrameWrite starts a goroutine to write wm (in a separate
  689. // goroutine since that might block on the network), and updates the
  690. // serve goroutine's state about the world, updated from info in wm.
  691. func (sc *serverConn) startFrameWrite(wm frameWriteMsg) {
  692. sc.serveG.check()
  693. if sc.writingFrame {
  694. panic("internal error: can only be writing one frame at a time")
  695. }
  696. sc.writingFrame = true
  697. st := wm.stream
  698. if st != nil {
  699. switch st.state {
  700. case stateHalfClosedLocal:
  701. panic("internal error: attempt to send frame on half-closed-local stream")
  702. case stateClosed:
  703. if st.sentReset || st.gotReset {
  704. // Skip this frame. But fake the frame write to reschedule:
  705. sc.wroteFrameCh <- struct{}{}
  706. return
  707. }
  708. panic(fmt.Sprintf("internal error: attempt to send a write %v on a closed stream", wm))
  709. }
  710. }
  711. sc.needsFrameFlush = true
  712. if endsStream(wm.write) {
  713. if st == nil {
  714. panic("internal error: expecting non-nil stream")
  715. }
  716. switch st.state {
  717. case stateOpen:
  718. // Here we would go to stateHalfClosedLocal in
  719. // theory, but since our handler is done and
  720. // the net/http package provides no mechanism
  721. // for finishing writing to a ResponseWriter
  722. // while still reading data (see possible TODO
  723. // at top of this file), we go into closed
  724. // state here anyway, after telling the peer
  725. // we're hanging up on them.
  726. st.state = stateHalfClosedLocal // won't last long, but necessary for closeStream via resetStream
  727. errCancel := StreamError{st.id, ErrCodeCancel}
  728. sc.resetStream(errCancel)
  729. case stateHalfClosedRemote:
  730. sc.closeStream(st, nil)
  731. }
  732. }
  733. go sc.writeFrameAsync(wm)
  734. }
  735. // scheduleFrameWrite tickles the frame writing scheduler.
  736. //
  737. // If a frame is already being written, nothing happens. This will be called again
  738. // when the frame is done being written.
  739. //
  740. // If a frame isn't being written we need to send one, the best frame
  741. // to send is selected, preferring first things that aren't
  742. // stream-specific (e.g. ACKing settings), and then finding the
  743. // highest priority stream.
  744. //
  745. // If a frame isn't being written and there's nothing else to send, we
  746. // flush the write buffer.
  747. func (sc *serverConn) scheduleFrameWrite() {
  748. sc.serveG.check()
  749. if sc.writingFrame {
  750. return
  751. }
  752. if sc.needToSendGoAway {
  753. sc.needToSendGoAway = false
  754. sc.startFrameWrite(frameWriteMsg{
  755. write: &writeGoAway{
  756. maxStreamID: sc.maxStreamID,
  757. code: sc.goAwayCode,
  758. },
  759. })
  760. return
  761. }
  762. if sc.needToSendSettingsAck {
  763. sc.needToSendSettingsAck = false
  764. sc.startFrameWrite(frameWriteMsg{write: writeSettingsAck{}})
  765. return
  766. }
  767. if !sc.inGoAway {
  768. if wm, ok := sc.writeSched.take(); ok {
  769. sc.startFrameWrite(wm)
  770. return
  771. }
  772. }
  773. if sc.needsFrameFlush {
  774. sc.startFrameWrite(frameWriteMsg{write: flushFrameWriter{}})
  775. sc.needsFrameFlush = false // after startFrameWrite, since it sets this true
  776. return
  777. }
  778. }
  779. func (sc *serverConn) goAway(code ErrCode) {
  780. sc.serveG.check()
  781. if sc.inGoAway {
  782. return
  783. }
  784. if code != ErrCodeNo {
  785. sc.shutDownIn(250 * time.Millisecond)
  786. } else {
  787. // TODO: configurable
  788. sc.shutDownIn(1 * time.Second)
  789. }
  790. sc.inGoAway = true
  791. sc.needToSendGoAway = true
  792. sc.goAwayCode = code
  793. sc.scheduleFrameWrite()
  794. }
  795. func (sc *serverConn) shutDownIn(d time.Duration) {
  796. sc.serveG.check()
  797. sc.shutdownTimer = time.NewTimer(d)
  798. sc.shutdownTimerCh = sc.shutdownTimer.C
  799. }
  800. func (sc *serverConn) resetStream(se StreamError) {
  801. sc.serveG.check()
  802. sc.writeFrame(frameWriteMsg{write: se})
  803. if st, ok := sc.streams[se.StreamID]; ok {
  804. st.sentReset = true
  805. sc.closeStream(st, se)
  806. }
  807. }
  808. // curHeaderStreamID returns the stream ID of the header block we're
  809. // currently in the middle of reading. If this returns non-zero, the
  810. // next frame must be a CONTINUATION with this stream id.
  811. func (sc *serverConn) curHeaderStreamID() uint32 {
  812. sc.serveG.check()
  813. st := sc.req.stream
  814. if st == nil {
  815. return 0
  816. }
  817. return st.id
  818. }
  819. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  820. // frame-reading goroutine.
  821. // processFrameFromReader returns whether the connection should be kept open.
  822. func (sc *serverConn) processFrameFromReader(fg frameAndGate, fgValid bool) bool {
  823. sc.serveG.check()
  824. var clientGone bool
  825. var err error
  826. if !fgValid {
  827. err = <-sc.readFrameErrCh
  828. if err == ErrFrameTooLarge {
  829. sc.goAway(ErrCodeFrameSize)
  830. return true // goAway will close the loop
  831. }
  832. clientGone = err == io.EOF || strings.Contains(err.Error(), "use of closed network connection")
  833. if clientGone {
  834. // TODO: could we also get into this state if
  835. // the peer does a half close
  836. // (e.g. CloseWrite) because they're done
  837. // sending frames but they're still wanting
  838. // our open replies? Investigate.
  839. // TODO: add CloseWrite to crypto/tls.Conn first
  840. // so we have a way to test this? I suppose
  841. // just for testing we could have a non-TLS mode.
  842. return false
  843. }
  844. }
  845. if fgValid {
  846. f := fg.f
  847. sc.vlogf("got %v: %#v", f.Header(), f)
  848. err = sc.processFrame(f)
  849. fg.g.Done() // unblock the readFrames goroutine
  850. if err == nil {
  851. return true
  852. }
  853. }
  854. switch ev := err.(type) {
  855. case StreamError:
  856. sc.resetStream(ev)
  857. return true
  858. case goAwayFlowError:
  859. sc.goAway(ErrCodeFlowControl)
  860. return true
  861. case ConnectionError:
  862. sc.logf("%v: %v", sc.conn.RemoteAddr(), ev)
  863. sc.goAway(ErrCode(ev))
  864. return true // goAway will handle shutdown
  865. default:
  866. if !fgValid {
  867. sc.logf("disconnecting; error reading frame from client %s: %v", sc.conn.RemoteAddr(), err)
  868. } else {
  869. sc.logf("disconnection due to other error: %v", err)
  870. }
  871. }
  872. return false
  873. }
  874. func (sc *serverConn) processFrame(f Frame) error {
  875. sc.serveG.check()
  876. // First frame received must be SETTINGS.
  877. if !sc.sawFirstSettings {
  878. if _, ok := f.(*SettingsFrame); !ok {
  879. return ConnectionError(ErrCodeProtocol)
  880. }
  881. sc.sawFirstSettings = true
  882. }
  883. if s := sc.curHeaderStreamID(); s != 0 {
  884. if cf, ok := f.(*ContinuationFrame); !ok {
  885. return ConnectionError(ErrCodeProtocol)
  886. } else if cf.Header().StreamID != s {
  887. return ConnectionError(ErrCodeProtocol)
  888. }
  889. }
  890. switch f := f.(type) {
  891. case *SettingsFrame:
  892. return sc.processSettings(f)
  893. case *HeadersFrame:
  894. return sc.processHeaders(f)
  895. case *ContinuationFrame:
  896. return sc.processContinuation(f)
  897. case *WindowUpdateFrame:
  898. return sc.processWindowUpdate(f)
  899. case *PingFrame:
  900. return sc.processPing(f)
  901. case *DataFrame:
  902. return sc.processData(f)
  903. case *RSTStreamFrame:
  904. return sc.processResetStream(f)
  905. case *PriorityFrame:
  906. return sc.processPriority(f)
  907. case *PushPromiseFrame:
  908. // A client cannot push. Thus, servers MUST treat the receipt of a PUSH_PROMISE
  909. // frame as a connection error (Section 5.4.1) of type PROTOCOL_ERROR.
  910. return ConnectionError(ErrCodeProtocol)
  911. default:
  912. log.Printf("Ignoring frame: %v", f.Header())
  913. return nil
  914. }
  915. }
  916. func (sc *serverConn) processPing(f *PingFrame) error {
  917. sc.serveG.check()
  918. if f.Flags.Has(FlagSettingsAck) {
  919. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  920. // containing this flag."
  921. return nil
  922. }
  923. if f.StreamID != 0 {
  924. // "PING frames are not associated with any individual
  925. // stream. If a PING frame is received with a stream
  926. // identifier field value other than 0x0, the recipient MUST
  927. // respond with a connection error (Section 5.4.1) of type
  928. // PROTOCOL_ERROR."
  929. return ConnectionError(ErrCodeProtocol)
  930. }
  931. sc.writeFrame(frameWriteMsg{write: writePingAck{f}})
  932. return nil
  933. }
  934. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  935. sc.serveG.check()
  936. switch {
  937. case f.StreamID != 0: // stream-level flow control
  938. st := sc.streams[f.StreamID]
  939. if st == nil {
  940. // "WINDOW_UPDATE can be sent by a peer that has sent a
  941. // frame bearing the END_STREAM flag. This means that a
  942. // receiver could receive a WINDOW_UPDATE frame on a "half
  943. // closed (remote)" or "closed" stream. A receiver MUST
  944. // NOT treat this as an error, see Section 5.1."
  945. return nil
  946. }
  947. if !st.flow.add(int32(f.Increment)) {
  948. return StreamError{f.StreamID, ErrCodeFlowControl}
  949. }
  950. default: // connection-level flow control
  951. if !sc.flow.add(int32(f.Increment)) {
  952. return goAwayFlowError{}
  953. }
  954. }
  955. sc.scheduleFrameWrite()
  956. return nil
  957. }
  958. func (sc *serverConn) processResetStream(f *RSTStreamFrame) error {
  959. sc.serveG.check()
  960. state, st := sc.state(f.StreamID)
  961. if state == stateIdle {
  962. // 6.4 "RST_STREAM frames MUST NOT be sent for a
  963. // stream in the "idle" state. If a RST_STREAM frame
  964. // identifying an idle stream is received, the
  965. // recipient MUST treat this as a connection error
  966. // (Section 5.4.1) of type PROTOCOL_ERROR.
  967. return ConnectionError(ErrCodeProtocol)
  968. }
  969. if st != nil {
  970. st.gotReset = true
  971. sc.closeStream(st, StreamError{f.StreamID, f.ErrCode})
  972. }
  973. return nil
  974. }
  975. func (sc *serverConn) closeStream(st *stream, err error) {
  976. sc.serveG.check()
  977. if st.state == stateIdle || st.state == stateClosed {
  978. panic(fmt.Sprintf("invariant; can't close stream in state %v", st.state))
  979. }
  980. st.state = stateClosed
  981. sc.curOpenStreams--
  982. delete(sc.streams, st.id)
  983. if p := st.body; p != nil {
  984. p.Close(err)
  985. }
  986. st.cw.Close() // signals Handler's CloseNotifier, unblocks writes, etc
  987. sc.writeSched.forgetStream(st.id)
  988. }
  989. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  990. sc.serveG.check()
  991. if f.IsAck() {
  992. sc.unackedSettings--
  993. if sc.unackedSettings < 0 {
  994. // Why is the peer ACKing settings we never sent?
  995. // The spec doesn't mention this case, but
  996. // hang up on them anyway.
  997. return ConnectionError(ErrCodeProtocol)
  998. }
  999. return nil
  1000. }
  1001. if err := f.ForeachSetting(sc.processSetting); err != nil {
  1002. return err
  1003. }
  1004. sc.needToSendSettingsAck = true
  1005. sc.scheduleFrameWrite()
  1006. return nil
  1007. }
  1008. func (sc *serverConn) processSetting(s Setting) error {
  1009. sc.serveG.check()
  1010. if err := s.Valid(); err != nil {
  1011. return err
  1012. }
  1013. sc.vlogf("processing setting %v", s)
  1014. switch s.ID {
  1015. case SettingHeaderTableSize:
  1016. sc.headerTableSize = s.Val
  1017. sc.hpackEncoder.SetMaxDynamicTableSize(s.Val)
  1018. case SettingEnablePush:
  1019. sc.pushEnabled = s.Val != 0
  1020. case SettingMaxConcurrentStreams:
  1021. sc.clientMaxStreams = s.Val
  1022. case SettingInitialWindowSize:
  1023. return sc.processSettingInitialWindowSize(s.Val)
  1024. case SettingMaxFrameSize:
  1025. sc.writeSched.maxFrameSize = s.Val
  1026. case SettingMaxHeaderListSize:
  1027. sc.maxHeaderListSize = s.Val
  1028. default:
  1029. // Unknown setting: "An endpoint that receives a SETTINGS
  1030. // frame with any unknown or unsupported identifier MUST
  1031. // ignore that setting."
  1032. }
  1033. return nil
  1034. }
  1035. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  1036. sc.serveG.check()
  1037. // Note: val already validated to be within range by
  1038. // processSetting's Valid call.
  1039. // "A SETTINGS frame can alter the initial flow control window
  1040. // size for all current streams. When the value of
  1041. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  1042. // adjust the size of all stream flow control windows that it
  1043. // maintains by the difference between the new value and the
  1044. // old value."
  1045. old := sc.initialWindowSize
  1046. sc.initialWindowSize = int32(val)
  1047. growth := sc.initialWindowSize - old // may be negative
  1048. for _, st := range sc.streams {
  1049. if !st.flow.add(growth) {
  1050. // 6.9.2 Initial Flow Control Window Size
  1051. // "An endpoint MUST treat a change to
  1052. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  1053. // control window to exceed the maximum size as a
  1054. // connection error (Section 5.4.1) of type
  1055. // FLOW_CONTROL_ERROR."
  1056. return ConnectionError(ErrCodeFlowControl)
  1057. }
  1058. }
  1059. return nil
  1060. }
  1061. func (sc *serverConn) processData(f *DataFrame) error {
  1062. sc.serveG.check()
  1063. // "If a DATA frame is received whose stream is not in "open"
  1064. // or "half closed (local)" state, the recipient MUST respond
  1065. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  1066. id := f.Header().StreamID
  1067. st, ok := sc.streams[id]
  1068. if !ok || st.state != stateOpen {
  1069. // This includes sending a RST_STREAM if the stream is
  1070. // in stateHalfClosedLocal (which currently means that
  1071. // the http.Handler returned, so it's done reading &
  1072. // done writing). Try to stop the client from sending
  1073. // more DATA.
  1074. return StreamError{id, ErrCodeStreamClosed}
  1075. }
  1076. if st.body == nil {
  1077. panic("internal error: should have a body in this state")
  1078. }
  1079. data := f.Data()
  1080. // Sender sending more than they'd declared?
  1081. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  1082. st.body.Close(fmt.Errorf("sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  1083. return StreamError{id, ErrCodeStreamClosed}
  1084. }
  1085. if len(data) > 0 {
  1086. // Check whether the client has flow control quota.
  1087. if int(st.inflow.available()) < len(data) {
  1088. return StreamError{id, ErrCodeFlowControl}
  1089. }
  1090. st.inflow.take(int32(len(data)))
  1091. wrote, err := st.body.Write(data)
  1092. if err != nil {
  1093. return StreamError{id, ErrCodeStreamClosed}
  1094. }
  1095. if wrote != len(data) {
  1096. panic("internal error: bad Writer")
  1097. }
  1098. st.bodyBytes += int64(len(data))
  1099. }
  1100. if f.StreamEnded() {
  1101. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  1102. st.body.Close(fmt.Errorf("request declared a Content-Length of %d but only wrote %d bytes",
  1103. st.declBodyBytes, st.bodyBytes))
  1104. } else {
  1105. st.body.Close(io.EOF)
  1106. }
  1107. st.state = stateHalfClosedRemote
  1108. }
  1109. return nil
  1110. }
  1111. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  1112. sc.serveG.check()
  1113. id := f.Header().StreamID
  1114. if sc.inGoAway {
  1115. // Ignore.
  1116. return nil
  1117. }
  1118. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  1119. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  1120. // Streams initiated by a client MUST use odd-numbered
  1121. // stream identifiers. [...] The identifier of a newly
  1122. // established stream MUST be numerically greater than all
  1123. // streams that the initiating endpoint has opened or
  1124. // reserved. [...] An endpoint that receives an unexpected
  1125. // stream identifier MUST respond with a connection error
  1126. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1127. return ConnectionError(ErrCodeProtocol)
  1128. }
  1129. if id > sc.maxStreamID {
  1130. sc.maxStreamID = id
  1131. }
  1132. st := &stream{
  1133. id: id,
  1134. state: stateOpen,
  1135. }
  1136. if f.StreamEnded() {
  1137. st.state = stateHalfClosedRemote
  1138. }
  1139. st.cw.Init()
  1140. st.flow.conn = &sc.flow // link to conn-level counter
  1141. st.flow.add(sc.initialWindowSize)
  1142. st.inflow.conn = &sc.inflow // link to conn-level counter
  1143. st.inflow.add(initialWindowSize) // TODO: update this when we send a higher initial window size in the initial settings
  1144. sc.streams[id] = st
  1145. if f.HasPriority() {
  1146. adjustStreamPriority(sc.streams, st.id, f.Priority)
  1147. }
  1148. sc.curOpenStreams++
  1149. sc.req = requestParam{
  1150. stream: st,
  1151. header: make(http.Header),
  1152. }
  1153. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1154. }
  1155. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  1156. sc.serveG.check()
  1157. st := sc.streams[f.Header().StreamID]
  1158. if st == nil || sc.curHeaderStreamID() != st.id {
  1159. return ConnectionError(ErrCodeProtocol)
  1160. }
  1161. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  1162. }
  1163. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  1164. sc.serveG.check()
  1165. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  1166. // TODO: convert to stream error I assume?
  1167. return err
  1168. }
  1169. if !end {
  1170. return nil
  1171. }
  1172. if err := sc.hpackDecoder.Close(); err != nil {
  1173. // TODO: convert to stream error I assume?
  1174. return err
  1175. }
  1176. defer sc.resetPendingRequest()
  1177. if sc.curOpenStreams > sc.advMaxStreams {
  1178. // "Endpoints MUST NOT exceed the limit set by their
  1179. // peer. An endpoint that receives a HEADERS frame
  1180. // that causes their advertised concurrent stream
  1181. // limit to be exceeded MUST treat this as a stream
  1182. // error (Section 5.4.2) of type PROTOCOL_ERROR or
  1183. // REFUSED_STREAM."
  1184. if sc.unackedSettings == 0 {
  1185. // They should know better.
  1186. return StreamError{st.id, ErrCodeProtocol}
  1187. }
  1188. // Assume it's a network race, where they just haven't
  1189. // received our last SETTINGS update. But actually
  1190. // this can't happen yet, because we don't yet provide
  1191. // a way for users to adjust server parameters at
  1192. // runtime.
  1193. return StreamError{st.id, ErrCodeRefusedStream}
  1194. }
  1195. rw, req, err := sc.newWriterAndRequest()
  1196. if err != nil {
  1197. return err
  1198. }
  1199. st.body = req.Body.(*requestBody).pipe // may be nil
  1200. st.declBodyBytes = req.ContentLength
  1201. go sc.runHandler(rw, req)
  1202. return nil
  1203. }
  1204. func (sc *serverConn) processPriority(f *PriorityFrame) error {
  1205. adjustStreamPriority(sc.streams, f.StreamID, f.PriorityParam)
  1206. return nil
  1207. }
  1208. func adjustStreamPriority(streams map[uint32]*stream, streamID uint32, priority PriorityParam) {
  1209. st, ok := streams[streamID]
  1210. if !ok {
  1211. // TODO: not quite correct (this streamID might
  1212. // already exist in the dep tree, but be closed), but
  1213. // close enough for now.
  1214. return
  1215. }
  1216. st.weight = priority.Weight
  1217. parent := streams[priority.StreamDep] // might be nil
  1218. if parent == st {
  1219. // if client tries to set this stream to be the parent of itself
  1220. // ignore and keep going
  1221. return
  1222. }
  1223. // section 5.3.3: If a stream is made dependent on one of its
  1224. // own dependencies, the formerly dependent stream is first
  1225. // moved to be dependent on the reprioritized stream's previous
  1226. // parent. The moved dependency retains its weight.
  1227. for piter := parent; piter != nil; piter = piter.parent {
  1228. if piter == st {
  1229. parent.parent = st.parent
  1230. break
  1231. }
  1232. }
  1233. st.parent = parent
  1234. if priority.Exclusive && (st.parent != nil || priority.StreamDep == 0) {
  1235. for _, openStream := range streams {
  1236. if openStream != st && openStream.parent == st.parent {
  1237. openStream.parent = st
  1238. }
  1239. }
  1240. }
  1241. }
  1242. // resetPendingRequest zeros out all state related to a HEADERS frame
  1243. // and its zero or more CONTINUATION frames sent to start a new
  1244. // request.
  1245. func (sc *serverConn) resetPendingRequest() {
  1246. sc.serveG.check()
  1247. sc.req = requestParam{}
  1248. }
  1249. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  1250. sc.serveG.check()
  1251. rp := &sc.req
  1252. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  1253. (rp.scheme != "https" && rp.scheme != "http") {
  1254. // See 8.1.2.6 Malformed Requests and Responses:
  1255. //
  1256. // Malformed requests or responses that are detected
  1257. // MUST be treated as a stream error (Section 5.4.2)
  1258. // of type PROTOCOL_ERROR."
  1259. //
  1260. // 8.1.2.3 Request Pseudo-Header Fields
  1261. // "All HTTP/2 requests MUST include exactly one valid
  1262. // value for the :method, :scheme, and :path
  1263. // pseudo-header fields"
  1264. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1265. }
  1266. var tlsState *tls.ConnectionState // nil if not scheme https
  1267. if rp.scheme == "https" {
  1268. tlsState = sc.tlsState
  1269. }
  1270. authority := rp.authority
  1271. if authority == "" {
  1272. authority = rp.header.Get("Host")
  1273. }
  1274. needsContinue := rp.header.Get("Expect") == "100-continue"
  1275. if needsContinue {
  1276. rp.header.Del("Expect")
  1277. }
  1278. bodyOpen := rp.stream.state == stateOpen
  1279. body := &requestBody{
  1280. conn: sc,
  1281. stream: rp.stream,
  1282. needsContinue: needsContinue,
  1283. }
  1284. // TODO: handle asterisk '*' requests + test
  1285. url, err := url.ParseRequestURI(rp.path)
  1286. if err != nil {
  1287. // TODO: find the right error code?
  1288. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  1289. }
  1290. req := &http.Request{
  1291. Method: rp.method,
  1292. URL: url,
  1293. RemoteAddr: sc.remoteAddrStr,
  1294. Header: rp.header,
  1295. RequestURI: rp.path,
  1296. Proto: "HTTP/2.0",
  1297. ProtoMajor: 2,
  1298. ProtoMinor: 0,
  1299. TLS: tlsState,
  1300. Host: authority,
  1301. Body: body,
  1302. }
  1303. if bodyOpen {
  1304. body.pipe = &pipe{
  1305. b: buffer{buf: make([]byte, initialWindowSize)}, // TODO: share/remove XXX
  1306. }
  1307. body.pipe.c.L = &body.pipe.m
  1308. if vv, ok := rp.header["Content-Length"]; ok {
  1309. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  1310. } else {
  1311. req.ContentLength = -1
  1312. }
  1313. }
  1314. rws := responseWriterStatePool.Get().(*responseWriterState)
  1315. bwSave := rws.bw
  1316. *rws = responseWriterState{} // zero all the fields
  1317. rws.conn = sc
  1318. rws.bw = bwSave
  1319. rws.bw.Reset(chunkWriter{rws})
  1320. rws.stream = rp.stream
  1321. rws.req = req
  1322. rws.body = body
  1323. rws.frameWriteCh = make(chan error, 1)
  1324. rw := &responseWriter{rws: rws}
  1325. return rw, req, nil
  1326. }
  1327. // Run on its own goroutine.
  1328. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request) {
  1329. defer rw.handlerDone()
  1330. // TODO: catch panics like net/http.Server
  1331. sc.handler.ServeHTTP(rw, req)
  1332. }
  1333. // called from handler goroutines.
  1334. // h may be nil.
  1335. func (sc *serverConn) writeHeaders(st *stream, headerData *writeResHeaders, tempCh chan error) {
  1336. sc.serveG.checkNotOn() // NOT on
  1337. var errc chan error
  1338. if headerData.h != nil {
  1339. // If there's a header map (which we don't own), so we have to block on
  1340. // waiting for this frame to be written, so an http.Flush mid-handler
  1341. // writes out the correct value of keys, before a handler later potentially
  1342. // mutates it.
  1343. errc = tempCh
  1344. }
  1345. sc.writeFrameFromHandler(frameWriteMsg{
  1346. write: headerData,
  1347. stream: st,
  1348. done: errc,
  1349. })
  1350. if errc != nil {
  1351. select {
  1352. case <-errc:
  1353. // Ignore. Just for synchronization.
  1354. // Any error will be handled in the writing goroutine.
  1355. case <-sc.doneServing:
  1356. // Client has closed the connection.
  1357. }
  1358. }
  1359. }
  1360. // called from handler goroutines.
  1361. func (sc *serverConn) write100ContinueHeaders(st *stream) {
  1362. sc.writeFrameFromHandler(frameWriteMsg{
  1363. write: write100ContinueHeadersFrame{st.id},
  1364. stream: st,
  1365. })
  1366. }
  1367. // A bodyReadMsg tells the server loop that the http.Handler read n
  1368. // bytes of the DATA from the client on the given stream.
  1369. type bodyReadMsg struct {
  1370. st *stream
  1371. n int
  1372. }
  1373. // called from handler goroutines.
  1374. // Notes that the handler for the given stream ID read n bytes of its body
  1375. // and schedules flow control tokens to be sent.
  1376. func (sc *serverConn) noteBodyReadFromHandler(st *stream, n int) {
  1377. sc.serveG.checkNotOn() // NOT on
  1378. sc.bodyReadCh <- bodyReadMsg{st, n}
  1379. }
  1380. func (sc *serverConn) noteBodyRead(st *stream, n int) {
  1381. sc.serveG.check()
  1382. sc.sendWindowUpdate(nil, n) // conn-level
  1383. if st.state != stateHalfClosedRemote && st.state != stateClosed {
  1384. // Don't send this WINDOW_UPDATE if the stream is closed
  1385. // remotely.
  1386. sc.sendWindowUpdate(st, n)
  1387. }
  1388. }
  1389. // st may be nil for conn-level
  1390. func (sc *serverConn) sendWindowUpdate(st *stream, n int) {
  1391. sc.serveG.check()
  1392. // "The legal range for the increment to the flow control
  1393. // window is 1 to 2^31-1 (2,147,483,647) octets."
  1394. // A Go Read call on 64-bit machines could in theory read
  1395. // a larger Read than this. Very unlikely, but we handle it here
  1396. // rather than elsewhere for now.
  1397. const maxUint31 = 1<<31 - 1
  1398. for n >= maxUint31 {
  1399. sc.sendWindowUpdate32(st, maxUint31)
  1400. n -= maxUint31
  1401. }
  1402. sc.sendWindowUpdate32(st, int32(n))
  1403. }
  1404. // st may be nil for conn-level
  1405. func (sc *serverConn) sendWindowUpdate32(st *stream, n int32) {
  1406. sc.serveG.check()
  1407. if n == 0 {
  1408. return
  1409. }
  1410. if n < 0 {
  1411. panic("negative update")
  1412. }
  1413. var streamID uint32
  1414. if st != nil {
  1415. streamID = st.id
  1416. }
  1417. sc.writeFrame(frameWriteMsg{
  1418. write: writeWindowUpdate{streamID: streamID, n: uint32(n)},
  1419. stream: st,
  1420. })
  1421. var ok bool
  1422. if st == nil {
  1423. ok = sc.inflow.add(n)
  1424. } else {
  1425. ok = st.inflow.add(n)
  1426. }
  1427. if !ok {
  1428. panic("internal error; sent too many window updates without decrements?")
  1429. }
  1430. }
  1431. type requestBody struct {
  1432. stream *stream
  1433. conn *serverConn
  1434. closed bool
  1435. pipe *pipe // non-nil if we have a HTTP entity message body
  1436. needsContinue bool // need to send a 100-continue
  1437. }
  1438. func (b *requestBody) Close() error {
  1439. if b.pipe != nil {
  1440. b.pipe.Close(errClosedBody)
  1441. }
  1442. b.closed = true
  1443. return nil
  1444. }
  1445. func (b *requestBody) Read(p []byte) (n int, err error) {
  1446. if b.needsContinue {
  1447. b.needsContinue = false
  1448. b.conn.write100ContinueHeaders(b.stream)
  1449. }
  1450. if b.pipe == nil {
  1451. return 0, io.EOF
  1452. }
  1453. n, err = b.pipe.Read(p)
  1454. if n > 0 {
  1455. b.conn.noteBodyReadFromHandler(b.stream, n)
  1456. }
  1457. return
  1458. }
  1459. // responseWriter is the http.ResponseWriter implementation. It's
  1460. // intentionally small (1 pointer wide) to minimize garbage. The
  1461. // responseWriterState pointer inside is zeroed at the end of a
  1462. // request (in handlerDone) and calls on the responseWriter thereafter
  1463. // simply crash (caller's mistake), but the much larger responseWriterState
  1464. // and buffers are reused between multiple requests.
  1465. type responseWriter struct {
  1466. rws *responseWriterState
  1467. }
  1468. // Optional http.ResponseWriter interfaces implemented.
  1469. var (
  1470. _ http.CloseNotifier = (*responseWriter)(nil)
  1471. _ http.Flusher = (*responseWriter)(nil)
  1472. _ stringWriter = (*responseWriter)(nil)
  1473. )
  1474. type responseWriterState struct {
  1475. // immutable within a request:
  1476. stream *stream
  1477. req *http.Request
  1478. body *requestBody // to close at end of request, if DATA frames didn't
  1479. conn *serverConn
  1480. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1481. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1482. // mutated by http.Handler goroutine:
  1483. handlerHeader http.Header // nil until called
  1484. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1485. status int // status code passed to WriteHeader
  1486. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1487. sentHeader bool // have we sent the header frame?
  1488. handlerDone bool // handler has finished
  1489. curWrite writeData
  1490. frameWriteCh chan error // re-used whenever we need to block on a frame being written
  1491. closeNotifierMu sync.Mutex // guards closeNotifierCh
  1492. closeNotifierCh chan bool // nil until first used
  1493. }
  1494. type chunkWriter struct{ rws *responseWriterState }
  1495. func (cw chunkWriter) Write(p []byte) (n int, err error) { return cw.rws.writeChunk(p) }
  1496. // writeChunk writes chunks from the bufio.Writer. But because
  1497. // bufio.Writer may bypass its chunking, sometimes p may be
  1498. // arbitrarily large.
  1499. //
  1500. // writeChunk is also responsible (on the first chunk) for sending the
  1501. // HEADER response.
  1502. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1503. if !rws.wroteHeader {
  1504. rws.writeHeader(200)
  1505. }
  1506. if !rws.sentHeader {
  1507. rws.sentHeader = true
  1508. var ctype, clen string // implicit ones, if we can calculate it
  1509. if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" {
  1510. clen = strconv.Itoa(len(p))
  1511. }
  1512. if rws.snapHeader.Get("Content-Type") == "" {
  1513. ctype = http.DetectContentType(p)
  1514. }
  1515. endStream := rws.handlerDone && len(p) == 0
  1516. rws.conn.writeHeaders(rws.stream, &writeResHeaders{
  1517. streamID: rws.stream.id,
  1518. httpResCode: rws.status,
  1519. h: rws.snapHeader,
  1520. endStream: endStream,
  1521. contentType: ctype,
  1522. contentLength: clen,
  1523. }, rws.frameWriteCh)
  1524. if endStream {
  1525. return 0, nil
  1526. }
  1527. }
  1528. if len(p) == 0 && !rws.handlerDone {
  1529. return 0, nil
  1530. }
  1531. curWrite := &rws.curWrite
  1532. curWrite.streamID = rws.stream.id
  1533. curWrite.p = p
  1534. curWrite.endStream = rws.handlerDone
  1535. if err := rws.conn.writeDataFromHandler(rws.stream, curWrite, rws.frameWriteCh); err != nil {
  1536. return 0, err
  1537. }
  1538. return len(p), nil
  1539. }
  1540. func (w *responseWriter) Flush() {
  1541. rws := w.rws
  1542. if rws == nil {
  1543. panic("Header called after Handler finished")
  1544. }
  1545. if rws.bw.Buffered() > 0 {
  1546. if err := rws.bw.Flush(); err != nil {
  1547. // Ignore the error. The frame writer already knows.
  1548. return
  1549. }
  1550. } else {
  1551. // The bufio.Writer won't call chunkWriter.Write
  1552. // (writeChunk with zero bytes, so we have to do it
  1553. // ourselves to force the HTTP response header and/or
  1554. // final DATA frame (with END_STREAM) to be sent.
  1555. rws.writeChunk(nil)
  1556. }
  1557. }
  1558. func (w *responseWriter) CloseNotify() <-chan bool {
  1559. rws := w.rws
  1560. if rws == nil {
  1561. panic("CloseNotify called after Handler finished")
  1562. }
  1563. rws.closeNotifierMu.Lock()
  1564. ch := rws.closeNotifierCh
  1565. if ch == nil {
  1566. ch = make(chan bool, 1)
  1567. rws.closeNotifierCh = ch
  1568. go func() {
  1569. rws.stream.cw.Wait() // wait for close
  1570. ch <- true
  1571. }()
  1572. }
  1573. rws.closeNotifierMu.Unlock()
  1574. return ch
  1575. }
  1576. func (w *responseWriter) Header() http.Header {
  1577. rws := w.rws
  1578. if rws == nil {
  1579. panic("Header called after Handler finished")
  1580. }
  1581. if rws.handlerHeader == nil {
  1582. rws.handlerHeader = make(http.Header)
  1583. }
  1584. return rws.handlerHeader
  1585. }
  1586. func (w *responseWriter) WriteHeader(code int) {
  1587. rws := w.rws
  1588. if rws == nil {
  1589. panic("WriteHeader called after Handler finished")
  1590. }
  1591. rws.writeHeader(code)
  1592. }
  1593. func (rws *responseWriterState) writeHeader(code int) {
  1594. if !rws.wroteHeader {
  1595. rws.wroteHeader = true
  1596. rws.status = code
  1597. if len(rws.handlerHeader) > 0 {
  1598. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1599. }
  1600. }
  1601. }
  1602. func cloneHeader(h http.Header) http.Header {
  1603. h2 := make(http.Header, len(h))
  1604. for k, vv := range h {
  1605. vv2 := make([]string, len(vv))
  1606. copy(vv2, vv)
  1607. h2[k] = vv2
  1608. }
  1609. return h2
  1610. }
  1611. // The Life Of A Write is like this:
  1612. //
  1613. // * Handler calls w.Write or w.WriteString ->
  1614. // * -> rws.bw (*bufio.Writer) ->
  1615. // * (Handler migth call Flush)
  1616. // * -> chunkWriter{rws}
  1617. // * -> responseWriterState.writeChunk(p []byte)
  1618. // * -> responseWriterState.writeChunk (most of the magic; see comment there)
  1619. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1620. return w.write(len(p), p, "")
  1621. }
  1622. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1623. return w.write(len(s), nil, s)
  1624. }
  1625. // either dataB or dataS is non-zero.
  1626. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1627. rws := w.rws
  1628. if rws == nil {
  1629. panic("Write called after Handler finished")
  1630. }
  1631. if !rws.wroteHeader {
  1632. w.WriteHeader(200)
  1633. }
  1634. if dataB != nil {
  1635. return rws.bw.Write(dataB)
  1636. } else {
  1637. return rws.bw.WriteString(dataS)
  1638. }
  1639. }
  1640. func (w *responseWriter) handlerDone() {
  1641. rws := w.rws
  1642. if rws == nil {
  1643. panic("handlerDone called twice")
  1644. }
  1645. rws.handlerDone = true
  1646. w.Flush()
  1647. w.rws = nil
  1648. responseWriterStatePool.Put(rws)
  1649. }