server.go 35 KB

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