frame.go 47 KB

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