frame.go 31 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112
  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 parsePingFrame(fh FrameHeader, payload []byte) (Frame, error) {
  513. if len(payload) != 8 {
  514. return nil, ConnectionError(ErrCodeFrameSize)
  515. }
  516. if fh.StreamID != 0 {
  517. return nil, ConnectionError(ErrCodeProtocol)
  518. }
  519. f := &PingFrame{FrameHeader: fh}
  520. copy(f.Data[:], payload)
  521. return f, nil
  522. }
  523. func (f *Framer) WritePing(ack bool, data [8]byte) error {
  524. var flags Flags
  525. if ack {
  526. flags = FlagPingAck
  527. }
  528. f.startWrite(FramePing, flags, 0)
  529. f.writeBytes(data[:])
  530. return f.endWrite()
  531. }
  532. // A GoAwayFrame informs the remote peer to stop creating streams on this connection.
  533. // See http://http2.github.io/http2-spec/#rfc.section.6.8
  534. type GoAwayFrame struct {
  535. FrameHeader
  536. LastStreamID uint32
  537. ErrCode ErrCode
  538. debugData []byte
  539. }
  540. // DebugData returns any debug data in the GOAWAY frame. Its contents
  541. // are not defined.
  542. // The caller must not retain the returned memory past the next
  543. // call to ReadFrame.
  544. func (f *GoAwayFrame) DebugData() []byte {
  545. f.checkValid()
  546. return f.debugData
  547. }
  548. func parseGoAwayFrame(fh FrameHeader, p []byte) (Frame, error) {
  549. if fh.StreamID != 0 {
  550. return nil, ConnectionError(ErrCodeProtocol)
  551. }
  552. if len(p) < 8 {
  553. return nil, ConnectionError(ErrCodeFrameSize)
  554. }
  555. return &GoAwayFrame{
  556. FrameHeader: fh,
  557. LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
  558. ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])),
  559. debugData: p[8:],
  560. }, nil
  561. }
  562. func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error {
  563. f.startWrite(FrameGoAway, 0, 0)
  564. f.writeUint32(maxStreamID & (1<<31 - 1))
  565. f.writeUint32(uint32(code))
  566. f.writeBytes(debugData)
  567. return f.endWrite()
  568. }
  569. // An UnknownFrame is the frame type returned when the frame type is unknown
  570. // or no specific frame type parser exists.
  571. type UnknownFrame struct {
  572. FrameHeader
  573. p []byte
  574. }
  575. // Payload returns the frame's payload (after the header). It is not
  576. // valid to call this method after a subsequent call to
  577. // Framer.ReadFrame, nor is it valid to retain the returned slice.
  578. // The memory is owned by the Framer and is invalidated when the next
  579. // frame is read.
  580. func (f *UnknownFrame) Payload() []byte {
  581. f.checkValid()
  582. return f.p
  583. }
  584. func parseUnknownFrame(fh FrameHeader, p []byte) (Frame, error) {
  585. return &UnknownFrame{fh, p}, nil
  586. }
  587. // A WindowUpdateFrame is used to implement flow control.
  588. // See http://http2.github.io/http2-spec/#rfc.section.6.9
  589. type WindowUpdateFrame struct {
  590. FrameHeader
  591. Increment uint32
  592. }
  593. func parseWindowUpdateFrame(fh FrameHeader, p []byte) (Frame, error) {
  594. if len(p) != 4 {
  595. return nil, ConnectionError(ErrCodeFrameSize)
  596. }
  597. inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
  598. if inc == 0 {
  599. // A receiver MUST treat the receipt of a
  600. // WINDOW_UPDATE frame with an flow control window
  601. // increment of 0 as a stream error (Section 5.4.2) of
  602. // type PROTOCOL_ERROR; errors on the connection flow
  603. // control window MUST be treated as a connection
  604. // error (Section 5.4.1).
  605. if fh.StreamID == 0 {
  606. return nil, ConnectionError(ErrCodeProtocol)
  607. }
  608. return nil, StreamError{fh.StreamID, ErrCodeProtocol}
  609. }
  610. return &WindowUpdateFrame{
  611. FrameHeader: fh,
  612. Increment: inc,
  613. }, nil
  614. }
  615. // WriteWindowUpdate writes a WINDOW_UPDATE frame.
  616. // The increment value must be between 1 and 2,147,483,647, inclusive.
  617. // If the Stream ID is zero, the window update applies to the
  618. // connection as a whole.
  619. func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error {
  620. // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
  621. if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
  622. return errors.New("illegal window increment value")
  623. }
  624. f.startWrite(FrameWindowUpdate, 0, streamID)
  625. f.writeUint32(incr)
  626. return f.endWrite()
  627. }
  628. // A HeadersFrame is used to open a stream and additionally carries a
  629. // header block fragment.
  630. type HeadersFrame struct {
  631. FrameHeader
  632. // Priority is set if FlagHeadersPriority is set in the FrameHeader.
  633. Priority PriorityParam
  634. headerFragBuf []byte // not owned
  635. }
  636. func (f *HeadersFrame) HeaderBlockFragment() []byte {
  637. f.checkValid()
  638. return f.headerFragBuf
  639. }
  640. func (f *HeadersFrame) HeadersEnded() bool {
  641. return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
  642. }
  643. func (f *HeadersFrame) StreamEnded() bool {
  644. return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
  645. }
  646. func (f *HeadersFrame) HasPriority() bool {
  647. return f.FrameHeader.Flags.Has(FlagHeadersPriority)
  648. }
  649. func parseHeadersFrame(fh FrameHeader, p []byte) (_ Frame, err error) {
  650. hf := &HeadersFrame{
  651. FrameHeader: fh,
  652. }
  653. if fh.StreamID == 0 {
  654. // HEADERS frames MUST be associated with a stream. If a HEADERS frame
  655. // is received whose stream identifier field is 0x0, the recipient MUST
  656. // respond with a connection error (Section 5.4.1) of type
  657. // PROTOCOL_ERROR.
  658. return nil, ConnectionError(ErrCodeProtocol)
  659. }
  660. var padLength uint8
  661. if fh.Flags.Has(FlagHeadersPadded) {
  662. if p, padLength, err = readByte(p); err != nil {
  663. return
  664. }
  665. }
  666. if fh.Flags.Has(FlagHeadersPriority) {
  667. var v uint32
  668. p, v, err = readUint32(p)
  669. if err != nil {
  670. return nil, err
  671. }
  672. hf.Priority.StreamDep = v & 0x7fffffff
  673. hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
  674. p, hf.Priority.Weight, err = readByte(p)
  675. if err != nil {
  676. return nil, err
  677. }
  678. }
  679. if len(p)-int(padLength) <= 0 {
  680. return nil, StreamError{fh.StreamID, ErrCodeProtocol}
  681. }
  682. hf.headerFragBuf = p[:len(p)-int(padLength)]
  683. return hf, nil
  684. }
  685. // HeadersFrameParam are the parameters for writing a HEADERS frame.
  686. type HeadersFrameParam struct {
  687. // StreamID is the required Stream ID to initiate.
  688. StreamID uint32
  689. // BlockFragment is part (or all) of a Header Block.
  690. BlockFragment []byte
  691. // EndStream indicates that the header block is the last that
  692. // the endpoint will send for the identified stream. Setting
  693. // this flag causes the stream to enter one of "half closed"
  694. // states.
  695. EndStream bool
  696. // EndHeaders indicates that this frame contains an entire
  697. // header block and is not followed by any
  698. // CONTINUATION frames.
  699. EndHeaders bool
  700. // PadLength is the optional number of bytes of zeros to add
  701. // to this frame.
  702. PadLength uint8
  703. // Priority, if non-zero, includes stream priority information
  704. // in the HEADER frame.
  705. Priority PriorityParam
  706. }
  707. // WriteHeaders writes a single HEADERS frame.
  708. //
  709. // This is a low-level header writing method. Encoding headers and
  710. // splitting them into any necessary CONTINUATION frames is handled
  711. // elsewhere.
  712. //
  713. // It will perform exactly one Write to the underlying Writer.
  714. // It is the caller's responsibility to not call other Write methods concurrently.
  715. func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
  716. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  717. return errStreamID
  718. }
  719. var flags Flags
  720. if p.PadLength != 0 {
  721. flags |= FlagHeadersPadded
  722. }
  723. if p.EndStream {
  724. flags |= FlagHeadersEndStream
  725. }
  726. if p.EndHeaders {
  727. flags |= FlagHeadersEndHeaders
  728. }
  729. if !p.Priority.IsZero() {
  730. flags |= FlagHeadersPriority
  731. }
  732. f.startWrite(FrameHeaders, flags, p.StreamID)
  733. if p.PadLength != 0 {
  734. f.writeByte(p.PadLength)
  735. }
  736. if !p.Priority.IsZero() {
  737. v := p.Priority.StreamDep
  738. if !validStreamID(v) && !f.AllowIllegalWrites {
  739. return errors.New("invalid dependent stream id")
  740. }
  741. if p.Priority.Exclusive {
  742. v |= 1 << 31
  743. }
  744. f.writeUint32(v)
  745. f.writeByte(p.Priority.Weight)
  746. }
  747. f.wbuf = append(f.wbuf, p.BlockFragment...)
  748. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  749. return f.endWrite()
  750. }
  751. // A PriorityFrame specifies the sender-advised priority of a stream.
  752. // See http://http2.github.io/http2-spec/#rfc.section.6.3
  753. type PriorityFrame struct {
  754. FrameHeader
  755. PriorityParam
  756. }
  757. // PriorityParam are the stream prioritzation parameters.
  758. type PriorityParam struct {
  759. // StreamDep is a 31-bit stream identifier for the
  760. // stream that this stream depends on. Zero means no
  761. // dependency.
  762. StreamDep uint32
  763. // Exclusive is whether the dependency is exclusive.
  764. Exclusive bool
  765. // Weight is the stream's zero-indexed weight. It should be
  766. // set together with StreamDep, or neither should be set. Per
  767. // the spec, "Add one to the value to obtain a weight between
  768. // 1 and 256."
  769. Weight uint8
  770. }
  771. func (p PriorityParam) IsZero() bool {
  772. return p == PriorityParam{}
  773. }
  774. func parsePriorityFrame(fh FrameHeader, payload []byte) (Frame, error) {
  775. if fh.StreamID == 0 {
  776. return nil, ConnectionError(ErrCodeProtocol)
  777. }
  778. if len(payload) != 5 {
  779. return nil, ConnectionError(ErrCodeFrameSize)
  780. }
  781. v := binary.BigEndian.Uint32(payload[:4])
  782. streamID := v & 0x7fffffff // mask off high bit
  783. return &PriorityFrame{
  784. FrameHeader: fh,
  785. PriorityParam: PriorityParam{
  786. Weight: payload[4],
  787. StreamDep: streamID,
  788. Exclusive: streamID != v, // was high bit set?
  789. },
  790. }, nil
  791. }
  792. // WritePriority writes a PRIORITY frame.
  793. //
  794. // It will perform exactly one Write to the underlying Writer.
  795. // It is the caller's responsibility to not call other Write methods concurrently.
  796. func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error {
  797. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  798. return errStreamID
  799. }
  800. f.startWrite(FramePriority, 0, streamID)
  801. v := p.StreamDep
  802. if p.Exclusive {
  803. v |= 1 << 31
  804. }
  805. f.writeUint32(v)
  806. f.writeByte(p.Weight)
  807. return f.endWrite()
  808. }
  809. // A RSTStreamFrame allows for abnormal termination of a stream.
  810. // See http://http2.github.io/http2-spec/#rfc.section.6.4
  811. type RSTStreamFrame struct {
  812. FrameHeader
  813. ErrCode ErrCode
  814. }
  815. func parseRSTStreamFrame(fh FrameHeader, p []byte) (Frame, error) {
  816. if len(p) != 4 {
  817. return nil, ConnectionError(ErrCodeFrameSize)
  818. }
  819. if fh.StreamID == 0 {
  820. return nil, ConnectionError(ErrCodeProtocol)
  821. }
  822. return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
  823. }
  824. // WriteRSTStream writes a RST_STREAM frame.
  825. //
  826. // It will perform exactly one Write to the underlying Writer.
  827. // It is the caller's responsibility to not call other Write methods concurrently.
  828. func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
  829. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  830. return errStreamID
  831. }
  832. f.startWrite(FrameRSTStream, 0, streamID)
  833. f.writeUint32(uint32(code))
  834. return f.endWrite()
  835. }
  836. // A ContinuationFrame is used to continue a sequence of header block fragments.
  837. // See http://http2.github.io/http2-spec/#rfc.section.6.10
  838. type ContinuationFrame struct {
  839. FrameHeader
  840. headerFragBuf []byte
  841. }
  842. func parseContinuationFrame(fh FrameHeader, p []byte) (Frame, error) {
  843. return &ContinuationFrame{fh, p}, nil
  844. }
  845. func (f *ContinuationFrame) StreamEnded() bool {
  846. return f.FrameHeader.Flags.Has(FlagDataEndStream)
  847. }
  848. func (f *ContinuationFrame) HeaderBlockFragment() []byte {
  849. f.checkValid()
  850. return f.headerFragBuf
  851. }
  852. func (f *ContinuationFrame) HeadersEnded() bool {
  853. return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
  854. }
  855. // WriteContinuation writes a CONTINUATION frame.
  856. //
  857. // It will perform exactly one Write to the underlying Writer.
  858. // It is the caller's responsibility to not call other Write methods concurrently.
  859. func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
  860. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  861. return errStreamID
  862. }
  863. var flags Flags
  864. if endHeaders {
  865. flags |= FlagContinuationEndHeaders
  866. }
  867. f.startWrite(FrameContinuation, flags, streamID)
  868. f.wbuf = append(f.wbuf, headerBlockFragment...)
  869. return f.endWrite()
  870. }
  871. // A PushPromiseFrame is used to initiate a server stream.
  872. // See http://http2.github.io/http2-spec/#rfc.section.6.6
  873. type PushPromiseFrame struct {
  874. FrameHeader
  875. PromiseID uint32
  876. headerFragBuf []byte // not owned
  877. }
  878. func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
  879. f.checkValid()
  880. return f.headerFragBuf
  881. }
  882. func (f *PushPromiseFrame) HeadersEnded() bool {
  883. return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
  884. }
  885. func parsePushPromise(fh FrameHeader, p []byte) (_ Frame, err error) {
  886. pp := &PushPromiseFrame{
  887. FrameHeader: fh,
  888. }
  889. if pp.StreamID == 0 {
  890. // PUSH_PROMISE frames MUST be associated with an existing,
  891. // peer-initiated stream. The stream identifier of a
  892. // PUSH_PROMISE frame indicates the stream it is associated
  893. // with. If the stream identifier field specifies the value
  894. // 0x0, a recipient MUST respond with a connection error
  895. // (Section 5.4.1) of type PROTOCOL_ERROR.
  896. return nil, ConnectionError(ErrCodeProtocol)
  897. }
  898. // The PUSH_PROMISE frame includes optional padding.
  899. // Padding fields and flags are identical to those defined for DATA frames
  900. var padLength uint8
  901. if fh.Flags.Has(FlagPushPromisePadded) {
  902. if p, padLength, err = readByte(p); err != nil {
  903. return
  904. }
  905. }
  906. p, pp.PromiseID, err = readUint32(p)
  907. if err != nil {
  908. return
  909. }
  910. pp.PromiseID = pp.PromiseID & (1<<31 - 1)
  911. if int(padLength) > len(p) {
  912. // like the DATA frame, error out if padding is longer than the body.
  913. return nil, ConnectionError(ErrCodeProtocol)
  914. }
  915. pp.headerFragBuf = p[:len(p)-int(padLength)]
  916. return pp, nil
  917. }
  918. // PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
  919. type PushPromiseParam struct {
  920. // StreamID is the required Stream ID to initiate.
  921. StreamID uint32
  922. // PromiseID is the required Stream ID which this
  923. // Push Promises
  924. PromiseID uint32
  925. // BlockFragment is part (or all) of a Header Block.
  926. BlockFragment []byte
  927. // EndHeaders indicates that this frame contains an entire
  928. // header block and is not followed by any
  929. // CONTINUATION frames.
  930. EndHeaders bool
  931. // PadLength is the optional number of bytes of zeros to add
  932. // to this frame.
  933. PadLength uint8
  934. }
  935. // WritePushPromise writes a single PushPromise Frame.
  936. //
  937. // As with Header Frames, This is the low level call for writing
  938. // individual frames. Continuation frames are handled elsewhere.
  939. //
  940. // It will perform exactly one Write to the underlying Writer.
  941. // It is the caller's responsibility to not call other Write methods concurrently.
  942. func (f *Framer) WritePushPromise(p PushPromiseParam) error {
  943. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  944. return errStreamID
  945. }
  946. var flags Flags
  947. if p.PadLength != 0 {
  948. flags |= FlagPushPromisePadded
  949. }
  950. if p.EndHeaders {
  951. flags |= FlagPushPromiseEndHeaders
  952. }
  953. f.startWrite(FramePushPromise, flags, p.StreamID)
  954. if p.PadLength != 0 {
  955. f.writeByte(p.PadLength)
  956. }
  957. if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
  958. return errStreamID
  959. }
  960. f.writeUint32(p.PromiseID)
  961. f.wbuf = append(f.wbuf, p.BlockFragment...)
  962. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  963. return f.endWrite()
  964. }
  965. // WriteRawFrame writes a raw frame. This can be used to write
  966. // extension frames unknown to this package.
  967. func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
  968. f.startWrite(t, flags, streamID)
  969. f.writeBytes(payload)
  970. return f.endWrite()
  971. }
  972. func readByte(p []byte) (remain []byte, b byte, err error) {
  973. if len(p) == 0 {
  974. return nil, 0, io.ErrUnexpectedEOF
  975. }
  976. return p[1:], p[0], nil
  977. }
  978. func readUint32(p []byte) (remain []byte, v uint32, err error) {
  979. if len(p) < 4 {
  980. return nil, 0, io.ErrUnexpectedEOF
  981. }
  982. return p[4:], binary.BigEndian.Uint32(p[:4]), nil
  983. }
  984. type streamEnder interface {
  985. StreamEnded() bool
  986. }
  987. type headersEnder interface {
  988. HeadersEnded() bool
  989. }