frame.go 26 KB

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