frame.go 42 KB

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