frame.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787
  1. // Copyright 2014 The Go Authors.
  2. // See https://code.google.com/p/go/source/browse/CONTRIBUTORS
  3. // Licensed under the same terms as Go itself:
  4. // https://code.google.com/p/go/source/browse/LICENSE
  5. package http2
  6. import (
  7. "bytes"
  8. "encoding/binary"
  9. "errors"
  10. "fmt"
  11. "io"
  12. "sync"
  13. )
  14. const frameHeaderLen = 9
  15. var padZeros = make([]byte, 255) // zeros for padding
  16. // A FrameType is a registered frame type as defined in
  17. // http://http2.github.io/http2-spec/#rfc.section.11.2
  18. type FrameType uint8
  19. const (
  20. FrameData FrameType = 0x0
  21. FrameHeaders FrameType = 0x1
  22. FramePriority FrameType = 0x2
  23. FrameRSTStream FrameType = 0x3
  24. FrameSettings FrameType = 0x4
  25. FramePushPromise FrameType = 0x5
  26. FramePing FrameType = 0x6
  27. FrameGoAway FrameType = 0x7
  28. FrameWindowUpdate FrameType = 0x8
  29. FrameContinuation FrameType = 0x9
  30. )
  31. var frameName = map[FrameType]string{
  32. FrameData: "DATA",
  33. FrameHeaders: "HEADERS",
  34. FramePriority: "PRIORITY",
  35. FrameRSTStream: "RST_STREAM",
  36. FrameSettings: "SETTINGS",
  37. FramePushPromise: "PUSH_PROMISE",
  38. FramePing: "PING",
  39. FrameGoAway: "GOAWAY",
  40. FrameWindowUpdate: "WINDOW_UPDATE",
  41. FrameContinuation: "CONTINUATION",
  42. }
  43. func (t FrameType) String() string {
  44. if s, ok := frameName[t]; ok {
  45. return s
  46. }
  47. return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t))
  48. }
  49. // Flags is a bitmask of HTTP/2 flags.
  50. // The meaning of flags varies depending on the frame type.
  51. type Flags uint8
  52. // Has reports whether f contains all (0 or more) flags in v.
  53. func (f Flags) Has(v Flags) bool {
  54. return (f & v) == v
  55. }
  56. // Frame-specific FrameHeader flag bits.
  57. const (
  58. // Data Frame
  59. FlagDataEndStream Flags = 0x1
  60. FlagDataPadded Flags = 0x8
  61. // Headers Frame
  62. FlagHeadersEndStream Flags = 0x1
  63. FlagHeadersEndHeaders Flags = 0x4
  64. FlagHeadersPadded Flags = 0x8
  65. FlagHeadersPriority Flags = 0x20
  66. // Settings Frame
  67. FlagSettingsAck Flags = 0x1
  68. // Ping Frame
  69. FlagPingAck Flags = 0x1
  70. // Continuation Frame
  71. FlagContinuationEndHeaders Flags = 0x4
  72. )
  73. var flagName = map[FrameType]map[Flags]string{
  74. FrameData: {
  75. FlagDataEndStream: "END_STREAM",
  76. FlagDataPadded: "PADDED",
  77. },
  78. FrameHeaders: {
  79. FlagHeadersEndStream: "END_STREAM",
  80. FlagHeadersEndHeaders: "END_HEADERS",
  81. FlagHeadersPadded: "PADDED",
  82. FlagHeadersPriority: "PRIORITY",
  83. },
  84. FrameSettings: {
  85. FlagSettingsAck: "ACK",
  86. },
  87. FramePing: {
  88. FlagPingAck: "ACK",
  89. },
  90. FrameContinuation: {
  91. FlagContinuationEndHeaders: "END_HEADERS",
  92. },
  93. }
  94. // A SettingID is an HTTP/2 setting as defined in
  95. // http://http2.github.io/http2-spec/#iana-settings
  96. type SettingID uint16
  97. const (
  98. SettingHeaderTableSize SettingID = 0x1
  99. SettingEnablePush SettingID = 0x2
  100. SettingMaxConcurrentStreams SettingID = 0x3
  101. SettingInitialWindowSize SettingID = 0x4
  102. SettingMaxFrameSize SettingID = 0x5
  103. SettingMaxHeaderListSize SettingID = 0x6
  104. )
  105. var settingName = map[SettingID]string{
  106. SettingHeaderTableSize: "HEADER_TABLE_SIZE",
  107. SettingEnablePush: "ENABLE_PUSH",
  108. SettingMaxConcurrentStreams: "MAX_CONCURRENT_STREAMS",
  109. SettingInitialWindowSize: "INITIAL_WINDOW_SIZE",
  110. SettingMaxFrameSize: "MAX_FRAME_SIZE",
  111. SettingMaxHeaderListSize: "MAX_HEADER_LIST_SIZE",
  112. }
  113. func (s SettingID) String() string {
  114. if v, ok := settingName[s]; ok {
  115. return v
  116. }
  117. return fmt.Sprintf("UNKNOWN_SETTING_%d", uint8(s))
  118. }
  119. // a frameParser parses a frame given its FrameHeader and payload
  120. // bytes. The length of payload will always equal fh.Length (which
  121. // might be 0).
  122. type frameParser func(fh FrameHeader, payload []byte) (Frame, error)
  123. var frameParsers = map[FrameType]frameParser{
  124. FrameData: parseDataFrame,
  125. FrameHeaders: parseHeadersFrame,
  126. FramePriority: nil, // TODO
  127. FrameRSTStream: parseRSTStreamFrame,
  128. FrameSettings: parseSettingsFrame,
  129. FramePushPromise: nil, // TODO
  130. FramePing: parsePingFrame,
  131. FrameGoAway: parseGoAwayFrame,
  132. FrameWindowUpdate: parseWindowUpdateFrame,
  133. FrameContinuation: parseContinuationFrame,
  134. }
  135. func typeFrameParser(t FrameType) frameParser {
  136. if f := frameParsers[t]; f != nil {
  137. return f
  138. }
  139. return parseUnknownFrame
  140. }
  141. // A FrameHeader is the 9 byte header of all HTTP/2 frames.
  142. //
  143. // See http://http2.github.io/http2-spec/#FrameHeader
  144. type FrameHeader struct {
  145. valid bool // caller can access []byte fields in the Frame
  146. Type FrameType
  147. Flags Flags
  148. Length uint32 // actually a uint24 max; default is uint16 max
  149. StreamID uint32
  150. }
  151. // Header returns h. It exists so FrameHeaders can be embedded in other
  152. // specific frame types and implement the Frame interface.
  153. func (h FrameHeader) Header() FrameHeader { return h }
  154. func (h FrameHeader) String() string {
  155. var buf bytes.Buffer
  156. buf.WriteString("[FrameHeader ")
  157. buf.WriteString(h.Type.String())
  158. if h.Flags != 0 {
  159. buf.WriteString(" flags=")
  160. set := 0
  161. for i := uint8(0); i < 8; i++ {
  162. if h.Flags&(1<<i) == 0 {
  163. continue
  164. }
  165. set++
  166. if set > 1 {
  167. buf.WriteByte('|')
  168. }
  169. name := flagName[h.Type][Flags(1<<i)]
  170. if name != "" {
  171. buf.WriteString(name)
  172. } else {
  173. fmt.Fprintf(&buf, "0x%x", 1<<i)
  174. }
  175. }
  176. }
  177. if h.StreamID != 0 {
  178. fmt.Fprintf(&buf, " stream=%d", h.StreamID)
  179. }
  180. fmt.Fprintf(&buf, " len=%d]", h.Length)
  181. return buf.String()
  182. }
  183. func (h *FrameHeader) checkValid() {
  184. if !h.valid {
  185. panic("Frame accessor called on non-owned Frame")
  186. }
  187. }
  188. func (h *FrameHeader) invalidate() { h.valid = false }
  189. // frame header bytes.
  190. // Used only by ReadFrameHeader.
  191. var fhBytes = sync.Pool{
  192. New: func() interface{} {
  193. buf := make([]byte, frameHeaderLen)
  194. return &buf
  195. },
  196. }
  197. // ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
  198. // Most users should use Framer.ReadFrame instead.
  199. func ReadFrameHeader(r io.Reader) (FrameHeader, error) {
  200. bufp := fhBytes.Get().(*[]byte)
  201. defer fhBytes.Put(bufp)
  202. return readFrameHeader(*bufp, r)
  203. }
  204. func readFrameHeader(buf []byte, r io.Reader) (FrameHeader, error) {
  205. _, err := io.ReadFull(r, buf[:frameHeaderLen])
  206. if err != nil {
  207. return FrameHeader{}, err
  208. }
  209. return FrameHeader{
  210. Length: (uint32(buf[0])<<16 | uint32(buf[1])<<7 | uint32(buf[2])),
  211. Type: FrameType(buf[3]),
  212. Flags: Flags(buf[4]),
  213. StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
  214. valid: true,
  215. }, nil
  216. }
  217. // A Frame is the base interface implemented by all frame types.
  218. // Callers will generally type-assert the specific frame type:
  219. // *HeadersFrame, *SettingsFrame, *WindowUpdateFrame, etc.
  220. //
  221. // Frames are only valid until the next call to Framer.ReadFrame.
  222. type Frame interface {
  223. Header() FrameHeader
  224. // invalidate is called by Framer.ReadFrame to make this
  225. // frame's buffers as being invalid, since the subsequent
  226. // frame will reuse them.
  227. invalidate()
  228. }
  229. // A Framer reads and writes Frames.
  230. type Framer struct {
  231. r io.Reader
  232. lr io.LimitedReader
  233. lastFrame Frame
  234. readBuf []byte
  235. w io.Writer
  236. wbuf []byte
  237. // AllowIllegalWrites permits the Framer's Write methods to
  238. // write frames that do not conform to the HTTP/2 spec. This
  239. // permits using the Framer to test other HTTP/2
  240. // implementations' conformance to the spec.
  241. // If false, the Write methods will prefer to return an error
  242. // rather than comply.
  243. AllowIllegalWrites bool
  244. }
  245. func (f *Framer) startWrite(ftype FrameType, flags Flags, streamID uint32) {
  246. // Write the FrameHeader.
  247. f.wbuf = append(f.wbuf[:0],
  248. 0, // 3 bytes of length, filled in in endWrite
  249. 0,
  250. 0,
  251. byte(ftype),
  252. byte(flags),
  253. byte(streamID>>24),
  254. byte(streamID>>16),
  255. byte(streamID>>8),
  256. byte(streamID))
  257. }
  258. func (f *Framer) endWrite() error {
  259. // Now that we know the final size, fill in the FrameHeader in
  260. // the space previously reserved for it. Abuse append.
  261. length := len(f.wbuf) - frameHeaderLen
  262. _ = append(f.wbuf[:0],
  263. byte(length>>16),
  264. byte(length>>8),
  265. byte(length))
  266. n, err := f.w.Write(f.wbuf)
  267. if err == nil && n != len(f.wbuf) {
  268. err = io.ErrShortWrite
  269. }
  270. return err
  271. }
  272. func (f *Framer) writeUint32(v uint32) {
  273. f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
  274. }
  275. func (f *Framer) writeByte(v byte) {
  276. f.wbuf = append(f.wbuf, v)
  277. }
  278. // NewFramer returns a Framer that writes frames to w and reads them from r.
  279. func NewFramer(w io.Writer, r io.Reader) *Framer {
  280. return &Framer{
  281. w: w,
  282. r: r,
  283. readBuf: make([]byte, 1<<10),
  284. }
  285. }
  286. // ReadFrame reads a single frame. The returned Frame is only valid
  287. // until the next call to ReadFrame.
  288. func (fr *Framer) ReadFrame() (Frame, error) {
  289. if fr.lastFrame != nil {
  290. fr.lastFrame.invalidate()
  291. }
  292. fh, err := readFrameHeader(fr.readBuf, fr.r)
  293. if err != nil {
  294. return nil, err
  295. }
  296. if uint32(len(fr.readBuf)) < fh.Length {
  297. fr.readBuf = make([]byte, fh.Length)
  298. }
  299. payload := fr.readBuf[:fh.Length]
  300. if _, err := io.ReadFull(fr.r, payload); err != nil {
  301. return nil, err
  302. }
  303. f, err := typeFrameParser(fh.Type)(fh, payload)
  304. if err != nil {
  305. return nil, err
  306. }
  307. fr.lastFrame = f
  308. return f, nil
  309. }
  310. // A DataFrame conveys arbitrary, variable-length sequences of octets
  311. // associated with a stream.
  312. // See http://http2.github.io/http2-spec/#rfc.section.6.1
  313. type DataFrame struct {
  314. FrameHeader
  315. data []byte
  316. }
  317. // Data returns the frame's data octets, not including any padding
  318. // size byte or padding suffix bytes.
  319. // The caller must not retain the returned memory past the next
  320. // call to ReadFrame.
  321. func (f *DataFrame) Data() []byte {
  322. f.checkValid()
  323. return f.data
  324. }
  325. func parseDataFrame(fh FrameHeader, payload []byte) (Frame, error) {
  326. if fh.StreamID == 0 {
  327. // DATA frames MUST be associated with a stream. If a
  328. // DATA frame is received whose stream identifier
  329. // field is 0x0, the recipient MUST respond with a
  330. // connection error (Section 5.4.1) of type
  331. // PROTOCOL_ERROR.
  332. return nil, ConnectionError(ErrCodeProtocol)
  333. }
  334. f := &DataFrame{
  335. FrameHeader: fh,
  336. }
  337. var padSize byte
  338. if fh.Flags.Has(FlagDataPadded) {
  339. var err error
  340. payload, padSize, err = readByte(payload)
  341. if err != nil {
  342. return nil, err
  343. }
  344. }
  345. if int(padSize) > len(payload) {
  346. // If the length of the padding is greater than the
  347. // length of the frame payload, the recipient MUST
  348. // treat this as a connection error.
  349. // Filed: https://github.com/http2/http2-spec/issues/610
  350. return nil, ConnectionError(ErrCodeProtocol)
  351. }
  352. f.data = payload[:len(payload)-int(padSize)]
  353. return f, nil
  354. }
  355. var errStreamID = errors.New("invalid streamid")
  356. func validStreamID(streamID uint32) bool {
  357. return streamID != 0 && streamID&(1<<31) == 0
  358. }
  359. // WriteData writes a DATA frame.
  360. //
  361. // It will perform exactly one Write to the underlying Writer.
  362. // It is the caller's responsibility to not call other Write methods concurrently.
  363. func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
  364. // TODO: ignoring padding for now. will add when somebody cares.
  365. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  366. return errStreamID
  367. }
  368. var flags Flags
  369. if endStream {
  370. flags |= FlagDataEndStream
  371. }
  372. f.startWrite(FrameData, flags, streamID)
  373. f.wbuf = append(f.wbuf, data...)
  374. return f.endWrite()
  375. }
  376. // A SettingsFrame conveys configuration parameters that affect how
  377. // endpoints communicate, such as preferences and constraints on peer
  378. // behavior.
  379. //
  380. // See http://http2.github.io/http2-spec/#SETTINGS
  381. type SettingsFrame struct {
  382. FrameHeader
  383. p []byte
  384. }
  385. func parseSettingsFrame(fh FrameHeader, p []byte) (Frame, error) {
  386. if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 {
  387. // When this (ACK 0x1) bit is set, the payload of the
  388. // SETTINGS frame MUST be empty. Receipt of a
  389. // SETTINGS frame with the ACK flag set and a length
  390. // field value other than 0 MUST be treated as a
  391. // connection error (Section 5.4.1) of type
  392. // FRAME_SIZE_ERROR.
  393. return nil, ConnectionError(ErrCodeFrameSize)
  394. }
  395. if fh.StreamID != 0 {
  396. // SETTINGS frames always apply to a connection,
  397. // never a single stream. The stream identifier for a
  398. // SETTINGS frame MUST be zero (0x0). If an endpoint
  399. // receives a SETTINGS frame whose stream identifier
  400. // field is anything other than 0x0, the endpoint MUST
  401. // respond with a connection error (Section 5.4.1) of
  402. // type PROTOCOL_ERROR.
  403. return nil, ConnectionError(ErrCodeProtocol)
  404. }
  405. if len(p)%6 != 0 {
  406. // Expecting even number of 6 byte settings.
  407. return nil, ConnectionError(ErrCodeFrameSize)
  408. }
  409. f := &SettingsFrame{FrameHeader: fh, p: p}
  410. if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 {
  411. // Values above the maximum flow control window size of 2^31 - 1 MUST
  412. // be treated as a connection error (Section 5.4.1) of type
  413. // FLOW_CONTROL_ERROR.
  414. return nil, ConnectionError(ErrCodeFlowControl)
  415. }
  416. return f, nil
  417. }
  418. func (f *SettingsFrame) Value(s SettingID) (v uint32, ok bool) {
  419. f.checkValid()
  420. buf := f.p
  421. for len(buf) > 0 {
  422. settingID := SettingID(binary.BigEndian.Uint16(buf[:2]))
  423. if settingID == s {
  424. return binary.BigEndian.Uint32(buf[2:4]), true
  425. }
  426. buf = buf[6:]
  427. }
  428. return 0, false
  429. }
  430. func (f *SettingsFrame) ForeachSetting(fn func(s SettingID, v uint32)) {
  431. f.checkValid()
  432. buf := f.p
  433. for len(buf) > 0 {
  434. fn(SettingID(binary.BigEndian.Uint16(buf[:2])), binary.BigEndian.Uint32(buf[2:4]))
  435. buf = buf[6:]
  436. }
  437. }
  438. // A PingFrame is a mechanism for measuring a minimal round trip time
  439. // from the sender, as well as determining whether an idle connection
  440. // is still functional.
  441. // See http://http2.github.io/http2-spec/#rfc.section.6.7
  442. type PingFrame struct {
  443. FrameHeader
  444. Data [8]byte
  445. }
  446. func parsePingFrame(fh FrameHeader, payload []byte) (Frame, error) {
  447. if len(payload) != 8 {
  448. return nil, ConnectionError(ErrCodeFrameSize)
  449. }
  450. if fh.StreamID != 0 {
  451. return nil, ConnectionError(ErrCodeProtocol)
  452. }
  453. f := &PingFrame{FrameHeader: fh}
  454. copy(f.Data[:], payload)
  455. return f, nil
  456. }
  457. // A GoAwayFrame informs the remote peer to stop creating streams on this connection.
  458. // See http://http2.github.io/http2-spec/#rfc.section.6.8
  459. type GoAwayFrame struct {
  460. FrameHeader
  461. LastStreamID uint32
  462. ErrCode uint32
  463. debugData []byte
  464. }
  465. // DebugData returns any debug data in the GOAWAY frame. Its contents
  466. // are not defined.
  467. // The caller must not retain the returned memory past the next
  468. // call to ReadFrame.
  469. func (f *GoAwayFrame) DebugData() []byte {
  470. f.checkValid()
  471. return f.debugData
  472. }
  473. func parseGoAwayFrame(fh FrameHeader, p []byte) (Frame, error) {
  474. if fh.StreamID != 0 {
  475. return nil, ConnectionError(ErrCodeProtocol)
  476. }
  477. if len(p) < 8 {
  478. return nil, ConnectionError(ErrCodeFrameSize)
  479. }
  480. return &GoAwayFrame{
  481. FrameHeader: fh,
  482. LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
  483. ErrCode: binary.BigEndian.Uint32(p[4:8]),
  484. debugData: p[:8],
  485. }, nil
  486. }
  487. // An UnknownFrame is the frame type returned when the frame type is unknown
  488. // or no specific frame type parser exists.
  489. type UnknownFrame struct {
  490. FrameHeader
  491. p []byte
  492. }
  493. // Payload returns the frame's payload (after the header).
  494. // It is not valid to call this method after a subsequent
  495. // call to Framer.ReadFrame.
  496. func (f *UnknownFrame) Payload() []byte {
  497. f.checkValid()
  498. return f.p
  499. }
  500. func parseUnknownFrame(fh FrameHeader, p []byte) (Frame, error) {
  501. return &UnknownFrame{fh, p}, nil
  502. }
  503. // A WindowUpdateFrame is used to implement flow control.
  504. // See http://http2.github.io/http2-spec/#rfc.section.6.9
  505. type WindowUpdateFrame struct {
  506. FrameHeader
  507. Increment uint32
  508. }
  509. func parseWindowUpdateFrame(fh FrameHeader, p []byte) (Frame, error) {
  510. if len(p) < 4 {
  511. // Too short.
  512. return nil, ConnectionError(ErrCodeProtocol)
  513. }
  514. return &WindowUpdateFrame{
  515. FrameHeader: fh,
  516. Increment: binary.BigEndian.Uint32(p[:4]) & 0x7fffffff, // mask off high reserved bit
  517. }, nil
  518. }
  519. // A HeadersFrame is used to open a stream and additionally carries a
  520. // header block fragment.
  521. type HeadersFrame struct {
  522. FrameHeader
  523. // Priority is set if FlagHeadersPriority is set in the FrameHeader.
  524. Priority PriorityParam
  525. headerFragBuf []byte // not owned
  526. }
  527. func (f *HeadersFrame) HeaderBlockFragment() []byte {
  528. f.checkValid()
  529. return f.headerFragBuf
  530. }
  531. func (f *HeadersFrame) HeadersEnded() bool {
  532. return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
  533. }
  534. func parseHeadersFrame(fh FrameHeader, p []byte) (_ Frame, err error) {
  535. hf := &HeadersFrame{
  536. FrameHeader: fh,
  537. }
  538. if fh.StreamID == 0 {
  539. // HEADERS frames MUST be associated with a stream. If a HEADERS frame
  540. // is received whose stream identifier field is 0x0, the recipient MUST
  541. // respond with a connection error (Section 5.4.1) of type
  542. // PROTOCOL_ERROR.
  543. return nil, ConnectionError(ErrCodeProtocol)
  544. }
  545. var padLength uint8
  546. if fh.Flags.Has(FlagHeadersPadded) {
  547. if p, padLength, err = readByte(p); err != nil {
  548. return
  549. }
  550. }
  551. if fh.Flags.Has(FlagHeadersPriority) {
  552. var v uint32
  553. p, v, err = readUint32(p)
  554. if err != nil {
  555. return nil, err
  556. }
  557. hf.Priority.StreamDep = v & 0x7fffffff
  558. hf.Priority.ExclusiveDep = (v != hf.Priority.StreamDep) // high bit was set
  559. p, hf.Priority.Weight, err = readByte(p)
  560. if err != nil {
  561. return nil, err
  562. }
  563. }
  564. if len(p)-int(padLength) <= 0 {
  565. return nil, StreamError(fh.StreamID)
  566. }
  567. hf.headerFragBuf = p[:len(p)-int(padLength)]
  568. return hf, nil
  569. }
  570. // HeadersFrameParam are the parameters for writing a HEADERS frame.
  571. type HeadersFrameParam struct {
  572. // StreamID is the required Stream ID to initiate.
  573. StreamID uint32
  574. // BlockFragment is part (or all) of a Header Block.
  575. BlockFragment []byte
  576. // EndStream indicates that the header block is the last that
  577. // the endpoint will send for the identified stream. Setting
  578. // this flag causes the stream to enter one of "half closed"
  579. // states.
  580. EndStream bool
  581. // EndHeaders indicates that this frame contains an entire
  582. // header block and is not followed by any
  583. // CONTINUATION frames.
  584. EndHeaders bool
  585. // PadLength is the optional number of bytes of zeros to add
  586. // to this frame.
  587. PadLength uint8
  588. // Priority, if non-zero, includes stream priority information
  589. // in the HEADER frame.
  590. Priority PriorityParam
  591. }
  592. // WriteHeaders writes a single HEADERS frame.
  593. //
  594. // This is a low-level header writing method. Encoding headers and
  595. // splitting them into any necessary CONTINUATION frames is handled
  596. // elsewhere.
  597. //
  598. // It will perform exactly one Write to the underlying Writer.
  599. // It is the caller's responsibility to not call other Write methods concurrently.
  600. func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
  601. var flags Flags
  602. if p.PadLength != 0 {
  603. flags |= FlagHeadersPadded
  604. }
  605. if p.EndStream {
  606. flags |= FlagHeadersEndStream
  607. }
  608. if p.EndHeaders {
  609. flags |= FlagHeadersEndHeaders
  610. }
  611. if !p.Priority.IsZero() {
  612. flags |= FlagHeadersPriority
  613. }
  614. f.startWrite(FrameHeaders, flags, p.StreamID)
  615. if p.PadLength != 0 {
  616. f.writeByte(p.PadLength)
  617. }
  618. if !p.Priority.IsZero() {
  619. v := p.Priority.StreamDep
  620. if !validStreamID(v) && !f.AllowIllegalWrites {
  621. return errors.New("invalid dependent stream id")
  622. }
  623. if p.Priority.ExclusiveDep {
  624. v |= 1 << 31
  625. }
  626. f.writeUint32(v)
  627. f.writeByte(p.Priority.Weight)
  628. }
  629. f.wbuf = append(f.wbuf, p.BlockFragment...)
  630. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  631. return f.endWrite()
  632. }
  633. // PriorityParam are the stream prioritzation parameters.
  634. type PriorityParam struct {
  635. // StreamDep is a 31-bit stream identifier for the
  636. // stream that this stream depends on. Zero means no
  637. // dependency.
  638. StreamDep uint32
  639. // ExclusiveDep is whether the dependency is exclusive.
  640. ExclusiveDep bool
  641. // Weight is the stream's weight. It should be set together
  642. // with StreamDep, or neither should be set.
  643. Weight uint8
  644. }
  645. func (p PriorityParam) IsZero() bool {
  646. return p == PriorityParam{}
  647. }
  648. // A RSTStreamFrame allows for abnormal termination of a stream.
  649. // See http://http2.github.io/http2-spec/#rfc.section.6.4
  650. type RSTStreamFrame struct {
  651. FrameHeader
  652. ErrCode uint32
  653. }
  654. func parseRSTStreamFrame(fh FrameHeader, p []byte) (Frame, error) {
  655. if fh.StreamID == 0 || len(p) < 4 {
  656. return nil, ConnectionError(ErrCodeProtocol)
  657. }
  658. return &RSTStreamFrame{fh, binary.BigEndian.Uint32(p[:4])}, nil
  659. }
  660. // WriteRSTStream writes a RST_STREAM frame.
  661. //
  662. // It will perform exactly one Write to the underlying Writer.
  663. // It is the caller's responsibility to not call other Write methods concurrently.
  664. func (f *Framer) WriteRSTStream(streamID, errCode uint32) error {
  665. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  666. return errStreamID
  667. }
  668. f.startWrite(FrameRSTStream, 0, streamID)
  669. f.writeUint32(errCode)
  670. return f.endWrite()
  671. }
  672. // A ContinuationFrame is used to continue a sequence of header block fragments.
  673. // See http://http2.github.io/http2-spec/#rfc.section.6.10
  674. type ContinuationFrame struct {
  675. FrameHeader
  676. headerFragBuf []byte
  677. }
  678. func parseContinuationFrame(fh FrameHeader, p []byte) (Frame, error) {
  679. return &ContinuationFrame{fh, p}, nil
  680. }
  681. func (f *ContinuationFrame) HeaderBlockFragment() []byte {
  682. f.checkValid()
  683. return f.headerFragBuf
  684. }
  685. func (f *ContinuationFrame) HeadersEnded() bool {
  686. return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
  687. }
  688. func readByte(p []byte) (remain []byte, b byte, err error) {
  689. if len(p) == 0 {
  690. return nil, 0, io.ErrUnexpectedEOF
  691. }
  692. return p[1:], p[0], nil
  693. }
  694. func readUint32(p []byte) (remain []byte, v uint32, err error) {
  695. if len(p) < 4 {
  696. return nil, 0, io.ErrUnexpectedEOF
  697. }
  698. return p[4:], binary.BigEndian.Uint32(p[:4]), nil
  699. }