server.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275
  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. sc.enqueueFrameWrite(frameWriteMsg{write: (*serverConn).sendInitialSettings})
  305. if err := sc.readPreface(); err != nil {
  306. sc.condlogf(err, "Error reading preface from client %v: %v", sc.conn.RemoteAddr(), err)
  307. return
  308. }
  309. go sc.readFrames() // closed by defer sc.conn.Close above
  310. go sc.writeFrames()
  311. defer close(sc.writeFrameCh) // shuts down writeFrames loop
  312. settingsTimer := time.NewTimer(firstSettingsTimeout)
  313. for {
  314. select {
  315. case wm := <-sc.wantWriteFrameCh:
  316. sc.enqueueFrameWrite(wm)
  317. case <-sc.wroteFrameCh:
  318. sc.writingFrame = false
  319. sc.scheduleFrameWrite()
  320. case fg, ok := <-sc.readFrameCh:
  321. if !sc.processFrameFromReader(fg, ok) {
  322. return
  323. }
  324. if settingsTimer.C != nil {
  325. settingsTimer.Stop()
  326. settingsTimer.C = nil
  327. }
  328. case <-settingsTimer.C:
  329. sc.logf("timeout waiting for SETTINGS frames from %v", sc.conn.RemoteAddr())
  330. return
  331. }
  332. }
  333. }
  334. func (sc *serverConn) sendInitialSettings(_ interface{}) error {
  335. sc.writeG.check()
  336. return sc.framer.WriteSettings( /* TODO: actual settings */ )
  337. }
  338. // readPreface reads the ClientPreface greeting from the peer
  339. // or returns an error on timeout or an invalid greeting.
  340. func (sc *serverConn) readPreface() error {
  341. errc := make(chan error, 1)
  342. go func() {
  343. // Read the client preface
  344. buf := make([]byte, len(ClientPreface))
  345. // TODO: timeout reading from the client
  346. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  347. errc <- err
  348. } else if !bytes.Equal(buf, clientPreface) {
  349. errc <- fmt.Errorf("bogus greeting %q", buf)
  350. } else {
  351. errc <- nil
  352. }
  353. }()
  354. timer := time.NewTimer(5 * time.Second) // TODO: configurable on *Server?
  355. defer timer.Stop()
  356. select {
  357. case <-timer.C:
  358. return errors.New("timeout waiting for client preface")
  359. case err := <-errc:
  360. if err == nil {
  361. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  362. }
  363. return err
  364. }
  365. }
  366. // should be called from non-serve() goroutines, otherwise the ends may deadlock
  367. // the serve loop. (it's only buffered a little bit).
  368. func (sc *serverConn) writeFrame(wm frameWriteMsg) {
  369. sc.serveG.checkNotOn() // note the "NOT"
  370. sc.wantWriteFrameCh <- wm
  371. }
  372. func (sc *serverConn) enqueueFrameWrite(wm frameWriteMsg) {
  373. sc.serveG.check()
  374. // Fast path for common case:
  375. if !sc.writingFrame {
  376. sc.writingFrame = true
  377. sc.writeFrameCh <- wm
  378. return
  379. }
  380. sc.writeQueue = append(sc.writeQueue, wm) // TODO: proper scheduler
  381. }
  382. func (sc *serverConn) enqueueSettingsAck() {
  383. sc.serveG.check()
  384. // Fast path for common case:
  385. if !sc.writingFrame {
  386. sc.writeFrameCh <- frameWriteMsg{write: (*serverConn).writeSettingsAck}
  387. return
  388. }
  389. sc.needToSendSettingsAck = true
  390. }
  391. func (sc *serverConn) scheduleFrameWrite() {
  392. sc.serveG.check()
  393. if sc.writingFrame {
  394. panic("invariant")
  395. }
  396. if sc.needToSendSettingsAck {
  397. sc.needToSendSettingsAck = false
  398. sc.enqueueSettingsAck()
  399. return
  400. }
  401. if len(sc.writeQueue) == 0 {
  402. // TODO: flush Framer's underlying buffered writer, once that's added
  403. return
  404. }
  405. // TODO: proper scheduler
  406. wm := sc.writeQueue[0]
  407. // shift it all down. kinda lame. will be removed later anyway.
  408. copy(sc.writeQueue, sc.writeQueue[1:])
  409. sc.writeQueue = sc.writeQueue[:len(sc.writeQueue)-1]
  410. // TODO: if wm is a data frame, make sure it's not too big
  411. // (because a SETTINGS frame changed our max frame size while
  412. // a stream was open and writing) and cut it up into smaller
  413. // bits.
  414. sc.writingFrame = true
  415. sc.writeFrameCh <- wm
  416. }
  417. func (sc *serverConn) goAway(code ErrCode) error {
  418. sc.serveG.check()
  419. sc.sentGoAway = true
  420. return sc.framer.WriteGoAway(sc.maxStreamID, code, nil)
  421. }
  422. func (sc *serverConn) resetStreamInLoop(se StreamError) error {
  423. sc.serveG.check()
  424. if err := sc.framer.WriteRSTStream(se.streamID, uint32(se.code)); err != nil {
  425. return err
  426. }
  427. delete(sc.streams, se.streamID)
  428. return nil
  429. }
  430. func (sc *serverConn) curHeaderStreamID() uint32 {
  431. sc.serveG.check()
  432. st := sc.req.stream
  433. if st == nil {
  434. return 0
  435. }
  436. return st.id
  437. }
  438. // processFrameFromReader processes the serve loop's read from readFrameCh from the
  439. // frame-reading goroutine.
  440. // processFrameFromReader returns whether the connection should be kept open.
  441. func (sc *serverConn) processFrameFromReader(fg frameAndGate, fgValid bool) bool {
  442. sc.serveG.check()
  443. if !fgValid {
  444. err := <-sc.readFrameErrCh
  445. if err != io.EOF {
  446. errstr := err.Error()
  447. if !strings.Contains(errstr, "use of closed network connection") {
  448. sc.logf("client %s stopped sending frames: %v", sc.conn.RemoteAddr(), errstr)
  449. }
  450. }
  451. // TODO: could we also get into this state if the peer does a half close (e.g. CloseWrite)
  452. // because they're done sending frames but they're still wanting our open replies?
  453. // Investigate.
  454. return false
  455. }
  456. f := fg.f
  457. sc.vlogf("got %v: %#v", f.Header(), f)
  458. err := sc.processFrame(f)
  459. fg.g.Done() // unblock the readFrames goroutine
  460. if err == nil {
  461. return true
  462. }
  463. switch ev := err.(type) {
  464. case StreamError:
  465. if err := sc.resetStreamInLoop(ev); err != nil {
  466. sc.logf("Error writing RSTSTream: %v", err)
  467. return false
  468. }
  469. return true
  470. case goAwayFlowError:
  471. if err := sc.goAway(ErrCodeFlowControl); err != nil {
  472. sc.condlogf(err, "failed to GOAWAY: %v", err)
  473. return false
  474. }
  475. return true
  476. case ConnectionError:
  477. sc.logf("disconnecting; %v", ev)
  478. default:
  479. sc.logf("Disconnection due to other error: %v", err)
  480. }
  481. return false
  482. }
  483. func (sc *serverConn) processFrame(f Frame) error {
  484. sc.serveG.check()
  485. // First frame received must be SETTINGS.
  486. if !sc.sawFirstSettings {
  487. if _, ok := f.(*SettingsFrame); !ok {
  488. return ConnectionError(ErrCodeProtocol)
  489. }
  490. sc.sawFirstSettings = true
  491. }
  492. if s := sc.curHeaderStreamID(); s != 0 {
  493. if cf, ok := f.(*ContinuationFrame); !ok {
  494. return ConnectionError(ErrCodeProtocol)
  495. } else if cf.Header().StreamID != s {
  496. return ConnectionError(ErrCodeProtocol)
  497. }
  498. }
  499. switch f := f.(type) {
  500. case *SettingsFrame:
  501. return sc.processSettings(f)
  502. case *HeadersFrame:
  503. return sc.processHeaders(f)
  504. case *ContinuationFrame:
  505. return sc.processContinuation(f)
  506. case *WindowUpdateFrame:
  507. return sc.processWindowUpdate(f)
  508. case *PingFrame:
  509. return sc.processPing(f)
  510. case *DataFrame:
  511. return sc.processData(f)
  512. default:
  513. log.Printf("Ignoring unknown frame %#v", f)
  514. return nil
  515. }
  516. }
  517. func (sc *serverConn) processPing(f *PingFrame) error {
  518. sc.serveG.check()
  519. if f.Flags.Has(FlagSettingsAck) {
  520. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  521. // containing this flag."
  522. return nil
  523. }
  524. if f.StreamID != 0 {
  525. // "PING frames are not associated with any individual
  526. // stream. If a PING frame is received with a stream
  527. // identifier field value other than 0x0, the recipient MUST
  528. // respond with a connection error (Section 5.4.1) of type
  529. // PROTOCOL_ERROR."
  530. return ConnectionError(ErrCodeProtocol)
  531. }
  532. sc.enqueueFrameWrite(frameWriteMsg{
  533. write: (*serverConn).writePingAck,
  534. v: f,
  535. })
  536. return nil
  537. }
  538. func (sc *serverConn) writePingAck(v interface{}) error {
  539. sc.writeG.check()
  540. pf := v.(*PingFrame) // contains the data we need to write back
  541. return sc.framer.WritePing(true, pf.Data)
  542. }
  543. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  544. sc.serveG.check()
  545. switch {
  546. case f.StreamID != 0: // stream-level flow control
  547. st := sc.streams[f.StreamID]
  548. if st == nil {
  549. // "WINDOW_UPDATE can be sent by a peer that has sent a
  550. // frame bearing the END_STREAM flag. This means that a
  551. // receiver could receive a WINDOW_UPDATE frame on a "half
  552. // closed (remote)" or "closed" stream. A receiver MUST
  553. // NOT treat this as an error, see Section 5.1."
  554. return nil
  555. }
  556. if !st.flow.add(int32(f.Increment)) {
  557. return StreamError{f.StreamID, ErrCodeFlowControl}
  558. }
  559. default: // connection-level flow control
  560. if !sc.flow.add(int32(f.Increment)) {
  561. return goAwayFlowError{}
  562. }
  563. }
  564. return nil
  565. }
  566. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  567. sc.serveG.check()
  568. if f.IsAck() {
  569. // TODO: do we need to do anything?
  570. return nil
  571. }
  572. if err := f.ForeachSetting(sc.processSetting); err != nil {
  573. return err
  574. }
  575. sc.enqueueSettingsAck()
  576. return nil
  577. }
  578. func (sc *serverConn) writeSettingsAck(_ interface{}) error {
  579. return sc.framer.WriteSettingsAck()
  580. }
  581. func (sc *serverConn) processSetting(s Setting) error {
  582. sc.serveG.check()
  583. sc.vlogf("processing setting %v", s)
  584. switch s.ID {
  585. case SettingInitialWindowSize:
  586. return sc.processSettingInitialWindowSize(s.Val)
  587. }
  588. log.Printf("TODO: handle %v", s)
  589. return nil
  590. }
  591. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  592. sc.serveG.check()
  593. if val > (1<<31 - 1) {
  594. // 6.5.2 Defined SETTINGS Parameters
  595. // "Values above the maximum flow control window size of
  596. // 231-1 MUST be treated as a connection error (Section
  597. // 5.4.1) of type FLOW_CONTROL_ERROR."
  598. return ConnectionError(ErrCodeFlowControl)
  599. }
  600. // "A SETTINGS frame can alter the initial flow control window
  601. // size for all current streams. When the value of
  602. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  603. // adjust the size of all stream flow control windows that it
  604. // maintains by the difference between the new value and the
  605. // old value."
  606. old := sc.initialWindowSize
  607. sc.initialWindowSize = int32(val)
  608. growth := sc.initialWindowSize - old // may be negative
  609. for _, st := range sc.streams {
  610. if !st.flow.add(growth) {
  611. // 6.9.2 Initial Flow Control Window Size
  612. // "An endpoint MUST treat a change to
  613. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  614. // control window to exceed the maximum size as a
  615. // connection error (Section 5.4.1) of type
  616. // FLOW_CONTROL_ERROR."
  617. return ConnectionError(ErrCodeFlowControl)
  618. }
  619. }
  620. return nil
  621. }
  622. func (sc *serverConn) processData(f *DataFrame) error {
  623. sc.serveG.check()
  624. // "If a DATA frame is received whose stream is not in "open"
  625. // or "half closed (local)" state, the recipient MUST respond
  626. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  627. id := f.Header().StreamID
  628. st, ok := sc.streams[id]
  629. if !ok || (st.state != stateOpen && st.state != stateHalfClosedLocal) {
  630. return StreamError{id, ErrCodeStreamClosed}
  631. }
  632. if st.body == nil {
  633. // Not expecting data.
  634. // TODO: which error code?
  635. return StreamError{id, ErrCodeStreamClosed}
  636. }
  637. data := f.Data()
  638. // Sender sending more than they'd declared?
  639. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  640. st.body.Close(fmt.Errorf("Sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  641. return StreamError{id, ErrCodeStreamClosed}
  642. }
  643. if len(data) > 0 {
  644. // TODO: verify they're allowed to write with the flow control
  645. // window we'd advertised to them.
  646. // TODO: verify n from Write
  647. if _, err := st.body.Write(data); err != nil {
  648. return StreamError{id, ErrCodeStreamClosed}
  649. }
  650. st.bodyBytes += int64(len(data))
  651. }
  652. if f.Header().Flags.Has(FlagDataEndStream) {
  653. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  654. st.body.Close(fmt.Errorf("Request declared a Content-Length of %d but only wrote %d bytes",
  655. st.declBodyBytes, st.bodyBytes))
  656. } else {
  657. st.body.Close(io.EOF)
  658. }
  659. }
  660. return nil
  661. }
  662. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  663. sc.serveG.check()
  664. id := f.Header().StreamID
  665. if sc.sentGoAway {
  666. // Ignore.
  667. return nil
  668. }
  669. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  670. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  671. // Streams initiated by a client MUST use odd-numbered
  672. // stream identifiers. [...] The identifier of a newly
  673. // established stream MUST be numerically greater than all
  674. // streams that the initiating endpoint has opened or
  675. // reserved. [...] An endpoint that receives an unexpected
  676. // stream identifier MUST respond with a connection error
  677. // (Section 5.4.1) of type PROTOCOL_ERROR.
  678. return ConnectionError(ErrCodeProtocol)
  679. }
  680. if id > sc.maxStreamID {
  681. sc.maxStreamID = id
  682. }
  683. st := &stream{
  684. id: id,
  685. state: stateOpen,
  686. flow: newFlow(sc.initialWindowSize),
  687. }
  688. if f.Header().Flags.Has(FlagHeadersEndStream) {
  689. st.state = stateHalfClosedRemote
  690. }
  691. sc.streams[id] = st
  692. sc.req = requestParam{
  693. stream: st,
  694. header: make(http.Header),
  695. }
  696. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  697. }
  698. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  699. sc.serveG.check()
  700. st := sc.streams[f.Header().StreamID]
  701. if st == nil || sc.curHeaderStreamID() != st.id {
  702. return ConnectionError(ErrCodeProtocol)
  703. }
  704. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  705. }
  706. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  707. sc.serveG.check()
  708. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  709. // TODO: convert to stream error I assume?
  710. return err
  711. }
  712. if !end {
  713. return nil
  714. }
  715. if err := sc.hpackDecoder.Close(); err != nil {
  716. // TODO: convert to stream error I assume?
  717. return err
  718. }
  719. rw, req, err := sc.newWriterAndRequest()
  720. sc.req = requestParam{}
  721. if err != nil {
  722. return err
  723. }
  724. st.body = req.Body.(*requestBody).pipe // may be nil
  725. st.declBodyBytes = req.ContentLength
  726. go sc.runHandler(rw, req)
  727. return nil
  728. }
  729. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  730. sc.serveG.check()
  731. rp := &sc.req
  732. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  733. (rp.scheme != "https" && rp.scheme != "http") {
  734. // See 8.1.2.6 Malformed Requests and Responses:
  735. //
  736. // Malformed requests or responses that are detected
  737. // MUST be treated as a stream error (Section 5.4.2)
  738. // of type PROTOCOL_ERROR."
  739. //
  740. // 8.1.2.3 Request Pseudo-Header Fields
  741. // "All HTTP/2 requests MUST include exactly one valid
  742. // value for the :method, :scheme, and :path
  743. // pseudo-header fields"
  744. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  745. }
  746. var tlsState *tls.ConnectionState // make this non-nil if https
  747. if rp.scheme == "https" {
  748. // TODO: get from sc's ConnectionState
  749. tlsState = &tls.ConnectionState{}
  750. }
  751. authority := rp.authority
  752. if authority == "" {
  753. authority = rp.header.Get("Host")
  754. }
  755. needsContinue := rp.header.Get("Expect") == "100-continue"
  756. if needsContinue {
  757. rp.header.Del("Expect")
  758. }
  759. bodyOpen := rp.stream.state == stateOpen
  760. body := &requestBody{
  761. sc: sc,
  762. streamID: rp.stream.id,
  763. needsContinue: needsContinue,
  764. }
  765. url, err := url.ParseRequestURI(rp.path)
  766. if err != nil {
  767. // TODO: find the right error code?
  768. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  769. }
  770. req := &http.Request{
  771. Method: rp.method,
  772. URL: url,
  773. RemoteAddr: sc.conn.RemoteAddr().String(),
  774. Header: rp.header,
  775. RequestURI: rp.path,
  776. Proto: "HTTP/2.0",
  777. ProtoMajor: 2,
  778. ProtoMinor: 0,
  779. TLS: tlsState,
  780. Host: authority,
  781. Body: body,
  782. }
  783. if bodyOpen {
  784. body.pipe = &pipe{
  785. b: buffer{buf: make([]byte, 65536)}, // TODO: share/remove
  786. }
  787. body.pipe.c.L = &body.pipe.m
  788. if vv, ok := rp.header["Content-Length"]; ok {
  789. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  790. } else {
  791. req.ContentLength = -1
  792. }
  793. }
  794. rws := responseWriterStatePool.Get().(*responseWriterState)
  795. bwSave := rws.bw
  796. *rws = responseWriterState{} // zero all the fields
  797. rws.bw = bwSave
  798. rws.bw.Reset(chunkWriter{rws})
  799. rws.sc = sc
  800. rws.streamID = rp.stream.id
  801. rws.req = req
  802. rws.body = body
  803. rws.chunkWrittenCh = make(chan error, 1)
  804. rw := &responseWriter{rws: rws}
  805. return rw, req, nil
  806. }
  807. const handlerChunkWriteSize = 4 << 10
  808. var responseWriterStatePool = sync.Pool{
  809. New: func() interface{} {
  810. rws := &responseWriterState{}
  811. rws.bw = bufio.NewWriterSize(chunkWriter{rws}, handlerChunkWriteSize)
  812. return rws
  813. },
  814. }
  815. // Run on its own goroutine.
  816. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request) {
  817. defer rw.handlerDone()
  818. // TODO: catch panics like net/http.Server
  819. sc.handler.ServeHTTP(rw, req)
  820. }
  821. type frameWriteMsg struct {
  822. // write runs on the writeFrames goroutine.
  823. write func(sc *serverConn, v interface{}) error
  824. v interface{} // passed to write
  825. cost uint32 // number of flow control bytes required
  826. streamID uint32 // used for prioritization
  827. // done, if non-nil, must be a buffered channel with space for
  828. // 1 message and is sent the return value from write (or an
  829. // earlier error) when the frame has been written.
  830. done chan error
  831. }
  832. // headerWriteReq is a request to write an HTTP response header from a server Handler.
  833. type headerWriteReq struct {
  834. streamID uint32
  835. httpResCode int
  836. h http.Header // may be nil
  837. endStream bool
  838. contentType string
  839. contentLength string
  840. }
  841. // called from handler goroutines.
  842. // h may be nil.
  843. func (sc *serverConn) writeHeaders(req headerWriteReq) {
  844. sc.serveG.checkNotOn()
  845. var errc chan error
  846. if req.h != nil {
  847. // If there's a header map (which we don't own), so we have to block on
  848. // waiting for this frame to be written, so an http.Flush mid-handler
  849. // writes out the correct value of keys, before a handler later potentially
  850. // mutates it.
  851. errc = make(chan error, 1)
  852. }
  853. sc.writeFrame(frameWriteMsg{
  854. write: (*serverConn).writeHeadersFrame,
  855. v: req,
  856. streamID: req.streamID,
  857. done: errc,
  858. })
  859. if errc != nil {
  860. <-errc
  861. }
  862. }
  863. func (sc *serverConn) writeHeadersFrame(v interface{}) error {
  864. sc.writeG.check()
  865. req := v.(headerWriteReq)
  866. sc.headerWriteBuf.Reset()
  867. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: ":status", Value: httpCodeString(req.httpResCode)})
  868. for k, vv := range req.h {
  869. k = lowerHeader(k)
  870. for _, v := range vv {
  871. // TODO: more of "8.1.2.2 Connection-Specific Header Fields"
  872. if k == "transfer-encoding" && v != "trailers" {
  873. continue
  874. }
  875. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: k, Value: v})
  876. }
  877. }
  878. if req.contentType != "" {
  879. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: "content-type", Value: req.contentType})
  880. }
  881. if req.contentLength != "" {
  882. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: "content-length", Value: req.contentLength})
  883. }
  884. headerBlock := sc.headerWriteBuf.Bytes()
  885. if len(headerBlock) > int(sc.maxWriteFrameSize) {
  886. // we'll need continuation ones.
  887. panic("TODO")
  888. }
  889. return sc.framer.WriteHeaders(HeadersFrameParam{
  890. StreamID: req.streamID,
  891. BlockFragment: headerBlock,
  892. EndStream: req.endStream,
  893. EndHeaders: true, // no continuation yet
  894. })
  895. }
  896. // called from handler goroutines.
  897. // h may be nil.
  898. func (sc *serverConn) write100ContinueHeaders(streamID uint32) {
  899. sc.serveG.checkNotOn()
  900. sc.writeFrame(frameWriteMsg{
  901. write: (*serverConn).write100ContinueHeadersFrame,
  902. v: &streamID,
  903. streamID: streamID,
  904. })
  905. }
  906. func (sc *serverConn) write100ContinueHeadersFrame(v interface{}) error {
  907. sc.writeG.check()
  908. streamID := *(v.(*uint32))
  909. sc.headerWriteBuf.Reset()
  910. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: ":status", Value: "100"})
  911. return sc.framer.WriteHeaders(HeadersFrameParam{
  912. StreamID: streamID,
  913. BlockFragment: sc.headerWriteBuf.Bytes(),
  914. EndStream: false,
  915. EndHeaders: true,
  916. })
  917. }
  918. func (sc *serverConn) writeDataFrame(v interface{}) error {
  919. sc.writeG.check()
  920. rws := v.(*responseWriterState)
  921. return sc.framer.WriteData(rws.streamID, rws.curChunkIsFinal, rws.curChunk)
  922. }
  923. type windowUpdateReq struct {
  924. streamID uint32
  925. n uint32
  926. }
  927. // called from handler goroutines
  928. func (sc *serverConn) sendWindowUpdate(streamID uint32, n int) {
  929. const maxUint32 = 2147483647
  930. for n >= maxUint32 {
  931. sc.writeFrame(frameWriteMsg{
  932. write: (*serverConn).sendWindowUpdateInLoop,
  933. v: windowUpdateReq{streamID, maxUint32},
  934. streamID: streamID,
  935. })
  936. n -= maxUint32
  937. }
  938. if n > 0 {
  939. sc.writeFrame(frameWriteMsg{
  940. write: (*serverConn).sendWindowUpdateInLoop,
  941. v: windowUpdateReq{streamID, uint32(n)},
  942. streamID: streamID,
  943. })
  944. }
  945. }
  946. func (sc *serverConn) sendWindowUpdateInLoop(v interface{}) error {
  947. sc.writeG.check()
  948. wu := v.(windowUpdateReq)
  949. if err := sc.framer.WriteWindowUpdate(0, wu.n); err != nil {
  950. return err
  951. }
  952. if err := sc.framer.WriteWindowUpdate(wu.streamID, wu.n); err != nil {
  953. return err
  954. }
  955. return nil
  956. }
  957. type requestBody struct {
  958. sc *serverConn
  959. streamID uint32
  960. closed bool
  961. pipe *pipe // non-nil if we have a HTTP entity message body
  962. needsContinue bool // need to send a 100-continue
  963. }
  964. var errClosedBody = errors.New("body closed by handler")
  965. func (b *requestBody) Close() error {
  966. if b.pipe != nil {
  967. b.pipe.Close(errClosedBody)
  968. }
  969. b.closed = true
  970. return nil
  971. }
  972. func (b *requestBody) Read(p []byte) (n int, err error) {
  973. if b.needsContinue {
  974. b.needsContinue = false
  975. b.sc.write100ContinueHeaders(b.streamID)
  976. }
  977. if b.pipe == nil {
  978. return 0, io.EOF
  979. }
  980. n, err = b.pipe.Read(p)
  981. if n > 0 {
  982. b.sc.sendWindowUpdate(b.streamID, n)
  983. // TODO: tell b.sc to send back 'n' flow control quota credits to the sender
  984. }
  985. return
  986. }
  987. // responseWriter is the http.ResponseWriter implementation. It's
  988. // intentionally small (1 pointer wide) to minimize garbage. The
  989. // responseWriterState pointer inside is zeroed at the end of a
  990. // request (in handlerDone) and calls on the responseWriter thereafter
  991. // simply crash (caller's mistake), but the much larger responseWriterState
  992. // and buffers are reused between multiple requests.
  993. type responseWriter struct {
  994. rws *responseWriterState
  995. }
  996. // Optional http.ResponseWriter interfaces implemented.
  997. var (
  998. _ http.Flusher = (*responseWriter)(nil)
  999. _ stringWriter = (*responseWriter)(nil)
  1000. // TODO: hijacker for websockets?
  1001. )
  1002. type responseWriterState struct {
  1003. // immutable within a request:
  1004. sc *serverConn
  1005. streamID uint32
  1006. req *http.Request
  1007. body *requestBody // to close at end of request, if DATA frames didn't
  1008. // TODO: adjust buffer writing sizes based on server config, frame size updates from peer, etc
  1009. bw *bufio.Writer // writing to a chunkWriter{this *responseWriterState}
  1010. // mutated by http.Handler goroutine:
  1011. handlerHeader http.Header // nil until called
  1012. snapHeader http.Header // snapshot of handlerHeader at WriteHeader time
  1013. wroteHeader bool // WriteHeader called (explicitly or implicitly). Not necessarily sent to user yet.
  1014. status int // status code passed to WriteHeader
  1015. sentHeader bool // have we sent the header frame?
  1016. handlerDone bool // handler has finished
  1017. curChunk []byte // current chunk we're writing
  1018. curChunkIsFinal bool
  1019. chunkWrittenCh chan error
  1020. }
  1021. type chunkWriter struct{ rws *responseWriterState }
  1022. // chunkWriter.Write is called from bufio.Writer. Because bufio.Writer passes through large
  1023. // writes, we break them up here if they're too big.
  1024. func (cw chunkWriter) Write(p []byte) (n int, err error) {
  1025. for len(p) > 0 {
  1026. chunk := p
  1027. if len(chunk) > handlerChunkWriteSize {
  1028. chunk = chunk[:handlerChunkWriteSize]
  1029. }
  1030. _, err = cw.rws.writeChunk(chunk)
  1031. if err != nil {
  1032. return
  1033. }
  1034. n += len(chunk)
  1035. p = p[len(chunk):]
  1036. }
  1037. return n, nil
  1038. }
  1039. // writeChunk writes small (max 4k, or handlerChunkWriteSize) chunks.
  1040. // It's also responsible for sending the HEADER response.
  1041. func (rws *responseWriterState) writeChunk(p []byte) (n int, err error) {
  1042. if !rws.wroteHeader {
  1043. rws.writeHeader(200)
  1044. }
  1045. if !rws.sentHeader {
  1046. rws.sentHeader = true
  1047. var ctype, clen string // implicit ones, if we can calculate it
  1048. if rws.handlerDone && rws.snapHeader.Get("Content-Length") == "" {
  1049. clen = strconv.Itoa(len(p))
  1050. }
  1051. if rws.snapHeader.Get("Content-Type") == "" {
  1052. ctype = http.DetectContentType(p)
  1053. }
  1054. rws.sc.writeHeaders(headerWriteReq{
  1055. streamID: rws.streamID,
  1056. httpResCode: rws.status,
  1057. h: rws.snapHeader,
  1058. endStream: rws.handlerDone && len(p) == 0,
  1059. contentType: ctype,
  1060. contentLength: clen,
  1061. })
  1062. }
  1063. if len(p) == 0 && !rws.handlerDone {
  1064. return
  1065. }
  1066. rws.curChunk = p
  1067. rws.curChunkIsFinal = rws.handlerDone
  1068. // TODO: await flow control tokens for both stream and conn
  1069. rws.sc.writeFrame(frameWriteMsg{
  1070. cost: uint32(len(p)),
  1071. streamID: rws.streamID,
  1072. write: (*serverConn).writeDataFrame,
  1073. done: rws.chunkWrittenCh,
  1074. v: rws, // writeDataInLoop uses only rws.curChunk and rws.curChunkIsFinal
  1075. })
  1076. err = <-rws.chunkWrittenCh // block until it's written
  1077. return len(p), err
  1078. }
  1079. func (w *responseWriter) Flush() {
  1080. rws := w.rws
  1081. if rws == nil {
  1082. panic("Header called after Handler finished")
  1083. }
  1084. if rws.bw.Buffered() > 0 {
  1085. if err := rws.bw.Flush(); err != nil {
  1086. // Ignore the error. The frame writer already knows.
  1087. return
  1088. }
  1089. } else {
  1090. // The bufio.Writer won't call chunkWriter.Write
  1091. // (writeChunk with zero bytes, so we have to do it
  1092. // ourselves to force the HTTP response header and/or
  1093. // final DATA frame (with END_STREAM) to be sent.
  1094. rws.writeChunk(nil)
  1095. }
  1096. }
  1097. func (w *responseWriter) Header() http.Header {
  1098. rws := w.rws
  1099. if rws == nil {
  1100. panic("Header called after Handler finished")
  1101. }
  1102. if rws.handlerHeader == nil {
  1103. rws.handlerHeader = make(http.Header)
  1104. }
  1105. return rws.handlerHeader
  1106. }
  1107. func (w *responseWriter) WriteHeader(code int) {
  1108. rws := w.rws
  1109. if rws == nil {
  1110. panic("WriteHeader called after Handler finished")
  1111. }
  1112. rws.writeHeader(code)
  1113. }
  1114. func (rws *responseWriterState) writeHeader(code int) {
  1115. if !rws.wroteHeader {
  1116. rws.wroteHeader = true
  1117. rws.status = code
  1118. if len(rws.handlerHeader) > 0 {
  1119. rws.snapHeader = cloneHeader(rws.handlerHeader)
  1120. }
  1121. }
  1122. }
  1123. func cloneHeader(h http.Header) http.Header {
  1124. h2 := make(http.Header, len(h))
  1125. for k, vv := range h {
  1126. vv2 := make([]string, len(vv))
  1127. copy(vv2, vv)
  1128. h2[k] = vv2
  1129. }
  1130. return h2
  1131. }
  1132. // The Life Of A Write is like this:
  1133. //
  1134. // TODO: copy/adapt the similar comment from Go's http server.go
  1135. func (w *responseWriter) Write(p []byte) (n int, err error) {
  1136. return w.write(len(p), p, "")
  1137. }
  1138. func (w *responseWriter) WriteString(s string) (n int, err error) {
  1139. return w.write(len(s), nil, s)
  1140. }
  1141. // either dataB or dataS is non-zero.
  1142. func (w *responseWriter) write(lenData int, dataB []byte, dataS string) (n int, err error) {
  1143. rws := w.rws
  1144. if rws == nil {
  1145. panic("Write called after Handler finished")
  1146. }
  1147. if !rws.wroteHeader {
  1148. w.WriteHeader(200)
  1149. }
  1150. if dataB != nil {
  1151. return rws.bw.Write(dataB)
  1152. } else {
  1153. return rws.bw.WriteString(dataS)
  1154. }
  1155. }
  1156. func (w *responseWriter) handlerDone() {
  1157. rws := w.rws
  1158. if rws == nil {
  1159. panic("handlerDone called twice")
  1160. }
  1161. rws.handlerDone = true
  1162. w.Flush()
  1163. w.rws = nil
  1164. responseWriterStatePool.Put(rws)
  1165. }