server.go 38 KB

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