http2.go 22 KB

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