http2.go 7.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299
  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. "io"
  21. "log"
  22. "net/http"
  23. "strings"
  24. "github.com/bradfitz/http2/hpack"
  25. )
  26. const (
  27. // ClientPreface is the string that must be sent by new
  28. // connections from clients.
  29. ClientPreface = "PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n"
  30. )
  31. var (
  32. clientPreface = []byte(ClientPreface)
  33. )
  34. const (
  35. npnProto = "h2-14"
  36. // http://http2.github.io/http2-spec/#SettingValues
  37. initialHeaderTableSize = 4096
  38. )
  39. // Server is an HTTP2 server.
  40. type Server struct {
  41. // MaxStreams optionally ...
  42. MaxStreams int
  43. }
  44. func (srv *Server) handleConn(hs *http.Server, c *tls.Conn, h http.Handler) {
  45. sc := &serverConn{
  46. hs: hs,
  47. conn: c,
  48. handler: h,
  49. framer: NewFramer(c, c),
  50. streams: make(map[uint32]*stream),
  51. canonHeader: make(map[string]string),
  52. }
  53. sc.hpackDecoder = hpack.NewDecoder(initialHeaderTableSize, sc.onNewHeaderField)
  54. sc.serve()
  55. }
  56. type serverConn struct {
  57. hs *http.Server
  58. conn *tls.Conn
  59. handler http.Handler
  60. framer *Framer
  61. maxStreamID uint32 // max ever seen
  62. streams map[uint32]*stream
  63. // State related to parsing current headers:
  64. hpackDecoder *hpack.Decoder
  65. header http.Header
  66. canonHeader map[string]string // http2-lower-case -> Go-Canonical-Case
  67. method, path, scheme, authority string
  68. // curHeaderStreamID is non-zero if we're in the middle
  69. // of parsing headers that span multiple frames.
  70. curHeaderStreamID uint32
  71. }
  72. type streamState int
  73. const (
  74. stateIdle streamState = iota
  75. stateOpen
  76. stateHalfClosedLocal
  77. stateHalfClosedRemote
  78. stateResvLocal
  79. stateResvRemote
  80. stateClosed
  81. )
  82. type stream struct {
  83. id uint32
  84. state streamState // owned by serverConn's processing loop
  85. }
  86. func (sc *serverConn) state(streamID uint32) streamState {
  87. // http://http2.github.io/http2-spec/#rfc.section.5.1
  88. if st, ok := sc.streams[streamID]; ok {
  89. return st.state
  90. }
  91. // "The first use of a new stream identifier implicitly closes all
  92. // streams in the "idle" state that might have been initiated by
  93. // that peer with a lower-valued stream identifier. For example, if
  94. // a client sends a HEADERS frame on stream 7 without ever sending a
  95. // frame on stream 5, then stream 5 transitions to the "closed"
  96. // state when the first frame for stream 7 is sent or received."
  97. if streamID <= sc.maxStreamID {
  98. return stateClosed
  99. }
  100. return stateIdle
  101. }
  102. func (sc *serverConn) logf(format string, args ...interface{}) {
  103. if lg := sc.hs.ErrorLog; lg != nil {
  104. lg.Printf(format, args...)
  105. } else {
  106. log.Printf(format, args...)
  107. }
  108. }
  109. func (sc *serverConn) onNewHeaderField(f hpack.HeaderField) {
  110. log.Printf("Header field: +%v", f)
  111. if strings.HasPrefix(f.Name, ":") {
  112. switch f.Name {
  113. case ":method":
  114. sc.method = f.Value
  115. case ":path":
  116. sc.path = f.Value
  117. case ":scheme":
  118. sc.scheme = f.Value
  119. case ":authority":
  120. sc.authority = f.Value
  121. default:
  122. log.Printf("Ignoring unknown pseudo-header %q", f.Name)
  123. }
  124. return
  125. }
  126. sc.header.Add(sc.canonicalHeader(f.Name), f.Value)
  127. }
  128. func (sc *serverConn) canonicalHeader(v string) string {
  129. // TODO: use a sync.Pool instead of putting the cache on *serverConn?
  130. cv, ok := sc.canonHeader[v]
  131. if !ok {
  132. cv = http.CanonicalHeaderKey(v)
  133. sc.canonHeader[v] = cv
  134. }
  135. return cv
  136. }
  137. func (sc *serverConn) serve() {
  138. defer sc.conn.Close()
  139. log.Printf("HTTP/2 connection from %v on %p", sc.conn.RemoteAddr(), sc.hs)
  140. buf := make([]byte, len(ClientPreface))
  141. // TODO: timeout reading from the client
  142. if _, err := io.ReadFull(sc.conn, buf); err != nil {
  143. sc.logf("error reading client preface: %v", err)
  144. return
  145. }
  146. if !bytes.Equal(buf, clientPreface) {
  147. sc.logf("bogus greeting from client: %q", buf)
  148. return
  149. }
  150. log.Printf("client %v said hello", sc.conn.RemoteAddr())
  151. for {
  152. f, err := sc.framer.ReadFrame()
  153. if err == nil {
  154. log.Printf("got %v: %#v", f.Header(), f)
  155. err = sc.processFrame(f)
  156. }
  157. if h2e, ok := err.(Error); ok {
  158. if h2e.IsConnectionError() {
  159. sc.logf("Disconnection; connection error: %v", err)
  160. return
  161. }
  162. // TODO: stream errors, etc
  163. }
  164. if err != nil {
  165. sc.logf("Disconnection due to other error: %v", err)
  166. return
  167. }
  168. }
  169. }
  170. func (sc *serverConn) processFrame(f Frame) error {
  171. if s := sc.curHeaderStreamID; s != 0 {
  172. if cf, ok := f.(*ContinuationFrame); !ok {
  173. return ConnectionError(ErrCodeProtocol)
  174. } else if cf.Header().StreamID != s {
  175. return ConnectionError(ErrCodeProtocol)
  176. }
  177. }
  178. switch f := f.(type) {
  179. case *SettingsFrame:
  180. return sc.processSettings(f)
  181. case *HeadersFrame:
  182. return sc.processHeaders(f)
  183. case *ContinuationFrame:
  184. return sc.processContinuation(f)
  185. default:
  186. log.Printf("Ignoring unknown %v", f.Header)
  187. return nil
  188. }
  189. }
  190. func (sc *serverConn) processSettings(f *SettingsFrame) error {
  191. f.ForeachSetting(func(s SettingID, v uint32) {
  192. log.Printf(" setting %s = %v", s, v)
  193. })
  194. return nil
  195. }
  196. func (sc *serverConn) processHeaders(f *HeadersFrame) error {
  197. id := f.Header().StreamID
  198. // http://http2.github.io/http2-spec/#rfc.section.5.1.1
  199. if id%2 != 1 || id <= sc.maxStreamID {
  200. // Streams initiated by a client MUST use odd-numbered
  201. // stream identifiers. [...] The identifier of a newly
  202. // established stream MUST be numerically greater than all
  203. // streams that the initiating endpoint has opened or
  204. // reserved. [...] An endpoint that receives an unexpected
  205. // stream identifier MUST respond with a connection error
  206. // (Section 5.4.1) of type PROTOCOL_ERROR.
  207. return ConnectionError(ErrCodeProtocol)
  208. }
  209. if id > sc.maxStreamID {
  210. sc.maxStreamID = id
  211. }
  212. sc.header = make(http.Header)
  213. sc.curHeaderStreamID = id
  214. return sc.processHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded())
  215. }
  216. func (sc *serverConn) processHeaderBlockFragment(frag []byte, end bool) error {
  217. if _, err := sc.hpackDecoder.Write(frag); err != nil {
  218. // TODO: convert to stream error I assume?
  219. }
  220. if end {
  221. if err := sc.hpackDecoder.Close(); err != nil {
  222. // TODO: convert to stream error I assume?
  223. return err
  224. }
  225. sc.curHeaderStreamID = 0
  226. // TODO: transition state
  227. }
  228. return nil
  229. }
  230. func (sc *serverConn) processContinuation(f *ContinuationFrame) error {
  231. return sc.processHeaderBlockFragment(f.HeaderBlockFragment(), f.HeadersEnded())
  232. }
  233. // ConfigureServer adds HTTP2 support to s as configured by the HTTP/2
  234. // server configuration in conf. The configuration may be nil.
  235. //
  236. // ConfigureServer must be called before s begins serving.
  237. func ConfigureServer(s *http.Server, conf *Server) {
  238. if conf == nil {
  239. conf = new(Server)
  240. }
  241. if s.TLSConfig == nil {
  242. s.TLSConfig = new(tls.Config)
  243. }
  244. haveNPN := false
  245. for _, p := range s.TLSConfig.NextProtos {
  246. if p == npnProto {
  247. haveNPN = true
  248. break
  249. }
  250. }
  251. if !haveNPN {
  252. s.TLSConfig.NextProtos = append(s.TLSConfig.NextProtos, npnProto)
  253. }
  254. if s.TLSNextProto == nil {
  255. s.TLSNextProto = map[string]func(*http.Server, *tls.Conn, http.Handler){}
  256. }
  257. s.TLSNextProto[npnProto] = func(hs *http.Server, c *tls.Conn, h http.Handler) {
  258. if testHookOnConn != nil {
  259. testHookOnConn()
  260. }
  261. conf.handleConn(hs, c, h)
  262. }
  263. }
  264. var testHookOnConn func() // for testing