frame.go 35 KB

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