http2.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575
  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. sc.logf("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. errstr := err.Error()
  239. if !strings.Contains(errstr, "use of closed network connection") {
  240. sc.logf("client %s stopped sending frames: %v", sc.conn.RemoteAddr(), errstr)
  241. }
  242. }
  243. return
  244. }
  245. f := fp.f
  246. log.Printf("got %v: %#v", f.Header(), f)
  247. err := sc.processFrame(f)
  248. fp.processed <- struct{}{} // let readFrames proceed
  249. if h2e, ok := err.(Error); ok {
  250. if h2e.IsConnectionError() {
  251. sc.logf("Disconnection; connection error: %v", err)
  252. return
  253. }
  254. // TODO: stream errors, etc
  255. }
  256. if err != nil {
  257. sc.logf("Disconnection due to other error: %v", err)
  258. return
  259. }
  260. }
  261. }
  262. }
  263. func (sc *serverConn) processFrame(f Frame) error {
  264. if s := sc.curHeaderStreamID; s != 0 {
  265. if cf, ok := f.(*ContinuationFrame); !ok {
  266. return ConnectionError(ErrCodeProtocol)
  267. } else if cf.Header().StreamID != s {
  268. return ConnectionError(ErrCodeProtocol)
  269. }
  270. }
  271. switch f := f.(type) {
  272. case *SettingsFrame:
  273. return sc.processSettings(f)
  274. case *HeadersFrame:
  275. return sc.processHeaders(f)
  276. case *ContinuationFrame:
  277. return sc.processContinuation(f)
  278. default:
  279. log.Printf("Ignoring unknown %v", f.Header)
  280. return nil
  281. }
  282. }
  283. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  284. f.ForeachSetting(func(s Setting) {
  285. log.Printf(" setting %s = %v", s.ID, s.Val)
  286. })
  287. return nil
  288. }
  289. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  290. id := f.Header().StreamID
  291. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  292. if id%2 != 1 || id <= sc.maxStreamID {
  293. // Streams initiated by a client MUST use odd-numbered
  294. // stream identifiers. [...] The identifier of a newly
  295. // established stream MUST be numerically greater than all
  296. // streams that the initiating endpoint has opened or
  297. // reserved. [...] An endpoint that receives an unexpected
  298. // stream identifier MUST respond with a connection error
  299. // (Section 5.4.1) of type PROTOCOL_ERROR.
  300. return ConnectionError(ErrCodeProtocol)
  301. }
  302. if id > sc.maxStreamID {
  303. sc.maxStreamID = id
  304. }
  305. st := &stream{
  306. id: id,
  307. state: stateOpen,
  308. }
  309. if f.Header().Flags.Has(FlagHeadersEndStream) {
  310. st.state = stateHalfClosedRemote
  311. }
  312. sc.streams[id] = st
  313. sc.header = make(http.Header)
  314. sc.curHeaderStreamID = id
  315. sc.curStream = st
  316. return sc.processHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded())
  317. }
  318. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  319. return sc.processHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded())
  320. }
  321. func (sc *serverConn) processHeaderBlockFragment(frag []byte, end bool) error {
  322. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  323. // TODO: convert to stream error I assume?
  324. return err
  325. }
  326. if !end {
  327. return nil
  328. }
  329. if err := sc.hpackDecoder.Close(); err != nil {
  330. // TODO: convert to stream error I assume?
  331. return err
  332. }
  333. curStream := sc.curStream
  334. sc.curHeaderStreamID = 0
  335. sc.curStream = nil
  336. // TODO: transition streamID state
  337. go sc.startHandler(curStream.id, curStream.state == stateOpen, sc.method, sc.path, sc.scheme, sc.authority, sc.header)
  338. return nil
  339. }
  340. func (sc *serverConn) startHandler(streamID uint32, bodyOpen bool, method, path, scheme, authority string, reqHeader http.Header) {
  341. var tlsState *tls.ConnectionState // make this non-nil if https
  342. if scheme == "https" {
  343. // TODO: get from sc's ConnectionState
  344. tlsState = &tls.ConnectionState{}
  345. }
  346. req := &http.Request{
  347. Method: method,
  348. URL: &url.URL{},
  349. RemoteAddr: sc.conn.RemoteAddr().String(),
  350. RequestURI: path,
  351. Proto: "HTTP/2.0",
  352. ProtoMajor: 2,
  353. ProtoMinor: 0,
  354. TLS: tlsState,
  355. Host: authority,
  356. Body: &requestBody{
  357. sc: sc,
  358. streamID: streamID,
  359. hasBody: bodyOpen,
  360. },
  361. }
  362. if vv, ok := reqHeader["Content-Length"]; ok {
  363. req.ContentLength, _ = strconv.ParseInt(vv[0], 10, 64)
  364. } else {
  365. req.ContentLength = -1
  366. }
  367. rw := &responseWriter{
  368. sc: sc,
  369. streamID: streamID,
  370. }
  371. defer rw.handlerDone()
  372. // TODO: catch panics like net/http.Server
  373. sc.handler.ServeHTTP(rw, req)
  374. }
  375. // called from handler goroutines
  376. func (sc *serverConn) writeData(streamID uint32, p []byte) (n int, err error) {
  377. // TODO: implement
  378. log.Printf("WRITE on %d: %q", streamID, p)
  379. return len(p), nil
  380. }
  381. // headerWriteReq is a request to write an HTTP response header from a server Handler.
  382. type headerWriteReq struct {
  383. streamID uint32
  384. httpResCode int
  385. h http.Header // may be nil
  386. endStream bool
  387. }
  388. // called from handler goroutines.
  389. // h may be nil.
  390. func (sc *serverConn) writeHeader(req headerWriteReq) {
  391. sc.writeHeaderCh <- req
  392. }
  393. // called from serverConn.serve loop.
  394. func (sc *serverConn) writeHeaderInLoop(req headerWriteReq) error {
  395. sc.headerWriteBuf.Reset()
  396. // TODO: remove this strconv
  397. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: ":status", Value: strconv.Itoa(req.httpResCode)})
  398. for k, vv := range req.h {
  399. for _, v := range vv {
  400. // TODO: for gargage, cache lowercase copies of headers at
  401. // least for common ones and/or popular recent ones for
  402. // this serverConn. LRU?
  403. sc.hpackEncoder.WriteField(hpack.HeaderField{Name: strings.ToLower(k), Value: v})
  404. }
  405. }
  406. headerBlock := sc.headerWriteBuf.Bytes()
  407. if len(headerBlock) > int(sc.maxWriteFrameSize) {
  408. // we'll need continuation ones.
  409. panic("TODO")
  410. }
  411. return sc.framer.WriteHeaders(HeadersFrameParam{
  412. StreamID: req.streamID,
  413. BlockFragment: headerBlock,
  414. EndStream: req.endStream,
  415. EndHeaders: true, // no continuation yet
  416. })
  417. }
  418. // ConfigureServer adds HTTP/2 support to a net/http Server.
  419. //
  420. // The configuration conf may be nil.
  421. //
  422. // ConfigureServer must be called before s begins serving.
  423. func ConfigureServer(s *http.Server, conf *Server) {
  424. if conf == nil {
  425. conf = new(Server)
  426. }
  427. if s.TLSConfig == nil {
  428. s.TLSConfig = new(tls.Config)
  429. }
  430. haveNPN := false
  431. for _, p := range s.TLSConfig.NextProtos {
  432. if p == npnProto {
  433. haveNPN = true
  434. break
  435. }
  436. }
  437. if !haveNPN {
  438. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, npnProto)
  439. }
  440. if s.TLSNextProto == nil {
  441. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  442. }
  443. s.TLSNextProto[npnProto] = func(hs *http.Server, c *tls.Conn, h http.Handler) {
  444. if testHookOnConn != nil {
  445. testHookOnConn()
  446. }
  447. conf.handleConn(hs, c, h)
  448. }
  449. }
  450. type requestBody struct {
  451. sc *serverConn
  452. streamID uint32
  453. hasBody bool
  454. closed bool
  455. }
  456. func (b *requestBody) Close() error {
  457. b.closed = true
  458. return nil
  459. }
  460. func (b *requestBody) Read(p []byte) (n int, err error) {
  461. if !b.hasBody {
  462. return 0, io.EOF
  463. }
  464. // TODO: implement
  465. return 0, errors.New("TODO: we don't handle request bodies yet")
  466. }
  467. type responseWriter struct {
  468. sc *serverConn
  469. streamID uint32
  470. wroteHeaders bool
  471. h http.Header
  472. }
  473. // TODO: bufio writing of responseWriter. add Flush, add pools of
  474. // bufio.Writers, adjust bufio writer sized based on frame size
  475. // updates from peer? For now: naive.
  476. func (w *responseWriter) Header() http.Header {
  477. if w.h == nil {
  478. w.h = make(http.Header)
  479. }
  480. return w.h
  481. }
  482. func (w *responseWriter) WriteHeader(code int) {
  483. if w.wroteHeaders {
  484. return
  485. }
  486. // TODO: defer actually writing this frame until a Flush or
  487. // handlerDone, like net/http's Server. then we can coalesce
  488. // e.g. a 204 response to have a Header response frame with
  489. // END_STREAM set, without a separate frame being sent in
  490. // handleDone.
  491. w.wroteHeaders = true
  492. w.sc.writeHeader(headerWriteReq{
  493. streamID: w.streamID,
  494. httpResCode: code,
  495. h: w.h,
  496. })
  497. }
  498. // TODO: responseWriter.WriteString too?
  499. func (w *responseWriter) Write(p []byte) (n int, err error) {
  500. if !w.wroteHeaders {
  501. w.WriteHeader(200)
  502. }
  503. return w.sc.writeData(w.streamID, p) // blocks waiting for tokens
  504. }
  505. func (w *responseWriter) handlerDone() {
  506. if !w.wroteHeaders {
  507. w.sc.writeHeader(headerWriteReq{
  508. streamID: w.streamID,
  509. httpResCode: 200,
  510. h: w.h,
  511. endStream: true, // handler has finished; can't be any data.
  512. })
  513. }
  514. }
  515. var testHookOnConn func() // for testing