frame.go 33 KB

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