server.go 37 KB

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