frame.go 41 KB

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