You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1579 lines
44 KiB

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