frame.go 43 KB

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