frame.go 35 KB

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