frame.go 33 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189
  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) HeaderBlockFragment() []byte {
  918. f.checkValid()
  919. return f.headerFragBuf
  920. }
  921. func (f *ContinuationFrame) HeadersEnded() bool {
  922. return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
  923. }
  924. // WriteContinuation writes a CONTINUATION frame.
  925. //
  926. // It will perform exactly one Write to the underlying Writer.
  927. // It is the caller's responsibility to not call other Write methods concurrently.
  928. func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
  929. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  930. return errStreamID
  931. }
  932. var flags Flags
  933. if endHeaders {
  934. flags |= FlagContinuationEndHeaders
  935. }
  936. f.startWrite(FrameContinuation, flags, streamID)
  937. f.wbuf = append(f.wbuf, headerBlockFragment...)
  938. return f.endWrite()
  939. }
  940. // A PushPromiseFrame is used to initiate a server stream.
  941. // See http://http2.github.io/http2-spec/#rfc.section.6.6
  942. type PushPromiseFrame struct {
  943. FrameHeader
  944. PromiseID uint32
  945. headerFragBuf []byte // not owned
  946. }
  947. func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
  948. f.checkValid()
  949. return f.headerFragBuf
  950. }
  951. func (f *PushPromiseFrame) HeadersEnded() bool {
  952. return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
  953. }
  954. func parsePushPromise(fh FrameHeader, p []byte) (_ Frame, err error) {
  955. pp := &PushPromiseFrame{
  956. FrameHeader: fh,
  957. }
  958. if pp.StreamID == 0 {
  959. // PUSH_PROMISE frames MUST be associated with an existing,
  960. // peer-initiated stream. The stream identifier of a
  961. // PUSH_PROMISE frame indicates the stream it is associated
  962. // with. If the stream identifier field specifies the value
  963. // 0x0, a recipient MUST respond with a connection error
  964. // (Section 5.4.1) of type PROTOCOL_ERROR.
  965. return nil, ConnectionError(ErrCodeProtocol)
  966. }
  967. // The PUSH_PROMISE frame includes optional padding.
  968. // Padding fields and flags are identical to those defined for DATA frames
  969. var padLength uint8
  970. if fh.Flags.Has(FlagPushPromisePadded) {
  971. if p, padLength, err = readByte(p); err != nil {
  972. return
  973. }
  974. }
  975. p, pp.PromiseID, err = readUint32(p)
  976. if err != nil {
  977. return
  978. }
  979. pp.PromiseID = pp.PromiseID & (1<<31 - 1)
  980. if int(padLength) > len(p) {
  981. // like the DATA frame, error out if padding is longer than the body.
  982. return nil, ConnectionError(ErrCodeProtocol)
  983. }
  984. pp.headerFragBuf = p[:len(p)-int(padLength)]
  985. return pp, nil
  986. }
  987. // PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
  988. type PushPromiseParam struct {
  989. // StreamID is the required Stream ID to initiate.
  990. StreamID uint32
  991. // PromiseID is the required Stream ID which this
  992. // Push Promises
  993. PromiseID uint32
  994. // BlockFragment is part (or all) of a Header Block.
  995. BlockFragment []byte
  996. // EndHeaders indicates that this frame contains an entire
  997. // header block and is not followed by any
  998. // CONTINUATION frames.
  999. EndHeaders bool
  1000. // PadLength is the optional number of bytes of zeros to add
  1001. // to this frame.
  1002. PadLength uint8
  1003. }
  1004. // WritePushPromise writes a single PushPromise Frame.
  1005. //
  1006. // As with Header Frames, This is the low level call for writing
  1007. // individual frames. Continuation frames are handled elsewhere.
  1008. //
  1009. // It will perform exactly one Write to the underlying Writer.
  1010. // It is the caller's responsibility to not call other Write methods concurrently.
  1011. func (f *Framer) WritePushPromise(p PushPromiseParam) error {
  1012. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  1013. return errStreamID
  1014. }
  1015. var flags Flags
  1016. if p.PadLength != 0 {
  1017. flags |= FlagPushPromisePadded
  1018. }
  1019. if p.EndHeaders {
  1020. flags |= FlagPushPromiseEndHeaders
  1021. }
  1022. f.startWrite(FramePushPromise, flags, p.StreamID)
  1023. if p.PadLength != 0 {
  1024. f.writeByte(p.PadLength)
  1025. }
  1026. if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
  1027. return errStreamID
  1028. }
  1029. f.writeUint32(p.PromiseID)
  1030. f.wbuf = append(f.wbuf, p.BlockFragment...)
  1031. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  1032. return f.endWrite()
  1033. }
  1034. // WriteRawFrame writes a raw frame. This can be used to write
  1035. // extension frames unknown to this package.
  1036. func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
  1037. f.startWrite(t, flags, streamID)
  1038. f.writeBytes(payload)
  1039. return f.endWrite()
  1040. }
  1041. func readByte(p []byte) (remain []byte, b byte, err error) {
  1042. if len(p) == 0 {
  1043. return nil, 0, io.ErrUnexpectedEOF
  1044. }
  1045. return p[1:], p[0], nil
  1046. }
  1047. func readUint32(p []byte) (remain []byte, v uint32, err error) {
  1048. if len(p) < 4 {
  1049. return nil, 0, io.ErrUnexpectedEOF
  1050. }
  1051. return p[4:], binary.BigEndian.Uint32(p[:4]), nil
  1052. }
  1053. type streamEnder interface {
  1054. StreamEnded() bool
  1055. }
  1056. type headersEnder interface {
  1057. HeadersEnded() bool
  1058. }