frame.go 43 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544
  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. )
  532. func validStreamIDOrZero(streamID uint32) bool {
  533. return streamID&(1<<31) == 0
  534. }
  535. func validStreamID(streamID uint32) bool {
  536. return streamID != 0 && streamID&(1<<31) == 0
  537. }
  538. // WriteData writes a DATA frame.
  539. //
  540. // It will perform exactly one Write to the underlying Writer.
  541. // It is the caller's responsibility not to violate the maximum frame size
  542. // and to not call other Write methods concurrently.
  543. func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
  544. return f.WriteDataPadded(streamID, endStream, data, nil)
  545. }
  546. // WriteData writes a DATA frame with optional padding.
  547. //
  548. // If pad is nil, the padding bit is not sent.
  549. // The length of pad must not exceed 255 bytes.
  550. //
  551. // It will perform exactly one Write to the underlying Writer.
  552. // It is the caller's responsibility not to violate the maximum frame size
  553. // and to not call other Write methods concurrently.
  554. func (f *Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
  555. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  556. return errStreamID
  557. }
  558. if len(pad) > 255 {
  559. return errPadLength
  560. }
  561. var flags Flags
  562. if endStream {
  563. flags |= FlagDataEndStream
  564. }
  565. if pad != nil {
  566. flags |= FlagDataPadded
  567. }
  568. f.startWrite(FrameData, flags, streamID)
  569. if pad != nil {
  570. f.wbuf = append(f.wbuf, byte(len(pad)))
  571. }
  572. f.wbuf = append(f.wbuf, data...)
  573. f.wbuf = append(f.wbuf, pad...)
  574. return f.endWrite()
  575. }
  576. // A SettingsFrame conveys configuration parameters that affect how
  577. // endpoints communicate, such as preferences and constraints on peer
  578. // behavior.
  579. //
  580. // See http://http2.github.io/http2-spec/#SETTINGS
  581. type SettingsFrame struct {
  582. FrameHeader
  583. p []byte
  584. }
  585. func parseSettingsFrame(fh FrameHeader, p []byte) (Frame, error) {
  586. if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 {
  587. // When this (ACK 0x1) bit is set, the payload of the
  588. // SETTINGS frame MUST be empty. Receipt of a
  589. // SETTINGS frame with the ACK flag set and a length
  590. // field value other than 0 MUST be treated as a
  591. // connection error (Section 5.4.1) of type
  592. // FRAME_SIZE_ERROR.
  593. return nil, ConnectionError(ErrCodeFrameSize)
  594. }
  595. if fh.StreamID != 0 {
  596. // SETTINGS frames always apply to a connection,
  597. // never a single stream. The stream identifier for a
  598. // SETTINGS frame MUST be zero (0x0). If an endpoint
  599. // receives a SETTINGS frame whose stream identifier
  600. // field is anything other than 0x0, the endpoint MUST
  601. // respond with a connection error (Section 5.4.1) of
  602. // type PROTOCOL_ERROR.
  603. return nil, ConnectionError(ErrCodeProtocol)
  604. }
  605. if len(p)%6 != 0 {
  606. // Expecting even number of 6 byte settings.
  607. return nil, ConnectionError(ErrCodeFrameSize)
  608. }
  609. f := &SettingsFrame{FrameHeader: fh, p: p}
  610. if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 {
  611. // Values above the maximum flow control window size of 2^31 - 1 MUST
  612. // be treated as a connection error (Section 5.4.1) of type
  613. // FLOW_CONTROL_ERROR.
  614. return nil, ConnectionError(ErrCodeFlowControl)
  615. }
  616. return f, nil
  617. }
  618. func (f *SettingsFrame) IsAck() bool {
  619. return f.FrameHeader.Flags.Has(FlagSettingsAck)
  620. }
  621. func (f *SettingsFrame) Value(s SettingID) (v uint32, ok bool) {
  622. f.checkValid()
  623. buf := f.p
  624. for len(buf) > 0 {
  625. settingID := SettingID(binary.BigEndian.Uint16(buf[:2]))
  626. if settingID == s {
  627. return binary.BigEndian.Uint32(buf[2:6]), true
  628. }
  629. buf = buf[6:]
  630. }
  631. return 0, false
  632. }
  633. // ForeachSetting runs fn for each setting.
  634. // It stops and returns the first error.
  635. func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error {
  636. f.checkValid()
  637. buf := f.p
  638. for len(buf) > 0 {
  639. if err := fn(Setting{
  640. SettingID(binary.BigEndian.Uint16(buf[:2])),
  641. binary.BigEndian.Uint32(buf[2:6]),
  642. }); err != nil {
  643. return err
  644. }
  645. buf = buf[6:]
  646. }
  647. return nil
  648. }
  649. // WriteSettings writes a SETTINGS frame with zero or more settings
  650. // specified and the ACK bit not set.
  651. //
  652. // It will perform exactly one Write to the underlying Writer.
  653. // It is the caller's responsibility to not call other Write methods concurrently.
  654. func (f *Framer) WriteSettings(settings ...Setting) error {
  655. f.startWrite(FrameSettings, 0, 0)
  656. for _, s := range settings {
  657. f.writeUint16(uint16(s.ID))
  658. f.writeUint32(s.Val)
  659. }
  660. return f.endWrite()
  661. }
  662. // WriteSettingsAck writes an empty SETTINGS frame with the ACK bit 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) WriteSettingsAck() error {
  667. f.startWrite(FrameSettings, FlagSettingsAck, 0)
  668. return f.endWrite()
  669. }
  670. // A PingFrame is a mechanism for measuring a minimal round trip time
  671. // from the sender, as well as determining whether an idle connection
  672. // is still functional.
  673. // See http://http2.github.io/http2-spec/#rfc.section.6.7
  674. type PingFrame struct {
  675. FrameHeader
  676. Data [8]byte
  677. }
  678. func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) }
  679. func parsePingFrame(fh FrameHeader, payload []byte) (Frame, error) {
  680. if len(payload) != 8 {
  681. return nil, ConnectionError(ErrCodeFrameSize)
  682. }
  683. if fh.StreamID != 0 {
  684. return nil, ConnectionError(ErrCodeProtocol)
  685. }
  686. f := &PingFrame{FrameHeader: fh}
  687. copy(f.Data[:], payload)
  688. return f, nil
  689. }
  690. func (f *Framer) WritePing(ack bool, data [8]byte) error {
  691. var flags Flags
  692. if ack {
  693. flags = FlagPingAck
  694. }
  695. f.startWrite(FramePing, flags, 0)
  696. f.writeBytes(data[:])
  697. return f.endWrite()
  698. }
  699. // A GoAwayFrame informs the remote peer to stop creating streams on this connection.
  700. // See http://http2.github.io/http2-spec/#rfc.section.6.8
  701. type GoAwayFrame struct {
  702. FrameHeader
  703. LastStreamID uint32
  704. ErrCode ErrCode
  705. debugData []byte
  706. }
  707. // DebugData returns any debug data in the GOAWAY frame. Its contents
  708. // are not defined.
  709. // The caller must not retain the returned memory past the next
  710. // call to ReadFrame.
  711. func (f *GoAwayFrame) DebugData() []byte {
  712. f.checkValid()
  713. return f.debugData
  714. }
  715. func parseGoAwayFrame(fh FrameHeader, p []byte) (Frame, error) {
  716. if fh.StreamID != 0 {
  717. return nil, ConnectionError(ErrCodeProtocol)
  718. }
  719. if len(p) < 8 {
  720. return nil, ConnectionError(ErrCodeFrameSize)
  721. }
  722. return &GoAwayFrame{
  723. FrameHeader: fh,
  724. LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
  725. ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])),
  726. debugData: p[8:],
  727. }, nil
  728. }
  729. func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error {
  730. f.startWrite(FrameGoAway, 0, 0)
  731. f.writeUint32(maxStreamID & (1<<31 - 1))
  732. f.writeUint32(uint32(code))
  733. f.writeBytes(debugData)
  734. return f.endWrite()
  735. }
  736. // An UnknownFrame is the frame type returned when the frame type is unknown
  737. // or no specific frame type parser exists.
  738. type UnknownFrame struct {
  739. FrameHeader
  740. p []byte
  741. }
  742. // Payload returns the frame's payload (after the header). It is not
  743. // valid to call this method after a subsequent call to
  744. // Framer.ReadFrame, nor is it valid to retain the returned slice.
  745. // The memory is owned by the Framer and is invalidated when the next
  746. // frame is read.
  747. func (f *UnknownFrame) Payload() []byte {
  748. f.checkValid()
  749. return f.p
  750. }
  751. func parseUnknownFrame(fh FrameHeader, p []byte) (Frame, error) {
  752. return &UnknownFrame{fh, p}, nil
  753. }
  754. // A WindowUpdateFrame is used to implement flow control.
  755. // See http://http2.github.io/http2-spec/#rfc.section.6.9
  756. type WindowUpdateFrame struct {
  757. FrameHeader
  758. Increment uint32 // never read with high bit set
  759. }
  760. func parseWindowUpdateFrame(fh FrameHeader, p []byte) (Frame, error) {
  761. if len(p) != 4 {
  762. return nil, ConnectionError(ErrCodeFrameSize)
  763. }
  764. inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
  765. if inc == 0 {
  766. // A receiver MUST treat the receipt of a
  767. // WINDOW_UPDATE frame with an flow control window
  768. // increment of 0 as a stream error (Section 5.4.2) of
  769. // type PROTOCOL_ERROR; errors on the connection flow
  770. // control window MUST be treated as a connection
  771. // error (Section 5.4.1).
  772. if fh.StreamID == 0 {
  773. return nil, ConnectionError(ErrCodeProtocol)
  774. }
  775. return nil, streamError(fh.StreamID, ErrCodeProtocol)
  776. }
  777. return &WindowUpdateFrame{
  778. FrameHeader: fh,
  779. Increment: inc,
  780. }, nil
  781. }
  782. // WriteWindowUpdate writes a WINDOW_UPDATE frame.
  783. // The increment value must be between 1 and 2,147,483,647, inclusive.
  784. // If the Stream ID is zero, the window update applies to the
  785. // connection as a whole.
  786. func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error {
  787. // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
  788. if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
  789. return errors.New("illegal window increment value")
  790. }
  791. f.startWrite(FrameWindowUpdate, 0, streamID)
  792. f.writeUint32(incr)
  793. return f.endWrite()
  794. }
  795. // A HeadersFrame is used to open a stream and additionally carries a
  796. // header block fragment.
  797. type HeadersFrame struct {
  798. FrameHeader
  799. // Priority is set if FlagHeadersPriority is set in the FrameHeader.
  800. Priority PriorityParam
  801. headerFragBuf []byte // not owned
  802. }
  803. func (f *HeadersFrame) HeaderBlockFragment() []byte {
  804. f.checkValid()
  805. return f.headerFragBuf
  806. }
  807. func (f *HeadersFrame) HeadersEnded() bool {
  808. return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
  809. }
  810. func (f *HeadersFrame) StreamEnded() bool {
  811. return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
  812. }
  813. func (f *HeadersFrame) HasPriority() bool {
  814. return f.FrameHeader.Flags.Has(FlagHeadersPriority)
  815. }
  816. func parseHeadersFrame(fh FrameHeader, p []byte) (_ Frame, err error) {
  817. hf := &HeadersFrame{
  818. FrameHeader: fh,
  819. }
  820. if fh.StreamID == 0 {
  821. // HEADERS frames MUST be associated with a stream. If a HEADERS frame
  822. // is received whose stream identifier field is 0x0, the recipient MUST
  823. // respond with a connection error (Section 5.4.1) of type
  824. // PROTOCOL_ERROR.
  825. return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"}
  826. }
  827. var padLength uint8
  828. if fh.Flags.Has(FlagHeadersPadded) {
  829. if p, padLength, err = readByte(p); err != nil {
  830. return
  831. }
  832. }
  833. if fh.Flags.Has(FlagHeadersPriority) {
  834. var v uint32
  835. p, v, err = readUint32(p)
  836. if err != nil {
  837. return nil, err
  838. }
  839. hf.Priority.StreamDep = v & 0x7fffffff
  840. hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
  841. p, hf.Priority.Weight, err = readByte(p)
  842. if err != nil {
  843. return nil, err
  844. }
  845. }
  846. if len(p)-int(padLength) <= 0 {
  847. return nil, streamError(fh.StreamID, ErrCodeProtocol)
  848. }
  849. hf.headerFragBuf = p[:len(p)-int(padLength)]
  850. return hf, nil
  851. }
  852. // HeadersFrameParam are the parameters for writing a HEADERS frame.
  853. type HeadersFrameParam struct {
  854. // StreamID is the required Stream ID to initiate.
  855. StreamID uint32
  856. // BlockFragment is part (or all) of a Header Block.
  857. BlockFragment []byte
  858. // EndStream indicates that the header block is the last that
  859. // the endpoint will send for the identified stream. Setting
  860. // this flag causes the stream to enter one of "half closed"
  861. // states.
  862. EndStream bool
  863. // EndHeaders indicates that this frame contains an entire
  864. // header block and is not followed by any
  865. // CONTINUATION frames.
  866. EndHeaders bool
  867. // PadLength is the optional number of bytes of zeros to add
  868. // to this frame.
  869. PadLength uint8
  870. // Priority, if non-zero, includes stream priority information
  871. // in the HEADER frame.
  872. Priority PriorityParam
  873. }
  874. // WriteHeaders writes a single HEADERS frame.
  875. //
  876. // This is a low-level header writing method. Encoding headers and
  877. // splitting them into any necessary CONTINUATION frames is handled
  878. // elsewhere.
  879. //
  880. // It will perform exactly one Write to the underlying Writer.
  881. // It is the caller's responsibility to not call other Write methods concurrently.
  882. func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
  883. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  884. return errStreamID
  885. }
  886. var flags Flags
  887. if p.PadLength != 0 {
  888. flags |= FlagHeadersPadded
  889. }
  890. if p.EndStream {
  891. flags |= FlagHeadersEndStream
  892. }
  893. if p.EndHeaders {
  894. flags |= FlagHeadersEndHeaders
  895. }
  896. if !p.Priority.IsZero() {
  897. flags |= FlagHeadersPriority
  898. }
  899. f.startWrite(FrameHeaders, flags, p.StreamID)
  900. if p.PadLength != 0 {
  901. f.writeByte(p.PadLength)
  902. }
  903. if !p.Priority.IsZero() {
  904. v := p.Priority.StreamDep
  905. if !validStreamIDOrZero(v) && !f.AllowIllegalWrites {
  906. return errDepStreamID
  907. }
  908. if p.Priority.Exclusive {
  909. v |= 1 << 31
  910. }
  911. f.writeUint32(v)
  912. f.writeByte(p.Priority.Weight)
  913. }
  914. f.wbuf = append(f.wbuf, p.BlockFragment...)
  915. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  916. return f.endWrite()
  917. }
  918. // A PriorityFrame specifies the sender-advised priority of a stream.
  919. // See http://http2.github.io/http2-spec/#rfc.section.6.3
  920. type PriorityFrame struct {
  921. FrameHeader
  922. PriorityParam
  923. }
  924. // PriorityParam are the stream prioritzation parameters.
  925. type PriorityParam struct {
  926. // StreamDep is a 31-bit stream identifier for the
  927. // stream that this stream depends on. Zero means no
  928. // dependency.
  929. StreamDep uint32
  930. // Exclusive is whether the dependency is exclusive.
  931. Exclusive bool
  932. // Weight is the stream's zero-indexed weight. It should be
  933. // set together with StreamDep, or neither should be set. Per
  934. // the spec, "Add one to the value to obtain a weight between
  935. // 1 and 256."
  936. Weight uint8
  937. }
  938. func (p PriorityParam) IsZero() bool {
  939. return p == PriorityParam{}
  940. }
  941. func parsePriorityFrame(fh FrameHeader, payload []byte) (Frame, error) {
  942. if fh.StreamID == 0 {
  943. return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"}
  944. }
  945. if len(payload) != 5 {
  946. return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))}
  947. }
  948. v := binary.BigEndian.Uint32(payload[:4])
  949. streamID := v & 0x7fffffff // mask off high bit
  950. return &PriorityFrame{
  951. FrameHeader: fh,
  952. PriorityParam: PriorityParam{
  953. Weight: payload[4],
  954. StreamDep: streamID,
  955. Exclusive: streamID != v, // was high bit set?
  956. },
  957. }, nil
  958. }
  959. // WritePriority writes a PRIORITY frame.
  960. //
  961. // It will perform exactly one Write to the underlying Writer.
  962. // It is the caller's responsibility to not call other Write methods concurrently.
  963. func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error {
  964. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  965. return errStreamID
  966. }
  967. if !validStreamIDOrZero(p.StreamDep) {
  968. return errDepStreamID
  969. }
  970. f.startWrite(FramePriority, 0, streamID)
  971. v := p.StreamDep
  972. if p.Exclusive {
  973. v |= 1 << 31
  974. }
  975. f.writeUint32(v)
  976. f.writeByte(p.Weight)
  977. return f.endWrite()
  978. }
  979. // A RSTStreamFrame allows for abnormal termination of a stream.
  980. // See http://http2.github.io/http2-spec/#rfc.section.6.4
  981. type RSTStreamFrame struct {
  982. FrameHeader
  983. ErrCode ErrCode
  984. }
  985. func parseRSTStreamFrame(fh FrameHeader, p []byte) (Frame, error) {
  986. if len(p) != 4 {
  987. return nil, ConnectionError(ErrCodeFrameSize)
  988. }
  989. if fh.StreamID == 0 {
  990. return nil, ConnectionError(ErrCodeProtocol)
  991. }
  992. return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
  993. }
  994. // WriteRSTStream writes a RST_STREAM frame.
  995. //
  996. // It will perform exactly one Write to the underlying Writer.
  997. // It is the caller's responsibility to not call other Write methods concurrently.
  998. func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
  999. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  1000. return errStreamID
  1001. }
  1002. f.startWrite(FrameRSTStream, 0, streamID)
  1003. f.writeUint32(uint32(code))
  1004. return f.endWrite()
  1005. }
  1006. // A ContinuationFrame is used to continue a sequence of header block fragments.
  1007. // See http://http2.github.io/http2-spec/#rfc.section.6.10
  1008. type ContinuationFrame struct {
  1009. FrameHeader
  1010. headerFragBuf []byte
  1011. }
  1012. func parseContinuationFrame(fh FrameHeader, p []byte) (Frame, error) {
  1013. if fh.StreamID == 0 {
  1014. return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"}
  1015. }
  1016. return &ContinuationFrame{fh, p}, nil
  1017. }
  1018. func (f *ContinuationFrame) HeaderBlockFragment() []byte {
  1019. f.checkValid()
  1020. return f.headerFragBuf
  1021. }
  1022. func (f *ContinuationFrame) HeadersEnded() bool {
  1023. return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
  1024. }
  1025. // WriteContinuation writes a CONTINUATION frame.
  1026. //
  1027. // It will perform exactly one Write to the underlying Writer.
  1028. // It is the caller's responsibility to not call other Write methods concurrently.
  1029. func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
  1030. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  1031. return errStreamID
  1032. }
  1033. var flags Flags
  1034. if endHeaders {
  1035. flags |= FlagContinuationEndHeaders
  1036. }
  1037. f.startWrite(FrameContinuation, flags, streamID)
  1038. f.wbuf = append(f.wbuf, headerBlockFragment...)
  1039. return f.endWrite()
  1040. }
  1041. // A PushPromiseFrame is used to initiate a server stream.
  1042. // See http://http2.github.io/http2-spec/#rfc.section.6.6
  1043. type PushPromiseFrame struct {
  1044. FrameHeader
  1045. PromiseID uint32
  1046. headerFragBuf []byte // not owned
  1047. }
  1048. func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
  1049. f.checkValid()
  1050. return f.headerFragBuf
  1051. }
  1052. func (f *PushPromiseFrame) HeadersEnded() bool {
  1053. return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
  1054. }
  1055. func parsePushPromise(fh FrameHeader, p []byte) (_ Frame, err error) {
  1056. pp := &PushPromiseFrame{
  1057. FrameHeader: fh,
  1058. }
  1059. if pp.StreamID == 0 {
  1060. // PUSH_PROMISE frames MUST be associated with an existing,
  1061. // peer-initiated stream. The stream identifier of a
  1062. // PUSH_PROMISE frame indicates the stream it is associated
  1063. // with. If the stream identifier field specifies the value
  1064. // 0x0, a recipient MUST respond with a connection error
  1065. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1066. return nil, ConnectionError(ErrCodeProtocol)
  1067. }
  1068. // The PUSH_PROMISE frame includes optional padding.
  1069. // Padding fields and flags are identical to those defined for DATA frames
  1070. var padLength uint8
  1071. if fh.Flags.Has(FlagPushPromisePadded) {
  1072. if p, padLength, err = readByte(p); err != nil {
  1073. return
  1074. }
  1075. }
  1076. p, pp.PromiseID, err = readUint32(p)
  1077. if err != nil {
  1078. return
  1079. }
  1080. pp.PromiseID = pp.PromiseID & (1<<31 - 1)
  1081. if int(padLength) > len(p) {
  1082. // like the DATA frame, error out if padding is longer than the body.
  1083. return nil, ConnectionError(ErrCodeProtocol)
  1084. }
  1085. pp.headerFragBuf = p[:len(p)-int(padLength)]
  1086. return pp, nil
  1087. }
  1088. // PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
  1089. type PushPromiseParam struct {
  1090. // StreamID is the required Stream ID to initiate.
  1091. StreamID uint32
  1092. // PromiseID is the required Stream ID which this
  1093. // Push Promises
  1094. PromiseID uint32
  1095. // BlockFragment is part (or all) of a Header Block.
  1096. BlockFragment []byte
  1097. // EndHeaders indicates that this frame contains an entire
  1098. // header block and is not followed by any
  1099. // CONTINUATION frames.
  1100. EndHeaders bool
  1101. // PadLength is the optional number of bytes of zeros to add
  1102. // to this frame.
  1103. PadLength uint8
  1104. }
  1105. // WritePushPromise writes a single PushPromise Frame.
  1106. //
  1107. // As with Header Frames, This is the low level call for writing
  1108. // individual frames. Continuation frames are handled elsewhere.
  1109. //
  1110. // It will perform exactly one Write to the underlying Writer.
  1111. // It is the caller's responsibility to not call other Write methods concurrently.
  1112. func (f *Framer) WritePushPromise(p PushPromiseParam) error {
  1113. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  1114. return errStreamID
  1115. }
  1116. var flags Flags
  1117. if p.PadLength != 0 {
  1118. flags |= FlagPushPromisePadded
  1119. }
  1120. if p.EndHeaders {
  1121. flags |= FlagPushPromiseEndHeaders
  1122. }
  1123. f.startWrite(FramePushPromise, flags, p.StreamID)
  1124. if p.PadLength != 0 {
  1125. f.writeByte(p.PadLength)
  1126. }
  1127. if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
  1128. return errStreamID
  1129. }
  1130. f.writeUint32(p.PromiseID)
  1131. f.wbuf = append(f.wbuf, p.BlockFragment...)
  1132. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  1133. return f.endWrite()
  1134. }
  1135. // WriteRawFrame writes a raw frame. This can be used to write
  1136. // extension frames unknown to this package.
  1137. func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
  1138. f.startWrite(t, flags, streamID)
  1139. f.writeBytes(payload)
  1140. return f.endWrite()
  1141. }
  1142. func readByte(p []byte) (remain []byte, b byte, err error) {
  1143. if len(p) == 0 {
  1144. return nil, 0, io.ErrUnexpectedEOF
  1145. }
  1146. return p[1:], p[0], nil
  1147. }
  1148. func readUint32(p []byte) (remain []byte, v uint32, err error) {
  1149. if len(p) < 4 {
  1150. return nil, 0, io.ErrUnexpectedEOF
  1151. }
  1152. return p[4:], binary.BigEndian.Uint32(p[:4]), nil
  1153. }
  1154. type streamEnder interface {
  1155. StreamEnded() bool
  1156. }
  1157. type headersEnder interface {
  1158. HeadersEnded() bool
  1159. }
  1160. type headersOrContinuation interface {
  1161. headersEnder
  1162. HeaderBlockFragment() []byte
  1163. }
  1164. // A MetaHeadersFrame is the representation of one HEADERS frame and
  1165. // zero or more contiguous CONTINUATION frames and the decoding of
  1166. // their HPACK-encoded contents.
  1167. //
  1168. // This type of frame does not appear on the wire and is only returned
  1169. // by the Framer when Framer.ReadMetaHeaders is set.
  1170. type MetaHeadersFrame struct {
  1171. *HeadersFrame
  1172. // Fields are the fields contained in the HEADERS and
  1173. // CONTINUATION frames. The underlying slice is owned by the
  1174. // Framer and must not be retained after the next call to
  1175. // ReadFrame.
  1176. //
  1177. // Fields are guaranteed to be in the correct http2 order and
  1178. // not have unknown pseudo header fields or invalid header
  1179. // field names or values. Required pseudo header fields may be
  1180. // missing, however. Use the MetaHeadersFrame.Pseudo accessor
  1181. // method access pseudo headers.
  1182. Fields []hpack.HeaderField
  1183. // Truncated is whether the max header list size limit was hit
  1184. // and Fields is incomplete. The hpack decoder state is still
  1185. // valid, however.
  1186. Truncated bool
  1187. }
  1188. // PseudoValue returns the given pseudo header field's value.
  1189. // The provided pseudo field should not contain the leading colon.
  1190. func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string {
  1191. for _, hf := range mh.Fields {
  1192. if !hf.IsPseudo() {
  1193. return ""
  1194. }
  1195. if hf.Name[1:] == pseudo {
  1196. return hf.Value
  1197. }
  1198. }
  1199. return ""
  1200. }
  1201. // RegularFields returns the regular (non-pseudo) header fields of mh.
  1202. // The caller does not own the returned slice.
  1203. func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField {
  1204. for i, hf := range mh.Fields {
  1205. if !hf.IsPseudo() {
  1206. return mh.Fields[i:]
  1207. }
  1208. }
  1209. return nil
  1210. }
  1211. // PseudoFields returns the pseudo header fields of mh.
  1212. // The caller does not own the returned slice.
  1213. func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField {
  1214. for i, hf := range mh.Fields {
  1215. if !hf.IsPseudo() {
  1216. return mh.Fields[:i]
  1217. }
  1218. }
  1219. return mh.Fields
  1220. }
  1221. func (mh *MetaHeadersFrame) checkPseudos() error {
  1222. var isRequest, isResponse bool
  1223. pf := mh.PseudoFields()
  1224. for i, hf := range pf {
  1225. switch hf.Name {
  1226. case ":method", ":path", ":scheme", ":authority":
  1227. isRequest = true
  1228. case ":status":
  1229. isResponse = true
  1230. default:
  1231. return pseudoHeaderError(hf.Name)
  1232. }
  1233. // Check for duplicates.
  1234. // This would be a bad algorithm, but N is 4.
  1235. // And this doesn't allocate.
  1236. for _, hf2 := range pf[:i] {
  1237. if hf.Name == hf2.Name {
  1238. return duplicatePseudoHeaderError(hf.Name)
  1239. }
  1240. }
  1241. }
  1242. if isRequest && isResponse {
  1243. return errMixPseudoHeaderTypes
  1244. }
  1245. return nil
  1246. }
  1247. func (fr *Framer) maxHeaderStringLen() int {
  1248. v := fr.maxHeaderListSize()
  1249. if uint32(int(v)) == v {
  1250. return int(v)
  1251. }
  1252. // They had a crazy big number for MaxHeaderBytes anyway,
  1253. // so give them unlimited header lengths:
  1254. return 0
  1255. }
  1256. // readMetaFrame returns 0 or more CONTINUATION frames from fr and
  1257. // merge them into into the provided hf and returns a MetaHeadersFrame
  1258. // with the decoded hpack values.
  1259. func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) {
  1260. if fr.AllowIllegalReads {
  1261. return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders")
  1262. }
  1263. mh := &MetaHeadersFrame{
  1264. HeadersFrame: hf,
  1265. }
  1266. var remainSize = fr.maxHeaderListSize()
  1267. var sawRegular bool
  1268. var invalid error // pseudo header field errors
  1269. hdec := fr.ReadMetaHeaders
  1270. hdec.SetEmitEnabled(true)
  1271. hdec.SetMaxStringLength(fr.maxHeaderStringLen())
  1272. hdec.SetEmitFunc(func(hf hpack.HeaderField) {
  1273. if VerboseLogs && fr.logReads {
  1274. fr.debugReadLoggerf("http2: decoded hpack field %+v", hf)
  1275. }
  1276. if !httplex.ValidHeaderFieldValue(hf.Value) {
  1277. invalid = headerFieldValueError(hf.Value)
  1278. }
  1279. isPseudo := strings.HasPrefix(hf.Name, ":")
  1280. if isPseudo {
  1281. if sawRegular {
  1282. invalid = errPseudoAfterRegular
  1283. }
  1284. } else {
  1285. sawRegular = true
  1286. if !validWireHeaderFieldName(hf.Name) {
  1287. invalid = headerFieldNameError(hf.Name)
  1288. }
  1289. }
  1290. if invalid != nil {
  1291. hdec.SetEmitEnabled(false)
  1292. return
  1293. }
  1294. size := hf.Size()
  1295. if size > remainSize {
  1296. hdec.SetEmitEnabled(false)
  1297. mh.Truncated = true
  1298. return
  1299. }
  1300. remainSize -= size
  1301. mh.Fields = append(mh.Fields, hf)
  1302. })
  1303. // Lose reference to MetaHeadersFrame:
  1304. defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {})
  1305. var hc headersOrContinuation = hf
  1306. for {
  1307. frag := hc.HeaderBlockFragment()
  1308. if _, err := hdec.Write(frag); err != nil {
  1309. return nil, ConnectionError(ErrCodeCompression)
  1310. }
  1311. if hc.HeadersEnded() {
  1312. break
  1313. }
  1314. if f, err := fr.ReadFrame(); err != nil {
  1315. return nil, err
  1316. } else {
  1317. hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder
  1318. }
  1319. }
  1320. mh.HeadersFrame.headerFragBuf = nil
  1321. mh.HeadersFrame.invalidate()
  1322. if err := hdec.Close(); err != nil {
  1323. return nil, ConnectionError(ErrCodeCompression)
  1324. }
  1325. if invalid != nil {
  1326. fr.errDetail = invalid
  1327. if VerboseLogs {
  1328. log.Printf("http2: invalid header: %v", invalid)
  1329. }
  1330. return nil, StreamError{mh.StreamID, ErrCodeProtocol, invalid}
  1331. }
  1332. if err := mh.checkPseudos(); err != nil {
  1333. fr.errDetail = err
  1334. if VerboseLogs {
  1335. log.Printf("http2: invalid pseudo headers: %v", err)
  1336. }
  1337. return nil, StreamError{mh.StreamID, ErrCodeProtocol, err}
  1338. }
  1339. return mh, nil
  1340. }
  1341. func summarizeFrame(f Frame) string {
  1342. var buf bytes.Buffer
  1343. f.Header().writeDebug(&buf)
  1344. switch f := f.(type) {
  1345. case *SettingsFrame:
  1346. n := 0
  1347. f.ForeachSetting(func(s Setting) error {
  1348. n++
  1349. if n == 1 {
  1350. buf.WriteString(", settings:")
  1351. }
  1352. fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val)
  1353. return nil
  1354. })
  1355. if n > 0 {
  1356. buf.Truncate(buf.Len() - 1) // remove trailing comma
  1357. }
  1358. case *DataFrame:
  1359. data := f.Data()
  1360. const max = 256
  1361. if len(data) > max {
  1362. data = data[:max]
  1363. }
  1364. fmt.Fprintf(&buf, " data=%q", data)
  1365. if len(f.Data()) > max {
  1366. fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max)
  1367. }
  1368. case *WindowUpdateFrame:
  1369. if f.StreamID == 0 {
  1370. buf.WriteString(" (conn)")
  1371. }
  1372. fmt.Fprintf(&buf, " incr=%v", f.Increment)
  1373. case *PingFrame:
  1374. fmt.Fprintf(&buf, " ping=%q", f.Data[:])
  1375. case *GoAwayFrame:
  1376. fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q",
  1377. f.LastStreamID, f.ErrCode, f.debugData)
  1378. case *RSTStreamFrame:
  1379. fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode)
  1380. }
  1381. return buf.String()
  1382. }