server.go 34 KB

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