frame.go 42 KB

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