server.go 35 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273
  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. package http2
  8. import (
  9. "bufio"
  10. "bytes"
  11. "crypto/tls"
  12. "errors"
  13. "fmt"
  14. "io"
  15. "log"
  16. "net"
  17. "net/http"
  18. "net/url"
  19. "strconv"
  20. "strings"
  21. "sync"
  22. "time"
  23. "github.com/bradfitz/http2/hpack"
  24. )
  25. const (
  26. prefaceTimeout = 5 * time.Second
  27. firstSettingsTimeout = 2 * time.Second // should be in-flight with preface anyway
  28. )
  29. // TODO: finish GOAWAY support. Consider each incoming frame type and
  30. // whether it should be ignored during a shutdown race.
  31. // TODO: (edge case?) if peer sends a SETTINGS frame with e.g. a
  32. // SETTINGS_MAX_FRAME_SIZE that's lower than what we had before,
  33. // before we ACK it we have to make sure all currently-active streams
  34. // know about that and don't have existing too-large frames in flight?
  35. // Perhaps the settings processing should just wait for new frame to
  36. // be in-flight and then the frame scheduler in the serve goroutine
  37. // will be responsible for splitting things.
  38. // Server is an HTTP/2 server.
  39. type Server struct {
  40. // MaxStreams optionally ...
  41. MaxStreams int
  42. }
  43. var testHookOnConn func() // for testing
  44. // ConfigureServer adds HTTP/2 support to a net/http Server.
  45. //
  46. // The configuration conf may be nil.
  47. //
  48. // ConfigureServer must be called before s begins serving.
  49. func ConfigureServer(s *http.Server, conf *Server) {
  50. if conf == nil {
  51. conf = new(Server)
  52. }
  53. if s.TLSConfig == nil {
  54. s.TLSConfig = new(tls.Config)
  55. }
  56. haveNPN := false
  57. for _, p := range s.TLSConfig.NextProtos {
  58. if p == npnProto {
  59. haveNPN = true
  60. break
  61. }
  62. }
  63. if !haveNPN {
  64. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, npnProto)
  65. }
  66. if s.TLSNextProto == nil {
  67. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  68. }
  69. s.TLSNextProto[npnProto] = func(hs *http.Server, c *tls.Conn, h http.Handler) {
  70. if testHookOnConn != nil {
  71. testHookOnConn()
  72. }
  73. conf.handleConn(hs, c, h)
  74. }
  75. }
  76. func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) {
  77. sc := &serverConn{
  78. hs: hs,
  79. conn: c,
  80. handler: h,
  81. framer: NewFramer(c, c), // TODO: write to a (custom?) buffered writer that can alternate when it's in buffered mode.
  82. streams: make(map[uint32]*stream),
  83. readFrameCh: make(chan frameAndGate),
  84. readFrameErrCh: make(chan error, 1), // must be buffered for 1
  85. wantWriteFrameCh: make(chan frameWriteMsg, 8),
  86. writeFrameCh: make(chan frameWriteMsg, 1), // may be 0 or 1, but more is useless. (max 1 in flight)
  87. wroteFrameCh: make(chan struct{}, 1),
  88. flow: newFlow(initialWindowSize),
  89. doneServing: make(chan struct{}),
  90. maxWriteFrameSize: initialMaxFrameSize,
  91. initialWindowSize: initialWindowSize,
  92. serveG: newGoroutineLock(),
  93. }
  94. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  95. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField)
  96. sc.serve()
  97. }
  98. // frameAndGates coordinates the readFrames and serve
  99. // goroutines. Because the Framer interface only permits the most
  100. // recently-read Frame from being accessed, the readFrames goroutine
  101. // blocks until it has a frame, passes it to serve, and then waits for
  102. // serve to be done with it before reading the next one.
  103. type frameAndGate struct {
  104. f Frame
  105. g gate
  106. }
  107. type serverConn struct {
  108. // Immutable:
  109. hs *http.Server
  110. conn net.Conn
  111. handler http.Handler
  112. framer *Framer
  113. hpackDecoder *hpack.Decoder
  114. doneServing chan struct{} // closed when serverConn.serve ends
  115. readFrameCh chan frameAndGate // written by serverConn.readFrames
  116. readFrameErrCh chan error
  117. wantWriteFrameCh chan frameWriteMsg // from handlers -> serve
  118. writeFrameCh chan frameWriteMsg // from serve -> writeFrames
  119. wroteFrameCh chan struct{} // from writeFrames -> serve, tickles more sends on writeFrameCh
  120. serveG goroutineLock // used to verify funcs are on serve()
  121. writeG goroutineLock // used to verify things running on writeLoop
  122. flow *flow // connection-wide (not stream-specific) flow control
  123. // Everything following is owned by the serve loop; use serveG.check():
  124. sawFirstSettings bool // got the initial SETTINGS frame after the preface
  125. needToSendSettingsAck bool
  126. maxStreamID uint32 // max ever seen
  127. streams map[uint32]*stream
  128. maxWriteFrameSize uint32 // TODO: update this when settings come in
  129. initialWindowSize int32
  130. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  131. sentGoAway bool
  132. req requestParam // non-zero while reading request headers
  133. writingFrame bool // sent on writeFrameCh but haven't heard back on wroteFrameCh yet
  134. writeQueue []frameWriteMsg // TODO: proper scheduler, not a queue
  135. // Owned by the writeFrames goroutine; use writeG.check():
  136. headerWriteBuf bytes.Buffer
  137. hpackEncoder *hpack.Encoder
  138. }
  139. // requestParam is the state of the next request, initialized over
  140. // potentially several frames HEADERS + zero or more CONTINUATION
  141. // frames.
  142. type requestParam struct {
  143. // stream is non-nil if we're reading (HEADER or CONTINUATION)
  144. // frames for a request (but not DATA).
  145. stream *stream
  146. header http.Header
  147. method, path string
  148. scheme, authority string
  149. sawRegularHeader bool // saw a non-pseudo header already
  150. invalidHeader bool // an invalid header was seen
  151. }
  152. type stream struct {
  153. id uint32
  154. state streamState // owned by serverConn's processing loop
  155. flow *flow // limits writing from Handler to client
  156. body *pipe // non-nil if expecting DATA frames
  157. bodyBytes int64 // body bytes seen so far
  158. declBodyBytes int64 // or -1 if undeclared
  159. }
  160. func (sc *serverConn) state(streamID uint32) streamState {
  161. sc.serveG.check()
  162. // http://http2.github.io/http2-spec/#rfc.section.5.1
  163. if st, ok := sc.streams[streamID]; ok {
  164. return st.state
  165. }
  166. // "The first use of a new stream identifier implicitly closes all
  167. // streams in the "idle" state that might have been initiated by
  168. // that peer with a lower-valued stream identifier. For example, if
  169. // a client sends a HEADERS frame on stream 7 without ever sending a
  170. // frame on stream 5, then stream 5 transitions to the "closed"
  171. // state when the first frame for stream 7 is sent or received."
  172. if streamID <= sc.maxStreamID {
  173. return stateClosed
  174. }
  175. return stateIdle
  176. }
  177. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  178. if VerboseLogs {
  179. sc.logf(format, args...)
  180. }
  181. }
  182. func (sc *serverConn) logf(format string, args ...interface{}) {
  183. if lg := sc.hs.ErrorLog; lg != nil {
  184. lg.Printf(format, args...)
  185. } else {
  186. log.Printf(format, args...)
  187. }
  188. }
  189. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  190. if err == nil {
  191. return
  192. }
  193. str := err.Error()
  194. if err == io.EOF || strings.Contains(str, "use of closed network connection") {
  195. // Boring, expected errors.
  196. sc.vlogf(format, args...)
  197. } else {
  198. sc.logf(format, args...)
  199. }
  200. }
  201. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  202. sc.serveG.check()
  203. switch {
  204. case !validHeader(f.Name):
  205. sc.req.invalidHeader = true
  206. case strings.HasPrefix(f.Name, ":"):
  207. if sc.req.sawRegularHeader {
  208. sc.logf("pseudo-header after regular header")
  209. sc.req.invalidHeader = true
  210. return
  211. }
  212. var dst *string
  213. switch f.Name {
  214. case ":method":
  215. dst = &sc.req.method
  216. case ":path":
  217. dst = &sc.req.path
  218. case ":scheme":
  219. dst = &sc.req.scheme
  220. case ":authority":
  221. dst = &sc.req.authority
  222. default:
  223. // 8.1.2.1 Pseudo-Header Fields
  224. // "Endpoints MUST treat a request or response
  225. // that contains undefined or invalid
  226. // pseudo-header fields as malformed (Section
  227. // 8.1.2.6)."
  228. sc.logf("invalid pseudo-header %q", f.Name)
  229. sc.req.invalidHeader = true
  230. return
  231. }
  232. if *dst != "" {
  233. sc.logf("duplicate pseudo-header %q sent", f.Name)
  234. sc.req.invalidHeader = true
  235. return
  236. }
  237. *dst = f.Value
  238. case f.Name == "cookie":
  239. sc.req.sawRegularHeader = true
  240. if s, ok := sc.req.header["Cookie"]; ok && len(s) == 1 {
  241. s[0] = s[0] + "; " + f.Value
  242. } else {
  243. sc.req.header.Add("Cookie", f.Value)
  244. }
  245. default:
  246. sc.req.sawRegularHeader = true
  247. sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value)
  248. }
  249. }
  250. func (sc *serverConn) canonicalHeader(v string) string {
  251. sc.serveG.check()
  252. cv, ok := commonCanonHeader[v]
  253. if ok {
  254. return cv
  255. }
  256. cv, ok = sc.canonHeader[v]
  257. if ok {
  258. return cv
  259. }
  260. if sc.canonHeader == nil {
  261. sc.canonHeader = make(map[string]string)
  262. }
  263. cv = http.CanonicalHeaderKey(v)
  264. sc.canonHeader[v] = cv
  265. return cv
  266. }
  267. // readFrames is the loop that reads incoming frames.
  268. // It's run on its own goroutine.
  269. func (sc *serverConn) readFrames() {
  270. g := make(gate, 1)
  271. for {
  272. f, err := sc.framer.ReadFrame()
  273. if err != nil {
  274. sc.readFrameErrCh <- err // BEFORE the close
  275. close(sc.readFrameCh)
  276. return
  277. }
  278. sc.readFrameCh <- frameAndGate{f, g}
  279. g.Wait()
  280. }
  281. }
  282. // writeFrames is the loop that writes frames to the peer
  283. // and is responsible for prioritization and buffering.
  284. // It's run on its own goroutine.
  285. func (sc *serverConn) writeFrames() {
  286. sc.writeG = newGoroutineLock()
  287. for wm := range sc.writeFrameCh {
  288. err := wm.write(sc, wm.v)
  289. if ch := wm.done; ch != nil {
  290. select {
  291. case ch <- err:
  292. default:
  293. panic(fmt.Sprintf("unbuffered done channel passed in for type %T", wm.v))
  294. }
  295. }
  296. sc.wroteFrameCh <- struct{}{} // tickle frame selection scheduler
  297. }
  298. }
  299. func (sc *serverConn) serve() {
  300. sc.serveG.check()
  301. defer sc.conn.Close()
  302. defer close(sc.doneServing)
  303. sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  304. if err := sc.framer.WriteSettings( /* TODO: actual settings */ ); err != nil {
  305. sc.logf("error writing server's initial settings: %v", err)
  306. return
  307. }
  308. if err := sc.readPreface(); err != nil {
  309. sc.condlogf(err, "Error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  310. return
  311. }
  312. go sc.readFrames() // closed by defer sc.conn.Close above
  313. go sc.writeFrames()
  314. defer close(sc.writeFrameCh) // shuts down writeFrames loop
  315. settingsTimer := time.NewTimer(firstSettingsTimeout)
  316. for {
  317. select {
  318. case wm := <-sc.wantWriteFrameCh:
  319. sc.enqueueFrameWrite(wm)
  320. case <-sc.wroteFrameCh:
  321. sc.writingFrame = false
  322. sc.scheduleFrameWrite()
  323. case fg, ok := <-sc.readFrameCh:
  324. if !sc.processFrameFromReader(fg, ok) {
  325. return
  326. }
  327. if settingsTimer.C != nil {
  328. settingsTimer.Stop()
  329. settingsTimer.C = nil
  330. }
  331. case <-settingsTimer.C:
  332. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  333. return
  334. }
  335. }
  336. }
  337. // readPreface reads the ClientPreface greeting from the peer
  338. // or returns an error on timeout or an invalid greeting.
  339. func (sc *serverConn) readPreface() error {
  340. errc := make(chan error, 1)
  341. go func() {
  342. // Read the client preface
  343. buf := make([]byte, len(ClientPreface))
  344. // TODO: timeout reading from the client
  345. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  346. errc <- err
  347. } else if !bytes.Equal(buf, clientPreface) {
  348. errc <- fmt.Errorf("bogus greeting %q", buf)
  349. } else {
  350. errc <- nil
  351. }
  352. }()
  353. timer := time.NewTimer(5 * time.Second) // TODO: configurable on *Server?
  354. defer timer.Stop()
  355. select {
  356. case <-timer.C:
  357. return errors.New("timeout waiting for client preface")
  358. case err := <-errc:
  359. if err == nil {
  360. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  361. }
  362. return err
  363. }
  364. }
  365. // should be called from non-serve() goroutines, otherwise the ends may deadlock
  366. // the serve loop. (it's only buffered a little bit).
  367. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  368. sc.serveG.checkNotOn() // note the "NOT"
  369. sc.wantWriteFrameCh <- wm
  370. }
  371. func (sc *serverConn) enqueueFrameWrite(wm frameWriteMsg) {
  372. sc.serveG.check()
  373. // Fast path for common case:
  374. if !sc.writingFrame {
  375. sc.writingFrame = true
  376. sc.writeFrameCh <- wm
  377. return
  378. }
  379. sc.writeQueue = append(sc.writeQueue, wm) // TODO: proper scheduler
  380. }
  381. func (sc *serverConn) enqueueSettingsAck() {
  382. sc.serveG.check()
  383. // Fast path for common case:
  384. if !sc.writingFrame {
  385. sc.writeFrameCh <- frameWriteMsg{write: (*serverConn).writeSettingsAck}
  386. return
  387. }
  388. sc.needToSendSettingsAck = true
  389. }
  390. func (sc *serverConn) scheduleFrameWrite() {
  391. sc.serveG.check()
  392. if sc.writingFrame {
  393. panic("invariant")
  394. }
  395. if sc.needToSendSettingsAck {
  396. sc.needToSendSettingsAck = false
  397. sc.enqueueSettingsAck()
  398. return
  399. }
  400. if len(sc.writeQueue) == 0 {
  401. // TODO: flush Framer's underlying buffered writer, once that's added
  402. return
  403. }
  404. // TODO: proper scheduler
  405. wm := sc.writeQueue[0]
  406. // shift it all down. kinda lame. will be removed later anyway.
  407. copy(sc.writeQueue, sc.writeQueue[1:])
  408. sc.writeQueue = sc.writeQueue[:len(sc.writeQueue)-1]
  409. // TODO: if wm is a data frame, make sure it's not too big
  410. // (because a SETTINGS frame changed our max frame size while
  411. // a stream was open and writing) and cut it up into smaller
  412. // bits.
  413. sc.writingFrame = true
  414. sc.writeFrameCh <- wm
  415. }
  416. func (sc *serverConn) goAway(code ErrCode) error {
  417. sc.serveG.check()
  418. sc.sentGoAway = true
  419. return sc.framer.WriteGoAway(sc.maxStreamID, code, nil)
  420. }
  421. func (sc *serverConn) resetStreamInLoop(se StreamError) error {
  422. sc.serveG.check()
  423. if err := sc.framer.WriteRSTStream(se.streamID, uint32(se.code)); err != nil {
  424. return err
  425. }
  426. delete(sc.streams, se.streamID)
  427. return nil
  428. }
  429. func (sc *serverConn) curHeaderStreamID() uint32 {
  430. sc.serveG.check()
  431. st := sc.req.stream
  432. if st == nil {
  433. return 0
  434. }
  435. return st.id
  436. }
  437. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  438. // frame-reading goroutine.
  439. // processFrameFromReader returns whether the connection should be kept open.
  440. func (sc *serverConn) processFrameFromReader(fg frameAndGate, fgValid bool) bool {
  441. sc.serveG.check()
  442. if !fgValid {
  443. err := <-sc.readFrameErrCh
  444. if err != io.EOF {
  445. errstr := err.Error()
  446. if !strings.Contains(errstr, "use of closed network connection") {
  447. sc.logf("client %s stopped sending frames: %v", sc.conn.RemoteAddr(), errstr)
  448. }
  449. }
  450. // TODO: could we also get into this state if the peer does a half close (e.g. CloseWrite)
  451. // because they're done sending frames but they're still wanting our open replies?
  452. // Investigate.
  453. return false
  454. }
  455. f := fg.f
  456. sc.vlogf("got %v: %#v", f.Header(), f)
  457. err := sc.processFrame(f)
  458. fg.g.Done() // unblock the readFrames goroutine
  459. if err == nil {
  460. return true
  461. }
  462. switch ev := err.(type) {
  463. case StreamError:
  464. if err := sc.resetStreamInLoop(ev); err != nil {
  465. sc.logf("Error writing RSTSTream: %v", err)
  466. return false
  467. }
  468. return true
  469. case goAwayFlowError:
  470. if err := sc.goAway(ErrCodeFlowControl); err != nil {
  471. sc.condlogf(err, "failed to GOAWAY: %v", err)
  472. return false
  473. }
  474. return true
  475. case ConnectionError:
  476. sc.logf("disconnecting; %v", ev)
  477. default:
  478. sc.logf("Disconnection due to other error: %v", err)
  479. }
  480. return false
  481. }
  482. func (sc *serverConn) processFrame(f Frame) error {
  483. sc.serveG.check()
  484. // First frame received must be SETTINGS.
  485. if !sc.sawFirstSettings {
  486. if _, ok := f.(*SettingsFrame); !ok {
  487. return ConnectionError(ErrCodeProtocol)
  488. }
  489. sc.sawFirstSettings = true
  490. }
  491. if s := sc.curHeaderStreamID(); s != 0 {
  492. if cf, ok := f.(*ContinuationFrame); !ok {
  493. return ConnectionError(ErrCodeProtocol)
  494. } else if cf.Header().StreamID != s {
  495. return ConnectionError(ErrCodeProtocol)
  496. }
  497. }
  498. switch f := f.(type) {
  499. case *SettingsFrame:
  500. return sc.processSettings(f)
  501. case *HeadersFrame:
  502. return sc.processHeaders(f)
  503. case *ContinuationFrame:
  504. return sc.processContinuation(f)
  505. case *WindowUpdateFrame:
  506. return sc.processWindowUpdate(f)
  507. case *PingFrame:
  508. return sc.processPing(f)
  509. case *DataFrame:
  510. return sc.processData(f)
  511. default:
  512. log.Printf("Ignoring unknown frame %#v", f)
  513. return nil
  514. }
  515. }
  516. func (sc *serverConn) processPing(f *PingFrame) error {
  517. sc.serveG.check()
  518. if f.Flags.Has(FlagSettingsAck) {
  519. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  520. // containing this flag."
  521. return nil
  522. }
  523. if f.StreamID != 0 {
  524. // "PING frames are not associated with any individual
  525. // stream. If a PING frame is received with a stream
  526. // identifier field value other than 0x0, the recipient MUST
  527. // respond with a connection error (Section 5.4.1) of type
  528. // PROTOCOL_ERROR."
  529. return ConnectionError(ErrCodeProtocol)
  530. }
  531. sc.enqueueFrameWrite(frameWriteMsg{
  532. write: (*serverConn).writePingAck,
  533. v: f,
  534. })
  535. return nil
  536. }
  537. func (sc *serverConn) writePingAck(v interface{}) error {
  538. sc.writeG.check()
  539. pf := v.(*PingFrame) // contains the data we need to write back
  540. return sc.framer.WritePing(true, pf.Data)
  541. }
  542. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  543. sc.serveG.check()
  544. switch {
  545. case f.StreamID != 0: // stream-level flow control
  546. st := sc.streams[f.StreamID]
  547. if st == nil {
  548. // "WINDOW_UPDATE can be sent by a peer that has sent a
  549. // frame bearing the END_STREAM flag. This means that a
  550. // receiver could receive a WINDOW_UPDATE frame on a "half
  551. // closed (remote)" or "closed" stream. A receiver MUST
  552. // NOT treat this as an error, see Section 5.1."
  553. return nil
  554. }
  555. if !st.flow.add(int32(f.Increment)) {
  556. return StreamError{f.StreamID, ErrCodeFlowControl}
  557. }
  558. default: // connection-level flow control
  559. if !sc.flow.add(int32(f.Increment)) {
  560. return goAwayFlowError{}
  561. }
  562. }
  563. return nil
  564. }
  565. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  566. sc.serveG.check()
  567. if f.IsAck() {
  568. // TODO: do we need to do anything?
  569. return nil
  570. }
  571. if err := f.ForeachSetting(sc.processSetting); err != nil {
  572. return err
  573. }
  574. sc.enqueueSettingsAck()
  575. return nil
  576. }
  577. func (sc *serverConn) writeSettingsAck(_ interface{}) error {
  578. return sc.framer.WriteSettingsAck()
  579. }
  580. func (sc *serverConn) processSetting(s Setting) error {
  581. sc.serveG.check()
  582. sc.vlogf("processing setting %v", s)
  583. switch s.ID {
  584. case SettingInitialWindowSize:
  585. return sc.processSettingInitialWindowSize(s.Val)
  586. }
  587. log.Printf("TODO: handle %v", s)
  588. return nil
  589. }
  590. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  591. sc.serveG.check()
  592. if val > (1<<31 - 1) {
  593. // 6.5.2 Defined SETTINGS Parameters
  594. // "Values above the maximum flow control window size of
  595. // 231-1 MUST be treated as a connection error (Section
  596. // 5.4.1) of type FLOW_CONTROL_ERROR."
  597. return ConnectionError(ErrCodeFlowControl)
  598. }
  599. // "A SETTINGS frame can alter the initial flow control window
  600. // size for all current streams. When the value of
  601. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  602. // adjust the size of all stream flow control windows that it
  603. // maintains by the difference between the new value and the
  604. // old value."
  605. old := sc.initialWindowSize
  606. sc.initialWindowSize = int32(val)
  607. growth := sc.initialWindowSize - old // may be negative
  608. for _, st := range sc.streams {
  609. if !st.flow.add(growth) {
  610. // 6.9.2 Initial Flow Control Window Size
  611. // "An endpoint MUST treat a change to
  612. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  613. // control window to exceed the maximum size as a
  614. // connection error (Section 5.4.1) of type
  615. // FLOW_CONTROL_ERROR."
  616. return ConnectionError(ErrCodeFlowControl)
  617. }
  618. }
  619. return nil
  620. }
  621. func (sc *serverConn) processData(f *DataFrame) error {
  622. sc.serveG.check()
  623. // "If a DATA frame is received whose stream is not in "open"
  624. // or "half closed (local)" state, the recipient MUST respond
  625. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  626. id := f.Header().StreamID
  627. st, ok := sc.streams[id]
  628. if !ok || (st.state != stateOpen && st.state != stateHalfClosedLocal) {
  629. return StreamError{id, ErrCodeStreamClosed}
  630. }
  631. if st.body == nil {
  632. // Not expecting data.
  633. // TODO: which error code?
  634. return StreamError{id, ErrCodeStreamClosed}
  635. }
  636. data := f.Data()
  637. // Sender sending more than they'd declared?
  638. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  639. st.body.Close(fmt.Errorf("Sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  640. return StreamError{id, ErrCodeStreamClosed}
  641. }
  642. if len(data) > 0 {
  643. // TODO: verify they're allowed to write with the flow control
  644. // window we'd advertised to them.
  645. // TODO: verify n from Write
  646. if _, err := st.body.Write(data); err != nil {
  647. return StreamError{id, ErrCodeStreamClosed}
  648. }
  649. st.bodyBytes += int64(len(data))
  650. }
  651. if f.Header().Flags.Has(FlagDataEndStream) {
  652. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  653. st.body.Close(fmt.Errorf("Request declared a Content-Length of %d but only wrote %d bytes",
  654. st.declBodyBytes, st.bodyBytes))
  655. } else {
  656. st.body.Close(io.EOF)
  657. }
  658. }
  659. return nil
  660. }
  661. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  662. sc.serveG.check()
  663. id := f.Header().StreamID
  664. if sc.sentGoAway {
  665. // Ignore.
  666. return nil
  667. }
  668. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  669. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  670. // Streams initiated by a client MUST use odd-numbered
  671. // stream identifiers. [...] The identifier of a newly
  672. // established stream MUST be numerically greater than all
  673. // streams that the initiating endpoint has opened or
  674. // reserved. [...] An endpoint that receives an unexpected
  675. // stream identifier MUST respond with a connection error
  676. // (Section 5.4.1) of type PROTOCOL_ERROR.
  677. return ConnectionError(ErrCodeProtocol)
  678. }
  679. if id > sc.maxStreamID {
  680. sc.maxStreamID = id
  681. }
  682. st := &stream{
  683. id: id,
  684. state: stateOpen,
  685. flow: newFlow(sc.initialWindowSize),
  686. }
  687. if f.Header().Flags.Has(FlagHeadersEndStream) {
  688. st.state = stateHalfClosedRemote
  689. }
  690. sc.streams[id] = st
  691. sc.req = requestParam{
  692. stream: st,
  693. header: make(http.Header),
  694. }
  695. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  696. }
  697. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  698. sc.serveG.check()
  699. st := sc.streams[f.Header().StreamID]
  700. if st == nil || sc.curHeaderStreamID() != st.id {
  701. return ConnectionError(ErrCodeProtocol)
  702. }
  703. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  704. }
  705. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  706. sc.serveG.check()
  707. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  708. // TODO: convert to stream error I assume?
  709. return err
  710. }
  711. if !end {
  712. return nil
  713. }
  714. if err := sc.hpackDecoder.Close(); err != nil {
  715. // TODO: convert to stream error I assume?
  716. return err
  717. }
  718. rw, req, err := sc.newWriterAndRequest()
  719. sc.req = requestParam{}
  720. if err != nil {
  721. return err
  722. }
  723. st.body = req.Body.(*requestBody).pipe // may be nil
  724. st.declBodyBytes = req.ContentLength
  725. go sc.runHandler(rw, req)
  726. return nil
  727. }
  728. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  729. sc.serveG.check()
  730. rp := &sc.req
  731. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  732. (rp.scheme != "https" && rp.scheme != "http") {
  733. // See 8.1.2.6 Malformed Requests and Responses:
  734. //
  735. // Malformed requests or responses that are detected
  736. // MUST be treated as a stream error (Section 5.4.2)
  737. // of type PROTOCOL_ERROR."
  738. //
  739. // 8.1.2.3 Request Pseudo-Header Fields
  740. // "All HTTP/2 requests MUST include exactly one valid
  741. // value for the :method, :scheme, and :path
  742. // pseudo-header fields"
  743. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  744. }
  745. var tlsState *tls.ConnectionState // make this non-nil if https
  746. if rp.scheme == "https" {
  747. // TODO: get from sc's ConnectionState
  748. tlsState = &tls.ConnectionState{}
  749. }
  750. authority := rp.authority
  751. if authority == "" {
  752. authority = rp.header.Get("Host")
  753. }
  754. needsContinue := rp.header.Get("Expect") == "100-continue"
  755. if needsContinue {
  756. rp.header.Del("Expect")
  757. }
  758. bodyOpen := rp.stream.state == stateOpen
  759. body := &requestBody{
  760. sc: sc,
  761. streamID: rp.stream.id,
  762. needsContinue: needsContinue,
  763. }
  764. url, err := url.ParseRequestURI(rp.path)
  765. if err != nil {
  766. // TODO: find the right error code?
  767. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  768. }
  769. req := &http.Request{
  770. Method: rp.method,
  771. URL: url,
  772. RemoteAddr: sc.conn.RemoteAddr().String(),
  773. Header: rp.header,
  774. RequestURI: rp.path,
  775. Proto: "HTTP/2.0",
  776. ProtoMajor: 2,
  777. ProtoMinor: 0,
  778. TLS: tlsState,
  779. Host: authority,
  780. Body: body,
  781. }
  782. if bodyOpen {
  783. body.pipe = &pipe{
  784. b: buffer{buf: make([]byte, 65536)}, // TODO: share/remove
  785. }
  786. body.pipe.c.L = &body.pipe.m
  787. if vv, ok := rp.header["Content-Length"]; ok {
  788. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  789. } else {
  790. req.ContentLength = -1
  791. }
  792. }
  793. rws := responseWriterStatePool.Get().(*responseWriterState)
  794. bwSave := rws.bw
  795. *rws = responseWriterState{} // zero all the fields
  796. rws.bw = bwSave
  797. rws.bw.Reset(chunkWriter{rws})
  798. rws.sc = sc
  799. rws.streamID = rp.stream.id
  800. rws.req = req
  801. rws.body = body
  802. rws.chunkWrittenCh = make(chan error, 1)
  803. rw := &responseWriter{rws: rws}
  804. return rw, req, nil
  805. }
  806. const handlerChunkWriteSize = 4 << 10
  807. var responseWriterStatePool = sync.Pool{
  808. New: func() interface{} {
  809. rws := &responseWriterState{}
  810. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  811. return rws
  812. },
  813. }
  814. // Run on its own goroutine.
  815. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request) {
  816. defer rw.handlerDone()
  817. // TODO: catch panics like net/http.Server
  818. sc.handler.ServeHTTP(rw, req)
  819. }
  820. type frameWriteMsg struct {
  821. // write runs on the writeFrames goroutine.
  822. write func(sc *serverConn, v interface{}) error
  823. v interface{} // passed to write
  824. cost uint32 // number of flow control bytes required
  825. streamID uint32 // used for prioritization
  826. // done, if non-nil, must be a buffered channel with space for
  827. // 1 message and is sent the return value from write (or an
  828. // earlier error) when the frame has been written.
  829. done chan error
  830. }
  831. // headerWriteReq is a request to write an HTTP response header from a server Handler.
  832. type headerWriteReq struct {
  833. streamID uint32
  834. httpResCode int
  835. h http.Header // may be nil
  836. endStream bool
  837. contentType string
  838. contentLength string
  839. }
  840. // called from handler goroutines.
  841. // h may be nil.
  842. func (sc *serverConn) writeHeaders(req headerWriteReq) {
  843. sc.serveG.checkNotOn()
  844. var errc chan error
  845. if req.h != nil {
  846. // If there's a header map (which we don't own), so we have to block on
  847. // waiting for this frame to be written, so an http.Flush mid-handler
  848. // writes out the correct value of keys, before a handler later potentially
  849. // mutates it.
  850. errc = make(chan error, 1)
  851. }
  852. sc.writeFrame(frameWriteMsg{
  853. write: (*serverConn).writeHeadersFrame,
  854. v: req,
  855. streamID: req.streamID,
  856. done: errc,
  857. })
  858. if errc != nil {
  859. <-errc
  860. }
  861. }
  862. func (sc *serverConn) writeHeadersFrame(v interface{}) error {
  863. sc.writeG.check()
  864. req := v.(headerWriteReq)
  865. sc.headerWriteBuf.Reset()
  866. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: ":status", Value: httpCodeString(req.httpResCode)})
  867. for k, vv := range req.h {
  868. k = lowerHeader(k)
  869. for _, v := range vv {
  870. // TODO: more of "8.1.2.2 Connection-Specific Header Fields"
  871. if k == "transfer-encoding" && v != "trailers" {
  872. continue
  873. }
  874. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: k, Value: v})
  875. }
  876. }
  877. if req.contentType != "" {
  878. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: "content-type", Value: req.contentType})
  879. }
  880. if req.contentLength != "" {
  881. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: "content-length", Value: req.contentLength})
  882. }
  883. headerBlock := sc.headerWriteBuf.Bytes()
  884. if len(headerBlock) > int(sc.maxWriteFrameSize) {
  885. // we'll need continuation ones.
  886. panic("TODO")
  887. }
  888. return sc.framer.WriteHeaders(HeadersFrameParam{
  889. StreamID: req.streamID,
  890. BlockFragment: headerBlock,
  891. EndStream: req.endStream,
  892. EndHeaders: true, // no continuation yet
  893. })
  894. }
  895. // called from handler goroutines.
  896. // h may be nil.
  897. func (sc *serverConn) write100ContinueHeaders(streamID uint32) {
  898. sc.serveG.checkNotOn()
  899. sc.writeFrame(frameWriteMsg{
  900. write: (*serverConn).write100ContinueHeadersFrame,
  901. v: &streamID,
  902. streamID: streamID,
  903. })
  904. }
  905. func (sc *serverConn) write100ContinueHeadersFrame(v interface{}) error {
  906. sc.writeG.check()
  907. streamID := *(v.(*uint32))
  908. sc.headerWriteBuf.Reset()
  909. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: ":status", Value: "100"})
  910. return sc.framer.WriteHeaders(HeadersFrameParam{
  911. StreamID: streamID,
  912. BlockFragment: sc.headerWriteBuf.Bytes(),
  913. EndStream: false,
  914. EndHeaders: true,
  915. })
  916. }
  917. func (sc *serverConn) writeDataFrame(v interface{}) error {
  918. sc.writeG.check()
  919. rws := v.(*responseWriterState)
  920. return sc.framer.WriteData(rws.streamID, rws.curChunkIsFinal, rws.curChunk)
  921. }
  922. type windowUpdateReq struct {
  923. streamID uint32
  924. n uint32
  925. }
  926. // called from handler goroutines
  927. func (sc *serverConn) sendWindowUpdate(streamID uint32, n int) {
  928. const maxUint32 = 2147483647
  929. for n >= maxUint32 {
  930. sc.writeFrame(frameWriteMsg{
  931. write: (*serverConn).sendWindowUpdateInLoop,
  932. v: windowUpdateReq{streamID, maxUint32},
  933. streamID: streamID,
  934. })
  935. n -= maxUint32
  936. }
  937. if n > 0 {
  938. sc.writeFrame(frameWriteMsg{
  939. write: (*serverConn).sendWindowUpdateInLoop,
  940. v: windowUpdateReq{streamID, uint32(n)},
  941. streamID: streamID,
  942. })
  943. }
  944. }
  945. func (sc *serverConn) sendWindowUpdateInLoop(v interface{}) error {
  946. sc.writeG.check()
  947. wu := v.(windowUpdateReq)
  948. if err := sc.framer.WriteWindowUpdate(0, wu.n); err != nil {
  949. return err
  950. }
  951. if err := sc.framer.WriteWindowUpdate(wu.streamID, wu.n); err != nil {
  952. return err
  953. }
  954. return nil
  955. }
  956. type requestBody struct {
  957. sc *serverConn
  958. streamID uint32
  959. closed bool
  960. pipe *pipe // non-nil if we have a HTTP entity message body
  961. needsContinue bool // need to send a 100-continue
  962. }
  963. var errClosedBody = errors.New("body closed by handler")
  964. func (b *requestBody) Close() error {
  965. if b.pipe != nil {
  966. b.pipe.Close(errClosedBody)
  967. }
  968. b.closed = true
  969. return nil
  970. }
  971. func (b *requestBody) Read(p []byte) (n int, err error) {
  972. if b.needsContinue {
  973. b.needsContinue = false
  974. b.sc.write100ContinueHeaders(b.streamID)
  975. }
  976. if b.pipe == nil {
  977. return 0, io.EOF
  978. }
  979. n, err = b.pipe.Read(p)
  980. if n > 0 {
  981. b.sc.sendWindowUpdate(b.streamID, n)
  982. // TODO: tell b.sc to send back 'n' flow control quota credits to the sender
  983. }
  984. return
  985. }
  986. // responseWriter is the http.ResponseWriter implementation. It's
  987. // intentionally small (1 pointer wide) to minimize garbage. The
  988. // responseWriterState pointer inside is zeroed at the end of a
  989. // request (in handlerDone) and calls on the responseWriter thereafter
  990. // simply crash (caller's mistake), but the much larger responseWriterState
  991. // and buffers are reused between multiple requests.
  992. type responseWriter struct {
  993. rws *responseWriterState
  994. }
  995. // Optional http.ResponseWriter interfaces implemented.
  996. var (
  997. _ http.Flusher = (*responseWriter)(nil)
  998. _ stringWriter = (*responseWriter)(nil)
  999. // TODO: hijacker for websockets?
  1000. )
  1001. type responseWriterState struct {
  1002. // immutable within a request:
  1003. sc *serverConn
  1004. streamID uint32
  1005. req *http.Request
  1006. body *requestBody // to close at end of request, if DATA frames didn't
  1007. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1008. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1009. // mutated by http.Handler goroutine:
  1010. handlerHeader http.Header // nil until called
  1011. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1012. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1013. status int // status code passed to WriteHeader
  1014. sentHeader bool // have we sent the header frame?
  1015. handlerDone bool // handler has finished
  1016. curChunk []byte // current chunk we're writing
  1017. curChunkIsFinal bool
  1018. chunkWrittenCh chan error
  1019. }
  1020. type chunkWriter struct{ rws *responseWriterState }
  1021. // chunkWriter.Write is called from bufio.Writer. Because bufio.Writer passes through large
  1022. // writes, we break them up here if they're too big.
  1023. func (cw chunkWriter) Write(p []byte) (n int, err error) {
  1024. for len(p) > 0 {
  1025. chunk := p
  1026. if len(chunk) > handlerChunkWriteSize {
  1027. chunk = chunk[:handlerChunkWriteSize]
  1028. }
  1029. _, err = cw.rws.writeChunk(chunk)
  1030. if err != nil {
  1031. return
  1032. }
  1033. n += len(chunk)
  1034. p = p[len(chunk):]
  1035. }
  1036. return n, nil
  1037. }
  1038. // writeChunk writes small (max 4k, or handlerChunkWriteSize) chunks.
  1039. // It's also responsible for sending the HEADER response.
  1040. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1041. if !rws.wroteHeader {
  1042. rws.writeHeader(200)
  1043. }
  1044. if !rws.sentHeader {
  1045. rws.sentHeader = true
  1046. var ctype, clen string // implicit ones, if we can calculate it
  1047. if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" {
  1048. clen = strconv.Itoa(len(p))
  1049. }
  1050. if rws.snapHeader.Get("Content-Type") == "" {
  1051. ctype = http.DetectContentType(p)
  1052. }
  1053. rws.sc.writeHeaders(headerWriteReq{
  1054. streamID: rws.streamID,
  1055. httpResCode: rws.status,
  1056. h: rws.snapHeader,
  1057. endStream: rws.handlerDone && len(p) == 0,
  1058. contentType: ctype,
  1059. contentLength: clen,
  1060. })
  1061. }
  1062. if len(p) == 0 && !rws.handlerDone {
  1063. return
  1064. }
  1065. rws.curChunk = p
  1066. rws.curChunkIsFinal = rws.handlerDone
  1067. // TODO: await flow control tokens for both stream and conn
  1068. rws.sc.writeFrame(frameWriteMsg{
  1069. cost: uint32(len(p)),
  1070. streamID: rws.streamID,
  1071. write: (*serverConn).writeDataFrame,
  1072. done: rws.chunkWrittenCh,
  1073. v: rws, // writeDataInLoop uses only rws.curChunk and rws.curChunkIsFinal
  1074. })
  1075. err = <-rws.chunkWrittenCh // block until it's written
  1076. return len(p), err
  1077. }
  1078. func (w *responseWriter) Flush() {
  1079. rws := w.rws
  1080. if rws == nil {
  1081. panic("Header called after Handler finished")
  1082. }
  1083. if rws.bw.Buffered() > 0 {
  1084. if err := rws.bw.Flush(); err != nil {
  1085. // Ignore the error. The frame writer already knows.
  1086. return
  1087. }
  1088. } else {
  1089. // The bufio.Writer won't call chunkWriter.Write
  1090. // (writeChunk with zero bytes, so we have to do it
  1091. // ourselves to force the HTTP response header and/or
  1092. // final DATA frame (with END_STREAM) to be sent.
  1093. rws.writeChunk(nil)
  1094. }
  1095. }
  1096. func (w *responseWriter) Header() http.Header {
  1097. rws := w.rws
  1098. if rws == nil {
  1099. panic("Header called after Handler finished")
  1100. }
  1101. if rws.handlerHeader == nil {
  1102. rws.handlerHeader = make(http.Header)
  1103. }
  1104. return rws.handlerHeader
  1105. }
  1106. func (w *responseWriter) WriteHeader(code int) {
  1107. rws := w.rws
  1108. if rws == nil {
  1109. panic("WriteHeader called after Handler finished")
  1110. }
  1111. rws.writeHeader(code)
  1112. }
  1113. func (rws *responseWriterState) writeHeader(code int) {
  1114. if !rws.wroteHeader {
  1115. rws.wroteHeader = true
  1116. rws.status = code
  1117. if len(rws.handlerHeader) > 0 {
  1118. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1119. }
  1120. }
  1121. }
  1122. func cloneHeader(h http.Header) http.Header {
  1123. h2 := make(http.Header, len(h))
  1124. for k, vv := range h {
  1125. vv2 := make([]string, len(vv))
  1126. copy(vv2, vv)
  1127. h2[k] = vv2
  1128. }
  1129. return h2
  1130. }
  1131. // The Life Of A Write is like this:
  1132. //
  1133. // TODO: copy/adapt the similar comment from Go's http server.go
  1134. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1135. return w.write(len(p), p, "")
  1136. }
  1137. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1138. return w.write(len(s), nil, s)
  1139. }
  1140. // either dataB or dataS is non-zero.
  1141. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1142. rws := w.rws
  1143. if rws == nil {
  1144. panic("Write called after Handler finished")
  1145. }
  1146. if !rws.wroteHeader {
  1147. w.WriteHeader(200)
  1148. }
  1149. if dataB != nil {
  1150. return rws.bw.Write(dataB)
  1151. } else {
  1152. return rws.bw.WriteString(dataS)
  1153. }
  1154. }
  1155. func (w *responseWriter) handlerDone() {
  1156. rws := w.rws
  1157. if rws == nil {
  1158. panic("handlerDone called twice")
  1159. }
  1160. rws.handlerDone = true
  1161. w.Flush()
  1162. w.rws = nil
  1163. responseWriterStatePool.Put(rws)
  1164. }