frame.go 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922
  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. readBuf []byte
  210. w io.Writer
  211. wbuf []byte
  212. // AllowIllegalWrites permits the Framer's Write methods to
  213. // write frames that do not conform to the HTTP/2 spec. This
  214. // permits using the Framer to test other HTTP/2
  215. // implementations' conformance to the spec.
  216. // If false, the Write methods will prefer to return an error
  217. // rather than comply.
  218. AllowIllegalWrites bool
  219. // TODO: track which type of frame & with which flags was sent
  220. // last. Then return an error (unless AllowIllegalWrites) if
  221. // we're in the middle of a header block and a
  222. // non-Continuation or Continuation on a different stream is
  223. // attempted to be written.
  224. // TODO: add limits on max frame size allowed to be read &
  225. // written.
  226. }
  227. func (f *Framer) startWrite(ftype FrameType, flags Flags, streamID uint32) {
  228. // Write the FrameHeader.
  229. f.wbuf = append(f.wbuf[:0],
  230. 0, // 3 bytes of length, filled in in endWrite
  231. 0,
  232. 0,
  233. byte(ftype),
  234. byte(flags),
  235. byte(streamID>>24),
  236. byte(streamID>>16),
  237. byte(streamID>>8),
  238. byte(streamID))
  239. }
  240. var errFrameTooLarge = errors.New("http2: frame too large")
  241. func (f *Framer) endWrite() error {
  242. // Now that we know the final size, fill in the FrameHeader in
  243. // the space previously reserved for it. Abuse append.
  244. length := len(f.wbuf) - frameHeaderLen
  245. if length >= (1 << 24) {
  246. return errFrameTooLarge
  247. }
  248. _ = append(f.wbuf[:0],
  249. byte(length>>16),
  250. byte(length>>8),
  251. byte(length))
  252. n, err := f.w.Write(f.wbuf)
  253. if err == nil && n != len(f.wbuf) {
  254. err = io.ErrShortWrite
  255. }
  256. return err
  257. }
  258. func (f *Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) }
  259. func (f *Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) }
  260. func (f *Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) }
  261. func (f *Framer) writeUint32(v uint32) {
  262. f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
  263. }
  264. // NewFramer returns a Framer that writes frames to w and reads them from r.
  265. func NewFramer(w io.Writer, r io.Reader) *Framer {
  266. return &Framer{
  267. w: w,
  268. r: r,
  269. readBuf: make([]byte, 1<<10),
  270. }
  271. }
  272. // ReadFrame reads a single frame. The returned Frame is only valid
  273. // until the next call to ReadFrame.
  274. func (fr *Framer) ReadFrame() (Frame, error) {
  275. if fr.lastFrame != nil {
  276. fr.lastFrame.invalidate()
  277. }
  278. fh, err := readFrameHeader(fr.readBuf, fr.r)
  279. if err != nil {
  280. return nil, err
  281. }
  282. if uint32(len(fr.readBuf)) < fh.Length {
  283. fr.readBuf = make([]byte, fh.Length)
  284. }
  285. payload := fr.readBuf[:fh.Length]
  286. if _, err := io.ReadFull(fr.r, payload); err != nil {
  287. return nil, err
  288. }
  289. f, err := typeFrameParser(fh.Type)(fh, payload)
  290. if err != nil {
  291. return nil, err
  292. }
  293. fr.lastFrame = f
  294. return f, nil
  295. }
  296. // A DataFrame conveys arbitrary, variable-length sequences of octets
  297. // associated with a stream.
  298. // See http://http2.github.io/http2-spec/#rfc.section.6.1
  299. type DataFrame struct {
  300. FrameHeader
  301. data []byte
  302. }
  303. func (f *DataFrame) StreamEnded() bool {
  304. return f.FrameHeader.Flags.Has(FlagDataEndStream)
  305. }
  306. // Data returns the frame's data octets, not including any padding
  307. // size byte or padding suffix bytes.
  308. // The caller must not retain the returned memory past the next
  309. // call to ReadFrame.
  310. func (f *DataFrame) Data() []byte {
  311. f.checkValid()
  312. return f.data
  313. }
  314. func parseDataFrame(fh FrameHeader, payload []byte) (Frame, error) {
  315. if fh.StreamID == 0 {
  316. // DATA frames MUST be associated with a stream. If a
  317. // DATA frame is received whose stream identifier
  318. // field is 0x0, the recipient MUST respond with a
  319. // connection error (Section 5.4.1) of type
  320. // PROTOCOL_ERROR.
  321. return nil, ConnectionError(ErrCodeProtocol)
  322. }
  323. f := &DataFrame{
  324. FrameHeader: fh,
  325. }
  326. var padSize byte
  327. if fh.Flags.Has(FlagDataPadded) {
  328. var err error
  329. payload, padSize, err = readByte(payload)
  330. if err != nil {
  331. return nil, err
  332. }
  333. }
  334. if int(padSize) > len(payload) {
  335. // If the length of the padding is greater than the
  336. // length of the frame payload, the recipient MUST
  337. // treat this as a connection error.
  338. // Filed: https://github.com/http2/http2-spec/issues/610
  339. return nil, ConnectionError(ErrCodeProtocol)
  340. }
  341. f.data = payload[:len(payload)-int(padSize)]
  342. return f, nil
  343. }
  344. var errStreamID = errors.New("invalid streamid")
  345. func validStreamID(streamID uint32) bool {
  346. return streamID != 0 && streamID&(1<<31) == 0
  347. }
  348. // WriteData writes a DATA frame.
  349. //
  350. // It will perform exactly one Write to the underlying Writer.
  351. // It is the caller's responsibility to not call other Write methods concurrently.
  352. func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
  353. // TODO: ignoring padding for now. will add when somebody cares.
  354. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  355. return errStreamID
  356. }
  357. var flags Flags
  358. if endStream {
  359. flags |= FlagDataEndStream
  360. }
  361. f.startWrite(FrameData, flags, streamID)
  362. f.wbuf = append(f.wbuf, data...)
  363. return f.endWrite()
  364. }
  365. // A SettingsFrame conveys configuration parameters that affect how
  366. // endpoints communicate, such as preferences and constraints on peer
  367. // behavior.
  368. //
  369. // See http://http2.github.io/http2-spec/#SETTINGS
  370. type SettingsFrame struct {
  371. FrameHeader
  372. p []byte
  373. }
  374. func parseSettingsFrame(fh FrameHeader, p []byte) (Frame, error) {
  375. if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 {
  376. // When this (ACK 0x1) bit is set, the payload of the
  377. // SETTINGS frame MUST be empty. Receipt of a
  378. // SETTINGS frame with the ACK flag set and a length
  379. // field value other than 0 MUST be treated as a
  380. // connection error (Section 5.4.1) of type
  381. // FRAME_SIZE_ERROR.
  382. return nil, ConnectionError(ErrCodeFrameSize)
  383. }
  384. if fh.StreamID != 0 {
  385. // SETTINGS frames always apply to a connection,
  386. // never a single stream. The stream identifier for a
  387. // SETTINGS frame MUST be zero (0x0). If an endpoint
  388. // receives a SETTINGS frame whose stream identifier
  389. // field is anything other than 0x0, the endpoint MUST
  390. // respond with a connection error (Section 5.4.1) of
  391. // type PROTOCOL_ERROR.
  392. return nil, ConnectionError(ErrCodeProtocol)
  393. }
  394. if len(p)%6 != 0 {
  395. // Expecting even number of 6 byte settings.
  396. return nil, ConnectionError(ErrCodeFrameSize)
  397. }
  398. f := &SettingsFrame{FrameHeader: fh, p: p}
  399. if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 {
  400. // Values above the maximum flow control window size of 2^31 - 1 MUST
  401. // be treated as a connection error (Section 5.4.1) of type
  402. // FLOW_CONTROL_ERROR.
  403. return nil, ConnectionError(ErrCodeFlowControl)
  404. }
  405. return f, nil
  406. }
  407. func (f *SettingsFrame) IsAck() bool {
  408. return f.FrameHeader.Flags.Has(FlagSettingsAck)
  409. }
  410. func (f *SettingsFrame) Value(s SettingID) (v uint32, ok bool) {
  411. f.checkValid()
  412. buf := f.p
  413. for len(buf) > 0 {
  414. settingID := SettingID(binary.BigEndian.Uint16(buf[:2]))
  415. if settingID == s {
  416. return binary.BigEndian.Uint32(buf[2:6]), true
  417. }
  418. buf = buf[6:]
  419. }
  420. return 0, false
  421. }
  422. // ForeachSetting runs fn for each setting.
  423. // It stops and returns the first error.
  424. func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error {
  425. f.checkValid()
  426. buf := f.p
  427. for len(buf) > 0 {
  428. if err := fn(Setting{
  429. SettingID(binary.BigEndian.Uint16(buf[:2])),
  430. binary.BigEndian.Uint32(buf[2:6]),
  431. }); err != nil {
  432. return err
  433. }
  434. buf = buf[6:]
  435. }
  436. return nil
  437. }
  438. // WriteSettings writes a SETTINGS frame with zero or more settings
  439. // specified and the ACK bit not set.
  440. //
  441. // It will perform exactly one Write to the underlying Writer.
  442. // It is the caller's responsibility to not call other Write methods concurrently.
  443. func (f *Framer) WriteSettings(settings ...Setting) error {
  444. f.startWrite(FrameSettings, 0, 0)
  445. for _, s := range settings {
  446. f.writeUint16(uint16(s.ID))
  447. f.writeUint32(s.Val)
  448. }
  449. return f.endWrite()
  450. }
  451. // WriteSettings writes an empty SETTINGS frame with the ACK bit set.
  452. //
  453. // It will perform exactly one Write to the underlying Writer.
  454. // It is the caller's responsibility to not call other Write methods concurrently.
  455. func (f *Framer) WriteSettingsAck() error {
  456. f.startWrite(FrameSettings, FlagSettingsAck, 0)
  457. return f.endWrite()
  458. }
  459. // A PingFrame is a mechanism for measuring a minimal round trip time
  460. // from the sender, as well as determining whether an idle connection
  461. // is still functional.
  462. // See http://http2.github.io/http2-spec/#rfc.section.6.7
  463. type PingFrame struct {
  464. FrameHeader
  465. Data [8]byte
  466. }
  467. func parsePingFrame(fh FrameHeader, payload []byte) (Frame, error) {
  468. if len(payload) != 8 {
  469. return nil, ConnectionError(ErrCodeFrameSize)
  470. }
  471. if fh.StreamID != 0 {
  472. return nil, ConnectionError(ErrCodeProtocol)
  473. }
  474. f := &PingFrame{FrameHeader: fh}
  475. copy(f.Data[:], payload)
  476. return f, nil
  477. }
  478. func (f *Framer) WritePing(ack bool, data [8]byte) error {
  479. var flags Flags
  480. if ack {
  481. flags = FlagPingAck
  482. }
  483. f.startWrite(FramePing, flags, 0)
  484. f.writeBytes(data[:])
  485. return f.endWrite()
  486. }
  487. // A GoAwayFrame informs the remote peer to stop creating streams on this connection.
  488. // See http://http2.github.io/http2-spec/#rfc.section.6.8
  489. type GoAwayFrame struct {
  490. FrameHeader
  491. LastStreamID uint32
  492. ErrCode ErrCode
  493. debugData []byte
  494. }
  495. // DebugData returns any debug data in the GOAWAY frame. Its contents
  496. // are not defined.
  497. // The caller must not retain the returned memory past the next
  498. // call to ReadFrame.
  499. func (f *GoAwayFrame) DebugData() []byte {
  500. f.checkValid()
  501. return f.debugData
  502. }
  503. func parseGoAwayFrame(fh FrameHeader, p []byte) (Frame, error) {
  504. if fh.StreamID != 0 {
  505. return nil, ConnectionError(ErrCodeProtocol)
  506. }
  507. if len(p) < 8 {
  508. return nil, ConnectionError(ErrCodeFrameSize)
  509. }
  510. return &GoAwayFrame{
  511. FrameHeader: fh,
  512. LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
  513. ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])),
  514. debugData: p[8:],
  515. }, nil
  516. }
  517. func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error {
  518. f.startWrite(FrameGoAway, 0, 0)
  519. f.writeUint32(maxStreamID & (1<<31 - 1))
  520. f.writeUint32(uint32(code))
  521. f.writeBytes(debugData)
  522. return f.endWrite()
  523. }
  524. // An UnknownFrame is the frame type returned when the frame type is unknown
  525. // or no specific frame type parser exists.
  526. type UnknownFrame struct {
  527. FrameHeader
  528. p []byte
  529. }
  530. // Payload returns the frame's payload (after the header).
  531. // It is not valid to call this method after a subsequent
  532. // call to Framer.ReadFrame.
  533. func (f *UnknownFrame) Payload() []byte {
  534. f.checkValid()
  535. return f.p
  536. }
  537. func parseUnknownFrame(fh FrameHeader, p []byte) (Frame, error) {
  538. return &UnknownFrame{fh, p}, nil
  539. }
  540. // A WindowUpdateFrame is used to implement flow control.
  541. // See http://http2.github.io/http2-spec/#rfc.section.6.9
  542. type WindowUpdateFrame struct {
  543. FrameHeader
  544. Increment uint32
  545. }
  546. func parseWindowUpdateFrame(fh FrameHeader, p []byte) (Frame, error) {
  547. if len(p) != 4 {
  548. return nil, ConnectionError(ErrCodeFrameSize)
  549. }
  550. inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
  551. if inc == 0 {
  552. // A receiver MUST treat the receipt of a
  553. // WINDOW_UPDATE frame with an flow control window
  554. // increment of 0 as a stream error (Section 5.4.2) of
  555. // type PROTOCOL_ERROR; errors on the connection flow
  556. // control window MUST be treated as a connection
  557. // error (Section 5.4.1).
  558. if fh.StreamID == 0 {
  559. return nil, ConnectionError(ErrCodeProtocol)
  560. }
  561. return nil, StreamError{fh.StreamID, ErrCodeProtocol}
  562. }
  563. return &WindowUpdateFrame{
  564. FrameHeader: fh,
  565. Increment: inc,
  566. }, nil
  567. }
  568. // WriteWindowUpdate writes a WINDOW_UPDATE frame.
  569. // The increment value must be between 1 and 2,147,483,647, inclusive.
  570. // If the Stream ID is zero, the window update applies to the
  571. // connection as a whole.
  572. func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error {
  573. // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
  574. if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
  575. return errors.New("illegal window increment value")
  576. }
  577. f.startWrite(FrameWindowUpdate, 0, streamID)
  578. f.writeUint32(incr)
  579. return f.endWrite()
  580. }
  581. // A HeadersFrame is used to open a stream and additionally carries a
  582. // header block fragment.
  583. type HeadersFrame struct {
  584. FrameHeader
  585. // Priority is set if FlagHeadersPriority is set in the FrameHeader.
  586. Priority PriorityParam
  587. headerFragBuf []byte // not owned
  588. }
  589. func (f *HeadersFrame) HeaderBlockFragment() []byte {
  590. f.checkValid()
  591. return f.headerFragBuf
  592. }
  593. func (f *HeadersFrame) HeadersEnded() bool {
  594. return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
  595. }
  596. func (f *HeadersFrame) StreamEnded() bool {
  597. return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
  598. }
  599. func parseHeadersFrame(fh FrameHeader, p []byte) (_ Frame, err error) {
  600. hf := &HeadersFrame{
  601. FrameHeader: fh,
  602. }
  603. if fh.StreamID == 0 {
  604. // HEADERS frames MUST be associated with a stream. If a HEADERS frame
  605. // is received whose stream identifier field is 0x0, the recipient MUST
  606. // respond with a connection error (Section 5.4.1) of type
  607. // PROTOCOL_ERROR.
  608. return nil, ConnectionError(ErrCodeProtocol)
  609. }
  610. var padLength uint8
  611. if fh.Flags.Has(FlagHeadersPadded) {
  612. if p, padLength, err = readByte(p); err != nil {
  613. return
  614. }
  615. }
  616. if fh.Flags.Has(FlagHeadersPriority) {
  617. var v uint32
  618. p, v, err = readUint32(p)
  619. if err != nil {
  620. return nil, err
  621. }
  622. hf.Priority.StreamDep = v & 0x7fffffff
  623. hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
  624. p, hf.Priority.Weight, err = readByte(p)
  625. if err != nil {
  626. return nil, err
  627. }
  628. }
  629. if len(p)-int(padLength) <= 0 {
  630. return nil, StreamError{fh.StreamID, ErrCodeProtocol}
  631. }
  632. hf.headerFragBuf = p[:len(p)-int(padLength)]
  633. return hf, nil
  634. }
  635. // HeadersFrameParam are the parameters for writing a HEADERS frame.
  636. type HeadersFrameParam struct {
  637. // StreamID is the required Stream ID to initiate.
  638. StreamID uint32
  639. // BlockFragment is part (or all) of a Header Block.
  640. BlockFragment []byte
  641. // EndStream indicates that the header block is the last that
  642. // the endpoint will send for the identified stream. Setting
  643. // this flag causes the stream to enter one of "half closed"
  644. // states.
  645. EndStream bool
  646. // EndHeaders indicates that this frame contains an entire
  647. // header block and is not followed by any
  648. // CONTINUATION frames.
  649. EndHeaders bool
  650. // PadLength is the optional number of bytes of zeros to add
  651. // to this frame.
  652. PadLength uint8
  653. // Priority, if non-zero, includes stream priority information
  654. // in the HEADER frame.
  655. Priority PriorityParam
  656. }
  657. // WriteHeaders writes a single HEADERS frame.
  658. //
  659. // This is a low-level header writing method. Encoding headers and
  660. // splitting them into any necessary CONTINUATION frames is handled
  661. // elsewhere.
  662. //
  663. // It will perform exactly one Write to the underlying Writer.
  664. // It is the caller's responsibility to not call other Write methods concurrently.
  665. func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
  666. var flags Flags
  667. if p.PadLength != 0 {
  668. flags |= FlagHeadersPadded
  669. }
  670. if p.EndStream {
  671. flags |= FlagHeadersEndStream
  672. }
  673. if p.EndHeaders {
  674. flags |= FlagHeadersEndHeaders
  675. }
  676. if !p.Priority.IsZero() {
  677. flags |= FlagHeadersPriority
  678. }
  679. f.startWrite(FrameHeaders, flags, p.StreamID)
  680. if p.PadLength != 0 {
  681. f.writeByte(p.PadLength)
  682. }
  683. if !p.Priority.IsZero() {
  684. v := p.Priority.StreamDep
  685. if !validStreamID(v) && !f.AllowIllegalWrites {
  686. return errors.New("invalid dependent stream id")
  687. }
  688. if p.Priority.Exclusive {
  689. v |= 1 << 31
  690. }
  691. f.writeUint32(v)
  692. f.writeByte(p.Priority.Weight)
  693. }
  694. f.wbuf = append(f.wbuf, p.BlockFragment...)
  695. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  696. return f.endWrite()
  697. }
  698. // A PriorityFrame specifies the sender-advised priority of a stream.
  699. // See http://http2.github.io/http2-spec/#rfc.section.6.3
  700. type PriorityFrame struct {
  701. FrameHeader
  702. PriorityParam
  703. }
  704. // PriorityParam are the stream prioritzation parameters.
  705. type PriorityParam struct {
  706. // StreamDep is a 31-bit stream identifier for the
  707. // stream that this stream depends on. Zero means no
  708. // dependency.
  709. StreamDep uint32
  710. // Exclusive is whether the dependency is exclusive.
  711. Exclusive bool
  712. // Weight is the stream's weight. It should be set together
  713. // with StreamDep, or neither should be set.
  714. Weight uint8
  715. }
  716. func (p PriorityParam) IsZero() bool {
  717. return p == PriorityParam{}
  718. }
  719. func parsePriorityFrame(fh FrameHeader, payload []byte) (Frame, error) {
  720. if fh.StreamID == 0 {
  721. return nil, ConnectionError(ErrCodeProtocol)
  722. }
  723. if len(payload) != 5 {
  724. return nil, ConnectionError(ErrCodeFrameSize)
  725. }
  726. v := binary.BigEndian.Uint32(payload[:4])
  727. streamID := v & 0x7fffffff // mask off high bit
  728. return &PriorityFrame{
  729. FrameHeader: fh,
  730. PriorityParam: PriorityParam{
  731. Weight: payload[4],
  732. StreamDep: streamID,
  733. Exclusive: streamID != v, // was high bit set?
  734. },
  735. }, nil
  736. }
  737. // WritePriority writes a PRIORITY frame.
  738. //
  739. // It will perform exactly one Write to the underlying Writer.
  740. // It is the caller's responsibility to not call other Write methods concurrently.
  741. func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error {
  742. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  743. return errStreamID
  744. }
  745. f.startWrite(FramePriority, 0, streamID)
  746. v := p.StreamDep
  747. if p.Exclusive {
  748. v |= 1 << 31
  749. }
  750. f.writeUint32(v)
  751. f.writeByte(p.Weight)
  752. return f.endWrite()
  753. }
  754. // A RSTStreamFrame allows for abnormal termination of a stream.
  755. // See http://http2.github.io/http2-spec/#rfc.section.6.4
  756. type RSTStreamFrame struct {
  757. FrameHeader
  758. ErrCode ErrCode
  759. }
  760. func parseRSTStreamFrame(fh FrameHeader, p []byte) (Frame, error) {
  761. if len(p) != 4 {
  762. return nil, ConnectionError(ErrCodeFrameSize)
  763. }
  764. if fh.StreamID == 0 {
  765. return nil, ConnectionError(ErrCodeProtocol)
  766. }
  767. return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
  768. }
  769. // WriteRSTStream writes a RST_STREAM frame.
  770. //
  771. // It will perform exactly one Write to the underlying Writer.
  772. // It is the caller's responsibility to not call other Write methods concurrently.
  773. func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
  774. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  775. return errStreamID
  776. }
  777. f.startWrite(FrameRSTStream, 0, streamID)
  778. f.writeUint32(uint32(code))
  779. return f.endWrite()
  780. }
  781. // A ContinuationFrame is used to continue a sequence of header block fragments.
  782. // See http://http2.github.io/http2-spec/#rfc.section.6.10
  783. type ContinuationFrame struct {
  784. FrameHeader
  785. headerFragBuf []byte
  786. }
  787. func parseContinuationFrame(fh FrameHeader, p []byte) (Frame, error) {
  788. return &ContinuationFrame{fh, p}, nil
  789. }
  790. func (f *ContinuationFrame) HeaderBlockFragment() []byte {
  791. f.checkValid()
  792. return f.headerFragBuf
  793. }
  794. func (f *ContinuationFrame) HeadersEnded() bool {
  795. return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
  796. }
  797. // WriteContinuation writes a CONTINUATION frame.
  798. //
  799. // It will perform exactly one Write to the underlying Writer.
  800. // It is the caller's responsibility to not call other Write methods concurrently.
  801. func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
  802. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  803. return errStreamID
  804. }
  805. var flags Flags
  806. if endHeaders {
  807. flags |= FlagContinuationEndHeaders
  808. }
  809. f.startWrite(FrameContinuation, flags, streamID)
  810. f.wbuf = append(f.wbuf, headerBlockFragment...)
  811. return f.endWrite()
  812. }
  813. func readByte(p []byte) (remain []byte, b byte, err error) {
  814. if len(p) == 0 {
  815. return nil, 0, io.ErrUnexpectedEOF
  816. }
  817. return p[1:], p[0], nil
  818. }
  819. func readUint32(p []byte) (remain []byte, v uint32, err error) {
  820. if len(p) < 4 {
  821. return nil, 0, io.ErrUnexpectedEOF
  822. }
  823. return p[4:], binary.BigEndian.Uint32(p[:4]), nil
  824. }