server.go 53 KB

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