frame.go 31 KB

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