frame.go 49 KB

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