frame.go 41 KB

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