frame.go 27 KB

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