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.
17 "golang.org/x/net/http/httpguts"
18 "golang.org/x/net/http2/hpack"
21 const frameHeaderLen = 9
23 var padZeros = make([]byte, 255) // zeros for padding
25 // A FrameType is a registered frame type as defined in
26 // http://http2.github.io/http2-spec/#rfc.section.11.2
30 FrameData FrameType = 0x0
31 FrameHeaders FrameType = 0x1
32 FramePriority FrameType = 0x2
33 FrameRSTStream FrameType = 0x3
34 FrameSettings FrameType = 0x4
35 FramePushPromise FrameType = 0x5
36 FramePing FrameType = 0x6
37 FrameGoAway FrameType = 0x7
38 FrameWindowUpdate FrameType = 0x8
39 FrameContinuation FrameType = 0x9
42 var frameName = map[FrameType]string{
44 FrameHeaders: "HEADERS",
45 FramePriority: "PRIORITY",
46 FrameRSTStream: "RST_STREAM",
47 FrameSettings: "SETTINGS",
48 FramePushPromise: "PUSH_PROMISE",
50 FrameGoAway: "GOAWAY",
51 FrameWindowUpdate: "WINDOW_UPDATE",
52 FrameContinuation: "CONTINUATION",
55 func (t FrameType) String() string {
56 if s, ok := frameName[t]; ok {
59 return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t))
62 // Flags is a bitmask of HTTP/2 flags.
63 // The meaning of flags varies depending on the frame type.
66 // Has reports whether f contains all (0 or more) flags in v.
67 func (f Flags) Has(v Flags) bool {
71 // Frame-specific FrameHeader flag bits.
74 FlagDataEndStream Flags = 0x1
75 FlagDataPadded Flags = 0x8
78 FlagHeadersEndStream Flags = 0x1
79 FlagHeadersEndHeaders Flags = 0x4
80 FlagHeadersPadded Flags = 0x8
81 FlagHeadersPriority Flags = 0x20
84 FlagSettingsAck Flags = 0x1
87 FlagPingAck Flags = 0x1
90 FlagContinuationEndHeaders Flags = 0x4
92 FlagPushPromiseEndHeaders Flags = 0x4
93 FlagPushPromisePadded Flags = 0x8
96 var flagName = map[FrameType]map[Flags]string{
98 FlagDataEndStream: "END_STREAM",
99 FlagDataPadded: "PADDED",
102 FlagHeadersEndStream: "END_STREAM",
103 FlagHeadersEndHeaders: "END_HEADERS",
104 FlagHeadersPadded: "PADDED",
105 FlagHeadersPriority: "PRIORITY",
108 FlagSettingsAck: "ACK",
114 FlagContinuationEndHeaders: "END_HEADERS",
117 FlagPushPromiseEndHeaders: "END_HEADERS",
118 FlagPushPromisePadded: "PADDED",
122 // a frameParser parses a frame given its FrameHeader and payload
123 // bytes. The length of payload will always equal fh.Length (which
125 type frameParser func(fc *frameCache, fh FrameHeader, payload []byte) (Frame, error)
127 var frameParsers = map[FrameType]frameParser{
128 FrameData: parseDataFrame,
129 FrameHeaders: parseHeadersFrame,
130 FramePriority: parsePriorityFrame,
131 FrameRSTStream: parseRSTStreamFrame,
132 FrameSettings: parseSettingsFrame,
133 FramePushPromise: parsePushPromise,
134 FramePing: parsePingFrame,
135 FrameGoAway: parseGoAwayFrame,
136 FrameWindowUpdate: parseWindowUpdateFrame,
137 FrameContinuation: parseContinuationFrame,
140 func typeFrameParser(t FrameType) frameParser {
141 if f := frameParsers[t]; f != nil {
144 return parseUnknownFrame
147 // A FrameHeader is the 9 byte header of all HTTP/2 frames.
149 // See http://http2.github.io/http2-spec/#FrameHeader
150 type FrameHeader struct {
151 valid bool // caller can access []byte fields in the Frame
153 // Type is the 1 byte frame type. There are ten standard frame
154 // types, but extension frame types may be written by WriteRawFrame
155 // and will be returned by ReadFrame (as UnknownFrame).
158 // Flags are the 1 byte of 8 potential bit flags per frame.
159 // They are specific to the frame type.
162 // Length is the length of the frame, not including the 9 byte header.
163 // The maximum size is one byte less than 16MB (uint24), but only
164 // frames up to 16KB are allowed without peer agreement.
167 // StreamID is which stream this frame is for. Certain frames
168 // are not stream-specific, in which case this field is 0.
172 // Header returns h. It exists so FrameHeaders can be embedded in other
173 // specific frame types and implement the Frame interface.
174 func (h FrameHeader) Header() FrameHeader { return h }
176 func (h FrameHeader) String() string {
178 buf.WriteString("[FrameHeader ")
184 func (h FrameHeader) writeDebug(buf *bytes.Buffer) {
185 buf.WriteString(h.Type.String())
187 buf.WriteString(" flags=")
189 for i := uint8(0); i < 8; i++ {
190 if h.Flags&(1<<i) == 0 {
197 name := flagName[h.Type][Flags(1<<i)]
199 buf.WriteString(name)
201 fmt.Fprintf(buf, "0x%x", 1<<i)
206 fmt.Fprintf(buf, " stream=%d", h.StreamID)
208 fmt.Fprintf(buf, " len=%d", h.Length)
211 func (h *FrameHeader) checkValid() {
213 panic("Frame accessor called on non-owned Frame")
217 func (h *FrameHeader) invalidate() { h.valid = false }
219 // frame header bytes.
220 // Used only by ReadFrameHeader.
221 var fhBytes = sync.Pool{
222 New: func() interface{} {
223 buf := make([]byte, frameHeaderLen)
228 // ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
229 // Most users should use Framer.ReadFrame instead.
230 func ReadFrameHeader(r io.Reader) (FrameHeader, error) {
231 bufp := fhBytes.Get().(*[]byte)
232 defer fhBytes.Put(bufp)
233 return readFrameHeader(*bufp, r)
236 func readFrameHeader(buf []byte, r io.Reader) (FrameHeader, error) {
237 _, err := io.ReadFull(r, buf[:frameHeaderLen])
239 return FrameHeader{}, err
242 Length: (uint32(buf[0])<<16 | uint32(buf[1])<<8 | uint32(buf[2])),
243 Type: FrameType(buf[3]),
244 Flags: Flags(buf[4]),
245 StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
250 // A Frame is the base interface implemented by all frame types.
251 // Callers will generally type-assert the specific frame type:
252 // *HeadersFrame, *SettingsFrame, *WindowUpdateFrame, etc.
254 // Frames are only valid until the next call to Framer.ReadFrame.
255 type Frame interface {
258 // invalidate is called by Framer.ReadFrame to make this
259 // frame's buffers as being invalid, since the subsequent
260 // frame will reuse them.
264 // A Framer reads and writes Frames.
270 // lastHeaderStream is non-zero if the last frame was an
271 // unfinished HEADERS/CONTINUATION.
272 lastHeaderStream uint32
275 headerBuf [frameHeaderLen]byte
277 // TODO: let getReadBuf be configurable, and use a less memory-pinning
278 // allocator in server.go to minimize memory pinned for many idle conns.
279 // Will probably also need to make frame invalidation have a hook too.
280 getReadBuf func(size uint32) []byte
281 readBuf []byte // cache for default getReadBuf
283 maxWriteSize uint32 // zero means unlimited; TODO: implement
288 // AllowIllegalWrites permits the Framer's Write methods to
289 // write frames that do not conform to the HTTP/2 spec. This
290 // permits using the Framer to test other HTTP/2
291 // implementations' conformance to the spec.
292 // If false, the Write methods will prefer to return an error
293 // rather than comply.
294 AllowIllegalWrites bool
296 // AllowIllegalReads permits the Framer's ReadFrame method
297 // to return non-compliant frames or frame orders.
298 // This is for testing and permits using the Framer to test
299 // other HTTP/2 implementations' conformance to the spec.
300 // It is not compatible with ReadMetaHeaders.
301 AllowIllegalReads bool
303 // ReadMetaHeaders if non-nil causes ReadFrame to merge
304 // HEADERS and CONTINUATION frames together and return
305 // MetaHeadersFrame instead.
306 ReadMetaHeaders *hpack.Decoder
308 // MaxHeaderListSize is the http2 MAX_HEADER_LIST_SIZE.
309 // It's used only if ReadMetaHeaders is set; 0 means a sane default
311 // If the limit is hit, MetaHeadersFrame.Truncated is set true.
312 MaxHeaderListSize uint32
314 // TODO: track which type of frame & with which flags was sent
315 // last. Then return an error (unless AllowIllegalWrites) if
316 // we're in the middle of a header block and a
317 // non-Continuation or Continuation on a different stream is
318 // attempted to be written.
320 logReads, logWrites bool
322 debugFramer *Framer // only use for logging written writes
323 debugFramerBuf *bytes.Buffer
324 debugReadLoggerf func(string, ...interface{})
325 debugWriteLoggerf func(string, ...interface{})
327 frameCache *frameCache // nil if frames aren't reused (default)
330 func (fr *Framer) maxHeaderListSize() uint32 {
331 if fr.MaxHeaderListSize == 0 {
332 return 16 << 20 // sane default, per docs
334 return fr.MaxHeaderListSize
337 func (f *Framer) startWrite(ftype FrameType, flags Flags, streamID uint32) {
338 // Write the FrameHeader.
339 f.wbuf = append(f.wbuf[:0],
340 0, // 3 bytes of length, filled in in endWrite
351 func (f *Framer) endWrite() error {
352 // Now that we know the final size, fill in the FrameHeader in
353 // the space previously reserved for it. Abuse append.
354 length := len(f.wbuf) - frameHeaderLen
355 if length >= (1 << 24) {
356 return ErrFrameTooLarge
358 _ = append(f.wbuf[:0],
366 n, err := f.w.Write(f.wbuf)
367 if err == nil && n != len(f.wbuf) {
368 err = io.ErrShortWrite
373 func (f *Framer) logWrite() {
374 if f.debugFramer == nil {
375 f.debugFramerBuf = new(bytes.Buffer)
376 f.debugFramer = NewFramer(nil, f.debugFramerBuf)
377 f.debugFramer.logReads = false // we log it ourselves, saying "wrote" below
378 // Let us read anything, even if we accidentally wrote it
379 // in the wrong order:
380 f.debugFramer.AllowIllegalReads = true
382 f.debugFramerBuf.Write(f.wbuf)
383 fr, err := f.debugFramer.ReadFrame()
385 f.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", f)
388 f.debugWriteLoggerf("http2: Framer %p: wrote %v", f, summarizeFrame(fr))
391 func (f *Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) }
392 func (f *Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) }
393 func (f *Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) }
394 func (f *Framer) writeUint32(v uint32) {
395 f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
399 minMaxFrameSize = 1 << 14
400 maxFrameSize = 1<<24 - 1
403 // SetReuseFrames allows the Framer to reuse Frames.
404 // If called on a Framer, Frames returned by calls to ReadFrame are only
405 // valid until the next call to ReadFrame.
406 func (fr *Framer) SetReuseFrames() {
407 if fr.frameCache != nil {
410 fr.frameCache = &frameCache{}
413 type frameCache struct {
417 func (fc *frameCache) getDataFrame() *DataFrame {
424 // NewFramer returns a Framer that writes frames to w and reads them from r.
425 func NewFramer(w io.Writer, r io.Reader) *Framer {
429 logReads: logFrameReads,
430 logWrites: logFrameWrites,
431 debugReadLoggerf: log.Printf,
432 debugWriteLoggerf: log.Printf,
434 fr.getReadBuf = func(size uint32) []byte {
435 if cap(fr.readBuf) >= int(size) {
436 return fr.readBuf[:size]
438 fr.readBuf = make([]byte, size)
441 fr.SetMaxReadFrameSize(maxFrameSize)
445 // SetMaxReadFrameSize sets the maximum size of a frame
446 // that will be read by a subsequent call to ReadFrame.
447 // It is the caller's responsibility to advertise this
448 // limit with a SETTINGS frame.
449 func (fr *Framer) SetMaxReadFrameSize(v uint32) {
450 if v > maxFrameSize {
456 // ErrorDetail returns a more detailed error of the last error
457 // returned by Framer.ReadFrame. For instance, if ReadFrame
458 // returns a StreamError with code PROTOCOL_ERROR, ErrorDetail
459 // will say exactly what was invalid. ErrorDetail is not guaranteed
460 // to return a non-nil value and like the rest of the http2 package,
461 // its return value is not protected by an API compatibility promise.
462 // ErrorDetail is reset after the next call to ReadFrame.
463 func (fr *Framer) ErrorDetail() error {
467 // ErrFrameTooLarge is returned from Framer.ReadFrame when the peer
468 // sends a frame that is larger than declared with SetMaxReadFrameSize.
469 var ErrFrameTooLarge = errors.New("http2: frame too large")
471 // terminalReadFrameError reports whether err is an unrecoverable
472 // error from ReadFrame and no other frames should be read.
473 func terminalReadFrameError(err error) bool {
474 if _, ok := err.(StreamError); ok {
480 // ReadFrame reads a single frame. The returned Frame is only valid
481 // until the next call to ReadFrame.
483 // If the frame is larger than previously set with SetMaxReadFrameSize, the
484 // returned error is ErrFrameTooLarge. Other errors may be of type
485 // ConnectionError, StreamError, or anything else from the underlying
487 func (fr *Framer) ReadFrame() (Frame, error) {
489 if fr.lastFrame != nil {
490 fr.lastFrame.invalidate()
492 fh, err := readFrameHeader(fr.headerBuf[:], fr.r)
496 if fh.Length > fr.maxReadSize {
497 return nil, ErrFrameTooLarge
499 payload := fr.getReadBuf(fh.Length)
500 if _, err := io.ReadFull(fr.r, payload); err != nil {
503 f, err := typeFrameParser(fh.Type)(fr.frameCache, fh, payload)
505 if ce, ok := err.(connError); ok {
506 return nil, fr.connError(ce.Code, ce.Reason)
510 if err := fr.checkFrameOrder(f); err != nil {
514 fr.debugReadLoggerf("http2: Framer %p: read %v", fr, summarizeFrame(f))
516 if fh.Type == FrameHeaders && fr.ReadMetaHeaders != nil {
517 return fr.readMetaFrame(f.(*HeadersFrame))
522 // connError returns ConnectionError(code) but first
523 // stashes away a public reason to the caller can optionally relay it
524 // to the peer before hanging up on them. This might help others debug
525 // their implementations.
526 func (fr *Framer) connError(code ErrCode, reason string) error {
527 fr.errDetail = errors.New(reason)
528 return ConnectionError(code)
531 // checkFrameOrder reports an error if f is an invalid frame to return
532 // next from ReadFrame. Mostly it checks whether HEADERS and
533 // CONTINUATION frames are contiguous.
534 func (fr *Framer) checkFrameOrder(f Frame) error {
537 if fr.AllowIllegalReads {
542 if fr.lastHeaderStream != 0 {
543 if fh.Type != FrameContinuation {
544 return fr.connError(ErrCodeProtocol,
545 fmt.Sprintf("got %s for stream %d; expected CONTINUATION following %s for stream %d",
546 fh.Type, fh.StreamID,
547 last.Header().Type, fr.lastHeaderStream))
549 if fh.StreamID != fr.lastHeaderStream {
550 return fr.connError(ErrCodeProtocol,
551 fmt.Sprintf("got CONTINUATION for stream %d; expected stream %d",
552 fh.StreamID, fr.lastHeaderStream))
554 } else if fh.Type == FrameContinuation {
555 return fr.connError(ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", fh.StreamID))
559 case FrameHeaders, FrameContinuation:
560 if fh.Flags.Has(FlagHeadersEndHeaders) {
561 fr.lastHeaderStream = 0
563 fr.lastHeaderStream = fh.StreamID
570 // A DataFrame conveys arbitrary, variable-length sequences of octets
571 // associated with a stream.
572 // See http://http2.github.io/http2-spec/#rfc.section.6.1
573 type DataFrame struct {
578 func (f *DataFrame) StreamEnded() bool {
579 return f.FrameHeader.Flags.Has(FlagDataEndStream)
582 // Data returns the frame's data octets, not including any padding
583 // size byte or padding suffix bytes.
584 // The caller must not retain the returned memory past the next
585 // call to ReadFrame.
586 func (f *DataFrame) Data() []byte {
591 func parseDataFrame(fc *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
592 if fh.StreamID == 0 {
593 // DATA frames MUST be associated with a stream. If a
594 // DATA frame is received whose stream identifier
595 // field is 0x0, the recipient MUST respond with a
596 // connection error (Section 5.4.1) of type
598 return nil, connError{ErrCodeProtocol, "DATA frame with stream ID 0"}
600 f := fc.getDataFrame()
604 if fh.Flags.Has(FlagDataPadded) {
606 payload, padSize, err = readByte(payload)
611 if int(padSize) > len(payload) {
612 // If the length of the padding is greater than the
613 // length of the frame payload, the recipient MUST
614 // treat this as a connection error.
615 // Filed: https://github.com/http2/http2-spec/issues/610
616 return nil, connError{ErrCodeProtocol, "pad size larger than data payload"}
618 f.data = payload[:len(payload)-int(padSize)]
623 errStreamID = errors.New("invalid stream ID")
624 errDepStreamID = errors.New("invalid dependent stream ID")
625 errPadLength = errors.New("pad length too large")
626 errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled")
629 func validStreamIDOrZero(streamID uint32) bool {
630 return streamID&(1<<31) == 0
633 func validStreamID(streamID uint32) bool {
634 return streamID != 0 && streamID&(1<<31) == 0
637 // WriteData writes a DATA frame.
639 // It will perform exactly one Write to the underlying Writer.
640 // It is the caller's responsibility not to violate the maximum frame size
641 // and to not call other Write methods concurrently.
642 func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
643 return f.WriteDataPadded(streamID, endStream, data, nil)
646 // WriteDataPadded writes a DATA frame with optional padding.
648 // If pad is nil, the padding bit is not sent.
649 // The length of pad must not exceed 255 bytes.
650 // The bytes of pad must all be zero, unless f.AllowIllegalWrites is set.
652 // It will perform exactly one Write to the underlying Writer.
653 // It is the caller's responsibility not to violate the maximum frame size
654 // and to not call other Write methods concurrently.
655 func (f *Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
656 if !validStreamID(streamID) && !f.AllowIllegalWrites {
663 if !f.AllowIllegalWrites {
664 for _, b := range pad {
666 // "Padding octets MUST be set to zero when sending."
674 flags |= FlagDataEndStream
677 flags |= FlagDataPadded
679 f.startWrite(FrameData, flags, streamID)
681 f.wbuf = append(f.wbuf, byte(len(pad)))
683 f.wbuf = append(f.wbuf, data...)
684 f.wbuf = append(f.wbuf, pad...)
688 // A SettingsFrame conveys configuration parameters that affect how
689 // endpoints communicate, such as preferences and constraints on peer
692 // See http://http2.github.io/http2-spec/#SETTINGS
693 type SettingsFrame struct {
698 func parseSettingsFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
699 if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 {
700 // When this (ACK 0x1) bit is set, the payload of the
701 // SETTINGS frame MUST be empty. Receipt of a
702 // SETTINGS frame with the ACK flag set and a length
703 // field value other than 0 MUST be treated as a
704 // connection error (Section 5.4.1) of type
706 return nil, ConnectionError(ErrCodeFrameSize)
708 if fh.StreamID != 0 {
709 // SETTINGS frames always apply to a connection,
710 // never a single stream. The stream identifier for a
711 // SETTINGS frame MUST be zero (0x0). If an endpoint
712 // receives a SETTINGS frame whose stream identifier
713 // field is anything other than 0x0, the endpoint MUST
714 // respond with a connection error (Section 5.4.1) of
715 // type PROTOCOL_ERROR.
716 return nil, ConnectionError(ErrCodeProtocol)
719 // Expecting even number of 6 byte settings.
720 return nil, ConnectionError(ErrCodeFrameSize)
722 f := &SettingsFrame{FrameHeader: fh, p: p}
723 if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 {
724 // Values above the maximum flow control window size of 2^31 - 1 MUST
725 // be treated as a connection error (Section 5.4.1) of type
726 // FLOW_CONTROL_ERROR.
727 return nil, ConnectionError(ErrCodeFlowControl)
732 func (f *SettingsFrame) IsAck() bool {
733 return f.FrameHeader.Flags.Has(FlagSettingsAck)
736 func (f *SettingsFrame) Value(id SettingID) (v uint32, ok bool) {
738 for i := 0; i < f.NumSettings(); i++ {
739 if s := f.Setting(i); s.ID == id {
746 // Setting returns the setting from the frame at the given 0-based index.
747 // The index must be >= 0 and less than f.NumSettings().
748 func (f *SettingsFrame) Setting(i int) Setting {
751 ID: SettingID(binary.BigEndian.Uint16(buf[i*6 : i*6+2])),
752 Val: binary.BigEndian.Uint32(buf[i*6+2 : i*6+6]),
756 func (f *SettingsFrame) NumSettings() int { return len(f.p) / 6 }
758 // HasDuplicates reports whether f contains any duplicate setting IDs.
759 func (f *SettingsFrame) HasDuplicates() bool {
760 num := f.NumSettings()
764 // If it's small enough (the common case), just do the n^2
765 // thing and avoid a map allocation.
767 for i := 0; i < num; i++ {
768 idi := f.Setting(i).ID
769 for j := i + 1; j < num; j++ {
770 idj := f.Setting(j).ID
778 seen := map[SettingID]bool{}
779 for i := 0; i < num; i++ {
780 id := f.Setting(i).ID
789 // ForeachSetting runs fn for each setting.
790 // It stops and returns the first error.
791 func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error {
793 for i := 0; i < f.NumSettings(); i++ {
794 if err := fn(f.Setting(i)); err != nil {
801 // WriteSettings writes a SETTINGS frame with zero or more settings
802 // specified and the ACK bit not set.
804 // It will perform exactly one Write to the underlying Writer.
805 // It is the caller's responsibility to not call other Write methods concurrently.
806 func (f *Framer) WriteSettings(settings ...Setting) error {
807 f.startWrite(FrameSettings, 0, 0)
808 for _, s := range settings {
809 f.writeUint16(uint16(s.ID))
815 // WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set.
817 // It will perform exactly one Write to the underlying Writer.
818 // It is the caller's responsibility to not call other Write methods concurrently.
819 func (f *Framer) WriteSettingsAck() error {
820 f.startWrite(FrameSettings, FlagSettingsAck, 0)
824 // A PingFrame is a mechanism for measuring a minimal round trip time
825 // from the sender, as well as determining whether an idle connection
826 // is still functional.
827 // See http://http2.github.io/http2-spec/#rfc.section.6.7
828 type PingFrame struct {
833 func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) }
835 func parsePingFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
836 if len(payload) != 8 {
837 return nil, ConnectionError(ErrCodeFrameSize)
839 if fh.StreamID != 0 {
840 return nil, ConnectionError(ErrCodeProtocol)
842 f := &PingFrame{FrameHeader: fh}
843 copy(f.Data[:], payload)
847 func (f *Framer) WritePing(ack bool, data [8]byte) error {
852 f.startWrite(FramePing, flags, 0)
853 f.writeBytes(data[:])
857 // A GoAwayFrame informs the remote peer to stop creating streams on this connection.
858 // See http://http2.github.io/http2-spec/#rfc.section.6.8
859 type GoAwayFrame struct {
866 // DebugData returns any debug data in the GOAWAY frame. Its contents
868 // The caller must not retain the returned memory past the next
869 // call to ReadFrame.
870 func (f *GoAwayFrame) DebugData() []byte {
875 func parseGoAwayFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
876 if fh.StreamID != 0 {
877 return nil, ConnectionError(ErrCodeProtocol)
880 return nil, ConnectionError(ErrCodeFrameSize)
884 LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
885 ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])),
890 func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error {
891 f.startWrite(FrameGoAway, 0, 0)
892 f.writeUint32(maxStreamID & (1<<31 - 1))
893 f.writeUint32(uint32(code))
894 f.writeBytes(debugData)
898 // An UnknownFrame is the frame type returned when the frame type is unknown
899 // or no specific frame type parser exists.
900 type UnknownFrame struct {
905 // Payload returns the frame's payload (after the header). It is not
906 // valid to call this method after a subsequent call to
907 // Framer.ReadFrame, nor is it valid to retain the returned slice.
908 // The memory is owned by the Framer and is invalidated when the next
910 func (f *UnknownFrame) Payload() []byte {
915 func parseUnknownFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
916 return &UnknownFrame{fh, p}, nil
919 // A WindowUpdateFrame is used to implement flow control.
920 // See http://http2.github.io/http2-spec/#rfc.section.6.9
921 type WindowUpdateFrame struct {
923 Increment uint32 // never read with high bit set
926 func parseWindowUpdateFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
928 return nil, ConnectionError(ErrCodeFrameSize)
930 inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
932 // A receiver MUST treat the receipt of a
933 // WINDOW_UPDATE frame with an flow control window
934 // increment of 0 as a stream error (Section 5.4.2) of
935 // type PROTOCOL_ERROR; errors on the connection flow
936 // control window MUST be treated as a connection
937 // error (Section 5.4.1).
938 if fh.StreamID == 0 {
939 return nil, ConnectionError(ErrCodeProtocol)
941 return nil, streamError(fh.StreamID, ErrCodeProtocol)
943 return &WindowUpdateFrame{
949 // WriteWindowUpdate writes a WINDOW_UPDATE frame.
950 // The increment value must be between 1 and 2,147,483,647, inclusive.
951 // If the Stream ID is zero, the window update applies to the
952 // connection as a whole.
953 func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error {
954 // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
955 if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
956 return errors.New("illegal window increment value")
958 f.startWrite(FrameWindowUpdate, 0, streamID)
963 // A HeadersFrame is used to open a stream and additionally carries a
964 // header block fragment.
965 type HeadersFrame struct {
968 // Priority is set if FlagHeadersPriority is set in the FrameHeader.
969 Priority PriorityParam
971 headerFragBuf []byte // not owned
974 func (f *HeadersFrame) HeaderBlockFragment() []byte {
976 return f.headerFragBuf
979 func (f *HeadersFrame) HeadersEnded() bool {
980 return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
983 func (f *HeadersFrame) StreamEnded() bool {
984 return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
987 func (f *HeadersFrame) HasPriority() bool {
988 return f.FrameHeader.Flags.Has(FlagHeadersPriority)
991 func parseHeadersFrame(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) {
995 if fh.StreamID == 0 {
996 // HEADERS frames MUST be associated with a stream. If a HEADERS frame
997 // is received whose stream identifier field is 0x0, the recipient MUST
998 // respond with a connection error (Section 5.4.1) of type
1000 return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"}
1003 if fh.Flags.Has(FlagHeadersPadded) {
1004 if p, padLength, err = readByte(p); err != nil {
1008 if fh.Flags.Has(FlagHeadersPriority) {
1010 p, v, err = readUint32(p)
1014 hf.Priority.StreamDep = v & 0x7fffffff
1015 hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
1016 p, hf.Priority.Weight, err = readByte(p)
1021 if len(p)-int(padLength) <= 0 {
1022 return nil, streamError(fh.StreamID, ErrCodeProtocol)
1024 hf.headerFragBuf = p[:len(p)-int(padLength)]
1028 // HeadersFrameParam are the parameters for writing a HEADERS frame.
1029 type HeadersFrameParam struct {
1030 // StreamID is the required Stream ID to initiate.
1032 // BlockFragment is part (or all) of a Header Block.
1033 BlockFragment []byte
1035 // EndStream indicates that the header block is the last that
1036 // the endpoint will send for the identified stream. Setting
1037 // this flag causes the stream to enter one of "half closed"
1041 // EndHeaders indicates that this frame contains an entire
1042 // header block and is not followed by any
1043 // CONTINUATION frames.
1046 // PadLength is the optional number of bytes of zeros to add
1050 // Priority, if non-zero, includes stream priority information
1051 // in the HEADER frame.
1052 Priority PriorityParam
1055 // WriteHeaders writes a single HEADERS frame.
1057 // This is a low-level header writing method. Encoding headers and
1058 // splitting them into any necessary CONTINUATION frames is handled
1061 // It will perform exactly one Write to the underlying Writer.
1062 // It is the caller's responsibility to not call other Write methods concurrently.
1063 func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
1064 if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
1068 if p.PadLength != 0 {
1069 flags |= FlagHeadersPadded
1072 flags |= FlagHeadersEndStream
1075 flags |= FlagHeadersEndHeaders
1077 if !p.Priority.IsZero() {
1078 flags |= FlagHeadersPriority
1080 f.startWrite(FrameHeaders, flags, p.StreamID)
1081 if p.PadLength != 0 {
1082 f.writeByte(p.PadLength)
1084 if !p.Priority.IsZero() {
1085 v := p.Priority.StreamDep
1086 if !validStreamIDOrZero(v) && !f.AllowIllegalWrites {
1087 return errDepStreamID
1089 if p.Priority.Exclusive {
1093 f.writeByte(p.Priority.Weight)
1095 f.wbuf = append(f.wbuf, p.BlockFragment...)
1096 f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
1100 // A PriorityFrame specifies the sender-advised priority of a stream.
1101 // See http://http2.github.io/http2-spec/#rfc.section.6.3
1102 type PriorityFrame struct {
1107 // PriorityParam are the stream prioritzation parameters.
1108 type PriorityParam struct {
1109 // StreamDep is a 31-bit stream identifier for the
1110 // stream that this stream depends on. Zero means no
1114 // Exclusive is whether the dependency is exclusive.
1117 // Weight is the stream's zero-indexed weight. It should be
1118 // set together with StreamDep, or neither should be set. Per
1119 // the spec, "Add one to the value to obtain a weight between
1124 func (p PriorityParam) IsZero() bool {
1125 return p == PriorityParam{}
1128 func parsePriorityFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
1129 if fh.StreamID == 0 {
1130 return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"}
1132 if len(payload) != 5 {
1133 return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))}
1135 v := binary.BigEndian.Uint32(payload[:4])
1136 streamID := v & 0x7fffffff // mask off high bit
1137 return &PriorityFrame{
1139 PriorityParam: PriorityParam{
1141 StreamDep: streamID,
1142 Exclusive: streamID != v, // was high bit set?
1147 // WritePriority writes a PRIORITY frame.
1149 // It will perform exactly one Write to the underlying Writer.
1150 // It is the caller's responsibility to not call other Write methods concurrently.
1151 func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error {
1152 if !validStreamID(streamID) && !f.AllowIllegalWrites {
1155 if !validStreamIDOrZero(p.StreamDep) {
1156 return errDepStreamID
1158 f.startWrite(FramePriority, 0, streamID)
1164 f.writeByte(p.Weight)
1168 // A RSTStreamFrame allows for abnormal termination of a stream.
1169 // See http://http2.github.io/http2-spec/#rfc.section.6.4
1170 type RSTStreamFrame struct {
1175 func parseRSTStreamFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
1177 return nil, ConnectionError(ErrCodeFrameSize)
1179 if fh.StreamID == 0 {
1180 return nil, ConnectionError(ErrCodeProtocol)
1182 return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
1185 // WriteRSTStream writes a RST_STREAM frame.
1187 // It will perform exactly one Write to the underlying Writer.
1188 // It is the caller's responsibility to not call other Write methods concurrently.
1189 func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
1190 if !validStreamID(streamID) && !f.AllowIllegalWrites {
1193 f.startWrite(FrameRSTStream, 0, streamID)
1194 f.writeUint32(uint32(code))
1198 // A ContinuationFrame is used to continue a sequence of header block fragments.
1199 // See http://http2.github.io/http2-spec/#rfc.section.6.10
1200 type ContinuationFrame struct {
1202 headerFragBuf []byte
1205 func parseContinuationFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
1206 if fh.StreamID == 0 {
1207 return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"}
1209 return &ContinuationFrame{fh, p}, nil
1212 func (f *ContinuationFrame) HeaderBlockFragment() []byte {
1214 return f.headerFragBuf
1217 func (f *ContinuationFrame) HeadersEnded() bool {
1218 return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
1221 // WriteContinuation writes a CONTINUATION frame.
1223 // It will perform exactly one Write to the underlying Writer.
1224 // It is the caller's responsibility to not call other Write methods concurrently.
1225 func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
1226 if !validStreamID(streamID) && !f.AllowIllegalWrites {
1231 flags |= FlagContinuationEndHeaders
1233 f.startWrite(FrameContinuation, flags, streamID)
1234 f.wbuf = append(f.wbuf, headerBlockFragment...)
1238 // A PushPromiseFrame is used to initiate a server stream.
1239 // See http://http2.github.io/http2-spec/#rfc.section.6.6
1240 type PushPromiseFrame struct {
1243 headerFragBuf []byte // not owned
1246 func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
1248 return f.headerFragBuf
1251 func (f *PushPromiseFrame) HeadersEnded() bool {
1252 return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
1255 func parsePushPromise(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) {
1256 pp := &PushPromiseFrame{
1259 if pp.StreamID == 0 {
1260 // PUSH_PROMISE frames MUST be associated with an existing,
1261 // peer-initiated stream. The stream identifier of a
1262 // PUSH_PROMISE frame indicates the stream it is associated
1263 // with. If the stream identifier field specifies the value
1264 // 0x0, a recipient MUST respond with a connection error
1265 // (Section 5.4.1) of type PROTOCOL_ERROR.
1266 return nil, ConnectionError(ErrCodeProtocol)
1268 // The PUSH_PROMISE frame includes optional padding.
1269 // Padding fields and flags are identical to those defined for DATA frames
1271 if fh.Flags.Has(FlagPushPromisePadded) {
1272 if p, padLength, err = readByte(p); err != nil {
1277 p, pp.PromiseID, err = readUint32(p)
1281 pp.PromiseID = pp.PromiseID & (1<<31 - 1)
1283 if int(padLength) > len(p) {
1284 // like the DATA frame, error out if padding is longer than the body.
1285 return nil, ConnectionError(ErrCodeProtocol)
1287 pp.headerFragBuf = p[:len(p)-int(padLength)]
1291 // PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
1292 type PushPromiseParam struct {
1293 // StreamID is the required Stream ID to initiate.
1296 // PromiseID is the required Stream ID which this
1300 // BlockFragment is part (or all) of a Header Block.
1301 BlockFragment []byte
1303 // EndHeaders indicates that this frame contains an entire
1304 // header block and is not followed by any
1305 // CONTINUATION frames.
1308 // PadLength is the optional number of bytes of zeros to add
1313 // WritePushPromise writes a single PushPromise Frame.
1315 // As with Header Frames, This is the low level call for writing
1316 // individual frames. Continuation frames are handled elsewhere.
1318 // It will perform exactly one Write to the underlying Writer.
1319 // It is the caller's responsibility to not call other Write methods concurrently.
1320 func (f *Framer) WritePushPromise(p PushPromiseParam) error {
1321 if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
1325 if p.PadLength != 0 {
1326 flags |= FlagPushPromisePadded
1329 flags |= FlagPushPromiseEndHeaders
1331 f.startWrite(FramePushPromise, flags, p.StreamID)
1332 if p.PadLength != 0 {
1333 f.writeByte(p.PadLength)
1335 if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
1338 f.writeUint32(p.PromiseID)
1339 f.wbuf = append(f.wbuf, p.BlockFragment...)
1340 f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
1344 // WriteRawFrame writes a raw frame. This can be used to write
1345 // extension frames unknown to this package.
1346 func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
1347 f.startWrite(t, flags, streamID)
1348 f.writeBytes(payload)
1352 func readByte(p []byte) (remain []byte, b byte, err error) {
1354 return nil, 0, io.ErrUnexpectedEOF
1356 return p[1:], p[0], nil
1359 func readUint32(p []byte) (remain []byte, v uint32, err error) {
1361 return nil, 0, io.ErrUnexpectedEOF
1363 return p[4:], binary.BigEndian.Uint32(p[:4]), nil
1366 type streamEnder interface {
1370 type headersEnder interface {
1374 type headersOrContinuation interface {
1376 HeaderBlockFragment() []byte
1379 // A MetaHeadersFrame is the representation of one HEADERS frame and
1380 // zero or more contiguous CONTINUATION frames and the decoding of
1381 // their HPACK-encoded contents.
1383 // This type of frame does not appear on the wire and is only returned
1384 // by the Framer when Framer.ReadMetaHeaders is set.
1385 type MetaHeadersFrame struct {
1388 // Fields are the fields contained in the HEADERS and
1389 // CONTINUATION frames. The underlying slice is owned by the
1390 // Framer and must not be retained after the next call to
1393 // Fields are guaranteed to be in the correct http2 order and
1394 // not have unknown pseudo header fields or invalid header
1395 // field names or values. Required pseudo header fields may be
1396 // missing, however. Use the MetaHeadersFrame.Pseudo accessor
1397 // method access pseudo headers.
1398 Fields []hpack.HeaderField
1400 // Truncated is whether the max header list size limit was hit
1401 // and Fields is incomplete. The hpack decoder state is still
1406 // PseudoValue returns the given pseudo header field's value.
1407 // The provided pseudo field should not contain the leading colon.
1408 func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string {
1409 for _, hf := range mh.Fields {
1413 if hf.Name[1:] == pseudo {
1420 // RegularFields returns the regular (non-pseudo) header fields of mh.
1421 // The caller does not own the returned slice.
1422 func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField {
1423 for i, hf := range mh.Fields {
1425 return mh.Fields[i:]
1431 // PseudoFields returns the pseudo header fields of mh.
1432 // The caller does not own the returned slice.
1433 func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField {
1434 for i, hf := range mh.Fields {
1436 return mh.Fields[:i]
1442 func (mh *MetaHeadersFrame) checkPseudos() error {
1443 var isRequest, isResponse bool
1444 pf := mh.PseudoFields()
1445 for i, hf := range pf {
1447 case ":method", ":path", ":scheme", ":authority":
1452 return pseudoHeaderError(hf.Name)
1454 // Check for duplicates.
1455 // This would be a bad algorithm, but N is 4.
1456 // And this doesn't allocate.
1457 for _, hf2 := range pf[:i] {
1458 if hf.Name == hf2.Name {
1459 return duplicatePseudoHeaderError(hf.Name)
1463 if isRequest && isResponse {
1464 return errMixPseudoHeaderTypes
1469 func (fr *Framer) maxHeaderStringLen() int {
1470 v := fr.maxHeaderListSize()
1471 if uint32(int(v)) == v {
1474 // They had a crazy big number for MaxHeaderBytes anyway,
1475 // so give them unlimited header lengths:
1479 // readMetaFrame returns 0 or more CONTINUATION frames from fr and
1480 // merge them into the provided hf and returns a MetaHeadersFrame
1481 // with the decoded hpack values.
1482 func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) {
1483 if fr.AllowIllegalReads {
1484 return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders")
1486 mh := &MetaHeadersFrame{
1489 var remainSize = fr.maxHeaderListSize()
1492 var invalid error // pseudo header field errors
1493 hdec := fr.ReadMetaHeaders
1494 hdec.SetEmitEnabled(true)
1495 hdec.SetMaxStringLength(fr.maxHeaderStringLen())
1496 hdec.SetEmitFunc(func(hf hpack.HeaderField) {
1497 if VerboseLogs && fr.logReads {
1498 fr.debugReadLoggerf("http2: decoded hpack field %+v", hf)
1500 if !httpguts.ValidHeaderFieldValue(hf.Value) {
1501 invalid = headerFieldValueError(hf.Value)
1503 isPseudo := strings.HasPrefix(hf.Name, ":")
1506 invalid = errPseudoAfterRegular
1510 if !validWireHeaderFieldName(hf.Name) {
1511 invalid = headerFieldNameError(hf.Name)
1516 hdec.SetEmitEnabled(false)
1521 if size > remainSize {
1522 hdec.SetEmitEnabled(false)
1528 mh.Fields = append(mh.Fields, hf)
1530 // Lose reference to MetaHeadersFrame:
1531 defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {})
1533 var hc headersOrContinuation = hf
1535 frag := hc.HeaderBlockFragment()
1536 if _, err := hdec.Write(frag); err != nil {
1537 return nil, ConnectionError(ErrCodeCompression)
1540 if hc.HeadersEnded() {
1543 if f, err := fr.ReadFrame(); err != nil {
1546 hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder
1550 mh.HeadersFrame.headerFragBuf = nil
1551 mh.HeadersFrame.invalidate()
1553 if err := hdec.Close(); err != nil {
1554 return nil, ConnectionError(ErrCodeCompression)
1557 fr.errDetail = invalid
1559 log.Printf("http2: invalid header: %v", invalid)
1561 return nil, StreamError{mh.StreamID, ErrCodeProtocol, invalid}
1563 if err := mh.checkPseudos(); err != nil {
1566 log.Printf("http2: invalid pseudo headers: %v", err)
1568 return nil, StreamError{mh.StreamID, ErrCodeProtocol, err}
1573 func summarizeFrame(f Frame) string {
1574 var buf bytes.Buffer
1575 f.Header().writeDebug(&buf)
1576 switch f := f.(type) {
1577 case *SettingsFrame:
1579 f.ForeachSetting(func(s Setting) error {
1582 buf.WriteString(", settings:")
1584 fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val)
1588 buf.Truncate(buf.Len() - 1) // remove trailing comma
1593 if len(data) > max {
1596 fmt.Fprintf(&buf, " data=%q", data)
1597 if len(f.Data()) > max {
1598 fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max)
1600 case *WindowUpdateFrame:
1601 if f.StreamID == 0 {
1602 buf.WriteString(" (conn)")
1604 fmt.Fprintf(&buf, " incr=%v", f.Increment)
1606 fmt.Fprintf(&buf, " ping=%q", f.Data[:])
1608 fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q",
1609 f.LastStreamID, f.ErrCode, f.debugData)
1610 case *RSTStreamFrame:
1611 fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode)