server.go 24 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870
  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. "bytes"
  10. "crypto/tls"
  11. "errors"
  12. "fmt"
  13. "io"
  14. "log"
  15. "net"
  16. "net/http"
  17. "net/url"
  18. "strconv"
  19. "strings"
  20. "github.com/bradfitz/http2/hpack"
  21. )
  22. // TODO: finish GOAWAY support. Consider each incoming frame type and whether
  23. // it should be ignored during a shutdown race.
  24. // Server is an HTTP/2 server.
  25. type Server struct {
  26. // MaxStreams optionally ...
  27. MaxStreams int
  28. }
  29. func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) {
  30. sc := &serverConn{
  31. hs: hs,
  32. conn: c,
  33. handler: h,
  34. framer: NewFramer(c, c), // TODO: write to a (custom?) buffered writer that can alternate when it's in buffered mode.
  35. streams: make(map[uint32]*stream),
  36. canonHeader: make(map[string]string),
  37. readFrameCh: make(chan frameAndProcessed),
  38. readFrameErrCh: make(chan error, 1),
  39. writeHeaderCh: make(chan headerWriteReq), // must not be buffered
  40. windowUpdateCh: make(chan windowUpdateReq, 8),
  41. flow: newFlow(initialWindowSize),
  42. doneServing: make(chan struct{}),
  43. maxWriteFrameSize: initialMaxFrameSize,
  44. initialWindowSize: initialWindowSize,
  45. serveG: newGoroutineLock(),
  46. }
  47. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  48. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField)
  49. sc.serve()
  50. }
  51. // frameAndProcessed coordinates the readFrames and serve goroutines, since
  52. // the Framer interface only permits the most recently-read Frame from being
  53. // accessed. The serve goroutine sends on processed to signal to the readFrames
  54. // goroutine that another frame may be read.
  55. type frameAndProcessed struct {
  56. f Frame
  57. processed chan struct{}
  58. }
  59. type serverConn struct {
  60. // Immutable:
  61. hs *http.Server
  62. conn net.Conn
  63. handler http.Handler
  64. framer *Framer
  65. hpackDecoder *hpack.Decoder
  66. hpackEncoder *hpack.Encoder
  67. doneServing chan struct{} // closed when serverConn.serve ends
  68. readFrameCh chan frameAndProcessed // written by serverConn.readFrames
  69. readFrameErrCh chan error
  70. writeHeaderCh chan headerWriteReq // must not be buffered
  71. windowUpdateCh chan windowUpdateReq
  72. serveG goroutineLock // used to verify funcs are on serve()
  73. flow *flow // the connection-wide one
  74. // Everything following is owned by the serve loop; use serveG.check()
  75. maxStreamID uint32 // max ever seen
  76. streams map[uint32]*stream
  77. maxWriteFrameSize uint32 // TODO: update this when settings come in
  78. initialWindowSize int32
  79. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  80. sentGoAway bool
  81. req requestParam // non-zero while reading request headers
  82. headerWriteBuf bytes.Buffer // used to write response headers
  83. }
  84. // requestParam is the state of the next request, initialized over
  85. // potentially several frames HEADERS + zero or more CONTINUATION
  86. // frames.
  87. type requestParam struct {
  88. // stream is non-nil if we're reading (HEADER or CONTINUATION)
  89. // frames for a request (but not DATA).
  90. stream *stream
  91. header http.Header
  92. method, path string
  93. scheme, authority string
  94. sawRegularHeader bool // saw a non-pseudo header already
  95. invalidHeader bool // an invalid header was seen
  96. }
  97. type stream struct {
  98. id uint32
  99. state streamState // owned by serverConn's processing loop
  100. flow *flow // limits writing from Handler to client
  101. body *pipe // non-nil if expecting DATA frames
  102. bodyBytes int64 // body bytes seen so far
  103. declBodyBytes int64 // or -1 if undeclared
  104. }
  105. func (sc *serverConn) state(streamID uint32) streamState {
  106. sc.serveG.check()
  107. // http://http2.github.io/http2-spec/#rfc.section.5.1
  108. if st, ok := sc.streams[streamID]; ok {
  109. return st.state
  110. }
  111. // "The first use of a new stream identifier implicitly closes all
  112. // streams in the "idle" state that might have been initiated by
  113. // that peer with a lower-valued stream identifier. For example, if
  114. // a client sends a HEADERS frame on stream 7 without ever sending a
  115. // frame on stream 5, then stream 5 transitions to the "closed"
  116. // state when the first frame for stream 7 is sent or received."
  117. if streamID <= sc.maxStreamID {
  118. return stateClosed
  119. }
  120. return stateIdle
  121. }
  122. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  123. if VerboseLogs {
  124. sc.logf(format, args...)
  125. }
  126. }
  127. func (sc *serverConn) logf(format string, args ...interface{}) {
  128. if lg := sc.hs.ErrorLog; lg != nil {
  129. lg.Printf(format, args...)
  130. } else {
  131. log.Printf(format, args...)
  132. }
  133. }
  134. func (sc *serverConn) condlogf(err error, format string, args ...interface{}) {
  135. if err == nil {
  136. return
  137. }
  138. str := err.Error()
  139. if strings.Contains(str, "use of closed network connection") {
  140. // Boring, expected errors.
  141. sc.vlogf(format, args...)
  142. } else {
  143. sc.logf(format, args...)
  144. }
  145. }
  146. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  147. sc.serveG.check()
  148. switch {
  149. case !validHeader(f.Name):
  150. sc.req.invalidHeader = true
  151. case strings.HasPrefix(f.Name, ":"):
  152. if sc.req.sawRegularHeader {
  153. sc.logf("pseudo-header after regular header")
  154. sc.req.invalidHeader = true
  155. return
  156. }
  157. var dst *string
  158. switch f.Name {
  159. case ":method":
  160. dst = &sc.req.method
  161. case ":path":
  162. dst = &sc.req.path
  163. case ":scheme":
  164. dst = &sc.req.scheme
  165. case ":authority":
  166. dst = &sc.req.authority
  167. default:
  168. // 8.1.2.1 Pseudo-Header Fields
  169. // "Endpoints MUST treat a request or response
  170. // that contains undefined or invalid
  171. // pseudo-header fields as malformed (Section
  172. // 8.1.2.6)."
  173. sc.logf("invalid pseudo-header %q", f.Name)
  174. sc.req.invalidHeader = true
  175. return
  176. }
  177. if *dst != "" {
  178. sc.logf("duplicate pseudo-header %q sent", f.Name)
  179. sc.req.invalidHeader = true
  180. return
  181. }
  182. *dst = f.Value
  183. case f.Name == "cookie":
  184. sc.req.sawRegularHeader = true
  185. if s, ok := sc.req.header["Cookie"]; ok && len(s) == 1 {
  186. s[0] = s[0] + "; " + f.Value
  187. } else {
  188. sc.req.header.Add("Cookie", f.Value)
  189. }
  190. default:
  191. sc.req.sawRegularHeader = true
  192. sc.req.header.Add(sc.canonicalHeader(f.Name), f.Value)
  193. }
  194. }
  195. func (sc *serverConn) canonicalHeader(v string) string {
  196. sc.serveG.check()
  197. // TODO: use a sync.Pool instead of putting the cache on *serverConn?
  198. cv, ok := sc.canonHeader[v]
  199. if !ok {
  200. cv = http.CanonicalHeaderKey(v)
  201. sc.canonHeader[v] = cv
  202. }
  203. return cv
  204. }
  205. // readFrames is the loop that reads incoming frames.
  206. // It's run on its own goroutine.
  207. func (sc *serverConn) readFrames() {
  208. processed := make(chan struct{}, 1)
  209. for {
  210. f, err := sc.framer.ReadFrame()
  211. if err != nil {
  212. close(sc.readFrameCh)
  213. sc.readFrameErrCh <- err
  214. return
  215. }
  216. sc.readFrameCh <- frameAndProcessed{f, processed}
  217. <-processed
  218. }
  219. }
  220. func (sc *serverConn) serve() {
  221. sc.serveG.check()
  222. defer sc.conn.Close()
  223. defer close(sc.doneServing)
  224. sc.vlogf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  225. // Read the client preface
  226. buf := make([]byte, len(ClientPreface))
  227. // TODO: timeout reading from the client
  228. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  229. sc.logf("error reading client preface: %v", err)
  230. return
  231. }
  232. if !bytes.Equal(buf, clientPreface) {
  233. sc.logf("bogus greeting from client: %q", buf)
  234. return
  235. }
  236. sc.vlogf("client %v said hello", sc.conn.RemoteAddr())
  237. f, err := sc.framer.ReadFrame()
  238. if err != nil {
  239. sc.logf("error reading initial frame from client: %v", err)
  240. return
  241. }
  242. sf, ok := f.(*SettingsFrame)
  243. if !ok {
  244. sc.logf("invalid initial frame type %T received from client", f)
  245. return
  246. }
  247. if err := sf.ForeachSetting(sc.processSetting); err != nil {
  248. sc.logf("initial settings error: %v", err)
  249. return
  250. }
  251. // TODO: don't send two network packets for our SETTINGS + our
  252. // ACK of their settings. But if we make framer write to a
  253. // *bufio.Writer, that increases the per-connection memory
  254. // overhead, and there could be many idle conns. So maybe some
  255. // liveswitchWriter-like thing where we only switch to a
  256. // *bufio Writer when we really need one temporarily, else go
  257. // back to an unbuffered writes by default.
  258. if err := sc.framer.WriteSettings( /* TODO: actual settings */ ); err != nil {
  259. sc.logf("error writing server's initial settings: %v", err)
  260. return
  261. }
  262. if err := sc.framer.WriteSettingsAck(); err != nil {
  263. sc.logf("error writing server's ack of client's settings: %v", err)
  264. return
  265. }
  266. go sc.readFrames()
  267. for {
  268. select {
  269. case hr := <-sc.writeHeaderCh:
  270. if err := sc.writeHeaderInLoop(hr); err != nil {
  271. sc.condlogf(err, "error writing response header: %v", err)
  272. return
  273. }
  274. case wu := <-sc.windowUpdateCh:
  275. if err := sc.sendWindowUpdateInLoop(wu); err != nil {
  276. sc.condlogf(err, "error writing window update: %v", err)
  277. return
  278. }
  279. case fp, ok := <-sc.readFrameCh:
  280. if !ok {
  281. err := <-sc.readFrameErrCh
  282. if err != io.EOF {
  283. errstr := err.Error()
  284. if !strings.Contains(errstr, "use of closed network connection") {
  285. sc.logf("client %s stopped sending frames: %v", sc.conn.RemoteAddr(), errstr)
  286. }
  287. }
  288. return
  289. }
  290. f := fp.f
  291. sc.vlogf("got %v: %#v", f.Header(), f)
  292. err := sc.processFrame(f)
  293. fp.processed <- struct{}{} // let readFrames proceed
  294. switch ev := err.(type) {
  295. case nil:
  296. // nothing.
  297. case StreamError:
  298. if err := sc.resetStreamInLoop(ev); err != nil {
  299. sc.logf("Error writing RSTSTream: %v", err)
  300. return
  301. }
  302. case ConnectionError:
  303. sc.logf("Disconnecting; %v", ev)
  304. return
  305. case goAwayFlowError:
  306. if err := sc.goAway(ErrCodeFlowControl); err != nil {
  307. sc.condlogf(err, "failed to GOAWAY: %v", err)
  308. return
  309. }
  310. default:
  311. sc.logf("Disconnection due to other error: %v", err)
  312. return
  313. }
  314. }
  315. }
  316. }
  317. func (sc *serverConn) goAway(code ErrCode) error {
  318. sc.serveG.check()
  319. sc.sentGoAway = true
  320. return sc.framer.WriteGoAway(sc.maxStreamID, code, nil)
  321. }
  322. func (sc *serverConn) resetStreamInLoop(se StreamError) error {
  323. sc.serveG.check()
  324. if err := sc.framer.WriteRSTStream(se.streamID, uint32(se.code)); err != nil {
  325. return err
  326. }
  327. delete(sc.streams, se.streamID)
  328. return nil
  329. }
  330. func (sc *serverConn) curHeaderStreamID() uint32 {
  331. sc.serveG.check()
  332. st := sc.req.stream
  333. if st == nil {
  334. return 0
  335. }
  336. return st.id
  337. }
  338. func (sc *serverConn) processFrame(f Frame) error {
  339. sc.serveG.check()
  340. if s := sc.curHeaderStreamID(); s != 0 {
  341. if cf, ok := f.(*ContinuationFrame); !ok {
  342. return ConnectionError(ErrCodeProtocol)
  343. } else if cf.Header().StreamID != s {
  344. return ConnectionError(ErrCodeProtocol)
  345. }
  346. }
  347. switch f := f.(type) {
  348. case *SettingsFrame:
  349. return sc.processSettings(f)
  350. case *HeadersFrame:
  351. return sc.processHeaders(f)
  352. case *ContinuationFrame:
  353. return sc.processContinuation(f)
  354. case *WindowUpdateFrame:
  355. return sc.processWindowUpdate(f)
  356. case *PingFrame:
  357. return sc.processPing(f)
  358. case *DataFrame:
  359. return sc.processData(f)
  360. default:
  361. log.Printf("Ignoring unknown frame %#v", f)
  362. return nil
  363. }
  364. }
  365. func (sc *serverConn) processPing(f *PingFrame) error {
  366. sc.serveG.check()
  367. if f.Flags.Has(FlagSettingsAck) {
  368. // 6.7 PING: " An endpoint MUST NOT respond to PING frames
  369. // containing this flag."
  370. return nil
  371. }
  372. if f.StreamID != 0 {
  373. // "PING frames are not associated with any individual
  374. // stream. If a PING frame is received with a stream
  375. // identifier field value other than 0x0, the recipient MUST
  376. // respond with a connection error (Section 5.4.1) of type
  377. // PROTOCOL_ERROR."
  378. return ConnectionError(ErrCodeProtocol)
  379. }
  380. return sc.framer.WritePing(true, f.Data)
  381. }
  382. func (sc *serverConn) processWindowUpdate(f *WindowUpdateFrame) error {
  383. sc.serveG.check()
  384. switch {
  385. case f.StreamID != 0: // stream-level flow control
  386. st := sc.streams[f.StreamID]
  387. if st == nil {
  388. // "WINDOW_UPDATE can be sent by a peer that has sent a
  389. // frame bearing the END_STREAM flag. This means that a
  390. // receiver could receive a WINDOW_UPDATE frame on a "half
  391. // closed (remote)" or "closed" stream. A receiver MUST
  392. // NOT treat this as an error, see Section 5.1."
  393. return nil
  394. }
  395. if !st.flow.add(int32(f.Increment)) {
  396. return StreamError{f.StreamID, ErrCodeFlowControl}
  397. }
  398. default: // connection-level flow control
  399. if !sc.flow.add(int32(f.Increment)) {
  400. return goAwayFlowError{}
  401. }
  402. }
  403. return nil
  404. }
  405. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  406. sc.serveG.check()
  407. return f.ForeachSetting(sc.processSetting)
  408. }
  409. func (sc *serverConn) processSetting(s Setting) error {
  410. sc.serveG.check()
  411. sc.vlogf("processing setting %v", s)
  412. switch s.ID {
  413. case SettingInitialWindowSize:
  414. return sc.processSettingInitialWindowSize(s.Val)
  415. }
  416. log.Printf("TODO: handle %v", s)
  417. return nil
  418. }
  419. func (sc *serverConn) processSettingInitialWindowSize(val uint32) error {
  420. sc.serveG.check()
  421. if val > (1<<31 - 1) {
  422. // 6.5.2 Defined SETTINGS Parameters
  423. // "Values above the maximum flow control window size of
  424. // 231-1 MUST be treated as a connection error (Section
  425. // 5.4.1) of type FLOW_CONTROL_ERROR."
  426. return ConnectionError(ErrCodeFlowControl)
  427. }
  428. // "A SETTINGS frame can alter the initial flow control window
  429. // size for all current streams. When the value of
  430. // SETTINGS_INITIAL_WINDOW_SIZE changes, a receiver MUST
  431. // adjust the size of all stream flow control windows that it
  432. // maintains by the difference between the new value and the
  433. // old value."
  434. old := sc.initialWindowSize
  435. sc.initialWindowSize = int32(val)
  436. growth := sc.initialWindowSize - old // may be negative
  437. for _, st := range sc.streams {
  438. if !st.flow.add(growth) {
  439. // 6.9.2 Initial Flow Control Window Size
  440. // "An endpoint MUST treat a change to
  441. // SETTINGS_INITIAL_WINDOW_SIZE that causes any flow
  442. // control window to exceed the maximum size as a
  443. // connection error (Section 5.4.1) of type
  444. // FLOW_CONTROL_ERROR."
  445. return ConnectionError(ErrCodeFlowControl)
  446. }
  447. }
  448. return nil
  449. }
  450. func (sc *serverConn) processData(f *DataFrame) error {
  451. sc.serveG.check()
  452. // "If a DATA frame is received whose stream is not in "open"
  453. // or "half closed (local)" state, the recipient MUST respond
  454. // with a stream error (Section 5.4.2) of type STREAM_CLOSED."
  455. id := f.Header().StreamID
  456. st, ok := sc.streams[id]
  457. if !ok || (st.state != stateOpen && st.state != stateHalfClosedLocal) {
  458. return StreamError{id, ErrCodeStreamClosed}
  459. }
  460. if st.body == nil {
  461. // Not expecting data.
  462. // TODO: which error code?
  463. return StreamError{id, ErrCodeStreamClosed}
  464. }
  465. data := f.Data()
  466. // Sender sending more than they'd declared?
  467. if st.declBodyBytes != -1 && st.bodyBytes+int64(len(data)) > st.declBodyBytes {
  468. st.body.Close(fmt.Errorf("Sender tried to send more than declared Content-Length of %d bytes", st.declBodyBytes))
  469. return StreamError{id, ErrCodeStreamClosed}
  470. }
  471. if len(data) > 0 {
  472. // TODO: verify they're allowed to write with the flow control
  473. // window we'd advertised to them.
  474. // TODO: verify n from Write
  475. if _, err := st.body.Write(data); err != nil {
  476. return StreamError{id, ErrCodeStreamClosed}
  477. }
  478. st.bodyBytes += int64(len(data))
  479. }
  480. if f.Header().Flags.Has(FlagDataEndStream) {
  481. if st.declBodyBytes != -1 && st.declBodyBytes != st.bodyBytes {
  482. st.body.Close(fmt.Errorf("Request declared a Content-Length of %d but only wrote %d bytes",
  483. st.declBodyBytes, st.bodyBytes))
  484. } else {
  485. st.body.Close(io.EOF)
  486. }
  487. }
  488. return nil
  489. }
  490. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  491. sc.serveG.check()
  492. id := f.Header().StreamID
  493. if sc.sentGoAway {
  494. // Ignore.
  495. return nil
  496. }
  497. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  498. if id%2 != 1 || id <= sc.maxStreamID || sc.req.stream != nil {
  499. // Streams initiated by a client MUST use odd-numbered
  500. // stream identifiers. [...] The identifier of a newly
  501. // established stream MUST be numerically greater than all
  502. // streams that the initiating endpoint has opened or
  503. // reserved. [...] An endpoint that receives an unexpected
  504. // stream identifier MUST respond with a connection error
  505. // (Section 5.4.1) of type PROTOCOL_ERROR.
  506. return ConnectionError(ErrCodeProtocol)
  507. }
  508. if id > sc.maxStreamID {
  509. sc.maxStreamID = id
  510. }
  511. st := &stream{
  512. id: id,
  513. state: stateOpen,
  514. flow: newFlow(sc.initialWindowSize),
  515. }
  516. if f.Header().Flags.Has(FlagHeadersEndStream) {
  517. st.state = stateHalfClosedRemote
  518. }
  519. sc.streams[id] = st
  520. sc.req = requestParam{
  521. stream: st,
  522. header: make(http.Header),
  523. }
  524. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  525. }
  526. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  527. sc.serveG.check()
  528. st := sc.streams[f.Header().StreamID]
  529. if st == nil || sc.curHeaderStreamID() != st.id {
  530. return ConnectionError(ErrCodeProtocol)
  531. }
  532. return sc.processHeaderBlockFragment(st, f.HeaderBlockFragment(), f.HeadersEnded())
  533. }
  534. func (sc *serverConn) processHeaderBlockFragment(st *stream, frag []byte, end bool) error {
  535. sc.serveG.check()
  536. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  537. // TODO: convert to stream error I assume?
  538. return err
  539. }
  540. if !end {
  541. return nil
  542. }
  543. if err := sc.hpackDecoder.Close(); err != nil {
  544. // TODO: convert to stream error I assume?
  545. return err
  546. }
  547. rw, req, err := sc.newWriterAndRequest()
  548. sc.req = requestParam{}
  549. if err != nil {
  550. return err
  551. }
  552. st.body = req.Body.(*requestBody).pipe // may be nil
  553. st.declBodyBytes = req.ContentLength
  554. go sc.runHandler(rw, req)
  555. return nil
  556. }
  557. func (sc *serverConn) newWriterAndRequest() (*responseWriter, *http.Request, error) {
  558. sc.serveG.check()
  559. rp := &sc.req
  560. if rp.invalidHeader || rp.method == "" || rp.path == "" ||
  561. (rp.scheme != "https" && rp.scheme != "http") {
  562. // See 8.1.2.6 Malformed Requests and Responses:
  563. //
  564. // Malformed requests or responses that are detected
  565. // MUST be treated as a stream error (Section 5.4.2)
  566. // of type PROTOCOL_ERROR."
  567. //
  568. // 8.1.2.3 Request Pseudo-Header Fields
  569. // "All HTTP/2 requests MUST include exactly one valid
  570. // value for the :method, :scheme, and :path
  571. // pseudo-header fields"
  572. return nil, nil, StreamError{rp.stream.id, ErrCodeProtocol}
  573. }
  574. var tlsState *tls.ConnectionState // make this non-nil if https
  575. if rp.scheme == "https" {
  576. // TODO: get from sc's ConnectionState
  577. tlsState = &tls.ConnectionState{}
  578. }
  579. authority := rp.authority
  580. if authority == "" {
  581. authority = rp.header.Get("Host")
  582. }
  583. bodyOpen := rp.stream.state == stateOpen
  584. body := &requestBody{
  585. sc: sc,
  586. streamID: rp.stream.id,
  587. }
  588. req := &http.Request{
  589. Method: rp.method,
  590. URL: &url.URL{},
  591. RemoteAddr: sc.conn.RemoteAddr().String(),
  592. Header: rp.header,
  593. RequestURI: rp.path,
  594. Proto: "HTTP/2.0",
  595. ProtoMajor: 2,
  596. ProtoMinor: 0,
  597. TLS: tlsState,
  598. Host: authority,
  599. Body: body,
  600. }
  601. if bodyOpen {
  602. body.pipe = &pipe{
  603. b: buffer{buf: make([]byte, 65536)}, // TODO: share/remove
  604. }
  605. body.pipe.c.L = &body.pipe.m
  606. if vv, ok := rp.header["Content-Length"]; ok {
  607. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  608. } else {
  609. req.ContentLength = -1
  610. }
  611. }
  612. rw := &responseWriter{
  613. sc: sc,
  614. streamID: rp.stream.id,
  615. req: req,
  616. body: body,
  617. }
  618. return rw, req, nil
  619. }
  620. // Run on its own goroutine.
  621. func (sc *serverConn) runHandler(rw *responseWriter, req *http.Request) {
  622. defer rw.handlerDone()
  623. // TODO: catch panics like net/http.Server
  624. sc.handler.ServeHTTP(rw, req)
  625. }
  626. // called from handler goroutines
  627. func (sc *serverConn) writeData(streamID uint32, p []byte) (n int, err error) {
  628. // TODO: implement
  629. log.Printf("WRITE on %d: %q", streamID, p)
  630. return len(p), nil
  631. }
  632. // headerWriteReq is a request to write an HTTP response header from a server Handler.
  633. type headerWriteReq struct {
  634. streamID uint32
  635. httpResCode int
  636. h http.Header // may be nil
  637. endStream bool
  638. }
  639. // called from handler goroutines.
  640. // h may be nil.
  641. func (sc *serverConn) writeHeader(req headerWriteReq) {
  642. sc.writeHeaderCh <- req
  643. }
  644. func (sc *serverConn) writeHeaderInLoop(req headerWriteReq) error {
  645. sc.serveG.check()
  646. sc.headerWriteBuf.Reset()
  647. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: ":status", Value: httpCodeString(req.httpResCode)})
  648. for k, vv := range req.h {
  649. for _, v := range vv {
  650. // TODO: for gargage, cache lowercase copies of headers at
  651. // least for common ones and/or popular recent ones for
  652. // this serverConn. LRU?
  653. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: strings.ToLower(k), Value: v})
  654. }
  655. }
  656. headerBlock := sc.headerWriteBuf.Bytes()
  657. if len(headerBlock) > int(sc.maxWriteFrameSize) {
  658. // we'll need continuation ones.
  659. panic("TODO")
  660. }
  661. return sc.framer.WriteHeaders(HeadersFrameParam{
  662. StreamID: req.streamID,
  663. BlockFragment: headerBlock,
  664. EndStream: req.endStream,
  665. EndHeaders: true, // no continuation yet
  666. })
  667. }
  668. type windowUpdateReq struct {
  669. streamID uint32
  670. n uint32
  671. }
  672. // called from handler goroutines
  673. func (sc *serverConn) sendWindowUpdate(streamID uint32, n int) {
  674. const maxUint32 = 2147483647
  675. for n >= maxUint32 {
  676. sc.windowUpdateCh <- windowUpdateReq{streamID, maxUint32}
  677. n -= maxUint32
  678. }
  679. if n > 0 {
  680. sc.windowUpdateCh <- windowUpdateReq{streamID, uint32(n)}
  681. }
  682. }
  683. func (sc *serverConn) sendWindowUpdateInLoop(wu windowUpdateReq) error {
  684. sc.serveG.check()
  685. // TODO: sc.bufferedOutput.StartBuffering()
  686. if err := sc.framer.WriteWindowUpdate(0, wu.n); err != nil {
  687. return err
  688. }
  689. if err := sc.framer.WriteWindowUpdate(wu.streamID, wu.n); err != nil {
  690. return err
  691. }
  692. // TODO: return sc.bufferedOutput.Flush()
  693. return nil
  694. }
  695. // ConfigureServer adds HTTP/2 support to a net/http Server.
  696. //
  697. // The configuration conf may be nil.
  698. //
  699. // ConfigureServer must be called before s begins serving.
  700. func ConfigureServer(s *http.Server, conf *Server) {
  701. if conf == nil {
  702. conf = new(Server)
  703. }
  704. if s.TLSConfig == nil {
  705. s.TLSConfig = new(tls.Config)
  706. }
  707. haveNPN := false
  708. for _, p := range s.TLSConfig.NextProtos {
  709. if p == npnProto {
  710. haveNPN = true
  711. break
  712. }
  713. }
  714. if !haveNPN {
  715. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, npnProto)
  716. }
  717. if s.TLSNextProto == nil {
  718. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  719. }
  720. s.TLSNextProto[npnProto] = func(hs *http.Server, c *tls.Conn, h http.Handler) {
  721. if testHookOnConn != nil {
  722. testHookOnConn()
  723. }
  724. conf.handleConn(hs, c, h)
  725. }
  726. }
  727. type requestBody struct {
  728. sc *serverConn
  729. streamID uint32
  730. closed bool
  731. pipe *pipe // non-nil if we have a HTTP entity message body
  732. }
  733. var errClosedBody = errors.New("body closed by handler")
  734. func (b *requestBody) Close() error {
  735. if b.pipe != nil {
  736. b.pipe.Close(errClosedBody)
  737. }
  738. b.closed = true
  739. return nil
  740. }
  741. func (b *requestBody) Read(p []byte) (n int, err error) {
  742. if b.pipe == nil {
  743. return 0, io.EOF
  744. }
  745. n, err = b.pipe.Read(p)
  746. if n > 0 {
  747. b.sc.sendWindowUpdate(b.streamID, n)
  748. // TODO: tell b.sc to send back 'n' flow control quota credits to the sender
  749. }
  750. return
  751. }
  752. type responseWriter struct {
  753. sc *serverConn
  754. streamID uint32
  755. wroteHeaders bool
  756. h http.Header
  757. req *http.Request
  758. body *requestBody // to close at end of request, if DATA frames didn't
  759. }
  760. // TODO: bufio writing of responseWriter. add Flush, add pools of
  761. // bufio.Writers, adjust bufio writer sized based on frame size
  762. // updates from peer? For now: naive.
  763. func (w *responseWriter) Header() http.Header {
  764. if w.h == nil {
  765. w.h = make(http.Header)
  766. }
  767. return w.h
  768. }
  769. func (w *responseWriter) WriteHeader(code int) {
  770. if w.wroteHeaders {
  771. return
  772. }
  773. // TODO: defer actually writing this frame until a Flush or
  774. // handlerDone, like net/http's Server. then we can coalesce
  775. // e.g. a 204 response to have a Header response frame with
  776. // END_STREAM set, without a separate frame being sent in
  777. // handleDone.
  778. w.wroteHeaders = true
  779. w.sc.writeHeader(headerWriteReq{
  780. streamID: w.streamID,
  781. httpResCode: code,
  782. h: w.h,
  783. })
  784. }
  785. // TODO: responseWriter.WriteString too?
  786. func (w *responseWriter) Write(p []byte) (n int, err error) {
  787. if !w.wroteHeaders {
  788. w.WriteHeader(200)
  789. }
  790. return w.sc.writeData(w.streamID, p) // blocks waiting for tokens
  791. }
  792. func (w *responseWriter) handlerDone() {
  793. if !w.wroteHeaders {
  794. w.sc.writeHeader(headerWriteReq{
  795. streamID: w.streamID,
  796. httpResCode: 200,
  797. h: w.h,
  798. endStream: true, // handler has finished; can't be any data.
  799. })
  800. }
  801. }
  802. var testHookOnConn func() // for testing