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
5package http2
6
7import (
8	"bytes"
9	"encoding/binary"
10	"errors"
11	"fmt"
12	"io"
13	"log"
14	"strings"
15	"sync"
16
17	"golang.org/x/net/http/httpguts"
18	"golang.org/x/net/http2/hpack"
19)
20
21const frameHeaderLen = 9
22
23var padZeros = make([]byte, 255) // zeros for padding
24
25// A FrameType is a registered frame type as defined in
26// http://http2.github.io/http2-spec/#rfc.section.11.2
27type FrameType uint8
28
29const (
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
40)
41
42var frameName = map[FrameType]string{
43	FrameData:         "DATA",
44	FrameHeaders:      "HEADERS",
45	FramePriority:     "PRIORITY",
46	FrameRSTStream:    "RST_STREAM",
47	FrameSettings:     "SETTINGS",
48	FramePushPromise:  "PUSH_PROMISE",
49	FramePing:         "PING",
50	FrameGoAway:       "GOAWAY",
51	FrameWindowUpdate: "WINDOW_UPDATE",
52	FrameContinuation: "CONTINUATION",
53}
54
55func (t FrameType) String() string {
56	if s, ok := frameName[t]; ok {
57		return s
58	}
59	return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", uint8(t))
60}
61
62// Flags is a bitmask of HTTP/2 flags.
63// The meaning of flags varies depending on the frame type.
64type Flags uint8
65
66// Has reports whether f contains all (0 or more) flags in v.
67func (f Flags) Has(v Flags) bool {
68	return (f & v) == v
69}
70
71// Frame-specific FrameHeader flag bits.
72const (
73	// Data Frame
74	FlagDataEndStream Flags = 0x1
75	FlagDataPadded    Flags = 0x8
76
77	// Headers Frame
78	FlagHeadersEndStream  Flags = 0x1
79	FlagHeadersEndHeaders Flags = 0x4
80	FlagHeadersPadded     Flags = 0x8
81	FlagHeadersPriority   Flags = 0x20
82
83	// Settings Frame
84	FlagSettingsAck Flags = 0x1
85
86	// Ping Frame
87	FlagPingAck Flags = 0x1
88
89	// Continuation Frame
90	FlagContinuationEndHeaders Flags = 0x4
91
92	FlagPushPromiseEndHeaders Flags = 0x4
93	FlagPushPromisePadded     Flags = 0x8
94)
95
96var flagName = map[FrameType]map[Flags]string{
97	FrameData: {
98		FlagDataEndStream: "END_STREAM",
99		FlagDataPadded:    "PADDED",
100	},
101	FrameHeaders: {
102		FlagHeadersEndStream:  "END_STREAM",
103		FlagHeadersEndHeaders: "END_HEADERS",
104		FlagHeadersPadded:     "PADDED",
105		FlagHeadersPriority:   "PRIORITY",
106	},
107	FrameSettings: {
108		FlagSettingsAck: "ACK",
109	},
110	FramePing: {
111		FlagPingAck: "ACK",
112	},
113	FrameContinuation: {
114		FlagContinuationEndHeaders: "END_HEADERS",
115	},
116	FramePushPromise: {
117		FlagPushPromiseEndHeaders: "END_HEADERS",
118		FlagPushPromisePadded:     "PADDED",
119	},
120}
121
122// a frameParser parses a frame given its FrameHeader and payload
123// bytes. The length of payload will always equal fh.Length (which
124// might be 0).
125type frameParser func(fc *frameCache, fh FrameHeader, payload []byte) (Frame, error)
126
127var 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,
138}
139
140func typeFrameParser(t FrameType) frameParser {
141	if f := frameParsers[t]; f != nil {
142		return f
143	}
144	return parseUnknownFrame
145}
146
147// A FrameHeader is the 9 byte header of all HTTP/2 frames.
148//
149// See http://http2.github.io/http2-spec/#FrameHeader
150type FrameHeader struct {
151	valid bool // caller can access []byte fields in the Frame
152
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).
156	Type FrameType
157
158	// Flags are the 1 byte of 8 potential bit flags per frame.
159	// They are specific to the frame type.
160	Flags Flags
161
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.
165	Length uint32
166
167	// StreamID is which stream this frame is for. Certain frames
168	// are not stream-specific, in which case this field is 0.
169	StreamID uint32
170}
171
172// Header returns h. It exists so FrameHeaders can be embedded in other
173// specific frame types and implement the Frame interface.
174func (h FrameHeader) Header() FrameHeader { return h }
175
176func (h FrameHeader) String() string {
177	var buf bytes.Buffer
178	buf.WriteString("[FrameHeader ")
179	h.writeDebug(&buf)
180	buf.WriteByte(']')
181	return buf.String()
182}
183
184func (h FrameHeader) writeDebug(buf *bytes.Buffer) {
185	buf.WriteString(h.Type.String())
186	if h.Flags != 0 {
187		buf.WriteString(" flags=")
188		set := 0
189		for i := uint8(0); i < 8; i++ {
190			if h.Flags&(1<<i) == 0 {
191				continue
192			}
193			set++
194			if set > 1 {
195				buf.WriteByte('|')
196			}
197			name := flagName[h.Type][Flags(1<<i)]
198			if name != "" {
199				buf.WriteString(name)
200			} else {
201				fmt.Fprintf(buf, "0x%x", 1<<i)
202			}
203		}
204	}
205	if h.StreamID != 0 {
206		fmt.Fprintf(buf, " stream=%d", h.StreamID)
207	}
208	fmt.Fprintf(buf, " len=%d", h.Length)
209}
210
211func (h *FrameHeader) checkValid() {
212	if !h.valid {
213		panic("Frame accessor called on non-owned Frame")
214	}
215}
216
217func (h *FrameHeader) invalidate() { h.valid = false }
218
219// frame header bytes.
220// Used only by ReadFrameHeader.
221var fhBytes = sync.Pool{
222	New: func() interface{} {
223		buf := make([]byte, frameHeaderLen)
224		return &buf
225	},
226}
227
228// ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
229// Most users should use Framer.ReadFrame instead.
230func ReadFrameHeader(r io.Reader) (FrameHeader, error) {
231	bufp := fhBytes.Get().(*[]byte)
232	defer fhBytes.Put(bufp)
233	return readFrameHeader(*bufp, r)
234}
235
236func readFrameHeader(buf []byte, r io.Reader) (FrameHeader, error) {
237	_, err := io.ReadFull(r, buf[:frameHeaderLen])
238	if err != nil {
239		return FrameHeader{}, err
240	}
241	return FrameHeader{
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),
246		valid:    true,
247	}, nil
248}
249
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.
253//
254// Frames are only valid until the next call to Framer.ReadFrame.
255type Frame interface {
256	Header() FrameHeader
257
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.
261	invalidate()
262}
263
264// A Framer reads and writes Frames.
265type Framer struct {
266	r         io.Reader
267	lastFrame Frame
268	errDetail error
269
270	// lastHeaderStream is non-zero if the last frame was an
271	// unfinished HEADERS/CONTINUATION.
272	lastHeaderStream uint32
273
274	maxReadSize uint32
275	headerBuf   [frameHeaderLen]byte
276
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
282
283	maxWriteSize uint32 // zero means unlimited; TODO: implement
284
285	w    io.Writer
286	wbuf []byte
287
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
295
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
302
303	// ReadMetaHeaders if non-nil causes ReadFrame to merge
304	// HEADERS and CONTINUATION frames together and return
305	// MetaHeadersFrame instead.
306	ReadMetaHeaders *hpack.Decoder
307
308	// MaxHeaderListSize is the http2 MAX_HEADER_LIST_SIZE.
309	// It's used only if ReadMetaHeaders is set; 0 means a sane default
310	// (currently 16MB)
311	// If the limit is hit, MetaHeadersFrame.Truncated is set true.
312	MaxHeaderListSize uint32
313
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.
319
320	logReads, logWrites bool
321
322	debugFramer       *Framer // only use for logging written writes
323	debugFramerBuf    *bytes.Buffer
324	debugReadLoggerf  func(string, ...interface{})
325	debugWriteLoggerf func(string, ...interface{})
326
327	frameCache *frameCache // nil if frames aren't reused (default)
328}
329
330func (fr *Framer) maxHeaderListSize() uint32 {
331	if fr.MaxHeaderListSize == 0 {
332		return 16 << 20 // sane default, per docs
333	}
334	return fr.MaxHeaderListSize
335}
336
337func (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
341		0,
342		0,
343		byte(ftype),
344		byte(flags),
345		byte(streamID>>24),
346		byte(streamID>>16),
347		byte(streamID>>8),
348		byte(streamID))
349}
350
351func (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
357	}
358	_ = append(f.wbuf[:0],
359		byte(length>>16),
360		byte(length>>8),
361		byte(length))
362	if f.logWrites {
363		f.logWrite()
364	}
365
366	n, err := f.w.Write(f.wbuf)
367	if err == nil && n != len(f.wbuf) {
368		err = io.ErrShortWrite
369	}
370	return err
371}
372
373func (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
381	}
382	f.debugFramerBuf.Write(f.wbuf)
383	fr, err := f.debugFramer.ReadFrame()
384	if err != nil {
385		f.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", f)
386		return
387	}
388	f.debugWriteLoggerf("http2: Framer %p: wrote %v", f, summarizeFrame(fr))
389}
390
391func (f *Framer) writeByte(v byte)     { f.wbuf = append(f.wbuf, v) }
392func (f *Framer) writeBytes(v []byte)  { f.wbuf = append(f.wbuf, v...) }
393func (f *Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) }
394func (f *Framer) writeUint32(v uint32) {
395	f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
396}
397
398const (
399	minMaxFrameSize = 1 << 14
400	maxFrameSize    = 1<<24 - 1
401)
402
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.
406func (fr *Framer) SetReuseFrames() {
407	if fr.frameCache != nil {
408		return
409	}
410	fr.frameCache = &frameCache{}
411}
412
413type frameCache struct {
414	dataFrame DataFrame
415}
416
417func (fc *frameCache) getDataFrame() *DataFrame {
418	if fc == nil {
419		return &DataFrame{}
420	}
421	return &fc.dataFrame
422}
423
424// NewFramer returns a Framer that writes frames to w and reads them from r.
425func NewFramer(w io.Writer, r io.Reader) *Framer {
426	fr := &Framer{
427		w:                 w,
428		r:                 r,
429		logReads:          logFrameReads,
430		logWrites:         logFrameWrites,
431		debugReadLoggerf:  log.Printf,
432		debugWriteLoggerf: log.Printf,
433	}
434	fr.getReadBuf = func(size uint32) []byte {
435		if cap(fr.readBuf) >= int(size) {
436			return fr.readBuf[:size]
437		}
438		fr.readBuf = make([]byte, size)
439		return fr.readBuf
440	}
441	fr.SetMaxReadFrameSize(maxFrameSize)
442	return fr
443}
444
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.
449func (fr *Framer) SetMaxReadFrameSize(v uint32) {
450	if v > maxFrameSize {
451		v = maxFrameSize
452	}
453	fr.maxReadSize = v
454}
455
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.
463func (fr *Framer) ErrorDetail() error {
464	return fr.errDetail
465}
466
467// ErrFrameTooLarge is returned from Framer.ReadFrame when the peer
468// sends a frame that is larger than declared with SetMaxReadFrameSize.
469var ErrFrameTooLarge = errors.New("http2: frame too large")
470
471// terminalReadFrameError reports whether err is an unrecoverable
472// error from ReadFrame and no other frames should be read.
473func terminalReadFrameError(err error) bool {
474	if _, ok := err.(StreamError); ok {
475		return false
476	}
477	return err != nil
478}
479
480// ReadFrame reads a single frame. The returned Frame is only valid
481// until the next call to ReadFrame.
482//
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
486// reader.
487func (fr *Framer) ReadFrame() (Frame, error) {
488	fr.errDetail = nil
489	if fr.lastFrame != nil {
490		fr.lastFrame.invalidate()
491	}
492	fh, err := readFrameHeader(fr.headerBuf[:], fr.r)
493	if err != nil {
494		return nil, err
495	}
496	if fh.Length > fr.maxReadSize {
497		return nil, ErrFrameTooLarge
498	}
499	payload := fr.getReadBuf(fh.Length)
500	if _, err := io.ReadFull(fr.r, payload); err != nil {
501		return nil, err
502	}
503	f, err := typeFrameParser(fh.Type)(fr.frameCache, fh, payload)
504	if err != nil {
505		if ce, ok := err.(connError); ok {
506			return nil, fr.connError(ce.Code, ce.Reason)
507		}
508		return nil, err
509	}
510	if err := fr.checkFrameOrder(f); err != nil {
511		return nil, err
512	}
513	if fr.logReads {
514		fr.debugReadLoggerf("http2: Framer %p: read %v", fr, summarizeFrame(f))
515	}
516	if fh.Type == FrameHeaders && fr.ReadMetaHeaders != nil {
517		return fr.readMetaFrame(f.(*HeadersFrame))
518	}
519	return f, nil
520}
521
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.
526func (fr *Framer) connError(code ErrCode, reason string) error {
527	fr.errDetail = errors.New(reason)
528	return ConnectionError(code)
529}
530
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.
534func (fr *Framer) checkFrameOrder(f Frame) error {
535	last := fr.lastFrame
536	fr.lastFrame = f
537	if fr.AllowIllegalReads {
538		return nil
539	}
540
541	fh := f.Header()
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))
548		}
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))
553		}
554	} else if fh.Type == FrameContinuation {
555		return fr.connError(ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", fh.StreamID))
556	}
557
558	switch fh.Type {
559	case FrameHeaders, FrameContinuation:
560		if fh.Flags.Has(FlagHeadersEndHeaders) {
561			fr.lastHeaderStream = 0
562		} else {
563			fr.lastHeaderStream = fh.StreamID
564		}
565	}
566
567	return nil
568}
569
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
573type DataFrame struct {
574	FrameHeader
575	data []byte
576}
577
578func (f *DataFrame) StreamEnded() bool {
579	return f.FrameHeader.Flags.Has(FlagDataEndStream)
580}
581
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.
586func (f *DataFrame) Data() []byte {
587	f.checkValid()
588	return f.data
589}
590
591func 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
597		// PROTOCOL_ERROR.
598		return nil, connError{ErrCodeProtocol, "DATA frame with stream ID 0"}
599	}
600	f := fc.getDataFrame()
601	f.FrameHeader = fh
602
603	var padSize byte
604	if fh.Flags.Has(FlagDataPadded) {
605		var err error
606		payload, padSize, err = readByte(payload)
607		if err != nil {
608			return nil, err
609		}
610	}
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"}
617	}
618	f.data = payload[:len(payload)-int(padSize)]
619	return f, nil
620}
621
622var (
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")
627)
628
629func validStreamIDOrZero(streamID uint32) bool {
630	return streamID&(1<<31) == 0
631}
632
633func validStreamID(streamID uint32) bool {
634	return streamID != 0 && streamID&(1<<31) == 0
635}
636
637// WriteData writes a DATA frame.
638//
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.
642func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
643	return f.WriteDataPadded(streamID, endStream, data, nil)
644}
645
646// WriteDataPadded writes a DATA frame with optional padding.
647//
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.
651//
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.
655func (f *Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
656	if !validStreamID(streamID) && !f.AllowIllegalWrites {
657		return errStreamID
658	}
659	if len(pad) > 0 {
660		if len(pad) > 255 {
661			return errPadLength
662		}
663		if !f.AllowIllegalWrites {
664			for _, b := range pad {
665				if b != 0 {
666					// "Padding octets MUST be set to zero when sending."
667					return errPadBytes
668				}
669			}
670		}
671	}
672	var flags Flags
673	if endStream {
674		flags |= FlagDataEndStream
675	}
676	if pad != nil {
677		flags |= FlagDataPadded
678	}
679	f.startWrite(FrameData, flags, streamID)
680	if pad != nil {
681		f.wbuf = append(f.wbuf, byte(len(pad)))
682	}
683	f.wbuf = append(f.wbuf, data...)
684	f.wbuf = append(f.wbuf, pad...)
685	return f.endWrite()
686}
687
688// A SettingsFrame conveys configuration parameters that affect how
689// endpoints communicate, such as preferences and constraints on peer
690// behavior.
691//
692// See http://http2.github.io/http2-spec/#SETTINGS
693type SettingsFrame struct {
694	FrameHeader
695	p []byte
696}
697
698func 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
705		// FRAME_SIZE_ERROR.
706		return nil, ConnectionError(ErrCodeFrameSize)
707	}
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)
717	}
718	if len(p)%6 != 0 {
719		// Expecting even number of 6 byte settings.
720		return nil, ConnectionError(ErrCodeFrameSize)
721	}
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)
728	}
729	return f, nil
730}
731
732func (f *SettingsFrame) IsAck() bool {
733	return f.FrameHeader.Flags.Has(FlagSettingsAck)
734}
735
736func (f *SettingsFrame) Value(id SettingID) (v uint32, ok bool) {
737	f.checkValid()
738	for i := 0; i < f.NumSettings(); i++ {
739		if s := f.Setting(i); s.ID == id {
740			return s.Val, true
741		}
742	}
743	return 0, false
744}
745
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().
748func (f *SettingsFrame) Setting(i int) Setting {
749	buf := f.p
750	return 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]),
753	}
754}
755
756func (f *SettingsFrame) NumSettings() int { return len(f.p) / 6 }
757
758// HasDuplicates reports whether f contains any duplicate setting IDs.
759func (f *SettingsFrame) HasDuplicates() bool {
760	num := f.NumSettings()
761	if num == 0 {
762		return false
763	}
764	// If it's small enough (the common case), just do the n^2
765	// thing and avoid a map allocation.
766	if num < 10 {
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
771				if idi == idj {
772					return true
773				}
774			}
775		}
776		return false
777	}
778	seen := map[SettingID]bool{}
779	for i := 0; i < num; i++ {
780		id := f.Setting(i).ID
781		if seen[id] {
782			return true
783		}
784		seen[id] = true
785	}
786	return false
787}
788
789// ForeachSetting runs fn for each setting.
790// It stops and returns the first error.
791func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error {
792	f.checkValid()
793	for i := 0; i < f.NumSettings(); i++ {
794		if err := fn(f.Setting(i)); err != nil {
795			return err
796		}
797	}
798	return nil
799}
800
801// WriteSettings writes a SETTINGS frame with zero or more settings
802// specified and the ACK bit not set.
803//
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.
806func (f *Framer) WriteSettings(settings ...Setting) error {
807	f.startWrite(FrameSettings, 0, 0)
808	for _, s := range settings {
809		f.writeUint16(uint16(s.ID))
810		f.writeUint32(s.Val)
811	}
812	return f.endWrite()
813}
814
815// WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set.
816//
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.
819func (f *Framer) WriteSettingsAck() error {
820	f.startWrite(FrameSettings, FlagSettingsAck, 0)
821	return f.endWrite()
822}
823
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
828type PingFrame struct {
829	FrameHeader
830	Data [8]byte
831}
832
833func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) }
834
835func parsePingFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
836	if len(payload) != 8 {
837		return nil, ConnectionError(ErrCodeFrameSize)
838	}
839	if fh.StreamID != 0 {
840		return nil, ConnectionError(ErrCodeProtocol)
841	}
842	f := &PingFrame{FrameHeader: fh}
843	copy(f.Data[:], payload)
844	return f, nil
845}
846
847func (f *Framer) WritePing(ack bool, data [8]byte) error {
848	var flags Flags
849	if ack {
850		flags = FlagPingAck
851	}
852	f.startWrite(FramePing, flags, 0)
853	f.writeBytes(data[:])
854	return f.endWrite()
855}
856
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
859type GoAwayFrame struct {
860	FrameHeader
861	LastStreamID uint32
862	ErrCode      ErrCode
863	debugData    []byte
864}
865
866// DebugData returns any debug data in the GOAWAY frame. Its contents
867// are not defined.
868// The caller must not retain the returned memory past the next
869// call to ReadFrame.
870func (f *GoAwayFrame) DebugData() []byte {
871	f.checkValid()
872	return f.debugData
873}
874
875func parseGoAwayFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
876	if fh.StreamID != 0 {
877		return nil, ConnectionError(ErrCodeProtocol)
878	}
879	if len(p) < 8 {
880		return nil, ConnectionError(ErrCodeFrameSize)
881	}
882	return &GoAwayFrame{
883		FrameHeader:  fh,
884		LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
885		ErrCode:      ErrCode(binary.BigEndian.Uint32(p[4:8])),
886		debugData:    p[8:],
887	}, nil
888}
889
890func (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)
895	return f.endWrite()
896}
897
898// An UnknownFrame is the frame type returned when the frame type is unknown
899// or no specific frame type parser exists.
900type UnknownFrame struct {
901	FrameHeader
902	p []byte
903}
904
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
909// frame is read.
910func (f *UnknownFrame) Payload() []byte {
911	f.checkValid()
912	return f.p
913}
914
915func parseUnknownFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
916	return &UnknownFrame{fh, p}, nil
917}
918
919// A WindowUpdateFrame is used to implement flow control.
920// See http://http2.github.io/http2-spec/#rfc.section.6.9
921type WindowUpdateFrame struct {
922	FrameHeader
923	Increment uint32 // never read with high bit set
924}
925
926func parseWindowUpdateFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
927	if len(p) != 4 {
928		return nil, ConnectionError(ErrCodeFrameSize)
929	}
930	inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
931	if inc == 0 {
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)
940		}
941		return nil, streamError(fh.StreamID, ErrCodeProtocol)
942	}
943	return &WindowUpdateFrame{
944		FrameHeader: fh,
945		Increment:   inc,
946	}, nil
947}
948
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.
953func (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")
957	}
958	f.startWrite(FrameWindowUpdate, 0, streamID)
959	f.writeUint32(incr)
960	return f.endWrite()
961}
962
963// A HeadersFrame is used to open a stream and additionally carries a
964// header block fragment.
965type HeadersFrame struct {
966	FrameHeader
967
968	// Priority is set if FlagHeadersPriority is set in the FrameHeader.
969	Priority PriorityParam
970
971	headerFragBuf []byte // not owned
972}
973
974func (f *HeadersFrame) HeaderBlockFragment() []byte {
975	f.checkValid()
976	return f.headerFragBuf
977}
978
979func (f *HeadersFrame) HeadersEnded() bool {
980	return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
981}
982
983func (f *HeadersFrame) StreamEnded() bool {
984	return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
985}
986
987func (f *HeadersFrame) HasPriority() bool {
988	return f.FrameHeader.Flags.Has(FlagHeadersPriority)
989}
990
991func parseHeadersFrame(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) {
992	hf := &HeadersFrame{
993		FrameHeader: fh,
994	}
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
999		// PROTOCOL_ERROR.
1000		return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"}
1001	}
1002	var padLength uint8
1003	if fh.Flags.Has(FlagHeadersPadded) {
1004		if p, padLength, err = readByte(p); err != nil {
1005			return
1006		}
1007	}
1008	if fh.Flags.Has(FlagHeadersPriority) {
1009		var v uint32
1010		p, v, err = readUint32(p)
1011		if err != nil {
1012			return nil, err
1013		}
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)
1017		if err != nil {
1018			return nil, err
1019		}
1020	}
1021	if len(p)-int(padLength) <= 0 {
1022		return nil, streamError(fh.StreamID, ErrCodeProtocol)
1023	}
1024	hf.headerFragBuf = p[:len(p)-int(padLength)]
1025	return hf, nil
1026}
1027
1028// HeadersFrameParam are the parameters for writing a HEADERS frame.
1029type HeadersFrameParam struct {
1030	// StreamID is the required Stream ID to initiate.
1031	StreamID uint32
1032	// BlockFragment is part (or all) of a Header Block.
1033	BlockFragment []byte
1034
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"
1038	// states.
1039	EndStream bool
1040
1041	// EndHeaders indicates that this frame contains an entire
1042	// header block and is not followed by any
1043	// CONTINUATION frames.
1044	EndHeaders bool
1045
1046	// PadLength is the optional number of bytes of zeros to add
1047	// to this frame.
1048	PadLength uint8
1049
1050	// Priority, if non-zero, includes stream priority information
1051	// in the HEADER frame.
1052	Priority PriorityParam
1053}
1054
1055// WriteHeaders writes a single HEADERS frame.
1056//
1057// This is a low-level header writing method. Encoding headers and
1058// splitting them into any necessary CONTINUATION frames is handled
1059// elsewhere.
1060//
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.
1063func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
1064	if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
1065		return errStreamID
1066	}
1067	var flags Flags
1068	if p.PadLength != 0 {
1069		flags |= FlagHeadersPadded
1070	}
1071	if p.EndStream {
1072		flags |= FlagHeadersEndStream
1073	}
1074	if p.EndHeaders {
1075		flags |= FlagHeadersEndHeaders
1076	}
1077	if !p.Priority.IsZero() {
1078		flags |= FlagHeadersPriority
1079	}
1080	f.startWrite(FrameHeaders, flags, p.StreamID)
1081	if p.PadLength != 0 {
1082		f.writeByte(p.PadLength)
1083	}
1084	if !p.Priority.IsZero() {
1085		v := p.Priority.StreamDep
1086		if !validStreamIDOrZero(v) && !f.AllowIllegalWrites {
1087			return errDepStreamID
1088		}
1089		if p.Priority.Exclusive {
1090			v |= 1 << 31
1091		}
1092		f.writeUint32(v)
1093		f.writeByte(p.Priority.Weight)
1094	}
1095	f.wbuf = append(f.wbuf, p.BlockFragment...)
1096	f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
1097	return f.endWrite()
1098}
1099
1100// A PriorityFrame specifies the sender-advised priority of a stream.
1101// See http://http2.github.io/http2-spec/#rfc.section.6.3
1102type PriorityFrame struct {
1103	FrameHeader
1104	PriorityParam
1105}
1106
1107// PriorityParam are the stream prioritzation parameters.
1108type PriorityParam struct {
1109	// StreamDep is a 31-bit stream identifier for the
1110	// stream that this stream depends on. Zero means no
1111	// dependency.
1112	StreamDep uint32
1113
1114	// Exclusive is whether the dependency is exclusive.
1115	Exclusive bool
1116
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
1120	// 1 and 256."
1121	Weight uint8
1122}
1123
1124func (p PriorityParam) IsZero() bool {
1125	return p == PriorityParam{}
1126}
1127
1128func parsePriorityFrame(_ *frameCache, fh FrameHeader, payload []byte) (Frame, error) {
1129	if fh.StreamID == 0 {
1130		return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"}
1131	}
1132	if len(payload) != 5 {
1133		return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))}
1134	}
1135	v := binary.BigEndian.Uint32(payload[:4])
1136	streamID := v & 0x7fffffff // mask off high bit
1137	return &PriorityFrame{
1138		FrameHeader: fh,
1139		PriorityParam: PriorityParam{
1140			Weight:    payload[4],
1141			StreamDep: streamID,
1142			Exclusive: streamID != v, // was high bit set?
1143		},
1144	}, nil
1145}
1146
1147// WritePriority writes a PRIORITY frame.
1148//
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.
1151func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error {
1152	if !validStreamID(streamID) && !f.AllowIllegalWrites {
1153		return errStreamID
1154	}
1155	if !validStreamIDOrZero(p.StreamDep) {
1156		return errDepStreamID
1157	}
1158	f.startWrite(FramePriority, 0, streamID)
1159	v := p.StreamDep
1160	if p.Exclusive {
1161		v |= 1 << 31
1162	}
1163	f.writeUint32(v)
1164	f.writeByte(p.Weight)
1165	return f.endWrite()
1166}
1167
1168// A RSTStreamFrame allows for abnormal termination of a stream.
1169// See http://http2.github.io/http2-spec/#rfc.section.6.4
1170type RSTStreamFrame struct {
1171	FrameHeader
1172	ErrCode ErrCode
1173}
1174
1175func parseRSTStreamFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
1176	if len(p) != 4 {
1177		return nil, ConnectionError(ErrCodeFrameSize)
1178	}
1179	if fh.StreamID == 0 {
1180		return nil, ConnectionError(ErrCodeProtocol)
1181	}
1182	return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
1183}
1184
1185// WriteRSTStream writes a RST_STREAM frame.
1186//
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.
1189func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
1190	if !validStreamID(streamID) && !f.AllowIllegalWrites {
1191		return errStreamID
1192	}
1193	f.startWrite(FrameRSTStream, 0, streamID)
1194	f.writeUint32(uint32(code))
1195	return f.endWrite()
1196}
1197
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
1200type ContinuationFrame struct {
1201	FrameHeader
1202	headerFragBuf []byte
1203}
1204
1205func parseContinuationFrame(_ *frameCache, fh FrameHeader, p []byte) (Frame, error) {
1206	if fh.StreamID == 0 {
1207		return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"}
1208	}
1209	return &ContinuationFrame{fh, p}, nil
1210}
1211
1212func (f *ContinuationFrame) HeaderBlockFragment() []byte {
1213	f.checkValid()
1214	return f.headerFragBuf
1215}
1216
1217func (f *ContinuationFrame) HeadersEnded() bool {
1218	return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
1219}
1220
1221// WriteContinuation writes a CONTINUATION frame.
1222//
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.
1225func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
1226	if !validStreamID(streamID) && !f.AllowIllegalWrites {
1227		return errStreamID
1228	}
1229	var flags Flags
1230	if endHeaders {
1231		flags |= FlagContinuationEndHeaders
1232	}
1233	f.startWrite(FrameContinuation, flags, streamID)
1234	f.wbuf = append(f.wbuf, headerBlockFragment...)
1235	return f.endWrite()
1236}
1237
1238// A PushPromiseFrame is used to initiate a server stream.
1239// See http://http2.github.io/http2-spec/#rfc.section.6.6
1240type PushPromiseFrame struct {
1241	FrameHeader
1242	PromiseID     uint32
1243	headerFragBuf []byte // not owned
1244}
1245
1246func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
1247	f.checkValid()
1248	return f.headerFragBuf
1249}
1250
1251func (f *PushPromiseFrame) HeadersEnded() bool {
1252	return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
1253}
1254
1255func parsePushPromise(_ *frameCache, fh FrameHeader, p []byte) (_ Frame, err error) {
1256	pp := &PushPromiseFrame{
1257		FrameHeader: fh,
1258	}
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)
1267	}
1268	// The PUSH_PROMISE frame includes optional padding.
1269	// Padding fields and flags are identical to those defined for DATA frames
1270	var padLength uint8
1271	if fh.Flags.Has(FlagPushPromisePadded) {
1272		if p, padLength, err = readByte(p); err != nil {
1273			return
1274		}
1275	}
1276
1277	p, pp.PromiseID, err = readUint32(p)
1278	if err != nil {
1279		return
1280	}
1281	pp.PromiseID = pp.PromiseID & (1<<31 - 1)
1282
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)
1286	}
1287	pp.headerFragBuf = p[:len(p)-int(padLength)]
1288	return pp, nil
1289}
1290
1291// PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
1292type PushPromiseParam struct {
1293	// StreamID is the required Stream ID to initiate.
1294	StreamID uint32
1295
1296	// PromiseID is the required Stream ID which this
1297	// Push Promises
1298	PromiseID uint32
1299
1300	// BlockFragment is part (or all) of a Header Block.
1301	BlockFragment []byte
1302
1303	// EndHeaders indicates that this frame contains an entire
1304	// header block and is not followed by any
1305	// CONTINUATION frames.
1306	EndHeaders bool
1307
1308	// PadLength is the optional number of bytes of zeros to add
1309	// to this frame.
1310	PadLength uint8
1311}
1312
1313// WritePushPromise writes a single PushPromise Frame.
1314//
1315// As with Header Frames, This is the low level call for writing
1316// individual frames. Continuation frames are handled elsewhere.
1317//
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.
1320func (f *Framer) WritePushPromise(p PushPromiseParam) error {
1321	if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
1322		return errStreamID
1323	}
1324	var flags Flags
1325	if p.PadLength != 0 {
1326		flags |= FlagPushPromisePadded
1327	}
1328	if p.EndHeaders {
1329		flags |= FlagPushPromiseEndHeaders
1330	}
1331	f.startWrite(FramePushPromise, flags, p.StreamID)
1332	if p.PadLength != 0 {
1333		f.writeByte(p.PadLength)
1334	}
1335	if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
1336		return errStreamID
1337	}
1338	f.writeUint32(p.PromiseID)
1339	f.wbuf = append(f.wbuf, p.BlockFragment...)
1340	f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
1341	return f.endWrite()
1342}
1343
1344// WriteRawFrame writes a raw frame. This can be used to write
1345// extension frames unknown to this package.
1346func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
1347	f.startWrite(t, flags, streamID)
1348	f.writeBytes(payload)
1349	return f.endWrite()
1350}
1351
1352func readByte(p []byte) (remain []byte, b byte, err error) {
1353	if len(p) == 0 {
1354		return nil, 0, io.ErrUnexpectedEOF
1355	}
1356	return p[1:], p[0], nil
1357}
1358
1359func readUint32(p []byte) (remain []byte, v uint32, err error) {
1360	if len(p) < 4 {
1361		return nil, 0, io.ErrUnexpectedEOF
1362	}
1363	return p[4:], binary.BigEndian.Uint32(p[:4]), nil
1364}
1365
1366type streamEnder interface {
1367	StreamEnded() bool
1368}
1369
1370type headersEnder interface {
1371	HeadersEnded() bool
1372}
1373
1374type headersOrContinuation interface {
1375	headersEnder
1376	HeaderBlockFragment() []byte
1377}
1378
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.
1382//
1383// This type of frame does not appear on the wire and is only returned
1384// by the Framer when Framer.ReadMetaHeaders is set.
1385type MetaHeadersFrame struct {
1386	*HeadersFrame
1387
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
1391	// ReadFrame.
1392	//
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
1399
1400	// Truncated is whether the max header list size limit was hit
1401	// and Fields is incomplete. The hpack decoder state is still
1402	// valid, however.
1403	Truncated bool
1404}
1405
1406// PseudoValue returns the given pseudo header field's value.
1407// The provided pseudo field should not contain the leading colon.
1408func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string {
1409	for _, hf := range mh.Fields {
1410		if !hf.IsPseudo() {
1411			return ""
1412		}
1413		if hf.Name[1:] == pseudo {
1414			return hf.Value
1415		}
1416	}
1417	return ""
1418}
1419
1420// RegularFields returns the regular (non-pseudo) header fields of mh.
1421// The caller does not own the returned slice.
1422func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField {
1423	for i, hf := range mh.Fields {
1424		if !hf.IsPseudo() {
1425			return mh.Fields[i:]
1426		}
1427	}
1428	return nil
1429}
1430
1431// PseudoFields returns the pseudo header fields of mh.
1432// The caller does not own the returned slice.
1433func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField {
1434	for i, hf := range mh.Fields {
1435		if !hf.IsPseudo() {
1436			return mh.Fields[:i]
1437		}
1438	}
1439	return mh.Fields
1440}
1441
1442func (mh *MetaHeadersFrame) checkPseudos() error {
1443	var isRequest, isResponse bool
1444	pf := mh.PseudoFields()
1445	for i, hf := range pf {
1446		switch hf.Name {
1447		case ":method", ":path", ":scheme", ":authority":
1448			isRequest = true
1449		case ":status":
1450			isResponse = true
1451		default:
1452			return pseudoHeaderError(hf.Name)
1453		}
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)
1460			}
1461		}
1462	}
1463	if isRequest && isResponse {
1464		return errMixPseudoHeaderTypes
1465	}
1466	return nil
1467}
1468
1469func (fr *Framer) maxHeaderStringLen() int {
1470	v := fr.maxHeaderListSize()
1471	if uint32(int(v)) == v {
1472		return int(v)
1473	}
1474	// They had a crazy big number for MaxHeaderBytes anyway,
1475	// so give them unlimited header lengths:
1476	return 0
1477}
1478
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.
1482func (fr *Framer) readMetaFrame(hf *HeadersFrame) (*MetaHeadersFrame, error) {
1483	if fr.AllowIllegalReads {
1484		return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders")
1485	}
1486	mh := &MetaHeadersFrame{
1487		HeadersFrame: hf,
1488	}
1489	var remainSize = fr.maxHeaderListSize()
1490	var sawRegular bool
1491
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)
1499		}
1500		if !httpguts.ValidHeaderFieldValue(hf.Value) {
1501			invalid = headerFieldValueError(hf.Value)
1502		}
1503		isPseudo := strings.HasPrefix(hf.Name, ":")
1504		if isPseudo {
1505			if sawRegular {
1506				invalid = errPseudoAfterRegular
1507			}
1508		} else {
1509			sawRegular = true
1510			if !validWireHeaderFieldName(hf.Name) {
1511				invalid = headerFieldNameError(hf.Name)
1512			}
1513		}
1514
1515		if invalid != nil {
1516			hdec.SetEmitEnabled(false)
1517			return
1518		}
1519
1520		size := hf.Size()
1521		if size > remainSize {
1522			hdec.SetEmitEnabled(false)
1523			mh.Truncated = true
1524			return
1525		}
1526		remainSize -= size
1527
1528		mh.Fields = append(mh.Fields, hf)
1529	})
1530	// Lose reference to MetaHeadersFrame:
1531	defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {})
1532
1533	var hc headersOrContinuation = hf
1534	for {
1535		frag := hc.HeaderBlockFragment()
1536		if _, err := hdec.Write(frag); err != nil {
1537			return nil, ConnectionError(ErrCodeCompression)
1538		}
1539
1540		if hc.HeadersEnded() {
1541			break
1542		}
1543		if f, err := fr.ReadFrame(); err != nil {
1544			return nil, err
1545		} else {
1546			hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder
1547		}
1548	}
1549
1550	mh.HeadersFrame.headerFragBuf = nil
1551	mh.HeadersFrame.invalidate()
1552
1553	if err := hdec.Close(); err != nil {
1554		return nil, ConnectionError(ErrCodeCompression)
1555	}
1556	if invalid != nil {
1557		fr.errDetail = invalid
1558		if VerboseLogs {
1559			log.Printf("http2: invalid header: %v", invalid)
1560		}
1561		return nil, StreamError{mh.StreamID, ErrCodeProtocol, invalid}
1562	}
1563	if err := mh.checkPseudos(); err != nil {
1564		fr.errDetail = err
1565		if VerboseLogs {
1566			log.Printf("http2: invalid pseudo headers: %v", err)
1567		}
1568		return nil, StreamError{mh.StreamID, ErrCodeProtocol, err}
1569	}
1570	return mh, nil
1571}
1572
1573func summarizeFrame(f Frame) string {
1574	var buf bytes.Buffer
1575	f.Header().writeDebug(&buf)
1576	switch f := f.(type) {
1577	case *SettingsFrame:
1578		n := 0
1579		f.ForeachSetting(func(s Setting) error {
1580			n++
1581			if n == 1 {
1582				buf.WriteString(", settings:")
1583			}
1584			fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val)
1585			return nil
1586		})
1587		if n > 0 {
1588			buf.Truncate(buf.Len() - 1) // remove trailing comma
1589		}
1590	case *DataFrame:
1591		data := f.Data()
1592		const max = 256
1593		if len(data) > max {
1594			data = data[:max]
1595		}
1596		fmt.Fprintf(&buf, " data=%q", data)
1597		if len(f.Data()) > max {
1598			fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max)
1599		}
1600	case *WindowUpdateFrame:
1601		if f.StreamID == 0 {
1602			buf.WriteString(" (conn)")
1603		}
1604		fmt.Fprintf(&buf, " incr=%v", f.Increment)
1605	case *PingFrame:
1606		fmt.Fprintf(&buf, " ping=%q", f.Data[:])
1607	case *GoAwayFrame:
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)
1612	}
1613	return buf.String()
1614}
1615