server.go 44 KB

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