frame.go 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  1. // Copyright 2014 The Go Authors.
  2. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS
  3. // Licensed under the same terms as Go itself:
  4. // https://code.google.com/p/go/source/browse/LICENSE
  5. package http2
  6. import (
  7. "encoding/binary"
  8. "fmt"
  9. "io"
  10. "sync"
  11. )
  12. const frameHeaderLen = 9
  13. // A FrameType is a registered frame type as defined in
  14. // http://http2.github.io/http2-spec/#rfc.section.11.2
  15. type FrameType uint8
  16. const (
  17. FrameData FrameType = 0x0
  18. FrameHeaders FrameType = 0x1
  19. FramePriority FrameType = 0x2
  20. FrameRSTStream FrameType = 0x3
  21. FrameSettings FrameType = 0x4
  22. FramePushPromise FrameType = 0x5
  23. FramePing FrameType = 0x6
  24. FrameGoAway FrameType = 0x7
  25. FrameWindowUpdate FrameType = 0x8
  26. FrameContinuation FrameType = 0x9
  27. )
  28. var frameName = map[FrameType]string{
  29. FrameData: "DATA",
  30. FrameHeaders: "HEADERS",
  31. FramePriority: "PRIORITY",
  32. FrameRSTStream: "RST_STREAM",
  33. FrameSettings: "SETTINGS",
  34. FramePushPromise: "PUSH_PROMISE",
  35. FramePing: "PING",
  36. FrameGoAway: "GOAWAY",
  37. FrameWindowUpdate: "WINDOW_UPDATE",
  38. FrameContinuation: "CONTINUATION",
  39. }
  40. func (t FrameType) String() string {
  41. if s, ok := frameName[t]; ok {
  42. return s
  43. }
  44. return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t))
  45. }
  46. // Flags is a bitmask of HTTP/2 flags.
  47. // The meaning of flags varies depending on the frame type.
  48. type Flags uint8
  49. // Has reports whether f contains all (0 or more) flags in v.
  50. func (f Flags) Has(v Flags) bool {
  51. return (f & v) == v
  52. }
  53. // Frame-specific FrameHeader flag bits.
  54. const (
  55. // Settings Frame
  56. FlagSettingsAck Flags = 0x1
  57. // Headers Frame
  58. FlagHeadersEndStream Flags = 0x1
  59. FlagHeadersEndSegment Flags = 0x2
  60. FlagHeadersEndHeaders Flags = 0x4
  61. FlagHeadersPadded Flags = 0x8
  62. FlagHeadersPriority Flags = 0x20
  63. FlagContinuationEndHeaders = FlagHeadersEndHeaders
  64. )
  65. // A SettingID is an HTTP/2 setting as defined in
  66. // http://http2.github.io/http2-spec/#iana-settings
  67. type SettingID uint16
  68. const (
  69. SettingHeaderTableSize SettingID = 0x1
  70. SettingEnablePush SettingID = 0x2
  71. SettingMaxConcurrentStreams SettingID = 0x3
  72. SettingInitialWindowSize SettingID = 0x4
  73. SettingMaxFrameSize SettingID = 0x5
  74. SettingMaxHeaderListSize SettingID = 0x6
  75. )
  76. var settingName = map[SettingID]string{
  77. SettingHeaderTableSize: "HEADER_TABLE_SIZE",
  78. SettingEnablePush: "ENABLE_PUSH",
  79. SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
  80. SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
  81. SettingMaxFrameSize: "MAX_FRAME_SIZE",
  82. SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
  83. }
  84. func (s SettingID) String() string {
  85. if v, ok := settingName[s]; ok {
  86. return v
  87. }
  88. return fmt.Sprintf("UNKNOWN_SETTING_%d", uint8(s))
  89. }
  90. // a frameParser parses a frame given its FrameHeader and payload
  91. // bytes. The length of payload will always equal fh.Length (which
  92. // might be 0).
  93. type frameParser func(fh FrameHeader, payload []byte) (Frame, error)
  94. var frameParsers = map[FrameType]frameParser{
  95. FrameData: nil, // TODO
  96. FrameHeaders: parseHeadersFrame,
  97. FramePriority: nil, // TODO
  98. FrameRSTStream: nil, // TODO
  99. FrameSettings: parseSettingsFrame,
  100. FramePushPromise: nil, // TODO
  101. FramePing: nil, // TODO
  102. FrameGoAway: nil, // TODO
  103. FrameWindowUpdate: parseWindowUpdateFrame,
  104. FrameContinuation: parseContinuationFrame,
  105. }
  106. func typeFrameParser(t FrameType) frameParser {
  107. if f := frameParsers[t]; f != nil {
  108. return f
  109. }
  110. return parseUnknownFrame
  111. }
  112. // A FrameHeader is the 9 byte header of all HTTP/2 frames.
  113. //
  114. // See http://http2.github.io/http2-spec/#FrameHeader
  115. type FrameHeader struct {
  116. valid bool // caller can access []byte fields in the Frame
  117. Type FrameType
  118. Flags Flags
  119. Length uint32 // actually a uint24 max; default is uint16 max
  120. StreamID uint32
  121. }
  122. // Header returns h. It exists so FrameHeaders can be embedded in other
  123. // specific frame types and implement the Frame interface.
  124. func (h FrameHeader) Header() FrameHeader { return h }
  125. func (h FrameHeader) String() string {
  126. return fmt.Sprintf("[FrameHeader type=%v flags=%v stream=%v len=%v]",
  127. h.Type, h.Flags, h.StreamID, h.Length)
  128. }
  129. func (h *FrameHeader) checkValid() {
  130. if !h.valid {
  131. panic("Frame accessor called on non-owned Frame")
  132. }
  133. }
  134. func (h *FrameHeader) invalidate() { h.valid = false }
  135. // frame header bytes.
  136. // Used only by ReadFrameHeader.
  137. var fhBytes = sync.Pool{
  138. New: func() interface{} {
  139. buf := make([]byte, frameHeaderLen)
  140. return &buf
  141. },
  142. }
  143. // ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
  144. // Most users should use Framer.ReadFrame instead.
  145. func ReadFrameHeader(r io.Reader) (FrameHeader, error) {
  146. bufp := fhBytes.Get().(*[]byte)
  147. defer fhBytes.Put(bufp)
  148. return readFrameHeader(*bufp, r)
  149. }
  150. func readFrameHeader(buf []byte, r io.Reader) (FrameHeader, error) {
  151. _, err := io.ReadFull(r, buf[:frameHeaderLen])
  152. if err != nil {
  153. return FrameHeader{}, err
  154. }
  155. return FrameHeader{
  156. Length: (uint32(buf[0])<<16 | uint32(buf[1])<<7 | uint32(buf[2])),
  157. Type: FrameType(buf[3]),
  158. Flags: Flags(buf[4]),
  159. StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
  160. valid: true,
  161. }, nil
  162. }
  163. // A Frame is the base interface implemented by all frame types.
  164. // Callers will generally type-assert the specific frame type:
  165. // *HeadersFrame, *SettingsFrame, *WindowUpdateFrame, etc.
  166. //
  167. // Frames are only valid until the next call to Framer.ReadFrame.
  168. type Frame interface {
  169. Header() FrameHeader
  170. // invalidate is called by Framer.ReadFrame to make this
  171. // frame's buffers as being invalid, since the subsequent
  172. // frame will reuse them.
  173. invalidate()
  174. }
  175. // A Framer reads and writes Frames.
  176. type Framer struct {
  177. r io.Reader
  178. lr io.LimitedReader
  179. lastFrame Frame
  180. readBuf []byte
  181. w io.Writer
  182. }
  183. // NewFramer returns a Framer that writes frames to w and reads them from r.
  184. func NewFramer(w io.Writer, r io.Reader) *Framer {
  185. return &Framer{
  186. w: w,
  187. r: r,
  188. readBuf: make([]byte, 1<<10),
  189. }
  190. }
  191. // ReadFrame reads a single frame. The returned Frame is only valid
  192. // until the next call to ReadFrame.
  193. func (fr *Framer) ReadFrame() (Frame, error) {
  194. if fr.lastFrame != nil {
  195. fr.lastFrame.invalidate()
  196. }
  197. fh, err := readFrameHeader(fr.readBuf, fr.r)
  198. if err != nil {
  199. return nil, err
  200. }
  201. if uint32(len(fr.readBuf)) < fh.Length {
  202. fr.readBuf = make([]byte, fh.Length)
  203. }
  204. payload := fr.readBuf[:fh.Length]
  205. if _, err := io.ReadFull(fr.r, payload); err != nil {
  206. return nil, err
  207. }
  208. f, err := typeFrameParser(fh.Type)(fh, payload)
  209. if err != nil {
  210. return nil, err
  211. }
  212. fr.lastFrame = f
  213. return f, nil
  214. }
  215. // A SettingsFrame conveys configuration parameters that affect how
  216. // endpoints communicate, such as preferences and constraints on peer
  217. // behavior.
  218. //
  219. // See http://http2.github.io/http2-spec/#SETTINGS
  220. type SettingsFrame struct {
  221. FrameHeader
  222. p []byte
  223. }
  224. func parseSettingsFrame(fh FrameHeader, p []byte) (Frame, error) {
  225. if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 {
  226. // When this (ACK 0x1) bit is set, the payload of the
  227. // SETTINGS frame MUST be empty. Receipt of a
  228. // SETTINGS frame with the ACK flag set and a length
  229. // field value other than 0 MUST be treated as a
  230. // connection error (Section 5.4.1) of type
  231. // FRAME_SIZE_ERROR.
  232. return nil, ConnectionError(ErrCodeFrameSize)
  233. }
  234. if fh.StreamID != 0 {
  235. // SETTINGS frames always apply to a connection,
  236. // never a single stream. The stream identifier for a
  237. // SETTINGS frame MUST be zero (0x0). If an endpoint
  238. // receives a SETTINGS frame whose stream identifier
  239. // field is anything other than 0x0, the endpoint MUST
  240. // respond with a connection error (Section 5.4.1) of
  241. // type PROTOCOL_ERROR.
  242. return nil, ConnectionError(ErrCodeProtocol)
  243. }
  244. if len(p)%6 != 0 {
  245. // Expecting even number of 6 byte settings.
  246. return nil, ConnectionError(ErrCodeFrameSize)
  247. }
  248. f := &SettingsFrame{FrameHeader: fh, p: p}
  249. if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 {
  250. // Values above the maximum flow control window size of 2^31 - 1 MUST
  251. // be treated as a connection error (Section 5.4.1) of type
  252. // FLOW_CONTROL_ERROR.
  253. return nil, ConnectionError(ErrCodeFlowControl)
  254. }
  255. return f, nil
  256. }
  257. func (f *SettingsFrame) Value(s SettingID) (v uint32, ok bool) {
  258. f.checkValid()
  259. buf := f.p
  260. for len(buf) > 0 {
  261. settingID := SettingID(binary.BigEndian.Uint16(buf[:2]))
  262. if settingID == s {
  263. return binary.BigEndian.Uint32(buf[2:4]), true
  264. }
  265. buf = buf[6:]
  266. }
  267. return 0, false
  268. }
  269. func (f *SettingsFrame) ForeachSetting(fn func(s SettingID, v uint32)) {
  270. f.checkValid()
  271. buf := f.p
  272. for len(buf) > 0 {
  273. fn(SettingID(binary.BigEndian.Uint16(buf[:2])), binary.BigEndian.Uint32(buf[2:4]))
  274. buf = buf[6:]
  275. }
  276. }
  277. // An UnknownFrame is the frame type returned when the frame type is unknown
  278. // or no specific frame type parser exists.
  279. type UnknownFrame struct {
  280. FrameHeader
  281. p []byte
  282. }
  283. // Payload returns the frame's payload (after the header).
  284. // It is not valid to call this method after a subsequent
  285. // call to Framer.ReadFrame.
  286. func (f *UnknownFrame) Payload() []byte {
  287. f.checkValid()
  288. return f.p
  289. }
  290. func parseUnknownFrame(fh FrameHeader, p []byte) (Frame, error) {
  291. return &UnknownFrame{fh, p}, nil
  292. }
  293. // A WindowUpdateFrame is used to implement flow control.
  294. // See http://http2.github.io/http2-spec/#rfc.section.6.9
  295. type WindowUpdateFrame struct {
  296. FrameHeader
  297. Increment uint32
  298. }
  299. func parseWindowUpdateFrame(fh FrameHeader, p []byte) (Frame, error) {
  300. if len(p) < 4 {
  301. // Too short.
  302. return nil, ConnectionError(ErrCodeProtocol)
  303. }
  304. return &WindowUpdateFrame{
  305. FrameHeader: fh,
  306. Increment: binary.BigEndian.Uint32(p[:4]) & 0x7fffffff, // mask off high reserved bit
  307. }, nil
  308. }
  309. // A HeadersFrame is used to open a stream and additionally carries a
  310. // header block fragment.
  311. type HeadersFrame struct {
  312. FrameHeader
  313. // If FlagHeadersPriority:
  314. ExclusiveDep bool
  315. StreamDep uint32
  316. // Weight is [0,255]. Only valid if FrameHeader.Flags has the
  317. // FlagHeadersPriority bit set, in which case the caller must
  318. // also add 1 to get to spec-defined [1,256] range.
  319. Weight uint8
  320. headerFragBuf []byte // not owned
  321. }
  322. func (f *HeadersFrame) HeaderBlockFragment() []byte {
  323. f.checkValid()
  324. return f.headerFragBuf
  325. }
  326. func (f *HeadersFrame) HeadersEnded() bool {
  327. return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
  328. }
  329. func parseHeadersFrame(fh FrameHeader, p []byte) (_ Frame, err error) {
  330. hf := &HeadersFrame{
  331. FrameHeader: fh,
  332. }
  333. if fh.StreamID == 0 {
  334. // HEADERS frames MUST be associated with a stream. If a HEADERS frame
  335. // is received whose stream identifier field is 0x0, the recipient MUST
  336. // respond with a connection error (Section 5.4.1) of type
  337. // PROTOCOL_ERROR.
  338. return nil, ConnectionError(ErrCodeProtocol)
  339. }
  340. var padLength uint8
  341. if fh.Flags.Has(FlagHeadersPadded) {
  342. if p, padLength, err = readByte(p); err != nil {
  343. return
  344. }
  345. }
  346. if fh.Flags.Has(FlagHeadersPriority) {
  347. var v uint32
  348. p, v, err = readUint32(p)
  349. if err != nil {
  350. return nil, err
  351. }
  352. hf.StreamDep = v & 0x7fffffff
  353. hf.ExclusiveDep = (v != hf.StreamDep) // high bit was set
  354. p, hf.Weight, err = readByte(p)
  355. if err != nil {
  356. return nil, err
  357. }
  358. }
  359. if len(p)-int(padLength) <= 0 {
  360. return nil, StreamError(fh.StreamID)
  361. }
  362. hf.headerFragBuf = p[:len(p)-int(padLength)]
  363. return hf, nil
  364. }
  365. // A ContinuationFrame is used to continue a sequence of header block fragments.
  366. // See http://http2.github.io/http2-spec/#rfc.section.6.10
  367. type ContinuationFrame struct {
  368. FrameHeader
  369. headerFragBuf []byte
  370. }
  371. func parseContinuationFrame(fh FrameHeader, p []byte) (Frame, error) {
  372. return &ContinuationFrame{fh, p}, nil
  373. }
  374. func (f *ContinuationFrame) HeaderBlockFragment() []byte {
  375. f.checkValid()
  376. return f.headerFragBuf
  377. }
  378. func (f *ContinuationFrame) HeadersEnded() bool {
  379. return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
  380. }
  381. func readByte(p []byte) (remain []byte, b byte, err error) {
  382. if len(p) == 0 {
  383. return nil, 0, io.ErrUnexpectedEOF
  384. }
  385. return p[1:], p[0], nil
  386. }
  387. func readUint32(p []byte) (remain []byte, v uint32, err error) {
  388. if len(p) < 4 {
  389. return nil, 0, io.ErrUnexpectedEOF
  390. }
  391. return p[4:], binary.BigEndian.Uint32(p[:4]), nil
  392. }