frame.go 47 KB

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