frame.go 43 KB

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