http2.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676
  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. import (
  18. "bytes"
  19. "crypto/tls"
  20. "errors"
  21. "io"
  22. "log"
  23. "net"
  24. "net/http"
  25. "net/url"
  26. "strconv"
  27. "strings"
  28. "github.com/bradfitz/http2/hpack"
  29. )
  30. var VerboseLogs = false
  31. const (
  32. // ClientPreface is the string that must be sent by new
  33. // connections from clients.
  34. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
  35. // SETTINGS_MAX_FRAME_SIZE default
  36. // http://http2.github.io/http2-spec/#rfc.section.6.5.2
  37. initialMaxFrameSize = 16384
  38. )
  39. var (
  40. clientPreface = []byte(ClientPreface)
  41. )
  42. const (
  43. npnProto = "h2-14"
  44. // http://http2.github.io/http2-spec/#SettingValues
  45. initialHeaderTableSize = 4096
  46. )
  47. // Server is an HTTP2 server.
  48. type Server struct {
  49. // MaxStreams optionally ...
  50. MaxStreams int
  51. }
  52. func (srv *Server) handleConn(hs *http.Server, c net.Conn, h http.Handler) {
  53. sc := &serverConn{
  54. hs: hs,
  55. conn: c,
  56. handler: h,
  57. framer: NewFramer(c, c),
  58. streams: make(map[uint32]*stream),
  59. canonHeader: make(map[string]string),
  60. readFrameCh: make(chan frameAndProcessed),
  61. readFrameErrCh: make(chan error, 1),
  62. writeHeaderCh: make(chan headerWriteReq), // must not be buffered
  63. doneServing: make(chan struct{}),
  64. maxWriteFrameSize: initialMaxFrameSize,
  65. serveG: newGoroutineLock(),
  66. }
  67. sc.hpackEncoder = hpack.NewEncoder(&sc.headerWriteBuf)
  68. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField)
  69. sc.serve()
  70. }
  71. // frameAndProcessed coordinates the readFrames and serve goroutines, since
  72. // the Framer interface only permits the most recently-read Frame from being
  73. // accessed. The serve goroutine sends on processed to signal to the readFrames
  74. // goroutine that another frame may be read.
  75. type frameAndProcessed struct {
  76. f Frame
  77. processed chan struct{}
  78. }
  79. type serverConn struct {
  80. // Immutable:
  81. hs *http.Server
  82. conn net.Conn
  83. handler http.Handler
  84. framer *Framer
  85. doneServing chan struct{} // closed when serverConn.serve ends
  86. readFrameCh chan frameAndProcessed // written by serverConn.readFrames
  87. readFrameErrCh chan error
  88. writeHeaderCh chan headerWriteReq // must not be buffered
  89. serveG goroutineLock // used to verify funcs are on serve()
  90. // Everything following is owned by the serve loop; use serveG.check()
  91. maxStreamID uint32 // max ever seen
  92. streams map[uint32]*stream
  93. maxWriteFrameSize uint32 // TODO: update this when settings come in
  94. // State related to parsing current headers:
  95. hpackDecoder *hpack.Decoder
  96. header http.Header
  97. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  98. method, path string
  99. scheme, authority string
  100. invalidHeader bool
  101. // State related to writing current headers:
  102. hpackEncoder *hpack.Encoder
  103. headerWriteBuf bytes.Buffer
  104. // curHeaderStreamID is non-zero if we're in the middle
  105. // of parsing headers that span multiple frames.
  106. curHeaderStreamID uint32
  107. curStream *stream
  108. }
  109. type streamState int
  110. const (
  111. stateIdle streamState = iota
  112. stateOpen
  113. stateHalfClosedLocal
  114. stateHalfClosedRemote
  115. stateResvLocal
  116. stateResvRemote
  117. stateClosed
  118. )
  119. type stream struct {
  120. id uint32
  121. state streamState // owned by serverConn's processing loop
  122. }
  123. func (sc *serverConn) state(streamID uint32) streamState {
  124. sc.serveG.check()
  125. // http://http2.github.io/http2-spec/#rfc.section.5.1
  126. if st, ok := sc.streams[streamID]; ok {
  127. return st.state
  128. }
  129. // "The first use of a new stream identifier implicitly closes all
  130. // streams in the "idle" state that might have been initiated by
  131. // that peer with a lower-valued stream identifier. For example, if
  132. // a client sends a HEADERS frame on stream 7 without ever sending a
  133. // frame on stream 5, then stream 5 transitions to the "closed"
  134. // state when the first frame for stream 7 is sent or received."
  135. if streamID <= sc.maxStreamID {
  136. return stateClosed
  137. }
  138. return stateIdle
  139. }
  140. func (sc *serverConn) vlogf(format string, args ...interface{}) {
  141. if VerboseLogs {
  142. sc.logf(format, args...)
  143. }
  144. }
  145. func (sc *serverConn) logf(format string, args ...interface{}) {
  146. if lg := sc.hs.ErrorLog; lg != nil {
  147. lg.Printf(format, args...)
  148. } else {
  149. log.Printf(format, args...)
  150. }
  151. }
  152. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  153. sc.serveG.check()
  154. switch {
  155. case !validHeader(f.Name):
  156. sc.invalidHeader = true
  157. case strings.HasPrefix(f.Name, ":"):
  158. switch f.Name {
  159. case ":method":
  160. sc.method = f.Value
  161. case ":path":
  162. sc.path = f.Value
  163. case ":scheme":
  164. sc.scheme = f.Value
  165. case ":authority":
  166. sc.authority = f.Value
  167. default:
  168. log.Printf("Ignoring unknown pseudo-header %q", f.Name)
  169. }
  170. return
  171. case f.Name == "cookie":
  172. if s, ok := sc.header["Cookie"]; ok && len(s) == 1 {
  173. s[0] = s[0] + "; " + f.Value
  174. } else {
  175. sc.header.Add("Cookie", f.Value)
  176. }
  177. default:
  178. sc.header.Add(sc.canonicalHeader(f.Name), f.Value)
  179. }
  180. }
  181. func (sc *serverConn) canonicalHeader(v string) string {
  182. sc.serveG.check()
  183. // TODO: use a sync.Pool instead of putting the cache on *serverConn?
  184. cv, ok := sc.canonHeader[v]
  185. if !ok {
  186. cv = http.CanonicalHeaderKey(v)
  187. sc.canonHeader[v] = cv
  188. }
  189. return cv
  190. }
  191. // readFrames is the loop that reads incoming frames.
  192. // It's run on its own goroutine.
  193. func (sc *serverConn) readFrames() {
  194. processed := make(chan struct{}, 1)
  195. for {
  196. f, err := sc.framer.ReadFrame()
  197. if err != nil {
  198. close(sc.readFrameCh)
  199. sc.readFrameErrCh <- err
  200. return
  201. }
  202. sc.readFrameCh <- frameAndProcessed{f, processed}
  203. <-processed
  204. }
  205. }
  206. func (sc *serverConn) serve() {
  207. sc.serveG.check()
  208. defer sc.conn.Close()
  209. defer close(sc.doneServing)
  210. sc.logf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  211. // Read the client preface
  212. buf := make([]byte, len(ClientPreface))
  213. // TODO: timeout reading from the client
  214. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  215. sc.logf("error reading client preface: %v", err)
  216. return
  217. }
  218. if !bytes.Equal(buf, clientPreface) {
  219. sc.logf("bogus greeting from client: %q", buf)
  220. return
  221. }
  222. sc.logf("client %v said hello", sc.conn.RemoteAddr())
  223. f, err := sc.framer.ReadFrame()
  224. if err != nil {
  225. sc.logf("error reading initial frame from client: %v", err)
  226. return
  227. }
  228. sf, ok := f.(*SettingsFrame)
  229. if !ok {
  230. sc.logf("invalid initial frame type %T received from client", f)
  231. return
  232. }
  233. sf.ForeachSetting(func(s Setting) {
  234. // TODO: process, record
  235. })
  236. // TODO: don't send two network packets for our SETTINGS + our
  237. // ACK of their settings. But if we make framer write to a
  238. // *bufio.Writer, that increases the per-connection memory
  239. // overhead, and there could be many idle conns. So maybe some
  240. // liveswitchWriter-like thing where we only switch to a
  241. // *bufio Writer when we really need one temporarily, else go
  242. // back to an unbuffered writes by default.
  243. if err := sc.framer.WriteSettings( /* TODO: actual settings */ ); err != nil {
  244. sc.logf("error writing server's initial settings: %v", err)
  245. return
  246. }
  247. if err := sc.framer.WriteSettingsAck(); err != nil {
  248. sc.logf("error writing server's ack of client's settings: %v", err)
  249. return
  250. }
  251. go sc.readFrames()
  252. for {
  253. select {
  254. case hr := <-sc.writeHeaderCh:
  255. if err := sc.writeHeaderInLoop(hr); err != nil {
  256. // TODO: diff error handling?
  257. sc.logf("error writing response header: %v", err)
  258. return
  259. }
  260. case fp, ok := <-sc.readFrameCh:
  261. if !ok {
  262. err := <-sc.readFrameErrCh
  263. if err != io.EOF {
  264. errstr := err.Error()
  265. if !strings.Contains(errstr, "use of closed network connection") {
  266. sc.logf("client %s stopped sending frames: %v", sc.conn.RemoteAddr(), errstr)
  267. }
  268. }
  269. return
  270. }
  271. f := fp.f
  272. sc.vlogf("got %v: %#v", f.Header(), f)
  273. err := sc.processFrame(f)
  274. fp.processed <- struct{}{} // let readFrames proceed
  275. switch ev := err.(type) {
  276. case nil:
  277. // nothing.
  278. case StreamError:
  279. if err := sc.resetStreamInLoop(ev); err != nil {
  280. sc.logf("Error writing RSTSTream: %v", err)
  281. return
  282. }
  283. case ConnectionError:
  284. sc.logf("Disconnecting; %v", ev)
  285. return
  286. default:
  287. sc.logf("Disconnection due to other error: %v", err)
  288. return
  289. }
  290. }
  291. }
  292. }
  293. func (sc *serverConn) resetStreamInLoop(se StreamError) error {
  294. sc.serveG.check()
  295. if err := sc.framer.WriteRSTStream(se.streamID, uint32(se.code)); err != nil {
  296. return err
  297. }
  298. delete(sc.streams, se.streamID)
  299. return nil
  300. }
  301. func (sc *serverConn) processFrame(f Frame) error {
  302. sc.serveG.check()
  303. if s := sc.curHeaderStreamID; s != 0 {
  304. if cf, ok := f.(*ContinuationFrame); !ok {
  305. return ConnectionError(ErrCodeProtocol)
  306. } else if cf.Header().StreamID != s {
  307. return ConnectionError(ErrCodeProtocol)
  308. }
  309. }
  310. switch f := f.(type) {
  311. case *SettingsFrame:
  312. return sc.processSettings(f)
  313. case *HeadersFrame:
  314. return sc.processHeaders(f)
  315. case *ContinuationFrame:
  316. return sc.processContinuation(f)
  317. default:
  318. log.Printf("Ignoring unknown %v", f.Header)
  319. return nil
  320. }
  321. }
  322. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  323. sc.serveG.check()
  324. f.ForeachSetting(func(s Setting) {
  325. log.Printf(" setting %s = %v", s.ID, s.Val)
  326. })
  327. return nil
  328. }
  329. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  330. sc.serveG.check()
  331. id := f.Header().StreamID
  332. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  333. if id%2 != 1 || id <= sc.maxStreamID {
  334. // Streams initiated by a client MUST use odd-numbered
  335. // stream identifiers. [...] The identifier of a newly
  336. // established stream MUST be numerically greater than all
  337. // streams that the initiating endpoint has opened or
  338. // reserved. [...] An endpoint that receives an unexpected
  339. // stream identifier MUST respond with a connection error
  340. // (Section 5.4.1) of type PROTOCOL_ERROR.
  341. return ConnectionError(ErrCodeProtocol)
  342. }
  343. if id > sc.maxStreamID {
  344. sc.maxStreamID = id
  345. }
  346. st := &stream{
  347. id: id,
  348. state: stateOpen,
  349. }
  350. if f.Header().Flags.Has(FlagHeadersEndStream) {
  351. st.state = stateHalfClosedRemote
  352. }
  353. sc.streams[id] = st
  354. sc.header = make(http.Header)
  355. sc.invalidHeader = false
  356. sc.curHeaderStreamID = id
  357. sc.curStream = st
  358. return sc.processHeaderBlockFragment(id, f.HeaderBlockFragment(), f.HeadersEnded())
  359. }
  360. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  361. sc.serveG.check()
  362. id := f.Header().StreamID
  363. if sc.curHeaderStreamID != id {
  364. return ConnectionError(ErrCodeProtocol)
  365. }
  366. return sc.processHeaderBlockFragment(id, f.HeaderBlockFragment(), f.HeadersEnded())
  367. }
  368. func (sc *serverConn) processHeaderBlockFragment(streamID uint32, frag []byte, end bool) error {
  369. sc.serveG.check()
  370. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  371. // TODO: convert to stream error I assume?
  372. return err
  373. }
  374. if !end {
  375. return nil
  376. }
  377. if err := sc.hpackDecoder.Close(); err != nil {
  378. // TODO: convert to stream error I assume?
  379. return err
  380. }
  381. if sc.invalidHeader {
  382. // See 8.1.2.6 Malformed Requests and Responses:
  383. //
  384. // Malformed requests or responses that are detected
  385. // MUST be treated as a stream error (Section 5.4.2)
  386. // of type PROTOCOL_ERROR."
  387. return StreamError{streamID, ErrCodeProtocol}
  388. }
  389. curStream := sc.curStream
  390. sc.curHeaderStreamID = 0
  391. sc.curStream = nil
  392. // TODO: transition streamID state
  393. go sc.startHandler(curStream.id, curStream.state == stateOpen, sc.method, sc.path, sc.scheme, sc.authority, sc.header)
  394. return nil
  395. }
  396. // Run on its own goroutine.
  397. func (sc *serverConn) startHandler(streamID uint32, bodyOpen bool, method, path, scheme, authority string, reqHeader http.Header) {
  398. var tlsState *tls.ConnectionState // make this non-nil if https
  399. if scheme == "https" {
  400. // TODO: get from sc's ConnectionState
  401. tlsState = &tls.ConnectionState{}
  402. }
  403. if authority == "" {
  404. authority = reqHeader.Get("Host")
  405. }
  406. req := &http.Request{
  407. Method: method,
  408. URL: &url.URL{},
  409. RemoteAddr: sc.conn.RemoteAddr().String(),
  410. Header: reqHeader,
  411. RequestURI: path,
  412. Proto: "HTTP/2.0",
  413. ProtoMajor: 2,
  414. ProtoMinor: 0,
  415. TLS: tlsState,
  416. Host: authority,
  417. Body: &requestBody{
  418. sc: sc,
  419. streamID: streamID,
  420. hasBody: bodyOpen,
  421. },
  422. }
  423. if bodyOpen {
  424. if vv, ok := reqHeader["Content-Length"]; ok {
  425. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  426. } else {
  427. req.ContentLength = -1
  428. }
  429. }
  430. rw := &responseWriter{
  431. sc: sc,
  432. streamID: streamID,
  433. }
  434. defer rw.handlerDone()
  435. // TODO: catch panics like net/http.Server
  436. sc.handler.ServeHTTP(rw, req)
  437. }
  438. // called from handler goroutines
  439. func (sc *serverConn) writeData(streamID uint32, p []byte) (n int, err error) {
  440. // TODO: implement
  441. log.Printf("WRITE on %d: %q", streamID, p)
  442. return len(p), nil
  443. }
  444. // headerWriteReq is a request to write an HTTP response header from a server Handler.
  445. type headerWriteReq struct {
  446. streamID uint32
  447. httpResCode int
  448. h http.Header // may be nil
  449. endStream bool
  450. }
  451. // called from handler goroutines.
  452. // h may be nil.
  453. func (sc *serverConn) writeHeader(req headerWriteReq) {
  454. sc.writeHeaderCh <- req
  455. }
  456. func (sc *serverConn) writeHeaderInLoop(req headerWriteReq) error {
  457. sc.serveG.check()
  458. sc.headerWriteBuf.Reset()
  459. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: ":status", Value: httpCodeString(req.httpResCode)})
  460. for k, vv := range req.h {
  461. for _, v := range vv {
  462. // TODO: for gargage, cache lowercase copies of headers at
  463. // least for common ones and/or popular recent ones for
  464. // this serverConn. LRU?
  465. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: strings.ToLower(k), Value: v})
  466. }
  467. }
  468. headerBlock := sc.headerWriteBuf.Bytes()
  469. if len(headerBlock) > int(sc.maxWriteFrameSize) {
  470. // we'll need continuation ones.
  471. panic("TODO")
  472. }
  473. return sc.framer.WriteHeaders(HeadersFrameParam{
  474. StreamID: req.streamID,
  475. BlockFragment: headerBlock,
  476. EndStream: req.endStream,
  477. EndHeaders: true, // no continuation yet
  478. })
  479. }
  480. // ConfigureServer adds HTTP/2 support to a net/http Server.
  481. //
  482. // The configuration conf may be nil.
  483. //
  484. // ConfigureServer must be called before s begins serving.
  485. func ConfigureServer(s *http.Server, conf *Server) {
  486. if conf == nil {
  487. conf = new(Server)
  488. }
  489. if s.TLSConfig == nil {
  490. s.TLSConfig = new(tls.Config)
  491. }
  492. haveNPN := false
  493. for _, p := range s.TLSConfig.NextProtos {
  494. if p == npnProto {
  495. haveNPN = true
  496. break
  497. }
  498. }
  499. if !haveNPN {
  500. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, npnProto)
  501. }
  502. if s.TLSNextProto == nil {
  503. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  504. }
  505. s.TLSNextProto[npnProto] = func(hs *http.Server, c *tls.Conn, h http.Handler) {
  506. if testHookOnConn != nil {
  507. testHookOnConn()
  508. }
  509. conf.handleConn(hs, c, h)
  510. }
  511. }
  512. type requestBody struct {
  513. sc *serverConn
  514. streamID uint32
  515. hasBody bool
  516. closed bool
  517. }
  518. func (b *requestBody) Close() error {
  519. b.closed = true
  520. return nil
  521. }
  522. func (b *requestBody) Read(p []byte) (n int, err error) {
  523. if !b.hasBody {
  524. return 0, io.EOF
  525. }
  526. // TODO: implement
  527. return 0, errors.New("TODO: we don't handle request bodies yet")
  528. }
  529. type responseWriter struct {
  530. sc *serverConn
  531. streamID uint32
  532. wroteHeaders bool
  533. h http.Header
  534. }
  535. // TODO: bufio writing of responseWriter. add Flush, add pools of
  536. // bufio.Writers, adjust bufio writer sized based on frame size
  537. // updates from peer? For now: naive.
  538. func (w *responseWriter) Header() http.Header {
  539. if w.h == nil {
  540. w.h = make(http.Header)
  541. }
  542. return w.h
  543. }
  544. func (w *responseWriter) WriteHeader(code int) {
  545. if w.wroteHeaders {
  546. return
  547. }
  548. // TODO: defer actually writing this frame until a Flush or
  549. // handlerDone, like net/http's Server. then we can coalesce
  550. // e.g. a 204 response to have a Header response frame with
  551. // END_STREAM set, without a separate frame being sent in
  552. // handleDone.
  553. w.wroteHeaders = true
  554. w.sc.writeHeader(headerWriteReq{
  555. streamID: w.streamID,
  556. httpResCode: code,
  557. h: w.h,
  558. })
  559. }
  560. // TODO: responseWriter.WriteString too?
  561. func (w *responseWriter) Write(p []byte) (n int, err error) {
  562. if !w.wroteHeaders {
  563. w.WriteHeader(200)
  564. }
  565. return w.sc.writeData(w.streamID, p) // blocks waiting for tokens
  566. }
  567. func (w *responseWriter) handlerDone() {
  568. if !w.wroteHeaders {
  569. w.sc.writeHeader(headerWriteReq{
  570. streamID: w.streamID,
  571. httpResCode: 200,
  572. h: w.h,
  573. endStream: true, // handler has finished; can't be any data.
  574. })
  575. }
  576. }
  577. var testHookOnConn func() // for testing
  578. func validHeader(v string) bool {
  579. if len(v) == 0 {
  580. return false
  581. }
  582. for _, r := range v {
  583. // "Just as in HTTP/1.x, header field names are
  584. // strings of ASCII characters that are compared in a
  585. // case-insensitive fashion. However, header field
  586. // names MUST be converted to lowercase prior to their
  587. // encoding in HTTP/2. "
  588. if r >= 127 || ('A' <= r && r <= 'Z') {
  589. return false
  590. }
  591. }
  592. return true
  593. }
  594. var httpCodeStringCommon = map[int]string{} // n -> strconv.Itoa(n)
  595. func init() {
  596. for i := 100; i <= 999; i++ {
  597. if v := http.StatusText(i); v != "" {
  598. httpCodeStringCommon[i] = strconv.Itoa(i)
  599. }
  600. }
  601. }
  602. func httpCodeString(code int) string {
  603. if s, ok := httpCodeStringCommon[code]; ok {
  604. return s
  605. }
  606. return strconv.Itoa(code)
  607. }