server.go 41 KB

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