frame.go 31 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114
  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. // ReadFrame reads a single frame. The returned Frame is only valid
  316. // until the next call to ReadFrame.
  317. // If the frame is larger than previously set with SetMaxReadFrameSize,
  318. // the returned error is ErrFrameTooLarge.
  319. func (fr *Framer) ReadFrame() (Frame, error) {
  320. if fr.lastFrame != nil {
  321. fr.lastFrame.invalidate()
  322. }
  323. fh, err := readFrameHeader(fr.headerBuf[:], fr.r)
  324. if err != nil {
  325. return nil, err
  326. }
  327. if fh.Length > fr.maxReadSize {
  328. return nil, ErrFrameTooLarge
  329. }
  330. payload := fr.getReadBuf(fh.Length)
  331. if _, err := io.ReadFull(fr.r, payload); err != nil {
  332. return nil, err
  333. }
  334. f, err := typeFrameParser(fh.Type)(fh, payload)
  335. if err != nil {
  336. return nil, err
  337. }
  338. fr.lastFrame = f
  339. return f, nil
  340. }
  341. // A DataFrame conveys arbitrary, variable-length sequences of octets
  342. // associated with a stream.
  343. // See http://http2.github.io/http2-spec/#rfc.section.6.1
  344. type DataFrame struct {
  345. FrameHeader
  346. data []byte
  347. }
  348. func (f *DataFrame) StreamEnded() bool {
  349. return f.FrameHeader.Flags.Has(FlagDataEndStream)
  350. }
  351. // Data returns the frame's data octets, not including any padding
  352. // size byte or padding suffix bytes.
  353. // The caller must not retain the returned memory past the next
  354. // call to ReadFrame.
  355. func (f *DataFrame) Data() []byte {
  356. f.checkValid()
  357. return f.data
  358. }
  359. func parseDataFrame(fh FrameHeader, payload []byte) (Frame, error) {
  360. if fh.StreamID == 0 {
  361. // DATA frames MUST be associated with a stream. If a
  362. // DATA frame is received whose stream identifier
  363. // field is 0x0, the recipient MUST respond with a
  364. // connection error (Section 5.4.1) of type
  365. // PROTOCOL_ERROR.
  366. return nil, ConnectionError(ErrCodeProtocol)
  367. }
  368. f := &DataFrame{
  369. FrameHeader: fh,
  370. }
  371. var padSize byte
  372. if fh.Flags.Has(FlagDataPadded) {
  373. var err error
  374. payload, padSize, err = readByte(payload)
  375. if err != nil {
  376. return nil, err
  377. }
  378. }
  379. if int(padSize) > len(payload) {
  380. // If the length of the padding is greater than the
  381. // length of the frame payload, the recipient MUST
  382. // treat this as a connection error.
  383. // Filed: https://github.com/http2/http2-spec/issues/610
  384. return nil, ConnectionError(ErrCodeProtocol)
  385. }
  386. f.data = payload[:len(payload)-int(padSize)]
  387. return f, nil
  388. }
  389. var errStreamID = errors.New("invalid streamid")
  390. func validStreamID(streamID uint32) bool {
  391. return streamID != 0 && streamID&(1<<31) == 0
  392. }
  393. // WriteData writes a DATA frame.
  394. //
  395. // It will perform exactly one Write to the underlying Writer.
  396. // It is the caller's responsibility to not call other Write methods concurrently.
  397. func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
  398. // TODO: ignoring padding for now. will add when somebody cares.
  399. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  400. return errStreamID
  401. }
  402. var flags Flags
  403. if endStream {
  404. flags |= FlagDataEndStream
  405. }
  406. f.startWrite(FrameData, flags, streamID)
  407. f.wbuf = append(f.wbuf, data...)
  408. return f.endWrite()
  409. }
  410. // A SettingsFrame conveys configuration parameters that affect how
  411. // endpoints communicate, such as preferences and constraints on peer
  412. // behavior.
  413. //
  414. // See http://http2.github.io/http2-spec/#SETTINGS
  415. type SettingsFrame struct {
  416. FrameHeader
  417. p []byte
  418. }
  419. func parseSettingsFrame(fh FrameHeader, p []byte) (Frame, error) {
  420. if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 {
  421. // When this (ACK 0x1) bit is set, the payload of the
  422. // SETTINGS frame MUST be empty. Receipt of a
  423. // SETTINGS frame with the ACK flag set and a length
  424. // field value other than 0 MUST be treated as a
  425. // connection error (Section 5.4.1) of type
  426. // FRAME_SIZE_ERROR.
  427. return nil, ConnectionError(ErrCodeFrameSize)
  428. }
  429. if fh.StreamID != 0 {
  430. // SETTINGS frames always apply to a connection,
  431. // never a single stream. The stream identifier for a
  432. // SETTINGS frame MUST be zero (0x0). If an endpoint
  433. // receives a SETTINGS frame whose stream identifier
  434. // field is anything other than 0x0, the endpoint MUST
  435. // respond with a connection error (Section 5.4.1) of
  436. // type PROTOCOL_ERROR.
  437. return nil, ConnectionError(ErrCodeProtocol)
  438. }
  439. if len(p)%6 != 0 {
  440. // Expecting even number of 6 byte settings.
  441. return nil, ConnectionError(ErrCodeFrameSize)
  442. }
  443. f := &SettingsFrame{FrameHeader: fh, p: p}
  444. if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 {
  445. // Values above the maximum flow control window size of 2^31 - 1 MUST
  446. // be treated as a connection error (Section 5.4.1) of type
  447. // FLOW_CONTROL_ERROR.
  448. return nil, ConnectionError(ErrCodeFlowControl)
  449. }
  450. return f, nil
  451. }
  452. func (f *SettingsFrame) IsAck() bool {
  453. return f.FrameHeader.Flags.Has(FlagSettingsAck)
  454. }
  455. func (f *SettingsFrame) Value(s SettingID) (v uint32, ok bool) {
  456. f.checkValid()
  457. buf := f.p
  458. for len(buf) > 0 {
  459. settingID := SettingID(binary.BigEndian.Uint16(buf[:2]))
  460. if settingID == s {
  461. return binary.BigEndian.Uint32(buf[2:6]), true
  462. }
  463. buf = buf[6:]
  464. }
  465. return 0, false
  466. }
  467. // ForeachSetting runs fn for each setting.
  468. // It stops and returns the first error.
  469. func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error {
  470. f.checkValid()
  471. buf := f.p
  472. for len(buf) > 0 {
  473. if err := fn(Setting{
  474. SettingID(binary.BigEndian.Uint16(buf[:2])),
  475. binary.BigEndian.Uint32(buf[2:6]),
  476. }); err != nil {
  477. return err
  478. }
  479. buf = buf[6:]
  480. }
  481. return nil
  482. }
  483. // WriteSettings writes a SETTINGS frame with zero or more settings
  484. // specified and the ACK bit not set.
  485. //
  486. // It will perform exactly one Write to the underlying Writer.
  487. // It is the caller's responsibility to not call other Write methods concurrently.
  488. func (f *Framer) WriteSettings(settings ...Setting) error {
  489. f.startWrite(FrameSettings, 0, 0)
  490. for _, s := range settings {
  491. f.writeUint16(uint16(s.ID))
  492. f.writeUint32(s.Val)
  493. }
  494. return f.endWrite()
  495. }
  496. // WriteSettings writes an empty SETTINGS frame with the ACK bit set.
  497. //
  498. // It will perform exactly one Write to the underlying Writer.
  499. // It is the caller's responsibility to not call other Write methods concurrently.
  500. func (f *Framer) WriteSettingsAck() error {
  501. f.startWrite(FrameSettings, FlagSettingsAck, 0)
  502. return f.endWrite()
  503. }
  504. // A PingFrame is a mechanism for measuring a minimal round trip time
  505. // from the sender, as well as determining whether an idle connection
  506. // is still functional.
  507. // See http://http2.github.io/http2-spec/#rfc.section.6.7
  508. type PingFrame struct {
  509. FrameHeader
  510. Data [8]byte
  511. }
  512. func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) }
  513. func parsePingFrame(fh FrameHeader, payload []byte) (Frame, error) {
  514. if len(payload) != 8 {
  515. return nil, ConnectionError(ErrCodeFrameSize)
  516. }
  517. if fh.StreamID != 0 {
  518. return nil, ConnectionError(ErrCodeProtocol)
  519. }
  520. f := &PingFrame{FrameHeader: fh}
  521. copy(f.Data[:], payload)
  522. return f, nil
  523. }
  524. func (f *Framer) WritePing(ack bool, data [8]byte) error {
  525. var flags Flags
  526. if ack {
  527. flags = FlagPingAck
  528. }
  529. f.startWrite(FramePing, flags, 0)
  530. f.writeBytes(data[:])
  531. return f.endWrite()
  532. }
  533. // A GoAwayFrame informs the remote peer to stop creating streams on this connection.
  534. // See http://http2.github.io/http2-spec/#rfc.section.6.8
  535. type GoAwayFrame struct {
  536. FrameHeader
  537. LastStreamID uint32
  538. ErrCode ErrCode
  539. debugData []byte
  540. }
  541. // DebugData returns any debug data in the GOAWAY frame. Its contents
  542. // are not defined.
  543. // The caller must not retain the returned memory past the next
  544. // call to ReadFrame.
  545. func (f *GoAwayFrame) DebugData() []byte {
  546. f.checkValid()
  547. return f.debugData
  548. }
  549. func parseGoAwayFrame(fh FrameHeader, p []byte) (Frame, error) {
  550. if fh.StreamID != 0 {
  551. return nil, ConnectionError(ErrCodeProtocol)
  552. }
  553. if len(p) < 8 {
  554. return nil, ConnectionError(ErrCodeFrameSize)
  555. }
  556. return &GoAwayFrame{
  557. FrameHeader: fh,
  558. LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
  559. ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])),
  560. debugData: p[8:],
  561. }, nil
  562. }
  563. func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error {
  564. f.startWrite(FrameGoAway, 0, 0)
  565. f.writeUint32(maxStreamID & (1<<31 - 1))
  566. f.writeUint32(uint32(code))
  567. f.writeBytes(debugData)
  568. return f.endWrite()
  569. }
  570. // An UnknownFrame is the frame type returned when the frame type is unknown
  571. // or no specific frame type parser exists.
  572. type UnknownFrame struct {
  573. FrameHeader
  574. p []byte
  575. }
  576. // Payload returns the frame's payload (after the header). It is not
  577. // valid to call this method after a subsequent call to
  578. // Framer.ReadFrame, nor is it valid to retain the returned slice.
  579. // The memory is owned by the Framer and is invalidated when the next
  580. // frame is read.
  581. func (f *UnknownFrame) Payload() []byte {
  582. f.checkValid()
  583. return f.p
  584. }
  585. func parseUnknownFrame(fh FrameHeader, p []byte) (Frame, error) {
  586. return &UnknownFrame{fh, p}, nil
  587. }
  588. // A WindowUpdateFrame is used to implement flow control.
  589. // See http://http2.github.io/http2-spec/#rfc.section.6.9
  590. type WindowUpdateFrame struct {
  591. FrameHeader
  592. Increment uint32 // never read with high bit set
  593. }
  594. func parseWindowUpdateFrame(fh FrameHeader, p []byte) (Frame, error) {
  595. if len(p) != 4 {
  596. return nil, ConnectionError(ErrCodeFrameSize)
  597. }
  598. inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
  599. if inc == 0 {
  600. // A receiver MUST treat the receipt of a
  601. // WINDOW_UPDATE frame with an flow control window
  602. // increment of 0 as a stream error (Section 5.4.2) of
  603. // type PROTOCOL_ERROR; errors on the connection flow
  604. // control window MUST be treated as a connection
  605. // error (Section 5.4.1).
  606. if fh.StreamID == 0 {
  607. return nil, ConnectionError(ErrCodeProtocol)
  608. }
  609. return nil, StreamError{fh.StreamID, ErrCodeProtocol}
  610. }
  611. return &WindowUpdateFrame{
  612. FrameHeader: fh,
  613. Increment: inc,
  614. }, nil
  615. }
  616. // WriteWindowUpdate writes a WINDOW_UPDATE frame.
  617. // The increment value must be between 1 and 2,147,483,647, inclusive.
  618. // If the Stream ID is zero, the window update applies to the
  619. // connection as a whole.
  620. func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error {
  621. // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
  622. if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
  623. return errors.New("illegal window increment value")
  624. }
  625. f.startWrite(FrameWindowUpdate, 0, streamID)
  626. f.writeUint32(incr)
  627. return f.endWrite()
  628. }
  629. // A HeadersFrame is used to open a stream and additionally carries a
  630. // header block fragment.
  631. type HeadersFrame struct {
  632. FrameHeader
  633. // Priority is set if FlagHeadersPriority is set in the FrameHeader.
  634. Priority PriorityParam
  635. headerFragBuf []byte // not owned
  636. }
  637. func (f *HeadersFrame) HeaderBlockFragment() []byte {
  638. f.checkValid()
  639. return f.headerFragBuf
  640. }
  641. func (f *HeadersFrame) HeadersEnded() bool {
  642. return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
  643. }
  644. func (f *HeadersFrame) StreamEnded() bool {
  645. return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
  646. }
  647. func (f *HeadersFrame) HasPriority() bool {
  648. return f.FrameHeader.Flags.Has(FlagHeadersPriority)
  649. }
  650. func parseHeadersFrame(fh FrameHeader, p []byte) (_ Frame, err error) {
  651. hf := &HeadersFrame{
  652. FrameHeader: fh,
  653. }
  654. if fh.StreamID == 0 {
  655. // HEADERS frames MUST be associated with a stream. If a HEADERS frame
  656. // is received whose stream identifier field is 0x0, the recipient MUST
  657. // respond with a connection error (Section 5.4.1) of type
  658. // PROTOCOL_ERROR.
  659. return nil, ConnectionError(ErrCodeProtocol)
  660. }
  661. var padLength uint8
  662. if fh.Flags.Has(FlagHeadersPadded) {
  663. if p, padLength, err = readByte(p); err != nil {
  664. return
  665. }
  666. }
  667. if fh.Flags.Has(FlagHeadersPriority) {
  668. var v uint32
  669. p, v, err = readUint32(p)
  670. if err != nil {
  671. return nil, err
  672. }
  673. hf.Priority.StreamDep = v & 0x7fffffff
  674. hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
  675. p, hf.Priority.Weight, err = readByte(p)
  676. if err != nil {
  677. return nil, err
  678. }
  679. }
  680. if len(p)-int(padLength) <= 0 {
  681. return nil, StreamError{fh.StreamID, ErrCodeProtocol}
  682. }
  683. hf.headerFragBuf = p[:len(p)-int(padLength)]
  684. return hf, nil
  685. }
  686. // HeadersFrameParam are the parameters for writing a HEADERS frame.
  687. type HeadersFrameParam struct {
  688. // StreamID is the required Stream ID to initiate.
  689. StreamID uint32
  690. // BlockFragment is part (or all) of a Header Block.
  691. BlockFragment []byte
  692. // EndStream indicates that the header block is the last that
  693. // the endpoint will send for the identified stream. Setting
  694. // this flag causes the stream to enter one of "half closed"
  695. // states.
  696. EndStream bool
  697. // EndHeaders indicates that this frame contains an entire
  698. // header block and is not followed by any
  699. // CONTINUATION frames.
  700. EndHeaders bool
  701. // PadLength is the optional number of bytes of zeros to add
  702. // to this frame.
  703. PadLength uint8
  704. // Priority, if non-zero, includes stream priority information
  705. // in the HEADER frame.
  706. Priority PriorityParam
  707. }
  708. // WriteHeaders writes a single HEADERS frame.
  709. //
  710. // This is a low-level header writing method. Encoding headers and
  711. // splitting them into any necessary CONTINUATION frames is handled
  712. // elsewhere.
  713. //
  714. // It will perform exactly one Write to the underlying Writer.
  715. // It is the caller's responsibility to not call other Write methods concurrently.
  716. func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
  717. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  718. return errStreamID
  719. }
  720. var flags Flags
  721. if p.PadLength != 0 {
  722. flags |= FlagHeadersPadded
  723. }
  724. if p.EndStream {
  725. flags |= FlagHeadersEndStream
  726. }
  727. if p.EndHeaders {
  728. flags |= FlagHeadersEndHeaders
  729. }
  730. if !p.Priority.IsZero() {
  731. flags |= FlagHeadersPriority
  732. }
  733. f.startWrite(FrameHeaders, flags, p.StreamID)
  734. if p.PadLength != 0 {
  735. f.writeByte(p.PadLength)
  736. }
  737. if !p.Priority.IsZero() {
  738. v := p.Priority.StreamDep
  739. if !validStreamID(v) && !f.AllowIllegalWrites {
  740. return errors.New("invalid dependent stream id")
  741. }
  742. if p.Priority.Exclusive {
  743. v |= 1 << 31
  744. }
  745. f.writeUint32(v)
  746. f.writeByte(p.Priority.Weight)
  747. }
  748. f.wbuf = append(f.wbuf, p.BlockFragment...)
  749. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  750. return f.endWrite()
  751. }
  752. // A PriorityFrame specifies the sender-advised priority of a stream.
  753. // See http://http2.github.io/http2-spec/#rfc.section.6.3
  754. type PriorityFrame struct {
  755. FrameHeader
  756. PriorityParam
  757. }
  758. // PriorityParam are the stream prioritzation parameters.
  759. type PriorityParam struct {
  760. // StreamDep is a 31-bit stream identifier for the
  761. // stream that this stream depends on. Zero means no
  762. // dependency.
  763. StreamDep uint32
  764. // Exclusive is whether the dependency is exclusive.
  765. Exclusive bool
  766. // Weight is the stream's zero-indexed weight. It should be
  767. // set together with StreamDep, or neither should be set. Per
  768. // the spec, "Add one to the value to obtain a weight between
  769. // 1 and 256."
  770. Weight uint8
  771. }
  772. func (p PriorityParam) IsZero() bool {
  773. return p == PriorityParam{}
  774. }
  775. func parsePriorityFrame(fh FrameHeader, payload []byte) (Frame, error) {
  776. if fh.StreamID == 0 {
  777. return nil, ConnectionError(ErrCodeProtocol)
  778. }
  779. if len(payload) != 5 {
  780. return nil, ConnectionError(ErrCodeFrameSize)
  781. }
  782. v := binary.BigEndian.Uint32(payload[:4])
  783. streamID := v & 0x7fffffff // mask off high bit
  784. return &PriorityFrame{
  785. FrameHeader: fh,
  786. PriorityParam: PriorityParam{
  787. Weight: payload[4],
  788. StreamDep: streamID,
  789. Exclusive: streamID != v, // was high bit set?
  790. },
  791. }, nil
  792. }
  793. // WritePriority writes a PRIORITY 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) WritePriority(streamID uint32, p PriorityParam) error {
  798. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  799. return errStreamID
  800. }
  801. f.startWrite(FramePriority, 0, streamID)
  802. v := p.StreamDep
  803. if p.Exclusive {
  804. v |= 1 << 31
  805. }
  806. f.writeUint32(v)
  807. f.writeByte(p.Weight)
  808. return f.endWrite()
  809. }
  810. // A RSTStreamFrame allows for abnormal termination of a stream.
  811. // See http://http2.github.io/http2-spec/#rfc.section.6.4
  812. type RSTStreamFrame struct {
  813. FrameHeader
  814. ErrCode ErrCode
  815. }
  816. func parseRSTStreamFrame(fh FrameHeader, p []byte) (Frame, error) {
  817. if len(p) != 4 {
  818. return nil, ConnectionError(ErrCodeFrameSize)
  819. }
  820. if fh.StreamID == 0 {
  821. return nil, ConnectionError(ErrCodeProtocol)
  822. }
  823. return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
  824. }
  825. // WriteRSTStream writes a RST_STREAM frame.
  826. //
  827. // It will perform exactly one Write to the underlying Writer.
  828. // It is the caller's responsibility to not call other Write methods concurrently.
  829. func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
  830. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  831. return errStreamID
  832. }
  833. f.startWrite(FrameRSTStream, 0, streamID)
  834. f.writeUint32(uint32(code))
  835. return f.endWrite()
  836. }
  837. // A ContinuationFrame is used to continue a sequence of header block fragments.
  838. // See http://http2.github.io/http2-spec/#rfc.section.6.10
  839. type ContinuationFrame struct {
  840. FrameHeader
  841. headerFragBuf []byte
  842. }
  843. func parseContinuationFrame(fh FrameHeader, p []byte) (Frame, error) {
  844. return &ContinuationFrame{fh, p}, nil
  845. }
  846. func (f *ContinuationFrame) StreamEnded() bool {
  847. return f.FrameHeader.Flags.Has(FlagDataEndStream)
  848. }
  849. func (f *ContinuationFrame) HeaderBlockFragment() []byte {
  850. f.checkValid()
  851. return f.headerFragBuf
  852. }
  853. func (f *ContinuationFrame) HeadersEnded() bool {
  854. return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
  855. }
  856. // WriteContinuation writes a CONTINUATION frame.
  857. //
  858. // It will perform exactly one Write to the underlying Writer.
  859. // It is the caller's responsibility to not call other Write methods concurrently.
  860. func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
  861. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  862. return errStreamID
  863. }
  864. var flags Flags
  865. if endHeaders {
  866. flags |= FlagContinuationEndHeaders
  867. }
  868. f.startWrite(FrameContinuation, flags, streamID)
  869. f.wbuf = append(f.wbuf, headerBlockFragment...)
  870. return f.endWrite()
  871. }
  872. // A PushPromiseFrame is used to initiate a server stream.
  873. // See http://http2.github.io/http2-spec/#rfc.section.6.6
  874. type PushPromiseFrame struct {
  875. FrameHeader
  876. PromiseID uint32
  877. headerFragBuf []byte // not owned
  878. }
  879. func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
  880. f.checkValid()
  881. return f.headerFragBuf
  882. }
  883. func (f *PushPromiseFrame) HeadersEnded() bool {
  884. return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
  885. }
  886. func parsePushPromise(fh FrameHeader, p []byte) (_ Frame, err error) {
  887. pp := &PushPromiseFrame{
  888. FrameHeader: fh,
  889. }
  890. if pp.StreamID == 0 {
  891. // PUSH_PROMISE frames MUST be associated with an existing,
  892. // peer-initiated stream. The stream identifier of a
  893. // PUSH_PROMISE frame indicates the stream it is associated
  894. // with. If the stream identifier field specifies the value
  895. // 0x0, a recipient MUST respond with a connection error
  896. // (Section 5.4.1) of type PROTOCOL_ERROR.
  897. return nil, ConnectionError(ErrCodeProtocol)
  898. }
  899. // The PUSH_PROMISE frame includes optional padding.
  900. // Padding fields and flags are identical to those defined for DATA frames
  901. var padLength uint8
  902. if fh.Flags.Has(FlagPushPromisePadded) {
  903. if p, padLength, err = readByte(p); err != nil {
  904. return
  905. }
  906. }
  907. p, pp.PromiseID, err = readUint32(p)
  908. if err != nil {
  909. return
  910. }
  911. pp.PromiseID = pp.PromiseID & (1<<31 - 1)
  912. if int(padLength) > len(p) {
  913. // like the DATA frame, error out if padding is longer than the body.
  914. return nil, ConnectionError(ErrCodeProtocol)
  915. }
  916. pp.headerFragBuf = p[:len(p)-int(padLength)]
  917. return pp, nil
  918. }
  919. // PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
  920. type PushPromiseParam struct {
  921. // StreamID is the required Stream ID to initiate.
  922. StreamID uint32
  923. // PromiseID is the required Stream ID which this
  924. // Push Promises
  925. PromiseID uint32
  926. // BlockFragment is part (or all) of a Header Block.
  927. BlockFragment []byte
  928. // EndHeaders indicates that this frame contains an entire
  929. // header block and is not followed by any
  930. // CONTINUATION frames.
  931. EndHeaders bool
  932. // PadLength is the optional number of bytes of zeros to add
  933. // to this frame.
  934. PadLength uint8
  935. }
  936. // WritePushPromise writes a single PushPromise Frame.
  937. //
  938. // As with Header Frames, This is the low level call for writing
  939. // individual frames. Continuation frames are handled elsewhere.
  940. //
  941. // It will perform exactly one Write to the underlying Writer.
  942. // It is the caller's responsibility to not call other Write methods concurrently.
  943. func (f *Framer) WritePushPromise(p PushPromiseParam) error {
  944. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  945. return errStreamID
  946. }
  947. var flags Flags
  948. if p.PadLength != 0 {
  949. flags |= FlagPushPromisePadded
  950. }
  951. if p.EndHeaders {
  952. flags |= FlagPushPromiseEndHeaders
  953. }
  954. f.startWrite(FramePushPromise, flags, p.StreamID)
  955. if p.PadLength != 0 {
  956. f.writeByte(p.PadLength)
  957. }
  958. if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
  959. return errStreamID
  960. }
  961. f.writeUint32(p.PromiseID)
  962. f.wbuf = append(f.wbuf, p.BlockFragment...)
  963. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  964. return f.endWrite()
  965. }
  966. // WriteRawFrame writes a raw frame. This can be used to write
  967. // extension frames unknown to this package.
  968. func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
  969. f.startWrite(t, flags, streamID)
  970. f.writeBytes(payload)
  971. return f.endWrite()
  972. }
  973. func readByte(p []byte) (remain []byte, b byte, err error) {
  974. if len(p) == 0 {
  975. return nil, 0, io.ErrUnexpectedEOF
  976. }
  977. return p[1:], p[0], nil
  978. }
  979. func readUint32(p []byte) (remain []byte, v uint32, err error) {
  980. if len(p) < 4 {
  981. return nil, 0, io.ErrUnexpectedEOF
  982. }
  983. return p[4:], binary.BigEndian.Uint32(p[:4]), nil
  984. }
  985. type streamEnder interface {
  986. StreamEnded() bool
  987. }
  988. type headersEnder interface {
  989. HeadersEnded() bool
  990. }