server.go 46 KB

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