Du kannst nicht mehr als 25 Themen auswählen Themen müssen entweder mit einem Buchstaben oder einer Ziffer beginnen. Sie können Bindestriche („-“) enthalten und bis zu 35 Zeichen lang sein.
 
 
 

1615 Zeilen
45 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/http/httpguts"
  15. "golang.org/x/net/http2/hpack"
  16. )
  17. const frameHeaderLen = 9
  18. var padZeros = make([]byte, 255) // zeros for padding
  19. // A FrameType is a registered frame type as defined in
  20. // 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. // WriteDataPadded 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(id SettingID) (v uint32, ok bool) {
  652. f.checkValid()
  653. for i := 0; i < f.NumSettings(); i++ {
  654. if s := f.Setting(i); s.ID == id {
  655. return s.Val, true
  656. }
  657. }
  658. return 0, false
  659. }
  660. // Setting returns the setting from the frame at the given 0-based index.
  661. // The index must be >= 0 and less than f.NumSettings().
  662. func (f *SettingsFrame) Setting(i int) Setting {
  663. buf := f.p
  664. return Setting{
  665. ID: SettingID(binary.BigEndian.Uint16(buf[i*6 : i*6+2])),
  666. Val: binary.BigEndian.Uint32(buf[i*6+2 : i*6+6]),
  667. }
  668. }
  669. func (f *SettingsFrame) NumSettings() int { return len(f.p) / 6 }
  670. // HasDuplicates reports whether f contains any duplicate setting IDs.
  671. func (f *SettingsFrame) HasDuplicates() bool {
  672. num := f.NumSettings()
  673. if num == 0 {
  674. return false
  675. }
  676. // If it's small enough (the common case), just do the n^2
  677. // thing and avoid a map allocation.
  678. if num < 10 {
  679. for i := 0; i < num; i++ {
  680. idi := f.Setting(i).ID
  681. for j := i + 1; j < num; j++ {
  682. idj := f.Setting(j).ID
  683. if idi == idj {
  684. return true
  685. }
  686. }
  687. }
  688. return false
  689. }
  690. seen := map[SettingID]bool{}
  691. for i := 0; i < num; i++ {
  692. id := f.Setting(i).ID
  693. if seen[id] {
  694. return true
  695. }
  696. seen[id] = true
  697. }
  698. return false
  699. }
  700. // ForeachSetting runs fn for each setting.
  701. // It stops and returns the first error.
  702. func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error {
  703. f.checkValid()
  704. for i := 0; i < f.NumSettings(); i++ {
  705. if err := fn(f.Setting(i)); err != nil {
  706. return err
  707. }
  708. }
  709. return nil
  710. }
  711. // WriteSettings writes a SETTINGS frame with zero or more settings
  712. // specified and the ACK bit not set.
  713. //
  714. // It will perform exactly one Write to the underlying Writer.
  715. // It is the caller's responsibility to not call other Write methods concurrently.
  716. func (f *Framer) WriteSettings(settings ...Setting) error {
  717. f.startWrite(FrameSettings, 0, 0)
  718. for _, s := range settings {
  719. f.writeUint16(uint16(s.ID))
  720. f.writeUint32(s.Val)
  721. }
  722. return f.endWrite()
  723. }
  724. // WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set.
  725. //
  726. // It will perform exactly one Write to the underlying Writer.
  727. // It is the caller's responsibility to not call other Write methods concurrently.
  728. func (f *Framer) WriteSettingsAck() error {
  729. f.startWrite(FrameSettings, FlagSettingsAck, 0)
  730. return f.endWrite()
  731. }
  732. // A PingFrame is a mechanism for measuring a minimal round trip time
  733. // from the sender, as well as determining whether an idle connection
  734. // is still functional.
  735. // See http://http2.github.io/http2-spec/#rfc.section.6.7
  736. type PingFrame struct {
  737. FrameHeader
  738. Data [8]byte
  739. }
  740. func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) }
  741. func parsePingFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
  742. if len(payload) != 8 {
  743. return nil, ConnectionError(ErrCodeFrameSize)
  744. }
  745. if fh.StreamID != 0 {
  746. return nil, ConnectionError(ErrCodeProtocol)
  747. }
  748. f := &PingFrame{FrameHeader: fh}
  749. copy(f.Data[:], payload)
  750. return f, nil
  751. }
  752. func (f *Framer) WritePing(ack bool, data [8]byte) error {
  753. var flags Flags
  754. if ack {
  755. flags = FlagPingAck
  756. }
  757. f.startWrite(FramePing, flags, 0)
  758. f.writeBytes(data[:])
  759. return f.endWrite()
  760. }
  761. // A GoAwayFrame informs the remote peer to stop creating streams on this connection.
  762. // See http://http2.github.io/http2-spec/#rfc.section.6.8
  763. type GoAwayFrame struct {
  764. FrameHeader
  765. LastStreamID uint32
  766. ErrCode ErrCode
  767. debugData []byte
  768. }
  769. // DebugData returns any debug data in the GOAWAY frame. Its contents
  770. // are not defined.
  771. // The caller must not retain the returned memory past the next
  772. // call to ReadFrame.
  773. func (f *GoAwayFrame) DebugData() []byte {
  774. f.checkValid()
  775. return f.debugData
  776. }
  777. func parseGoAwayFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
  778. if fh.StreamID != 0 {
  779. return nil, ConnectionError(ErrCodeProtocol)
  780. }
  781. if len(p) < 8 {
  782. return nil, ConnectionError(ErrCodeFrameSize)
  783. }
  784. return &GoAwayFrame{
  785. FrameHeader: fh,
  786. LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
  787. ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])),
  788. debugData: p[8:],
  789. }, nil
  790. }
  791. func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error {
  792. f.startWrite(FrameGoAway, 0, 0)
  793. f.writeUint32(maxStreamID & (1<<31 - 1))
  794. f.writeUint32(uint32(code))
  795. f.writeBytes(debugData)
  796. return f.endWrite()
  797. }
  798. // An UnknownFrame is the frame type returned when the frame type is unknown
  799. // or no specific frame type parser exists.
  800. type UnknownFrame struct {
  801. FrameHeader
  802. p []byte
  803. }
  804. // Payload returns the frame's payload (after the header). It is not
  805. // valid to call this method after a subsequent call to
  806. // Framer.ReadFrame, nor is it valid to retain the returned slice.
  807. // The memory is owned by the Framer and is invalidated when the next
  808. // frame is read.
  809. func (f *UnknownFrame) Payload() []byte {
  810. f.checkValid()
  811. return f.p
  812. }
  813. func parseUnknownFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
  814. return &UnknownFrame{fh, p}, nil
  815. }
  816. // A WindowUpdateFrame is used to implement flow control.
  817. // See http://http2.github.io/http2-spec/#rfc.section.6.9
  818. type WindowUpdateFrame struct {
  819. FrameHeader
  820. Increment uint32 // never read with high bit set
  821. }
  822. func parseWindowUpdateFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
  823. if len(p) != 4 {
  824. return nil, ConnectionError(ErrCodeFrameSize)
  825. }
  826. inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
  827. if inc == 0 {
  828. // A receiver MUST treat the receipt of a
  829. // WINDOW_UPDATE frame with an flow control window
  830. // increment of 0 as a stream error (Section 5.4.2) of
  831. // type PROTOCOL_ERROR; errors on the connection flow
  832. // control window MUST be treated as a connection
  833. // error (Section 5.4.1).
  834. if fh.StreamID == 0 {
  835. return nil, ConnectionError(ErrCodeProtocol)
  836. }
  837. return nil, streamError(fh.StreamID, ErrCodeProtocol)
  838. }
  839. return &WindowUpdateFrame{
  840. FrameHeader: fh,
  841. Increment: inc,
  842. }, nil
  843. }
  844. // WriteWindowUpdate writes a WINDOW_UPDATE frame.
  845. // The increment value must be between 1 and 2,147,483,647, inclusive.
  846. // If the Stream ID is zero, the window update applies to the
  847. // connection as a whole.
  848. func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error {
  849. // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
  850. if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
  851. return errors.New("illegal window increment value")
  852. }
  853. f.startWrite(FrameWindowUpdate, 0, streamID)
  854. f.writeUint32(incr)
  855. return f.endWrite()
  856. }
  857. // A HeadersFrame is used to open a stream and additionally carries a
  858. // header block fragment.
  859. type HeadersFrame struct {
  860. FrameHeader
  861. // Priority is set if FlagHeadersPriority is set in the FrameHeader.
  862. Priority PriorityParam
  863. headerFragBuf []byte // not owned
  864. }
  865. func (f *HeadersFrame) HeaderBlockFragment() []byte {
  866. f.checkValid()
  867. return f.headerFragBuf
  868. }
  869. func (f *HeadersFrame) HeadersEnded() bool {
  870. return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
  871. }
  872. func (f *HeadersFrame) StreamEnded() bool {
  873. return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
  874. }
  875. func (f *HeadersFrame) HasPriority() bool {
  876. return f.FrameHeader.Flags.Has(FlagHeadersPriority)
  877. }
  878. func parseHeadersFrame(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) {
  879. hf := &HeadersFrame{
  880. FrameHeader: fh,
  881. }
  882. if fh.StreamID == 0 {
  883. // HEADERS frames MUST be associated with a stream. If a HEADERS frame
  884. // is received whose stream identifier field is 0x0, the recipient MUST
  885. // respond with a connection error (Section 5.4.1) of type
  886. // PROTOCOL_ERROR.
  887. return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"}
  888. }
  889. var padLength uint8
  890. if fh.Flags.Has(FlagHeadersPadded) {
  891. if p, padLength, err = readByte(p); err != nil {
  892. return
  893. }
  894. }
  895. if fh.Flags.Has(FlagHeadersPriority) {
  896. var v uint32
  897. p, v, err = readUint32(p)
  898. if err != nil {
  899. return nil, err
  900. }
  901. hf.Priority.StreamDep = v & 0x7fffffff
  902. hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
  903. p, hf.Priority.Weight, err = readByte(p)
  904. if err != nil {
  905. return nil, err
  906. }
  907. }
  908. if len(p)-int(padLength) <= 0 {
  909. return nil, streamError(fh.StreamID, ErrCodeProtocol)
  910. }
  911. hf.headerFragBuf = p[:len(p)-int(padLength)]
  912. return hf, nil
  913. }
  914. // HeadersFrameParam are the parameters for writing a HEADERS frame.
  915. type HeadersFrameParam struct {
  916. // StreamID is the required Stream ID to initiate.
  917. StreamID uint32
  918. // BlockFragment is part (or all) of a Header Block.
  919. BlockFragment []byte
  920. // EndStream indicates that the header block is the last that
  921. // the endpoint will send for the identified stream. Setting
  922. // this flag causes the stream to enter one of "half closed"
  923. // states.
  924. EndStream bool
  925. // EndHeaders indicates that this frame contains an entire
  926. // header block and is not followed by any
  927. // CONTINUATION frames.
  928. EndHeaders bool
  929. // PadLength is the optional number of bytes of zeros to add
  930. // to this frame.
  931. PadLength uint8
  932. // Priority, if non-zero, includes stream priority information
  933. // in the HEADER frame.
  934. Priority PriorityParam
  935. }
  936. // WriteHeaders writes a single HEADERS frame.
  937. //
  938. // This is a low-level header writing method. Encoding headers and
  939. // splitting them into any necessary CONTINUATION frames is handled
  940. // elsewhere.
  941. //
  942. // It will perform exactly one Write to the underlying Writer.
  943. // It is the caller's responsibility to not call other Write methods concurrently.
  944. func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
  945. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  946. return errStreamID
  947. }
  948. var flags Flags
  949. if p.PadLength != 0 {
  950. flags |= FlagHeadersPadded
  951. }
  952. if p.EndStream {
  953. flags |= FlagHeadersEndStream
  954. }
  955. if p.EndHeaders {
  956. flags |= FlagHeadersEndHeaders
  957. }
  958. if !p.Priority.IsZero() {
  959. flags |= FlagHeadersPriority
  960. }
  961. f.startWrite(FrameHeaders, flags, p.StreamID)
  962. if p.PadLength != 0 {
  963. f.writeByte(p.PadLength)
  964. }
  965. if !p.Priority.IsZero() {
  966. v := p.Priority.StreamDep
  967. if !validStreamIDOrZero(v) && !f.AllowIllegalWrites {
  968. return errDepStreamID
  969. }
  970. if p.Priority.Exclusive {
  971. v |= 1 << 31
  972. }
  973. f.writeUint32(v)
  974. f.writeByte(p.Priority.Weight)
  975. }
  976. f.wbuf = append(f.wbuf, p.BlockFragment...)
  977. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  978. return f.endWrite()
  979. }
  980. // A PriorityFrame specifies the sender-advised priority of a stream.
  981. // See http://http2.github.io/http2-spec/#rfc.section.6.3
  982. type PriorityFrame struct {
  983. FrameHeader
  984. PriorityParam
  985. }
  986. // PriorityParam are the stream prioritzation parameters.
  987. type PriorityParam struct {
  988. // StreamDep is a 31-bit stream identifier for the
  989. // stream that this stream depends on. Zero means no
  990. // dependency.
  991. StreamDep uint32
  992. // Exclusive is whether the dependency is exclusive.
  993. Exclusive bool
  994. // Weight is the stream's zero-indexed weight. It should be
  995. // set together with StreamDep, or neither should be set. Per
  996. // the spec, "Add one to the value to obtain a weight between
  997. // 1 and 256."
  998. Weight uint8
  999. }
  1000. func (p PriorityParam) IsZero() bool {
  1001. return p == PriorityParam{}
  1002. }
  1003. func parsePriorityFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
  1004. if fh.StreamID == 0 {
  1005. return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"}
  1006. }
  1007. if len(payload) != 5 {
  1008. return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))}
  1009. }
  1010. v := binary.BigEndian.Uint32(payload[:4])
  1011. streamID := v & 0x7fffffff // mask off high bit
  1012. return &PriorityFrame{
  1013. FrameHeader: fh,
  1014. PriorityParam: PriorityParam{
  1015. Weight: payload[4],
  1016. StreamDep: streamID,
  1017. Exclusive: streamID != v, // was high bit set?
  1018. },
  1019. }, nil
  1020. }
  1021. // WritePriority writes a PRIORITY frame.
  1022. //
  1023. // It will perform exactly one Write to the underlying Writer.
  1024. // It is the caller's responsibility to not call other Write methods concurrently.
  1025. func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error {
  1026. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  1027. return errStreamID
  1028. }
  1029. if !validStreamIDOrZero(p.StreamDep) {
  1030. return errDepStreamID
  1031. }
  1032. f.startWrite(FramePriority, 0, streamID)
  1033. v := p.StreamDep
  1034. if p.Exclusive {
  1035. v |= 1 << 31
  1036. }
  1037. f.writeUint32(v)
  1038. f.writeByte(p.Weight)
  1039. return f.endWrite()
  1040. }
  1041. // A RSTStreamFrame allows for abnormal termination of a stream.
  1042. // See http://http2.github.io/http2-spec/#rfc.section.6.4
  1043. type RSTStreamFrame struct {
  1044. FrameHeader
  1045. ErrCode ErrCode
  1046. }
  1047. func parseRSTStreamFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
  1048. if len(p) != 4 {
  1049. return nil, ConnectionError(ErrCodeFrameSize)
  1050. }
  1051. if fh.StreamID == 0 {
  1052. return nil, ConnectionError(ErrCodeProtocol)
  1053. }
  1054. return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
  1055. }
  1056. // WriteRSTStream writes a RST_STREAM frame.
  1057. //
  1058. // It will perform exactly one Write to the underlying Writer.
  1059. // It is the caller's responsibility to not call other Write methods concurrently.
  1060. func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
  1061. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  1062. return errStreamID
  1063. }
  1064. f.startWrite(FrameRSTStream, 0, streamID)
  1065. f.writeUint32(uint32(code))
  1066. return f.endWrite()
  1067. }
  1068. // A ContinuationFrame is used to continue a sequence of header block fragments.
  1069. // See http://http2.github.io/http2-spec/#rfc.section.6.10
  1070. type ContinuationFrame struct {
  1071. FrameHeader
  1072. headerFragBuf []byte
  1073. }
  1074. func parseContinuationFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
  1075. if fh.StreamID == 0 {
  1076. return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"}
  1077. }
  1078. return &ContinuationFrame{fh, p}, nil
  1079. }
  1080. func (f *ContinuationFrame) HeaderBlockFragment() []byte {
  1081. f.checkValid()
  1082. return f.headerFragBuf
  1083. }
  1084. func (f *ContinuationFrame) HeadersEnded() bool {
  1085. return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
  1086. }
  1087. // WriteContinuation writes a CONTINUATION frame.
  1088. //
  1089. // It will perform exactly one Write to the underlying Writer.
  1090. // It is the caller's responsibility to not call other Write methods concurrently.
  1091. func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
  1092. if !validStreamID(streamID) && !f.AllowIllegalWrites {
  1093. return errStreamID
  1094. }
  1095. var flags Flags
  1096. if endHeaders {
  1097. flags |= FlagContinuationEndHeaders
  1098. }
  1099. f.startWrite(FrameContinuation, flags, streamID)
  1100. f.wbuf = append(f.wbuf, headerBlockFragment...)
  1101. return f.endWrite()
  1102. }
  1103. // A PushPromiseFrame is used to initiate a server stream.
  1104. // See http://http2.github.io/http2-spec/#rfc.section.6.6
  1105. type PushPromiseFrame struct {
  1106. FrameHeader
  1107. PromiseID uint32
  1108. headerFragBuf []byte // not owned
  1109. }
  1110. func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
  1111. f.checkValid()
  1112. return f.headerFragBuf
  1113. }
  1114. func (f *PushPromiseFrame) HeadersEnded() bool {
  1115. return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
  1116. }
  1117. func parsePushPromise(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) {
  1118. pp := &PushPromiseFrame{
  1119. FrameHeader: fh,
  1120. }
  1121. if pp.StreamID == 0 {
  1122. // PUSH_PROMISE frames MUST be associated with an existing,
  1123. // peer-initiated stream. The stream identifier of a
  1124. // PUSH_PROMISE frame indicates the stream it is associated
  1125. // with. If the stream identifier field specifies the value
  1126. // 0x0, a recipient MUST respond with a connection error
  1127. // (Section 5.4.1) of type PROTOCOL_ERROR.
  1128. return nil, ConnectionError(ErrCodeProtocol)
  1129. }
  1130. // The PUSH_PROMISE frame includes optional padding.
  1131. // Padding fields and flags are identical to those defined for DATA frames
  1132. var padLength uint8
  1133. if fh.Flags.Has(FlagPushPromisePadded) {
  1134. if p, padLength, err = readByte(p); err != nil {
  1135. return
  1136. }
  1137. }
  1138. p, pp.PromiseID, err = readUint32(p)
  1139. if err != nil {
  1140. return
  1141. }
  1142. pp.PromiseID = pp.PromiseID & (1<<31 - 1)
  1143. if int(padLength) > len(p) {
  1144. // like the DATA frame, error out if padding is longer than the body.
  1145. return nil, ConnectionError(ErrCodeProtocol)
  1146. }
  1147. pp.headerFragBuf = p[:len(p)-int(padLength)]
  1148. return pp, nil
  1149. }
  1150. // PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
  1151. type PushPromiseParam struct {
  1152. // StreamID is the required Stream ID to initiate.
  1153. StreamID uint32
  1154. // PromiseID is the required Stream ID which this
  1155. // Push Promises
  1156. PromiseID uint32
  1157. // BlockFragment is part (or all) of a Header Block.
  1158. BlockFragment []byte
  1159. // EndHeaders indicates that this frame contains an entire
  1160. // header block and is not followed by any
  1161. // CONTINUATION frames.
  1162. EndHeaders bool
  1163. // PadLength is the optional number of bytes of zeros to add
  1164. // to this frame.
  1165. PadLength uint8
  1166. }
  1167. // WritePushPromise writes a single PushPromise Frame.
  1168. //
  1169. // As with Header Frames, This is the low level call for writing
  1170. // individual frames. Continuation frames are handled elsewhere.
  1171. //
  1172. // It will perform exactly one Write to the underlying Writer.
  1173. // It is the caller's responsibility to not call other Write methods concurrently.
  1174. func (f *Framer) WritePushPromise(p PushPromiseParam) error {
  1175. if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
  1176. return errStreamID
  1177. }
  1178. var flags Flags
  1179. if p.PadLength != 0 {
  1180. flags |= FlagPushPromisePadded
  1181. }
  1182. if p.EndHeaders {
  1183. flags |= FlagPushPromiseEndHeaders
  1184. }
  1185. f.startWrite(FramePushPromise, flags, p.StreamID)
  1186. if p.PadLength != 0 {
  1187. f.writeByte(p.PadLength)
  1188. }
  1189. if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
  1190. return errStreamID
  1191. }
  1192. f.writeUint32(p.PromiseID)
  1193. f.wbuf = append(f.wbuf, p.BlockFragment...)
  1194. f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
  1195. return f.endWrite()
  1196. }
  1197. // WriteRawFrame writes a raw frame. This can be used to write
  1198. // extension frames unknown to this package.
  1199. func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
  1200. f.startWrite(t, flags, streamID)
  1201. f.writeBytes(payload)
  1202. return f.endWrite()
  1203. }
  1204. func readByte(p []byte) (remain []byte, b byte, err error) {
  1205. if len(p) == 0 {
  1206. return nil, 0, io.ErrUnexpectedEOF
  1207. }
  1208. return p[1:], p[0], nil
  1209. }
  1210. func readUint32(p []byte) (remain []byte, v uint32, err error) {
  1211. if len(p) < 4 {
  1212. return nil, 0, io.ErrUnexpectedEOF
  1213. }
  1214. return p[4:], binary.BigEndian.Uint32(p[:4]), nil
  1215. }
  1216. type streamEnder interface {
  1217. StreamEnded() bool
  1218. }
  1219. type headersEnder interface {
  1220. HeadersEnded() bool
  1221. }
  1222. type headersOrContinuation interface {
  1223. headersEnder
  1224. HeaderBlockFragment() []byte
  1225. }
  1226. // A MetaHeadersFrame is the representation of one HEADERS frame and
  1227. // zero or more contiguous CONTINUATION frames and the decoding of
  1228. // their HPACK-encoded contents.
  1229. //
  1230. // This type of frame does not appear on the wire and is only returned
  1231. // by the Framer when Framer.ReadMetaHeaders is set.
  1232. type MetaHeadersFrame struct {
  1233. *HeadersFrame
  1234. // Fields are the fields contained in the HEADERS and
  1235. // CONTINUATION frames. The underlying slice is owned by the
  1236. // Framer and must not be retained after the next call to
  1237. // ReadFrame.
  1238. //
  1239. // Fields are guaranteed to be in the correct http2 order and
  1240. // not have unknown pseudo header fields or invalid header
  1241. // field names or values. Required pseudo header fields may be
  1242. // missing, however. Use the MetaHeadersFrame.Pseudo accessor
  1243. // method access pseudo headers.
  1244. Fields []hpack.HeaderField
  1245. // Truncated is whether the max header list size limit was hit
  1246. // and Fields is incomplete. The hpack decoder state is still
  1247. // valid, however.
  1248. Truncated bool
  1249. }
  1250. // PseudoValue returns the given pseudo header field's value.
  1251. // The provided pseudo field should not contain the leading colon.
  1252. func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string {
  1253. for _, hf := range mh.Fields {
  1254. if !hf.IsPseudo() {
  1255. return ""
  1256. }
  1257. if hf.Name[1:] == pseudo {
  1258. return hf.Value
  1259. }
  1260. }
  1261. return ""
  1262. }
  1263. // RegularFields returns the regular (non-pseudo) header fields of mh.
  1264. // The caller does not own the returned slice.
  1265. func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField {
  1266. for i, hf := range mh.Fields {
  1267. if !hf.IsPseudo() {
  1268. return mh.Fields[i:]
  1269. }
  1270. }
  1271. return nil
  1272. }
  1273. // PseudoFields returns the pseudo header fields of mh.
  1274. // The caller does not own the returned slice.
  1275. func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField {
  1276. for i, hf := range mh.Fields {
  1277. if !hf.IsPseudo() {
  1278. return mh.Fields[:i]
  1279. }
  1280. }
  1281. return mh.Fields
  1282. }
  1283. func (mh *MetaHeadersFrame) checkPseudos() error {
  1284. var isRequest, isResponse bool
  1285. pf := mh.PseudoFields()
  1286. for i, hf := range pf {
  1287. switch hf.Name {
  1288. case ":method", ":path", ":scheme", ":authority":
  1289. isRequest = true
  1290. case ":status":
  1291. isResponse = true
  1292. default:
  1293. return pseudoHeaderError(hf.Name)
  1294. }
  1295. // Check for duplicates.
  1296. // This would be a bad algorithm, but N is 4.
  1297. // And this doesn't allocate.
  1298. for _, hf2 := range pf[:i] {
  1299. if hf.Name == hf2.Name {
  1300. return duplicatePseudoHeaderError(hf.Name)
  1301. }
  1302. }
  1303. }
  1304. if isRequest && isResponse {
  1305. return errMixPseudoHeaderTypes
  1306. }
  1307. return nil
  1308. }
  1309. func (fr *Framer) maxHeaderStringLen() int {
  1310. v := fr.maxHeaderListSize()
  1311. if uint32(int(v)) == v {
  1312. return int(v)
  1313. }
  1314. // They had a crazy big number for MaxHeaderBytes anyway,
  1315. // so give them unlimited header lengths:
  1316. return 0
  1317. }
  1318. // readMetaFrame returns 0 or more CONTINUATION frames from fr and
  1319. // merge them into the provided hf and returns a MetaHeadersFrame
  1320. // with the decoded hpack values.
  1321. func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) {
  1322. if fr.AllowIllegalReads {
  1323. return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders")
  1324. }
  1325. mh := &MetaHeadersFrame{
  1326. HeadersFrame: hf,
  1327. }
  1328. var remainSize = fr.maxHeaderListSize()
  1329. var sawRegular bool
  1330. var invalid error // pseudo header field errors
  1331. hdec := fr.ReadMetaHeaders
  1332. hdec.SetEmitEnabled(true)
  1333. hdec.SetMaxStringLength(fr.maxHeaderStringLen())
  1334. hdec.SetEmitFunc(func(hf hpack.HeaderField) {
  1335. if VerboseLogs && fr.logReads {
  1336. fr.debugReadLoggerf("http2: decoded hpack field %+v", hf)
  1337. }
  1338. if !httpguts.ValidHeaderFieldValue(hf.Value) {
  1339. invalid = headerFieldValueError(hf.Value)
  1340. }
  1341. isPseudo := strings.HasPrefix(hf.Name, ":")
  1342. if isPseudo {
  1343. if sawRegular {
  1344. invalid = errPseudoAfterRegular
  1345. }
  1346. } else {
  1347. sawRegular = true
  1348. if !validWireHeaderFieldName(hf.Name) {
  1349. invalid = headerFieldNameError(hf.Name)
  1350. }
  1351. }
  1352. if invalid != nil {
  1353. hdec.SetEmitEnabled(false)
  1354. return
  1355. }
  1356. size := hf.Size()
  1357. if size > remainSize {
  1358. hdec.SetEmitEnabled(false)
  1359. mh.Truncated = true
  1360. return
  1361. }
  1362. remainSize -= size
  1363. mh.Fields = append(mh.Fields, hf)
  1364. })
  1365. // Lose reference to MetaHeadersFrame:
  1366. defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {})
  1367. var hc headersOrContinuation = hf
  1368. for {
  1369. frag := hc.HeaderBlockFragment()
  1370. if _, err := hdec.Write(frag); err != nil {
  1371. return nil, ConnectionError(ErrCodeCompression)
  1372. }
  1373. if hc.HeadersEnded() {
  1374. break
  1375. }
  1376. if f, err := fr.ReadFrame(); err != nil {
  1377. return nil, err
  1378. } else {
  1379. hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder
  1380. }
  1381. }
  1382. mh.HeadersFrame.headerFragBuf = nil
  1383. mh.HeadersFrame.invalidate()
  1384. if err := hdec.Close(); err != nil {
  1385. return nil, ConnectionError(ErrCodeCompression)
  1386. }
  1387. if invalid != nil {
  1388. fr.errDetail = invalid
  1389. if VerboseLogs {
  1390. log.Printf("http2: invalid header: %v", invalid)
  1391. }
  1392. return nil, StreamError{mh.StreamID, ErrCodeProtocol, invalid}
  1393. }
  1394. if err := mh.checkPseudos(); err != nil {
  1395. fr.errDetail = err
  1396. if VerboseLogs {
  1397. log.Printf("http2: invalid pseudo headers: %v", err)
  1398. }
  1399. return nil, StreamError{mh.StreamID, ErrCodeProtocol, err}
  1400. }
  1401. return mh, nil
  1402. }
  1403. func summarizeFrame(f Frame) string {
  1404. var buf bytes.Buffer
  1405. f.Header().writeDebug(&buf)
  1406. switch f := f.(type) {
  1407. case *SettingsFrame:
  1408. n := 0
  1409. f.ForeachSetting(func(s Setting) error {
  1410. n++
  1411. if n == 1 {
  1412. buf.WriteString(", settings:")
  1413. }
  1414. fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val)
  1415. return nil
  1416. })
  1417. if n > 0 {
  1418. buf.Truncate(buf.Len() - 1) // remove trailing comma
  1419. }
  1420. case *DataFrame:
  1421. data := f.Data()
  1422. const max = 256
  1423. if len(data) > max {
  1424. data = data[:max]
  1425. }
  1426. fmt.Fprintf(&buf, " data=%q", data)
  1427. if len(f.Data()) > max {
  1428. fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max)
  1429. }
  1430. case *WindowUpdateFrame:
  1431. if f.StreamID == 0 {
  1432. buf.WriteString(" (conn)")
  1433. }
  1434. fmt.Fprintf(&buf, " incr=%v", f.Increment)
  1435. case *PingFrame:
  1436. fmt.Fprintf(&buf, " ping=%q", f.Data[:])
  1437. case *GoAwayFrame:
  1438. fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q",
  1439. f.LastStreamID, f.ErrCode, f.debugData)
  1440. case *RSTStreamFrame:
  1441. fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode)
  1442. }
  1443. return buf.String()
  1444. }