frame.go 11 KB

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