frame.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113
  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. "bytes"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "sync"
  13. )
  14. const frameHeaderLen = 9
  15. var padZeros = make([]byte, 255) // zeros for padding
  16. // A FrameType is a registered frame type as defined in
  17. // http://http2.github.io/http2-spec/#rfc.section.11.2
  18. type FrameType uint8
  19. const (
  20. FrameData FrameType = 0x0
  21. FrameHeaders FrameType = 0x1
  22. FramePriority FrameType = 0x2
  23. FrameRSTStream FrameType = 0x3
  24. FrameSettings FrameType = 0x4
  25. FramePushPromise FrameType = 0x5
  26. FramePing FrameType = 0x6
  27. FrameGoAway FrameType = 0x7
  28. FrameWindowUpdate FrameType = 0x8
  29. FrameContinuation FrameType = 0x9
  30. )
  31. var frameName = map[FrameType]string{
  32. FrameData: "DATA",
  33. FrameHeaders: "HEADERS",
  34. FramePriority: "PRIORITY",
  35. FrameRSTStream: "RST_STREAM",
  36. FrameSettings: "SETTINGS",
  37. FramePushPromise: "PUSH_PROMISE",
  38. FramePing: "PING",
  39. FrameGoAway: "GOAWAY",
  40. FrameWindowUpdate: "WINDOW_UPDATE",
  41. FrameContinuation: "CONTINUATION",
  42. }
  43. func (t FrameType) String() string {
  44. if s, ok := frameName[t]; ok {
  45. return s
  46. }
  47. return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t))
  48. }
  49. // Flags is a bitmask of HTTP/2 flags.
  50. // The meaning of flags varies depending on the frame type.
  51. type Flags uint8
  52. // Has reports whether f contains all (0 or more) flags in v.
  53. func (f Flags) Has(v Flags) bool {
  54. return (f & v) == v
  55. }
  56. // Frame-specific FrameHeader flag bits.
  57. const (
  58. // Data Frame
  59. FlagDataEndStream Flags = 0x1
  60. FlagDataPadded Flags = 0x8
  61. // Headers Frame
  62. FlagHeadersEndStream Flags = 0x1
  63. FlagHeadersEndHeaders Flags = 0x4
  64. FlagHeadersPadded Flags = 0x8
  65. FlagHeadersPriority Flags = 0x20
  66. // Settings Frame
  67. FlagSettingsAck Flags = 0x1
  68. // Ping Frame
  69. FlagPingAck Flags = 0x1
  70. // Continuation Frame
  71. FlagContinuationEndHeaders Flags = 0x4
  72. FlagPushPromiseEndHeaders Flags = 0x4
  73. FlagPushPromisePadded Flags = 0x8
  74. )
  75. var flagName = map[FrameType]map[Flags]string{
  76. FrameData: {
  77. FlagDataEndStream: "END_STREAM",
  78. FlagDataPadded: "PADDED",
  79. },
  80. FrameHeaders: {
  81. FlagHeadersEndStream: "END_STREAM",
  82. FlagHeadersEndHeaders: "END_HEADERS",
  83. FlagHeadersPadded: "PADDED",
  84. FlagHeadersPriority: "PRIORITY",
  85. },
  86. FrameSettings: {
  87. FlagSettingsAck: "ACK",
  88. },
  89. FramePing: {
  90. FlagPingAck: "ACK",
  91. },
  92. FrameContinuation: {
  93. FlagContinuationEndHeaders: "END_HEADERS",
  94. },
  95. FramePushPromise: {
  96. FlagPushPromiseEndHeaders: "END_HEADERS",
  97. FlagPushPromisePadded: "PADDED",
  98. },
  99. }
  100. // a frameParser parses a frame given its FrameHeader and payload
  101. // bytes. The length of payload will always equal fh.Length (which
  102. // might be 0).
  103. type frameParser func(fh FrameHeader, payload []byte) (Frame, error)
  104. var frameParsers = map[FrameType]frameParser{
  105. FrameData: parseDataFrame,
  106. FrameHeaders: parseHeadersFrame,
  107. FramePriority: parsePriorityFrame,
  108. FrameRSTStream: parseRSTStreamFrame,
  109. FrameSettings: parseSettingsFrame,
  110. FramePushPromise: parsePushPromise,
  111. FramePing: parsePingFrame,
  112. FrameGoAway: parseGoAwayFrame,
  113. FrameWindowUpdate: parseWindowUpdateFrame,
  114. FrameContinuation: parseContinuationFrame,
  115. }
  116. func typeFrameParser(t FrameType) frameParser {
  117. if f := frameParsers[t]; f != nil {
  118. return f
  119. }
  120. return parseUnknownFrame
  121. }
  122. // A FrameHeader is the 9 byte header of all HTTP/2 frames.
  123. //
  124. // See http://http2.github.io/http2-spec/#FrameHeader
  125. type FrameHeader struct {
  126. valid bool // caller can access []byte fields in the Frame
  127. // Type is the 1 byte frame type. There are ten standard frame
  128. // types, but extension frame types may be written by WriteRawFrame
  129. // and will be returned by ReadFrame (as UnknownFrame).
  130. Type FrameType
  131. // Flags are the 1 byte of 8 potential bit flags per frame.
  132. // They are specific to the frame type.
  133. Flags Flags
  134. // Length is the length of the frame, not including the 9 byte header.
  135. // The maximum size is one byte less than 16MB (uint24), but only
  136. // frames up to 16KB are allowed without peer agreement.
  137. Length uint32
  138. // StreamID is which stream this frame is for. Certain frames
  139. // are not stream-specific, in which case this field is 0.
  140. StreamID uint32
  141. }
  142. // Header returns h. It exists so FrameHeaders can be embedded in other
  143. // specific frame types and implement the Frame interface.
  144. func (h FrameHeader) Header() FrameHeader { return h }
  145. func (h FrameHeader) String() string {
  146. var buf bytes.Buffer
  147. buf.WriteString("[FrameHeader ")
  148. buf.WriteString(h.Type.String())
  149. if h.Flags != 0 {
  150. buf.WriteString(" flags=")
  151. set := 0
  152. for i := uint8(0); i < 8; i++ {
  153. if h.Flags&(1<<i) == 0 {
  154. continue
  155. }
  156. set++
  157. if set > 1 {
  158. buf.WriteByte('|')
  159. }
  160. name := flagName[h.Type][Flags(1<<i)]
  161. if name != "" {
  162. buf.WriteString(name)
  163. } else {
  164. fmt.Fprintf(&buf, "0x%x", 1<<i)
  165. }
  166. }
  167. }
  168. if h.StreamID != 0 {
  169. fmt.Fprintf(&buf, " stream=%d", h.StreamID)
  170. }
  171. fmt.Fprintf(&buf, " len=%d]", h.Length)
  172. return buf.String()
  173. }
  174. func (h *FrameHeader) checkValid() {
  175. if !h.valid {
  176. panic("Frame accessor called on non-owned Frame")
  177. }
  178. }
  179. func (h *FrameHeader) invalidate() { h.valid = false }
  180. // frame header bytes.
  181. // Used only by ReadFrameHeader.
  182. var fhBytes = sync.Pool{
  183. New: func() interface{} {
  184. buf := make([]byte, frameHeaderLen)
  185. return &buf
  186. },
  187. }
  188. // ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
  189. // Most users should use Framer.ReadFrame instead.
  190. func ReadFrameHeader(r io.Reader) (FrameHeader, error) {
  191. bufp := fhBytes.Get().(*[]byte)
  192. defer fhBytes.Put(bufp)
  193. return readFrameHeader(*bufp, r)
  194. }
  195. func readFrameHeader(buf []byte, r io.Reader) (FrameHeader, error) {
  196. _, err := io.ReadFull(r, buf[:frameHeaderLen])
  197. if err != nil {
  198. return FrameHeader{}, err
  199. }
  200. return FrameHeader{
  201. Length: (uint32(buf[0])<<16 | uint32(buf[1])<<8 | uint32(buf[2])),
  202. Type: FrameType(buf[3]),
  203. Flags: Flags(buf[4]),
  204. StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
  205. valid: true,
  206. }, nil
  207. }
  208. // A Frame is the base interface implemented by all frame types.
  209. // Callers will generally type-assert the specific frame type:
  210. // *HeadersFrame, *SettingsFrame, *WindowUpdateFrame, etc.
  211. //
  212. // Frames are only valid until the next call to Framer.ReadFrame.
  213. type Frame interface {
  214. Header() FrameHeader
  215. // invalidate is called by Framer.ReadFrame to make this
  216. // frame's buffers as being invalid, since the subsequent
  217. // frame will reuse them.
  218. invalidate()
  219. }
  220. // A Framer reads and writes Frames.
  221. type Framer struct {
  222. r io.Reader
  223. lastFrame Frame
  224. maxReadSize uint32
  225. headerBuf [frameHeaderLen]byte
  226. // TODO: let getReadBuf be configurable, and use a less memory-pinning
  227. // allocator in server.go to minimize memory pinned for many idle conns.
  228. // Will probably also need to make frame invalidation have a hook too.
  229. getReadBuf func(size uint32) []byte
  230. readBuf []byte // cache for default getReadBuf
  231. maxWriteSize uint32 // zero means unlimited; TODO: implement
  232. w io.Writer
  233. wbuf []byte
  234. // AllowIllegalWrites permits the Framer's Write methods to
  235. // write frames that do not conform to the HTTP/2 spec. This
  236. // permits using the Framer to test other HTTP/2
  237. // implementations' conformance to the spec.
  238. // If false, the Write methods will prefer to return an error
  239. // rather than comply.
  240. AllowIllegalWrites bool
  241. // TODO: track which type of frame & with which flags was sent
  242. // last. Then return an error (unless AllowIllegalWrites) if
  243. // we're in the middle of a header block and a
  244. // non-Continuation or Continuation on a different stream is
  245. // attempted to be written.
  246. }
  247. func (f *Framer) startWrite(ftype FrameType, flags Flags, streamID uint32) {
  248. // Write the FrameHeader.
  249. f.wbuf = append(f.wbuf[:0],
  250. 0, // 3 bytes of length, filled in in endWrite
  251. 0,
  252. 0,
  253. byte(ftype),
  254. byte(flags),
  255. byte(streamID>>24),
  256. byte(streamID>>16),
  257. byte(streamID>>8),
  258. byte(streamID))
  259. }
  260. func (f *Framer) endWrite() error {
  261. // Now that we know the final size, fill in the FrameHeader in
  262. // the space previously reserved for it. Abuse append.
  263. length := len(f.wbuf) - frameHeaderLen
  264. if length >= (1 << 24) {
  265. return ErrFrameTooLarge
  266. }
  267. _ = append(f.wbuf[:0],
  268. byte(length>>16),
  269. byte(length>>8),
  270. byte(length))
  271. n, err := f.w.Write(f.wbuf)
  272. if err == nil && n != len(f.wbuf) {
  273. err = io.ErrShortWrite
  274. }
  275. return err
  276. }
  277. func (f *Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) }
  278. func (f *Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) }
  279. func (f *Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) }
  280. func (f *Framer) writeUint32(v uint32) {
  281. f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
  282. }
  283. const (
  284. minMaxFrameSize = 1 << 14
  285. maxFrameSize = 1<<24 - 1
  286. )
  287. // NewFramer returns a Framer that writes frames to w and reads them from r.
  288. func NewFramer(w io.Writer, r io.Reader) *Framer {
  289. fr := &Framer{
  290. w: w,
  291. r: r,
  292. }
  293. fr.getReadBuf = func(size uint32) []byte {
  294. if cap(fr.readBuf) >= int(size) {
  295. return fr.readBuf[:size]
  296. }
  297. fr.readBuf = make([]byte, size)
  298. return fr.readBuf
  299. }
  300. fr.SetMaxReadFrameSize(maxFrameSize)
  301. return fr
  302. }
  303. // SetMaxReadFrameSize sets the maximum size of a frame
  304. // that will be read by a subsequent call to ReadFrame.
  305. // It is the caller's responsibility to advertise this
  306. // limit with a SETTINGS frame.
  307. func (fr *Framer) SetMaxReadFrameSize(v uint32) {
  308. if v > maxFrameSize {
  309. v = maxFrameSize
  310. }
  311. fr.maxReadSize = v
  312. }
  313. // ErrFrameTooLarge is returned from Framer.ReadFrame when the peer
  314. // sends a frame that is larger than declared with SetMaxReadFrameSize.
  315. var ErrFrameTooLarge = errors.New("http2: frame too large")
  316. // ReadFrame reads a single frame. The returned Frame is only valid
  317. // until the next call to ReadFrame.
  318. // If the frame is larger than previously set with SetMaxReadFrameSize,
  319. // the returned error is ErrFrameTooLarge.
  320. func (fr *Framer) ReadFrame() (Frame, error) {
  321. if fr.lastFrame != nil {
  322. fr.lastFrame.invalidate()
  323. }
  324. fh, err := readFrameHeader(fr.headerBuf[:], fr.r)
  325. if err != nil {
  326. return nil, err
  327. }
  328. if fh.Length > fr.maxReadSize {
  329. return nil, ErrFrameTooLarge
  330. }
  331. payload := fr.getReadBuf(fh.Length)
  332. if _, err := io.ReadFull(fr.r, payload); err != nil {
  333. return nil, err
  334. }
  335. f, err := typeFrameParser(fh.Type)(fh, payload)
  336. if err != nil {
  337. return nil, err
  338. }
  339. fr.lastFrame = f
  340. return f, nil
  341. }
  342. // A DataFrame conveys arbitrary, variable-length sequences of octets
  343. // associated with a stream.
  344. // See http://http2.github.io/http2-spec/#rfc.section.6.1
  345. type DataFrame struct {
  346. FrameHeader
  347. data []byte
  348. }
  349. func (f *DataFrame) StreamEnded() bool {
  350. return f.FrameHeader.Flags.Has(FlagDataEndStream)
  351. }
  352. // Data returns the frame's data octets, not including any padding
  353. // size byte or padding suffix bytes.
  354. // The caller must not retain the returned memory past the next
  355. // call to ReadFrame.
  356. func (f *DataFrame) Data() []byte {
  357. f.checkValid()
  358. return f.data
  359. }
  360. func parseDataFrame(fh FrameHeader, payload []byte) (Frame, error) {
  361. if fh.StreamID == 0 {
  362. // DATA frames MUST be associated with a stream. If a
  363. // DATA frame is received whose stream identifier
  364. // field is 0x0, the recipient MUST respond with a
  365. // connection error (Section 5.4.1) of type
  366. // PROTOCOL_ERROR.
  367. return nil, ConnectionError(ErrCodeProtocol)
  368. }
  369. f := &DataFrame{
  370. FrameHeader: fh,
  371. }
  372. var padSize byte
  373. if fh.Flags.Has(FlagDataPadded) {
  374. var err error
  375. payload, padSize, err = readByte(payload)
  376. if err != nil {
  377. return nil, err
  378. }
  379. }
  380. if int(padSize) > len(payload) {
  381. // If the length of the padding is greater than the
  382. // length of the frame payload, the recipient MUST
  383. // treat this as a connection error.
  384. // Filed: https://github.com/http2/http2-spec/issues/610
  385. return nil, ConnectionError(ErrCodeProtocol)
  386. }
  387. f.data = payload[:len(payload)-int(padSize)]
  388. return f, nil
  389. }
  390. var errStreamID = errors.New("invalid streamid")
  391. func validStreamID(streamID uint32) bool {
  392. return streamID != 0 && streamID&(1<<31) == 0
  393. }
  394. // WriteData writes a DATA frame.
  395. //
  396. // It will perform exactly one Write to the underlying Writer.
  397. // It is the caller's responsibility to not call other Write methods concurrently.
  398. func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
  399. // TODO: ignoring padding for now. will add when somebody cares.
  400. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  401. return errStreamID
  402. }
  403. var flags Flags
  404. if endStream {
  405. flags |= FlagDataEndStream
  406. }
  407. f.startWrite(FrameData, flags, streamID)
  408. f.wbuf = append(f.wbuf, data...)
  409. return f.endWrite()
  410. }
  411. // A SettingsFrame conveys configuration parameters that affect how
  412. // endpoints communicate, such as preferences and constraints on peer
  413. // behavior.
  414. //
  415. // See http://http2.github.io/http2-spec/#SETTINGS
  416. type SettingsFrame struct {
  417. FrameHeader
  418. p []byte
  419. }
  420. func parseSettingsFrame(fh FrameHeader, p []byte) (Frame, error) {
  421. if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 {
  422. // When this (ACK 0x1) bit is set, the payload of the
  423. // SETTINGS frame MUST be empty. Receipt of a
  424. // SETTINGS frame with the ACK flag set and a length
  425. // field value other than 0 MUST be treated as a
  426. // connection error (Section 5.4.1) of type
  427. // FRAME_SIZE_ERROR.
  428. return nil, ConnectionError(ErrCodeFrameSize)
  429. }
  430. if fh.StreamID != 0 {
  431. // SETTINGS frames always apply to a connection,
  432. // never a single stream. The stream identifier for a
  433. // SETTINGS frame MUST be zero (0x0). If an endpoint
  434. // receives a SETTINGS frame whose stream identifier
  435. // field is anything other than 0x0, the endpoint MUST
  436. // respond with a connection error (Section 5.4.1) of
  437. // type PROTOCOL_ERROR.
  438. return nil, ConnectionError(ErrCodeProtocol)
  439. }
  440. if len(p)%6 != 0 {
  441. // Expecting even number of 6 byte settings.
  442. return nil, ConnectionError(ErrCodeFrameSize)
  443. }
  444. f := &SettingsFrame{FrameHeader: fh, p: p}
  445. if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 {
  446. // Values above the maximum flow control window size of 2^31 - 1 MUST
  447. // be treated as a connection error (Section 5.4.1) of type
  448. // FLOW_CONTROL_ERROR.
  449. return nil, ConnectionError(ErrCodeFlowControl)
  450. }
  451. return f, nil
  452. }
  453. func (f *SettingsFrame) IsAck() bool {
  454. return f.FrameHeader.Flags.Has(FlagSettingsAck)
  455. }
  456. func (f *SettingsFrame) Value(s SettingID) (v uint32, ok bool) {
  457. f.checkValid()
  458. buf := f.p
  459. for len(buf) > 0 {
  460. settingID := SettingID(binary.BigEndian.Uint16(buf[:2]))
  461. if settingID == s {
  462. return binary.BigEndian.Uint32(buf[2:6]), true
  463. }
  464. buf = buf[6:]
  465. }
  466. return 0, false
  467. }
  468. // ForeachSetting runs fn for each setting.
  469. // It stops and returns the first error.
  470. func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error {
  471. f.checkValid()
  472. buf := f.p
  473. for len(buf) > 0 {
  474. if err := fn(Setting{
  475. SettingID(binary.BigEndian.Uint16(buf[:2])),
  476. binary.BigEndian.Uint32(buf[2:6]),
  477. }); err != nil {
  478. return err
  479. }
  480. buf = buf[6:]
  481. }
  482. return nil
  483. }
  484. // WriteSettings writes a SETTINGS frame with zero or more settings
  485. // specified and the ACK bit not set.
  486. //
  487. // It will perform exactly one Write to the underlying Writer.
  488. // It is the caller's responsibility to not call other Write methods concurrently.
  489. func (f *Framer) WriteSettings(settings ...Setting) error {
  490. f.startWrite(FrameSettings, 0, 0)
  491. for _, s := range settings {
  492. f.writeUint16(uint16(s.ID))
  493. f.writeUint32(s.Val)
  494. }
  495. return f.endWrite()
  496. }
  497. // WriteSettings writes an empty SETTINGS frame with the ACK bit set.
  498. //
  499. // It will perform exactly one Write to the underlying Writer.
  500. // It is the caller's responsibility to not call other Write methods concurrently.
  501. func (f *Framer) WriteSettingsAck() error {
  502. f.startWrite(FrameSettings, FlagSettingsAck, 0)
  503. return f.endWrite()
  504. }
  505. // A PingFrame is a mechanism for measuring a minimal round trip time
  506. // from the sender, as well as determining whether an idle connection
  507. // is still functional.
  508. // See http://http2.github.io/http2-spec/#rfc.section.6.7
  509. type PingFrame struct {
  510. FrameHeader
  511. Data [8]byte
  512. }
  513. func parsePingFrame(fh FrameHeader, payload []byte) (Frame, error) {
  514. if len(payload) != 8 {
  515. return nil, ConnectionError(ErrCodeFrameSize)
  516. }
  517. if fh.StreamID != 0 {
  518. return nil, ConnectionError(ErrCodeProtocol)
  519. }
  520. f := &PingFrame{FrameHeader: fh}
  521. copy(f.Data[:], payload)
  522. return f, nil
  523. }
  524. func (f *Framer) WritePing(ack bool, data [8]byte) error {
  525. var flags Flags
  526. if ack {
  527. flags = FlagPingAck
  528. }
  529. f.startWrite(FramePing, flags, 0)
  530. f.writeBytes(data[:])
  531. return f.endWrite()
  532. }
  533. // A GoAwayFrame informs the remote peer to stop creating streams on this connection.
  534. // See http://http2.github.io/http2-spec/#rfc.section.6.8
  535. type GoAwayFrame struct {
  536. FrameHeader
  537. LastStreamID uint32
  538. ErrCode ErrCode
  539. debugData []byte
  540. }
  541. // DebugData returns any debug data in the GOAWAY frame. Its contents
  542. // are not defined.
  543. // The caller must not retain the returned memory past the next
  544. // call to ReadFrame.
  545. func (f *GoAwayFrame) DebugData() []byte {
  546. f.checkValid()
  547. return f.debugData
  548. }
  549. func parseGoAwayFrame(fh FrameHeader, p []byte) (Frame, error) {
  550. if fh.StreamID != 0 {
  551. return nil, ConnectionError(ErrCodeProtocol)
  552. }
  553. if len(p) < 8 {
  554. return nil, ConnectionError(ErrCodeFrameSize)
  555. }
  556. return &GoAwayFrame{
  557. FrameHeader: fh,
  558. LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
  559. ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])),
  560. debugData: p[8:],
  561. }, nil
  562. }
  563. func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error {
  564. f.startWrite(FrameGoAway, 0, 0)
  565. f.writeUint32(maxStreamID & (1<<31 - 1))
  566. f.writeUint32(uint32(code))
  567. f.writeBytes(debugData)
  568. return f.endWrite()
  569. }
  570. // An UnknownFrame is the frame type returned when the frame type is unknown
  571. // or no specific frame type parser exists.
  572. type UnknownFrame struct {
  573. FrameHeader
  574. p []byte
  575. }
  576. // Payload returns the frame's payload (after the header). It is not
  577. // valid to call this method after a subsequent call to
  578. // Framer.ReadFrame, nor is it valid to retain the returned slice.
  579. // The memory is owned by the Framer and is invalidated when the next
  580. // frame is read.
  581. func (f *UnknownFrame) Payload() []byte {
  582. f.checkValid()
  583. return f.p
  584. }
  585. func parseUnknownFrame(fh FrameHeader, p []byte) (Frame, error) {
  586. return &UnknownFrame{fh, p}, nil
  587. }
  588. // A WindowUpdateFrame is used to implement flow control.
  589. // See http://http2.github.io/http2-spec/#rfc.section.6.9
  590. type WindowUpdateFrame struct {
  591. FrameHeader
  592. Increment uint32
  593. }
  594. func parseWindowUpdateFrame(fh FrameHeader, p []byte) (Frame, error) {
  595. if len(p) != 4 {
  596. return nil, ConnectionError(ErrCodeFrameSize)
  597. }
  598. inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
  599. if inc == 0 {
  600. // A receiver MUST treat the receipt of a
  601. // WINDOW_UPDATE frame with an flow control window
  602. // increment of 0 as a stream error (Section 5.4.2) of
  603. // type PROTOCOL_ERROR; errors on the connection flow
  604. // control window MUST be treated as a connection
  605. // error (Section 5.4.1).
  606. if fh.StreamID == 0 {
  607. return nil, ConnectionError(ErrCodeProtocol)
  608. }
  609. return nil, StreamError{fh.StreamID, ErrCodeProtocol}
  610. }
  611. return &WindowUpdateFrame{
  612. FrameHeader: fh,
  613. Increment: inc,
  614. }, nil
  615. }
  616. // WriteWindowUpdate writes a WINDOW_UPDATE frame.
  617. // The increment value must be between 1 and 2,147,483,647, inclusive.
  618. // If the Stream ID is zero, the window update applies to the
  619. // connection as a whole.
  620. func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error {
  621. // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
  622. if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
  623. return errors.New("illegal window increment value")
  624. }
  625. f.startWrite(FrameWindowUpdate, 0, streamID)
  626. f.writeUint32(incr)
  627. return f.endWrite()
  628. }
  629. // A HeadersFrame is used to open a stream and additionally carries a
  630. // header block fragment.
  631. type HeadersFrame struct {
  632. FrameHeader
  633. // Priority is set if FlagHeadersPriority is set in the FrameHeader.
  634. Priority PriorityParam
  635. headerFragBuf []byte // not owned
  636. }
  637. func (f *HeadersFrame) HeaderBlockFragment() []byte {
  638. f.checkValid()
  639. return f.headerFragBuf
  640. }
  641. func (f *HeadersFrame) HeadersEnded() bool {
  642. return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
  643. }
  644. func (f *HeadersFrame) StreamEnded() bool {
  645. return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
  646. }
  647. func (f *HeadersFrame) HasPriority() bool {
  648. return f.FrameHeader.Flags.Has(FlagHeadersPriority)
  649. }
  650. func parseHeadersFrame(fh FrameHeader, p []byte) (_ Frame, err error) {
  651. hf := &HeadersFrame{
  652. FrameHeader: fh,
  653. }
  654. if fh.StreamID == 0 {
  655. // HEADERS frames MUST be associated with a stream. If a HEADERS frame
  656. // is received whose stream identifier field is 0x0, the recipient MUST
  657. // respond with a connection error (Section 5.4.1) of type
  658. // PROTOCOL_ERROR.
  659. return nil, ConnectionError(ErrCodeProtocol)
  660. }
  661. var padLength uint8
  662. if fh.Flags.Has(FlagHeadersPadded) {
  663. if p, padLength, err = readByte(p); err != nil {
  664. return
  665. }
  666. }
  667. if fh.Flags.Has(FlagHeadersPriority) {
  668. var v uint32
  669. p, v, err = readUint32(p)
  670. if err != nil {
  671. return nil, err
  672. }
  673. hf.Priority.StreamDep = v & 0x7fffffff
  674. hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
  675. p, hf.Priority.Weight, err = readByte(p)
  676. if err != nil {
  677. return nil, err
  678. }
  679. }
  680. if len(p)-int(padLength) <= 0 {
  681. return nil, StreamError{fh.StreamID, ErrCodeProtocol}
  682. }
  683. hf.headerFragBuf = p[:len(p)-int(padLength)]
  684. return hf, nil
  685. }
  686. // HeadersFrameParam are the parameters for writing a HEADERS frame.
  687. type HeadersFrameParam struct {
  688. // StreamID is the required Stream ID to initiate.
  689. StreamID uint32
  690. // BlockFragment is part (or all) of a Header Block.
  691. BlockFragment []byte
  692. // EndStream indicates that the header block is the last that
  693. // the endpoint will send for the identified stream. Setting
  694. // this flag causes the stream to enter one of "half closed"
  695. // states.
  696. EndStream bool
  697. // EndHeaders indicates that this frame contains an entire
  698. // header block and is not followed by any
  699. // CONTINUATION frames.
  700. EndHeaders bool
  701. // PadLength is the optional number of bytes of zeros to add
  702. // to this frame.
  703. PadLength uint8
  704. // Priority, if non-zero, includes stream priority information
  705. // in the HEADER frame.
  706. Priority PriorityParam
  707. }
  708. // WriteHeaders writes a single HEADERS frame.
  709. //
  710. // This is a low-level header writing method. Encoding headers and
  711. // splitting them into any necessary CONTINUATION frames is handled
  712. // elsewhere.
  713. //
  714. // It will perform exactly one Write to the underlying Writer.
  715. // It is the caller's responsibility to not call other Write methods concurrently.
  716. func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
  717. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  718. return errStreamID
  719. }
  720. var flags Flags
  721. if p.PadLength != 0 {
  722. flags |= FlagHeadersPadded
  723. }
  724. if p.EndStream {
  725. flags |= FlagHeadersEndStream
  726. }
  727. if p.EndHeaders {
  728. flags |= FlagHeadersEndHeaders
  729. }
  730. if !p.Priority.IsZero() {
  731. flags |= FlagHeadersPriority
  732. }
  733. f.startWrite(FrameHeaders, flags, p.StreamID)
  734. if p.PadLength != 0 {
  735. f.writeByte(p.PadLength)
  736. }
  737. if !p.Priority.IsZero() {
  738. v := p.Priority.StreamDep
  739. if !validStreamID(v) && !f.AllowIllegalWrites {
  740. return errors.New("invalid dependent stream id")
  741. }
  742. if p.Priority.Exclusive {
  743. v |= 1 << 31
  744. }
  745. f.writeUint32(v)
  746. f.writeByte(p.Priority.Weight)
  747. }
  748. f.wbuf = append(f.wbuf, p.BlockFragment...)
  749. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  750. return f.endWrite()
  751. }
  752. // A PriorityFrame specifies the sender-advised priority of a stream.
  753. // See http://http2.github.io/http2-spec/#rfc.section.6.3
  754. type PriorityFrame struct {
  755. FrameHeader
  756. PriorityParam
  757. }
  758. // PriorityParam are the stream prioritzation parameters.
  759. type PriorityParam struct {
  760. // StreamDep is a 31-bit stream identifier for the
  761. // stream that this stream depends on. Zero means no
  762. // dependency.
  763. StreamDep uint32
  764. // Exclusive is whether the dependency is exclusive.
  765. Exclusive bool
  766. // Weight is the stream's zero-indexed weight. It should be
  767. // set together with StreamDep, or neither should be set. Per
  768. // the spec, "Add one to the value to obtain a weight between
  769. // 1 and 256."
  770. Weight uint8
  771. }
  772. func (p PriorityParam) IsZero() bool {
  773. return p == PriorityParam{}
  774. }
  775. func parsePriorityFrame(fh FrameHeader, payload []byte) (Frame, error) {
  776. if fh.StreamID == 0 {
  777. return nil, ConnectionError(ErrCodeProtocol)
  778. }
  779. if len(payload) != 5 {
  780. return nil, ConnectionError(ErrCodeFrameSize)
  781. }
  782. v := binary.BigEndian.Uint32(payload[:4])
  783. streamID := v & 0x7fffffff // mask off high bit
  784. return &PriorityFrame{
  785. FrameHeader: fh,
  786. PriorityParam: PriorityParam{
  787. Weight: payload[4],
  788. StreamDep: streamID,
  789. Exclusive: streamID != v, // was high bit set?
  790. },
  791. }, nil
  792. }
  793. // WritePriority writes a PRIORITY frame.
  794. //
  795. // It will perform exactly one Write to the underlying Writer.
  796. // It is the caller's responsibility to not call other Write methods concurrently.
  797. func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error {
  798. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  799. return errStreamID
  800. }
  801. f.startWrite(FramePriority, 0, streamID)
  802. v := p.StreamDep
  803. if p.Exclusive {
  804. v |= 1 << 31
  805. }
  806. f.writeUint32(v)
  807. f.writeByte(p.Weight)
  808. return f.endWrite()
  809. }
  810. // A RSTStreamFrame allows for abnormal termination of a stream.
  811. // See http://http2.github.io/http2-spec/#rfc.section.6.4
  812. type RSTStreamFrame struct {
  813. FrameHeader
  814. ErrCode ErrCode
  815. }
  816. func parseRSTStreamFrame(fh FrameHeader, p []byte) (Frame, error) {
  817. if len(p) != 4 {
  818. return nil, ConnectionError(ErrCodeFrameSize)
  819. }
  820. if fh.StreamID == 0 {
  821. return nil, ConnectionError(ErrCodeProtocol)
  822. }
  823. return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
  824. }
  825. // WriteRSTStream writes a RST_STREAM frame.
  826. //
  827. // It will perform exactly one Write to the underlying Writer.
  828. // It is the caller's responsibility to not call other Write methods concurrently.
  829. func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
  830. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  831. return errStreamID
  832. }
  833. f.startWrite(FrameRSTStream, 0, streamID)
  834. f.writeUint32(uint32(code))
  835. return f.endWrite()
  836. }
  837. // A ContinuationFrame is used to continue a sequence of header block fragments.
  838. // See http://http2.github.io/http2-spec/#rfc.section.6.10
  839. type ContinuationFrame struct {
  840. FrameHeader
  841. headerFragBuf []byte
  842. }
  843. func parseContinuationFrame(fh FrameHeader, p []byte) (Frame, error) {
  844. return &ContinuationFrame{fh, p}, nil
  845. }
  846. func (f *ContinuationFrame) StreamEnded() bool {
  847. return f.FrameHeader.Flags.Has(FlagDataEndStream)
  848. }
  849. func (f *ContinuationFrame) HeaderBlockFragment() []byte {
  850. f.checkValid()
  851. return f.headerFragBuf
  852. }
  853. func (f *ContinuationFrame) HeadersEnded() bool {
  854. return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
  855. }
  856. // WriteContinuation writes a CONTINUATION frame.
  857. //
  858. // It will perform exactly one Write to the underlying Writer.
  859. // It is the caller's responsibility to not call other Write methods concurrently.
  860. func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
  861. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  862. return errStreamID
  863. }
  864. var flags Flags
  865. if endHeaders {
  866. flags |= FlagContinuationEndHeaders
  867. }
  868. f.startWrite(FrameContinuation, flags, streamID)
  869. f.wbuf = append(f.wbuf, headerBlockFragment...)
  870. return f.endWrite()
  871. }
  872. // A PushPromiseFrame is used to initiate a server stream.
  873. // See http://http2.github.io/http2-spec/#rfc.section.6.6
  874. type PushPromiseFrame struct {
  875. FrameHeader
  876. PromiseID uint32
  877. headerFragBuf []byte // not owned
  878. }
  879. func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
  880. f.checkValid()
  881. return f.headerFragBuf
  882. }
  883. func (f *PushPromiseFrame) HeadersEnded() bool {
  884. return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
  885. }
  886. func parsePushPromise(fh FrameHeader, p []byte) (_ Frame, err error) {
  887. pp := &PushPromiseFrame{
  888. FrameHeader: fh,
  889. }
  890. if pp.StreamID == 0 {
  891. // PUSH_PROMISE frames MUST be associated with an existing,
  892. // peer-initiated stream. The stream identifier of a
  893. // PUSH_PROMISE frame indicates the stream it is associated
  894. // with. If the stream identifier field specifies the value
  895. // 0x0, a recipient MUST respond with a connection error
  896. // (Section 5.4.1) of type PROTOCOL_ERROR.
  897. return nil, ConnectionError(ErrCodeProtocol)
  898. }
  899. // The PUSH_PROMISE frame includes optional padding.
  900. // Padding fields and flags are identical to those defined for DATA frames
  901. var padLength uint8
  902. if fh.Flags.Has(FlagPushPromisePadded) {
  903. if p, padLength, err = readByte(p); err != nil {
  904. return
  905. }
  906. }
  907. p, pp.PromiseID, err = readUint32(p)
  908. if err != nil {
  909. return
  910. }
  911. pp.PromiseID = pp.PromiseID & (1<<31 - 1)
  912. if int(padLength) > len(p) {
  913. // like the DATA frame, error out if padding is longer than the body.
  914. return nil, ConnectionError(ErrCodeProtocol)
  915. }
  916. pp.headerFragBuf = p[:len(p)-int(padLength)]
  917. return pp, nil
  918. }
  919. // PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
  920. type PushPromiseParam struct {
  921. // StreamID is the required Stream ID to initiate.
  922. StreamID uint32
  923. // PromiseID is the required Stream ID which this
  924. // Push Promises
  925. PromiseID uint32
  926. // BlockFragment is part (or all) of a Header Block.
  927. BlockFragment []byte
  928. // EndHeaders indicates that this frame contains an entire
  929. // header block and is not followed by any
  930. // CONTINUATION frames.
  931. EndHeaders bool
  932. // PadLength is the optional number of bytes of zeros to add
  933. // to this frame.
  934. PadLength uint8
  935. }
  936. // WritePushPromise writes a single PushPromise Frame.
  937. //
  938. // As with Header Frames, This is the low level call for writing
  939. // individual frames. Continuation frames are handled elsewhere.
  940. //
  941. // It will perform exactly one Write to the underlying Writer.
  942. // It is the caller's responsibility to not call other Write methods concurrently.
  943. func (f *Framer) WritePushPromise(p PushPromiseParam) error {
  944. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  945. return errStreamID
  946. }
  947. var flags Flags
  948. if p.PadLength != 0 {
  949. flags |= FlagPushPromisePadded
  950. }
  951. if p.EndHeaders {
  952. flags |= FlagPushPromiseEndHeaders
  953. }
  954. f.startWrite(FramePushPromise, flags, p.StreamID)
  955. if p.PadLength != 0 {
  956. f.writeByte(p.PadLength)
  957. }
  958. if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
  959. return errStreamID
  960. }
  961. f.writeUint32(p.PromiseID)
  962. f.wbuf = append(f.wbuf, p.BlockFragment...)
  963. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  964. return f.endWrite()
  965. }
  966. // WriteRawFrame writes a raw frame. This can be used to write
  967. // extension frames unknown to this package.
  968. func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
  969. f.startWrite(t, flags, streamID)
  970. f.writeBytes(payload)
  971. return f.endWrite()
  972. }
  973. func readByte(p []byte) (remain []byte, b byte, err error) {
  974. if len(p) == 0 {
  975. return nil, 0, io.ErrUnexpectedEOF
  976. }
  977. return p[1:], p[0], nil
  978. }
  979. func readUint32(p []byte) (remain []byte, v uint32, err error) {
  980. if len(p) < 4 {
  981. return nil, 0, io.ErrUnexpectedEOF
  982. }
  983. return p[4:], binary.BigEndian.Uint32(p[:4]), nil
  984. }
  985. type streamEnder interface {
  986. StreamEnded() bool
  987. }
  988. type headersEnder interface {
  989. HeadersEnded() bool
  990. }