server.go 32 KB

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