frame.go 31 KB

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