http2.go 15 KB

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