blob: 93bcaab03a4b3f2b8007ff96e093bc43c210946c [file] [log] [blame]
khenaidooac637102019-01-14 15:44:34 -05001// 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
mgouda64be8822025-05-30 10:44:00 +053026// https://httpwg.org/specs/rfc7540.html#rfc.section.11.2
khenaidooac637102019-01-14 15:44:34 -050027type 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
Abhay Kumara2ae5992025-11-10 14:02:24 +000042var frameNames = [...]string{
khenaidooac637102019-01-14 15:44:34 -050043 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 {
Abhay Kumara2ae5992025-11-10 14:02:24 +000056 if int(t) < len(frameNames) {
57 return frameNames[t]
khenaidooac637102019-01-14 15:44:34 -050058 }
Abhay Kumara2ae5992025-11-10 14:02:24 +000059 return fmt.Sprintf("UNKNOWN_FRAME_TYPE_%d", t)
khenaidooac637102019-01-14 15:44:34 -050060}
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).
mgouda64be8822025-05-30 10:44:00 +0530125type frameParser func(fc *frameCache, fh FrameHeader, countError func(string), payload []byte) (Frame, error)
khenaidooac637102019-01-14 15:44:34 -0500126
Abhay Kumara2ae5992025-11-10 14:02:24 +0000127var frameParsers = [...]frameParser{
khenaidooac637102019-01-14 15:44:34 -0500128 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 {
Abhay Kumara2ae5992025-11-10 14:02:24 +0000141 if int(t) < len(frameParsers) {
142 return frameParsers[t]
khenaidooac637102019-01-14 15:44:34 -0500143 }
144 return parseUnknownFrame
145}
146
147// A FrameHeader is the 9 byte header of all HTTP/2 frames.
148//
mgouda64be8822025-05-30 10:44:00 +0530149// See https://httpwg.org/specs/rfc7540.html#FrameHeader
khenaidooac637102019-01-14 15:44:34 -0500150type 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
Abhay Kumara2ae5992025-11-10 14:02:24 +0000228func invalidHTTP1LookingFrameHeader() FrameHeader {
229 fh, _ := readFrameHeader(make([]byte, frameHeaderLen), strings.NewReader("HTTP/1.1 "))
230 return fh
231}
232
khenaidooac637102019-01-14 15:44:34 -0500233// ReadFrameHeader reads 9 bytes from r and returns a FrameHeader.
234// Most users should use Framer.ReadFrame instead.
235func ReadFrameHeader(r io.Reader) (FrameHeader, error) {
236 bufp := fhBytes.Get().(*[]byte)
237 defer fhBytes.Put(bufp)
238 return readFrameHeader(*bufp, r)
239}
240
241func readFrameHeader(buf []byte, r io.Reader) (FrameHeader, error) {
242 _, err := io.ReadFull(r, buf[:frameHeaderLen])
243 if err != nil {
244 return FrameHeader{}, err
245 }
246 return FrameHeader{
247 Length: (uint32(buf[0])<<16 | uint32(buf[1])<<8 | uint32(buf[2])),
248 Type: FrameType(buf[3]),
249 Flags: Flags(buf[4]),
250 StreamID: binary.BigEndian.Uint32(buf[5:]) & (1<<31 - 1),
251 valid: true,
252 }, nil
253}
254
255// A Frame is the base interface implemented by all frame types.
256// Callers will generally type-assert the specific frame type:
257// *HeadersFrame, *SettingsFrame, *WindowUpdateFrame, etc.
258//
259// Frames are only valid until the next call to Framer.ReadFrame.
260type Frame interface {
261 Header() FrameHeader
262
263 // invalidate is called by Framer.ReadFrame to make this
264 // frame's buffers as being invalid, since the subsequent
265 // frame will reuse them.
266 invalidate()
267}
268
269// A Framer reads and writes Frames.
270type Framer struct {
271 r io.Reader
272 lastFrame Frame
273 errDetail error
274
mgouda64be8822025-05-30 10:44:00 +0530275 // countError is a non-nil func that's called on a frame parse
276 // error with some unique error path token. It's initialized
277 // from Transport.CountError or Server.CountError.
278 countError func(errToken string)
279
khenaidooac637102019-01-14 15:44:34 -0500280 // lastHeaderStream is non-zero if the last frame was an
281 // unfinished HEADERS/CONTINUATION.
282 lastHeaderStream uint32
283
284 maxReadSize uint32
285 headerBuf [frameHeaderLen]byte
286
287 // TODO: let getReadBuf be configurable, and use a less memory-pinning
288 // allocator in server.go to minimize memory pinned for many idle conns.
289 // Will probably also need to make frame invalidation have a hook too.
290 getReadBuf func(size uint32) []byte
291 readBuf []byte // cache for default getReadBuf
292
293 maxWriteSize uint32 // zero means unlimited; TODO: implement
294
295 w io.Writer
296 wbuf []byte
297
298 // AllowIllegalWrites permits the Framer's Write methods to
299 // write frames that do not conform to the HTTP/2 spec. This
300 // permits using the Framer to test other HTTP/2
301 // implementations' conformance to the spec.
302 // If false, the Write methods will prefer to return an error
303 // rather than comply.
304 AllowIllegalWrites bool
305
306 // AllowIllegalReads permits the Framer's ReadFrame method
307 // to return non-compliant frames or frame orders.
308 // This is for testing and permits using the Framer to test
309 // other HTTP/2 implementations' conformance to the spec.
310 // It is not compatible with ReadMetaHeaders.
311 AllowIllegalReads bool
312
313 // ReadMetaHeaders if non-nil causes ReadFrame to merge
314 // HEADERS and CONTINUATION frames together and return
315 // MetaHeadersFrame instead.
316 ReadMetaHeaders *hpack.Decoder
317
318 // MaxHeaderListSize is the http2 MAX_HEADER_LIST_SIZE.
319 // It's used only if ReadMetaHeaders is set; 0 means a sane default
320 // (currently 16MB)
321 // If the limit is hit, MetaHeadersFrame.Truncated is set true.
322 MaxHeaderListSize uint32
323
324 // TODO: track which type of frame & with which flags was sent
325 // last. Then return an error (unless AllowIllegalWrites) if
326 // we're in the middle of a header block and a
327 // non-Continuation or Continuation on a different stream is
328 // attempted to be written.
329
330 logReads, logWrites bool
331
332 debugFramer *Framer // only use for logging written writes
333 debugFramerBuf *bytes.Buffer
334 debugReadLoggerf func(string, ...interface{})
335 debugWriteLoggerf func(string, ...interface{})
336
337 frameCache *frameCache // nil if frames aren't reused (default)
338}
339
340func (fr *Framer) maxHeaderListSize() uint32 {
341 if fr.MaxHeaderListSize == 0 {
342 return 16 << 20 // sane default, per docs
343 }
344 return fr.MaxHeaderListSize
345}
346
347func (f *Framer) startWrite(ftype FrameType, flags Flags, streamID uint32) {
348 // Write the FrameHeader.
349 f.wbuf = append(f.wbuf[:0],
Abhay Kumara2ae5992025-11-10 14:02:24 +0000350 0, // 3 bytes of length, filled in endWrite
khenaidooac637102019-01-14 15:44:34 -0500351 0,
352 0,
353 byte(ftype),
354 byte(flags),
355 byte(streamID>>24),
356 byte(streamID>>16),
357 byte(streamID>>8),
358 byte(streamID))
359}
360
361func (f *Framer) endWrite() error {
362 // Now that we know the final size, fill in the FrameHeader in
363 // the space previously reserved for it. Abuse append.
364 length := len(f.wbuf) - frameHeaderLen
365 if length >= (1 << 24) {
366 return ErrFrameTooLarge
367 }
368 _ = append(f.wbuf[:0],
369 byte(length>>16),
370 byte(length>>8),
371 byte(length))
372 if f.logWrites {
373 f.logWrite()
374 }
375
376 n, err := f.w.Write(f.wbuf)
377 if err == nil && n != len(f.wbuf) {
378 err = io.ErrShortWrite
379 }
380 return err
381}
382
383func (f *Framer) logWrite() {
384 if f.debugFramer == nil {
385 f.debugFramerBuf = new(bytes.Buffer)
386 f.debugFramer = NewFramer(nil, f.debugFramerBuf)
387 f.debugFramer.logReads = false // we log it ourselves, saying "wrote" below
388 // Let us read anything, even if we accidentally wrote it
389 // in the wrong order:
390 f.debugFramer.AllowIllegalReads = true
391 }
392 f.debugFramerBuf.Write(f.wbuf)
393 fr, err := f.debugFramer.ReadFrame()
394 if err != nil {
395 f.debugWriteLoggerf("http2: Framer %p: failed to decode just-written frame", f)
396 return
397 }
398 f.debugWriteLoggerf("http2: Framer %p: wrote %v", f, summarizeFrame(fr))
399}
400
401func (f *Framer) writeByte(v byte) { f.wbuf = append(f.wbuf, v) }
402func (f *Framer) writeBytes(v []byte) { f.wbuf = append(f.wbuf, v...) }
403func (f *Framer) writeUint16(v uint16) { f.wbuf = append(f.wbuf, byte(v>>8), byte(v)) }
404func (f *Framer) writeUint32(v uint32) {
405 f.wbuf = append(f.wbuf, byte(v>>24), byte(v>>16), byte(v>>8), byte(v))
406}
407
408const (
409 minMaxFrameSize = 1 << 14
410 maxFrameSize = 1<<24 - 1
411)
412
413// SetReuseFrames allows the Framer to reuse Frames.
414// If called on a Framer, Frames returned by calls to ReadFrame are only
415// valid until the next call to ReadFrame.
416func (fr *Framer) SetReuseFrames() {
417 if fr.frameCache != nil {
418 return
419 }
420 fr.frameCache = &frameCache{}
421}
422
423type frameCache struct {
424 dataFrame DataFrame
425}
426
427func (fc *frameCache) getDataFrame() *DataFrame {
428 if fc == nil {
429 return &DataFrame{}
430 }
431 return &fc.dataFrame
432}
433
434// NewFramer returns a Framer that writes frames to w and reads them from r.
435func NewFramer(w io.Writer, r io.Reader) *Framer {
436 fr := &Framer{
437 w: w,
438 r: r,
mgouda64be8822025-05-30 10:44:00 +0530439 countError: func(string) {},
khenaidooac637102019-01-14 15:44:34 -0500440 logReads: logFrameReads,
441 logWrites: logFrameWrites,
442 debugReadLoggerf: log.Printf,
443 debugWriteLoggerf: log.Printf,
444 }
445 fr.getReadBuf = func(size uint32) []byte {
446 if cap(fr.readBuf) >= int(size) {
447 return fr.readBuf[:size]
448 }
449 fr.readBuf = make([]byte, size)
450 return fr.readBuf
451 }
452 fr.SetMaxReadFrameSize(maxFrameSize)
453 return fr
454}
455
456// SetMaxReadFrameSize sets the maximum size of a frame
457// that will be read by a subsequent call to ReadFrame.
458// It is the caller's responsibility to advertise this
459// limit with a SETTINGS frame.
460func (fr *Framer) SetMaxReadFrameSize(v uint32) {
461 if v > maxFrameSize {
462 v = maxFrameSize
463 }
464 fr.maxReadSize = v
465}
466
467// ErrorDetail returns a more detailed error of the last error
468// returned by Framer.ReadFrame. For instance, if ReadFrame
469// returns a StreamError with code PROTOCOL_ERROR, ErrorDetail
470// will say exactly what was invalid. ErrorDetail is not guaranteed
471// to return a non-nil value and like the rest of the http2 package,
472// its return value is not protected by an API compatibility promise.
473// ErrorDetail is reset after the next call to ReadFrame.
474func (fr *Framer) ErrorDetail() error {
475 return fr.errDetail
476}
477
478// ErrFrameTooLarge is returned from Framer.ReadFrame when the peer
479// sends a frame that is larger than declared with SetMaxReadFrameSize.
480var ErrFrameTooLarge = errors.New("http2: frame too large")
481
482// terminalReadFrameError reports whether err is an unrecoverable
483// error from ReadFrame and no other frames should be read.
484func terminalReadFrameError(err error) bool {
485 if _, ok := err.(StreamError); ok {
486 return false
487 }
488 return err != nil
489}
490
491// ReadFrame reads a single frame. The returned Frame is only valid
492// until the next call to ReadFrame.
493//
494// If the frame is larger than previously set with SetMaxReadFrameSize, the
495// returned error is ErrFrameTooLarge. Other errors may be of type
496// ConnectionError, StreamError, or anything else from the underlying
497// reader.
mgouda64be8822025-05-30 10:44:00 +0530498//
499// If ReadFrame returns an error and a non-nil Frame, the Frame's StreamID
500// indicates the stream responsible for the error.
khenaidooac637102019-01-14 15:44:34 -0500501func (fr *Framer) ReadFrame() (Frame, error) {
502 fr.errDetail = nil
503 if fr.lastFrame != nil {
504 fr.lastFrame.invalidate()
505 }
506 fh, err := readFrameHeader(fr.headerBuf[:], fr.r)
507 if err != nil {
508 return nil, err
509 }
510 if fh.Length > fr.maxReadSize {
Abhay Kumara2ae5992025-11-10 14:02:24 +0000511 if fh == invalidHTTP1LookingFrameHeader() {
512 return nil, fmt.Errorf("http2: failed reading the frame payload: %w, note that the frame header looked like an HTTP/1.1 header", ErrFrameTooLarge)
513 }
khenaidooac637102019-01-14 15:44:34 -0500514 return nil, ErrFrameTooLarge
515 }
516 payload := fr.getReadBuf(fh.Length)
517 if _, err := io.ReadFull(fr.r, payload); err != nil {
Abhay Kumara2ae5992025-11-10 14:02:24 +0000518 if fh == invalidHTTP1LookingFrameHeader() {
519 return nil, fmt.Errorf("http2: failed reading the frame payload: %w, note that the frame header looked like an HTTP/1.1 header", err)
520 }
khenaidooac637102019-01-14 15:44:34 -0500521 return nil, err
522 }
mgouda64be8822025-05-30 10:44:00 +0530523 f, err := typeFrameParser(fh.Type)(fr.frameCache, fh, fr.countError, payload)
khenaidooac637102019-01-14 15:44:34 -0500524 if err != nil {
525 if ce, ok := err.(connError); ok {
526 return nil, fr.connError(ce.Code, ce.Reason)
527 }
528 return nil, err
529 }
530 if err := fr.checkFrameOrder(f); err != nil {
531 return nil, err
532 }
533 if fr.logReads {
534 fr.debugReadLoggerf("http2: Framer %p: read %v", fr, summarizeFrame(f))
535 }
536 if fh.Type == FrameHeaders && fr.ReadMetaHeaders != nil {
537 return fr.readMetaFrame(f.(*HeadersFrame))
538 }
539 return f, nil
540}
541
542// connError returns ConnectionError(code) but first
543// stashes away a public reason to the caller can optionally relay it
544// to the peer before hanging up on them. This might help others debug
545// their implementations.
546func (fr *Framer) connError(code ErrCode, reason string) error {
547 fr.errDetail = errors.New(reason)
548 return ConnectionError(code)
549}
550
551// checkFrameOrder reports an error if f is an invalid frame to return
552// next from ReadFrame. Mostly it checks whether HEADERS and
553// CONTINUATION frames are contiguous.
554func (fr *Framer) checkFrameOrder(f Frame) error {
555 last := fr.lastFrame
556 fr.lastFrame = f
557 if fr.AllowIllegalReads {
558 return nil
559 }
560
561 fh := f.Header()
562 if fr.lastHeaderStream != 0 {
563 if fh.Type != FrameContinuation {
564 return fr.connError(ErrCodeProtocol,
565 fmt.Sprintf("got %s for stream %d; expected CONTINUATION following %s for stream %d",
566 fh.Type, fh.StreamID,
567 last.Header().Type, fr.lastHeaderStream))
568 }
569 if fh.StreamID != fr.lastHeaderStream {
570 return fr.connError(ErrCodeProtocol,
571 fmt.Sprintf("got CONTINUATION for stream %d; expected stream %d",
572 fh.StreamID, fr.lastHeaderStream))
573 }
574 } else if fh.Type == FrameContinuation {
575 return fr.connError(ErrCodeProtocol, fmt.Sprintf("unexpected CONTINUATION for stream %d", fh.StreamID))
576 }
577
578 switch fh.Type {
579 case FrameHeaders, FrameContinuation:
580 if fh.Flags.Has(FlagHeadersEndHeaders) {
581 fr.lastHeaderStream = 0
582 } else {
583 fr.lastHeaderStream = fh.StreamID
584 }
585 }
586
587 return nil
588}
589
590// A DataFrame conveys arbitrary, variable-length sequences of octets
591// associated with a stream.
mgouda64be8822025-05-30 10:44:00 +0530592// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.1
khenaidooac637102019-01-14 15:44:34 -0500593type DataFrame struct {
594 FrameHeader
595 data []byte
596}
597
598func (f *DataFrame) StreamEnded() bool {
599 return f.FrameHeader.Flags.Has(FlagDataEndStream)
600}
601
602// Data returns the frame's data octets, not including any padding
603// size byte or padding suffix bytes.
604// The caller must not retain the returned memory past the next
605// call to ReadFrame.
606func (f *DataFrame) Data() []byte {
607 f.checkValid()
608 return f.data
609}
610
mgouda64be8822025-05-30 10:44:00 +0530611func parseDataFrame(fc *frameCache, fh FrameHeader, countError func(string), payload []byte) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -0500612 if fh.StreamID == 0 {
613 // DATA frames MUST be associated with a stream. If a
614 // DATA frame is received whose stream identifier
615 // field is 0x0, the recipient MUST respond with a
616 // connection error (Section 5.4.1) of type
617 // PROTOCOL_ERROR.
mgouda64be8822025-05-30 10:44:00 +0530618 countError("frame_data_stream_0")
khenaidooac637102019-01-14 15:44:34 -0500619 return nil, connError{ErrCodeProtocol, "DATA frame with stream ID 0"}
620 }
621 f := fc.getDataFrame()
622 f.FrameHeader = fh
623
624 var padSize byte
625 if fh.Flags.Has(FlagDataPadded) {
626 var err error
627 payload, padSize, err = readByte(payload)
628 if err != nil {
mgouda64be8822025-05-30 10:44:00 +0530629 countError("frame_data_pad_byte_short")
khenaidooac637102019-01-14 15:44:34 -0500630 return nil, err
631 }
632 }
633 if int(padSize) > len(payload) {
634 // If the length of the padding is greater than the
635 // length of the frame payload, the recipient MUST
636 // treat this as a connection error.
637 // Filed: https://github.com/http2/http2-spec/issues/610
mgouda64be8822025-05-30 10:44:00 +0530638 countError("frame_data_pad_too_big")
khenaidooac637102019-01-14 15:44:34 -0500639 return nil, connError{ErrCodeProtocol, "pad size larger than data payload"}
640 }
641 f.data = payload[:len(payload)-int(padSize)]
642 return f, nil
643}
644
645var (
646 errStreamID = errors.New("invalid stream ID")
647 errDepStreamID = errors.New("invalid dependent stream ID")
648 errPadLength = errors.New("pad length too large")
649 errPadBytes = errors.New("padding bytes must all be zeros unless AllowIllegalWrites is enabled")
650)
651
652func validStreamIDOrZero(streamID uint32) bool {
653 return streamID&(1<<31) == 0
654}
655
656func validStreamID(streamID uint32) bool {
657 return streamID != 0 && streamID&(1<<31) == 0
658}
659
660// WriteData writes a DATA frame.
661//
662// It will perform exactly one Write to the underlying Writer.
663// It is the caller's responsibility not to violate the maximum frame size
664// and to not call other Write methods concurrently.
665func (f *Framer) WriteData(streamID uint32, endStream bool, data []byte) error {
666 return f.WriteDataPadded(streamID, endStream, data, nil)
667}
668
William Kurkiandaa6bb22019-03-07 12:26:28 -0500669// WriteDataPadded writes a DATA frame with optional padding.
khenaidooac637102019-01-14 15:44:34 -0500670//
671// If pad is nil, the padding bit is not sent.
672// The length of pad must not exceed 255 bytes.
673// The bytes of pad must all be zero, unless f.AllowIllegalWrites is set.
674//
675// It will perform exactly one Write to the underlying Writer.
676// It is the caller's responsibility not to violate the maximum frame size
677// and to not call other Write methods concurrently.
678func (f *Framer) WriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
mgouda64be8822025-05-30 10:44:00 +0530679 if err := f.startWriteDataPadded(streamID, endStream, data, pad); err != nil {
680 return err
681 }
682 return f.endWrite()
683}
684
685// startWriteDataPadded is WriteDataPadded, but only writes the frame to the Framer's internal buffer.
686// The caller should call endWrite to flush the frame to the underlying writer.
687func (f *Framer) startWriteDataPadded(streamID uint32, endStream bool, data, pad []byte) error {
khenaidooac637102019-01-14 15:44:34 -0500688 if !validStreamID(streamID) && !f.AllowIllegalWrites {
689 return errStreamID
690 }
691 if len(pad) > 0 {
692 if len(pad) > 255 {
693 return errPadLength
694 }
695 if !f.AllowIllegalWrites {
696 for _, b := range pad {
697 if b != 0 {
698 // "Padding octets MUST be set to zero when sending."
699 return errPadBytes
700 }
701 }
702 }
703 }
704 var flags Flags
705 if endStream {
706 flags |= FlagDataEndStream
707 }
708 if pad != nil {
709 flags |= FlagDataPadded
710 }
711 f.startWrite(FrameData, flags, streamID)
712 if pad != nil {
713 f.wbuf = append(f.wbuf, byte(len(pad)))
714 }
715 f.wbuf = append(f.wbuf, data...)
716 f.wbuf = append(f.wbuf, pad...)
mgouda64be8822025-05-30 10:44:00 +0530717 return nil
khenaidooac637102019-01-14 15:44:34 -0500718}
719
720// A SettingsFrame conveys configuration parameters that affect how
721// endpoints communicate, such as preferences and constraints on peer
722// behavior.
723//
mgouda64be8822025-05-30 10:44:00 +0530724// See https://httpwg.org/specs/rfc7540.html#SETTINGS
khenaidooac637102019-01-14 15:44:34 -0500725type SettingsFrame struct {
726 FrameHeader
727 p []byte
728}
729
mgouda64be8822025-05-30 10:44:00 +0530730func parseSettingsFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -0500731 if fh.Flags.Has(FlagSettingsAck) && fh.Length > 0 {
732 // When this (ACK 0x1) bit is set, the payload of the
733 // SETTINGS frame MUST be empty. Receipt of a
734 // SETTINGS frame with the ACK flag set and a length
735 // field value other than 0 MUST be treated as a
736 // connection error (Section 5.4.1) of type
737 // FRAME_SIZE_ERROR.
mgouda64be8822025-05-30 10:44:00 +0530738 countError("frame_settings_ack_with_length")
khenaidooac637102019-01-14 15:44:34 -0500739 return nil, ConnectionError(ErrCodeFrameSize)
740 }
741 if fh.StreamID != 0 {
742 // SETTINGS frames always apply to a connection,
743 // never a single stream. The stream identifier for a
744 // SETTINGS frame MUST be zero (0x0). If an endpoint
745 // receives a SETTINGS frame whose stream identifier
746 // field is anything other than 0x0, the endpoint MUST
747 // respond with a connection error (Section 5.4.1) of
748 // type PROTOCOL_ERROR.
mgouda64be8822025-05-30 10:44:00 +0530749 countError("frame_settings_has_stream")
khenaidooac637102019-01-14 15:44:34 -0500750 return nil, ConnectionError(ErrCodeProtocol)
751 }
752 if len(p)%6 != 0 {
mgouda64be8822025-05-30 10:44:00 +0530753 countError("frame_settings_mod_6")
khenaidooac637102019-01-14 15:44:34 -0500754 // Expecting even number of 6 byte settings.
755 return nil, ConnectionError(ErrCodeFrameSize)
756 }
757 f := &SettingsFrame{FrameHeader: fh, p: p}
758 if v, ok := f.Value(SettingInitialWindowSize); ok && v > (1<<31)-1 {
mgouda64be8822025-05-30 10:44:00 +0530759 countError("frame_settings_window_size_too_big")
khenaidooac637102019-01-14 15:44:34 -0500760 // Values above the maximum flow control window size of 2^31 - 1 MUST
761 // be treated as a connection error (Section 5.4.1) of type
762 // FLOW_CONTROL_ERROR.
763 return nil, ConnectionError(ErrCodeFlowControl)
764 }
765 return f, nil
766}
767
768func (f *SettingsFrame) IsAck() bool {
769 return f.FrameHeader.Flags.Has(FlagSettingsAck)
770}
771
772func (f *SettingsFrame) Value(id SettingID) (v uint32, ok bool) {
773 f.checkValid()
774 for i := 0; i < f.NumSettings(); i++ {
775 if s := f.Setting(i); s.ID == id {
776 return s.Val, true
777 }
778 }
779 return 0, false
780}
781
782// Setting returns the setting from the frame at the given 0-based index.
783// The index must be >= 0 and less than f.NumSettings().
784func (f *SettingsFrame) Setting(i int) Setting {
785 buf := f.p
786 return Setting{
787 ID: SettingID(binary.BigEndian.Uint16(buf[i*6 : i*6+2])),
788 Val: binary.BigEndian.Uint32(buf[i*6+2 : i*6+6]),
789 }
790}
791
792func (f *SettingsFrame) NumSettings() int { return len(f.p) / 6 }
793
794// HasDuplicates reports whether f contains any duplicate setting IDs.
795func (f *SettingsFrame) HasDuplicates() bool {
796 num := f.NumSettings()
797 if num == 0 {
798 return false
799 }
800 // If it's small enough (the common case), just do the n^2
801 // thing and avoid a map allocation.
802 if num < 10 {
803 for i := 0; i < num; i++ {
804 idi := f.Setting(i).ID
805 for j := i + 1; j < num; j++ {
806 idj := f.Setting(j).ID
807 if idi == idj {
808 return true
809 }
810 }
811 }
812 return false
813 }
814 seen := map[SettingID]bool{}
815 for i := 0; i < num; i++ {
816 id := f.Setting(i).ID
817 if seen[id] {
818 return true
819 }
820 seen[id] = true
821 }
822 return false
823}
824
825// ForeachSetting runs fn for each setting.
826// It stops and returns the first error.
827func (f *SettingsFrame) ForeachSetting(fn func(Setting) error) error {
828 f.checkValid()
829 for i := 0; i < f.NumSettings(); i++ {
830 if err := fn(f.Setting(i)); err != nil {
831 return err
832 }
833 }
834 return nil
835}
836
837// WriteSettings writes a SETTINGS frame with zero or more settings
838// specified and the ACK bit not set.
839//
840// It will perform exactly one Write to the underlying Writer.
841// It is the caller's responsibility to not call other Write methods concurrently.
842func (f *Framer) WriteSettings(settings ...Setting) error {
843 f.startWrite(FrameSettings, 0, 0)
844 for _, s := range settings {
845 f.writeUint16(uint16(s.ID))
846 f.writeUint32(s.Val)
847 }
848 return f.endWrite()
849}
850
851// WriteSettingsAck writes an empty SETTINGS frame with the ACK bit set.
852//
853// It will perform exactly one Write to the underlying Writer.
854// It is the caller's responsibility to not call other Write methods concurrently.
855func (f *Framer) WriteSettingsAck() error {
856 f.startWrite(FrameSettings, FlagSettingsAck, 0)
857 return f.endWrite()
858}
859
860// A PingFrame is a mechanism for measuring a minimal round trip time
861// from the sender, as well as determining whether an idle connection
862// is still functional.
mgouda64be8822025-05-30 10:44:00 +0530863// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.7
khenaidooac637102019-01-14 15:44:34 -0500864type PingFrame struct {
865 FrameHeader
866 Data [8]byte
867}
868
869func (f *PingFrame) IsAck() bool { return f.Flags.Has(FlagPingAck) }
870
mgouda64be8822025-05-30 10:44:00 +0530871func parsePingFrame(_ *frameCache, fh FrameHeader, countError func(string), payload []byte) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -0500872 if len(payload) != 8 {
mgouda64be8822025-05-30 10:44:00 +0530873 countError("frame_ping_length")
khenaidooac637102019-01-14 15:44:34 -0500874 return nil, ConnectionError(ErrCodeFrameSize)
875 }
876 if fh.StreamID != 0 {
mgouda64be8822025-05-30 10:44:00 +0530877 countError("frame_ping_has_stream")
khenaidooac637102019-01-14 15:44:34 -0500878 return nil, ConnectionError(ErrCodeProtocol)
879 }
880 f := &PingFrame{FrameHeader: fh}
881 copy(f.Data[:], payload)
882 return f, nil
883}
884
885func (f *Framer) WritePing(ack bool, data [8]byte) error {
886 var flags Flags
887 if ack {
888 flags = FlagPingAck
889 }
890 f.startWrite(FramePing, flags, 0)
891 f.writeBytes(data[:])
892 return f.endWrite()
893}
894
895// A GoAwayFrame informs the remote peer to stop creating streams on this connection.
mgouda64be8822025-05-30 10:44:00 +0530896// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.8
khenaidooac637102019-01-14 15:44:34 -0500897type GoAwayFrame struct {
898 FrameHeader
899 LastStreamID uint32
900 ErrCode ErrCode
901 debugData []byte
902}
903
904// DebugData returns any debug data in the GOAWAY frame. Its contents
905// are not defined.
906// The caller must not retain the returned memory past the next
907// call to ReadFrame.
908func (f *GoAwayFrame) DebugData() []byte {
909 f.checkValid()
910 return f.debugData
911}
912
mgouda64be8822025-05-30 10:44:00 +0530913func parseGoAwayFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -0500914 if fh.StreamID != 0 {
mgouda64be8822025-05-30 10:44:00 +0530915 countError("frame_goaway_has_stream")
khenaidooac637102019-01-14 15:44:34 -0500916 return nil, ConnectionError(ErrCodeProtocol)
917 }
918 if len(p) < 8 {
mgouda64be8822025-05-30 10:44:00 +0530919 countError("frame_goaway_short")
khenaidooac637102019-01-14 15:44:34 -0500920 return nil, ConnectionError(ErrCodeFrameSize)
921 }
922 return &GoAwayFrame{
923 FrameHeader: fh,
924 LastStreamID: binary.BigEndian.Uint32(p[:4]) & (1<<31 - 1),
925 ErrCode: ErrCode(binary.BigEndian.Uint32(p[4:8])),
926 debugData: p[8:],
927 }, nil
928}
929
930func (f *Framer) WriteGoAway(maxStreamID uint32, code ErrCode, debugData []byte) error {
931 f.startWrite(FrameGoAway, 0, 0)
932 f.writeUint32(maxStreamID & (1<<31 - 1))
933 f.writeUint32(uint32(code))
934 f.writeBytes(debugData)
935 return f.endWrite()
936}
937
938// An UnknownFrame is the frame type returned when the frame type is unknown
939// or no specific frame type parser exists.
940type UnknownFrame struct {
941 FrameHeader
942 p []byte
943}
944
945// Payload returns the frame's payload (after the header). It is not
946// valid to call this method after a subsequent call to
947// Framer.ReadFrame, nor is it valid to retain the returned slice.
948// The memory is owned by the Framer and is invalidated when the next
949// frame is read.
950func (f *UnknownFrame) Payload() []byte {
951 f.checkValid()
952 return f.p
953}
954
mgouda64be8822025-05-30 10:44:00 +0530955func parseUnknownFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -0500956 return &UnknownFrame{fh, p}, nil
957}
958
959// A WindowUpdateFrame is used to implement flow control.
mgouda64be8822025-05-30 10:44:00 +0530960// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.9
khenaidooac637102019-01-14 15:44:34 -0500961type WindowUpdateFrame struct {
962 FrameHeader
963 Increment uint32 // never read with high bit set
964}
965
mgouda64be8822025-05-30 10:44:00 +0530966func parseWindowUpdateFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -0500967 if len(p) != 4 {
mgouda64be8822025-05-30 10:44:00 +0530968 countError("frame_windowupdate_bad_len")
khenaidooac637102019-01-14 15:44:34 -0500969 return nil, ConnectionError(ErrCodeFrameSize)
970 }
971 inc := binary.BigEndian.Uint32(p[:4]) & 0x7fffffff // mask off high reserved bit
972 if inc == 0 {
973 // A receiver MUST treat the receipt of a
974 // WINDOW_UPDATE frame with an flow control window
975 // increment of 0 as a stream error (Section 5.4.2) of
976 // type PROTOCOL_ERROR; errors on the connection flow
977 // control window MUST be treated as a connection
978 // error (Section 5.4.1).
979 if fh.StreamID == 0 {
mgouda64be8822025-05-30 10:44:00 +0530980 countError("frame_windowupdate_zero_inc_conn")
khenaidooac637102019-01-14 15:44:34 -0500981 return nil, ConnectionError(ErrCodeProtocol)
982 }
mgouda64be8822025-05-30 10:44:00 +0530983 countError("frame_windowupdate_zero_inc_stream")
khenaidooac637102019-01-14 15:44:34 -0500984 return nil, streamError(fh.StreamID, ErrCodeProtocol)
985 }
986 return &WindowUpdateFrame{
987 FrameHeader: fh,
988 Increment: inc,
989 }, nil
990}
991
992// WriteWindowUpdate writes a WINDOW_UPDATE frame.
993// The increment value must be between 1 and 2,147,483,647, inclusive.
994// If the Stream ID is zero, the window update applies to the
995// connection as a whole.
996func (f *Framer) WriteWindowUpdate(streamID, incr uint32) error {
997 // "The legal range for the increment to the flow control window is 1 to 2^31-1 (2,147,483,647) octets."
998 if (incr < 1 || incr > 2147483647) && !f.AllowIllegalWrites {
999 return errors.New("illegal window increment value")
1000 }
1001 f.startWrite(FrameWindowUpdate, 0, streamID)
1002 f.writeUint32(incr)
1003 return f.endWrite()
1004}
1005
1006// A HeadersFrame is used to open a stream and additionally carries a
1007// header block fragment.
1008type HeadersFrame struct {
1009 FrameHeader
1010
1011 // Priority is set if FlagHeadersPriority is set in the FrameHeader.
1012 Priority PriorityParam
1013
1014 headerFragBuf []byte // not owned
1015}
1016
1017func (f *HeadersFrame) HeaderBlockFragment() []byte {
1018 f.checkValid()
1019 return f.headerFragBuf
1020}
1021
1022func (f *HeadersFrame) HeadersEnded() bool {
1023 return f.FrameHeader.Flags.Has(FlagHeadersEndHeaders)
1024}
1025
1026func (f *HeadersFrame) StreamEnded() bool {
1027 return f.FrameHeader.Flags.Has(FlagHeadersEndStream)
1028}
1029
1030func (f *HeadersFrame) HasPriority() bool {
1031 return f.FrameHeader.Flags.Has(FlagHeadersPriority)
1032}
1033
mgouda64be8822025-05-30 10:44:00 +05301034func parseHeadersFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (_ Frame, err error) {
khenaidooac637102019-01-14 15:44:34 -05001035 hf := &HeadersFrame{
1036 FrameHeader: fh,
1037 }
1038 if fh.StreamID == 0 {
1039 // HEADERS frames MUST be associated with a stream. If a HEADERS frame
1040 // is received whose stream identifier field is 0x0, the recipient MUST
1041 // respond with a connection error (Section 5.4.1) of type
1042 // PROTOCOL_ERROR.
mgouda64be8822025-05-30 10:44:00 +05301043 countError("frame_headers_zero_stream")
khenaidooac637102019-01-14 15:44:34 -05001044 return nil, connError{ErrCodeProtocol, "HEADERS frame with stream ID 0"}
1045 }
1046 var padLength uint8
1047 if fh.Flags.Has(FlagHeadersPadded) {
1048 if p, padLength, err = readByte(p); err != nil {
mgouda64be8822025-05-30 10:44:00 +05301049 countError("frame_headers_pad_short")
khenaidooac637102019-01-14 15:44:34 -05001050 return
1051 }
1052 }
1053 if fh.Flags.Has(FlagHeadersPriority) {
1054 var v uint32
1055 p, v, err = readUint32(p)
1056 if err != nil {
mgouda64be8822025-05-30 10:44:00 +05301057 countError("frame_headers_prio_short")
khenaidooac637102019-01-14 15:44:34 -05001058 return nil, err
1059 }
1060 hf.Priority.StreamDep = v & 0x7fffffff
1061 hf.Priority.Exclusive = (v != hf.Priority.StreamDep) // high bit was set
1062 p, hf.Priority.Weight, err = readByte(p)
1063 if err != nil {
mgouda64be8822025-05-30 10:44:00 +05301064 countError("frame_headers_prio_weight_short")
khenaidooac637102019-01-14 15:44:34 -05001065 return nil, err
1066 }
1067 }
mgouda64be8822025-05-30 10:44:00 +05301068 if len(p)-int(padLength) < 0 {
1069 countError("frame_headers_pad_too_big")
khenaidooac637102019-01-14 15:44:34 -05001070 return nil, streamError(fh.StreamID, ErrCodeProtocol)
1071 }
1072 hf.headerFragBuf = p[:len(p)-int(padLength)]
1073 return hf, nil
1074}
1075
1076// HeadersFrameParam are the parameters for writing a HEADERS frame.
1077type HeadersFrameParam struct {
1078 // StreamID is the required Stream ID to initiate.
1079 StreamID uint32
1080 // BlockFragment is part (or all) of a Header Block.
1081 BlockFragment []byte
1082
1083 // EndStream indicates that the header block is the last that
1084 // the endpoint will send for the identified stream. Setting
1085 // this flag causes the stream to enter one of "half closed"
1086 // states.
1087 EndStream bool
1088
1089 // EndHeaders indicates that this frame contains an entire
1090 // header block and is not followed by any
1091 // CONTINUATION frames.
1092 EndHeaders bool
1093
1094 // PadLength is the optional number of bytes of zeros to add
1095 // to this frame.
1096 PadLength uint8
1097
1098 // Priority, if non-zero, includes stream priority information
1099 // in the HEADER frame.
1100 Priority PriorityParam
1101}
1102
1103// WriteHeaders writes a single HEADERS frame.
1104//
1105// This is a low-level header writing method. Encoding headers and
1106// splitting them into any necessary CONTINUATION frames is handled
1107// elsewhere.
1108//
1109// It will perform exactly one Write to the underlying Writer.
1110// It is the caller's responsibility to not call other Write methods concurrently.
1111func (f *Framer) WriteHeaders(p HeadersFrameParam) error {
1112 if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
1113 return errStreamID
1114 }
1115 var flags Flags
1116 if p.PadLength != 0 {
1117 flags |= FlagHeadersPadded
1118 }
1119 if p.EndStream {
1120 flags |= FlagHeadersEndStream
1121 }
1122 if p.EndHeaders {
1123 flags |= FlagHeadersEndHeaders
1124 }
1125 if !p.Priority.IsZero() {
1126 flags |= FlagHeadersPriority
1127 }
1128 f.startWrite(FrameHeaders, flags, p.StreamID)
1129 if p.PadLength != 0 {
1130 f.writeByte(p.PadLength)
1131 }
1132 if !p.Priority.IsZero() {
1133 v := p.Priority.StreamDep
1134 if !validStreamIDOrZero(v) && !f.AllowIllegalWrites {
1135 return errDepStreamID
1136 }
1137 if p.Priority.Exclusive {
1138 v |= 1 << 31
1139 }
1140 f.writeUint32(v)
1141 f.writeByte(p.Priority.Weight)
1142 }
1143 f.wbuf = append(f.wbuf, p.BlockFragment...)
1144 f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
1145 return f.endWrite()
1146}
1147
1148// A PriorityFrame specifies the sender-advised priority of a stream.
mgouda64be8822025-05-30 10:44:00 +05301149// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.3
khenaidooac637102019-01-14 15:44:34 -05001150type PriorityFrame struct {
1151 FrameHeader
1152 PriorityParam
1153}
1154
Abhay Kumara2ae5992025-11-10 14:02:24 +00001155var defaultRFC9218Priority = PriorityParam{
1156 incremental: 0,
1157 urgency: 3,
1158}
1159
1160// Note that HTTP/2 has had two different prioritization schemes, and
1161// PriorityParam struct below is a superset of both schemes. The exported
1162// symbols are from RFC 7540 and the non-exported ones are from RFC 9218.
1163
khenaidooac637102019-01-14 15:44:34 -05001164// PriorityParam are the stream prioritzation parameters.
1165type PriorityParam struct {
1166 // StreamDep is a 31-bit stream identifier for the
1167 // stream that this stream depends on. Zero means no
1168 // dependency.
1169 StreamDep uint32
1170
1171 // Exclusive is whether the dependency is exclusive.
1172 Exclusive bool
1173
1174 // Weight is the stream's zero-indexed weight. It should be
1175 // set together with StreamDep, or neither should be set. Per
1176 // the spec, "Add one to the value to obtain a weight between
1177 // 1 and 256."
1178 Weight uint8
Abhay Kumara2ae5992025-11-10 14:02:24 +00001179
1180 // "The urgency (u) parameter value is Integer (see Section 3.3.1 of
1181 // [STRUCTURED-FIELDS]), between 0 and 7 inclusive, in descending order of
1182 // priority. The default is 3."
1183 urgency uint8
1184
1185 // "The incremental (i) parameter value is Boolean (see Section 3.3.6 of
1186 // [STRUCTURED-FIELDS]). It indicates if an HTTP response can be processed
1187 // incrementally, i.e., provide some meaningful output as chunks of the
1188 // response arrive."
1189 //
1190 // We use uint8 (i.e. 0 is false, 1 is true) instead of bool so we can
1191 // avoid unnecessary type conversions and because either type takes 1 byte.
1192 incremental uint8
khenaidooac637102019-01-14 15:44:34 -05001193}
1194
1195func (p PriorityParam) IsZero() bool {
1196 return p == PriorityParam{}
1197}
1198
mgouda64be8822025-05-30 10:44:00 +05301199func parsePriorityFrame(_ *frameCache, fh FrameHeader, countError func(string), payload []byte) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -05001200 if fh.StreamID == 0 {
mgouda64be8822025-05-30 10:44:00 +05301201 countError("frame_priority_zero_stream")
khenaidooac637102019-01-14 15:44:34 -05001202 return nil, connError{ErrCodeProtocol, "PRIORITY frame with stream ID 0"}
1203 }
1204 if len(payload) != 5 {
mgouda64be8822025-05-30 10:44:00 +05301205 countError("frame_priority_bad_length")
khenaidooac637102019-01-14 15:44:34 -05001206 return nil, connError{ErrCodeFrameSize, fmt.Sprintf("PRIORITY frame payload size was %d; want 5", len(payload))}
1207 }
1208 v := binary.BigEndian.Uint32(payload[:4])
1209 streamID := v & 0x7fffffff // mask off high bit
1210 return &PriorityFrame{
1211 FrameHeader: fh,
1212 PriorityParam: PriorityParam{
1213 Weight: payload[4],
1214 StreamDep: streamID,
1215 Exclusive: streamID != v, // was high bit set?
1216 },
1217 }, nil
1218}
1219
1220// WritePriority writes a PRIORITY frame.
1221//
1222// It will perform exactly one Write to the underlying Writer.
1223// It is the caller's responsibility to not call other Write methods concurrently.
1224func (f *Framer) WritePriority(streamID uint32, p PriorityParam) error {
1225 if !validStreamID(streamID) && !f.AllowIllegalWrites {
1226 return errStreamID
1227 }
1228 if !validStreamIDOrZero(p.StreamDep) {
1229 return errDepStreamID
1230 }
1231 f.startWrite(FramePriority, 0, streamID)
1232 v := p.StreamDep
1233 if p.Exclusive {
1234 v |= 1 << 31
1235 }
1236 f.writeUint32(v)
1237 f.writeByte(p.Weight)
1238 return f.endWrite()
1239}
1240
1241// A RSTStreamFrame allows for abnormal termination of a stream.
mgouda64be8822025-05-30 10:44:00 +05301242// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.4
khenaidooac637102019-01-14 15:44:34 -05001243type RSTStreamFrame struct {
1244 FrameHeader
1245 ErrCode ErrCode
1246}
1247
mgouda64be8822025-05-30 10:44:00 +05301248func parseRSTStreamFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -05001249 if len(p) != 4 {
mgouda64be8822025-05-30 10:44:00 +05301250 countError("frame_rststream_bad_len")
khenaidooac637102019-01-14 15:44:34 -05001251 return nil, ConnectionError(ErrCodeFrameSize)
1252 }
1253 if fh.StreamID == 0 {
mgouda64be8822025-05-30 10:44:00 +05301254 countError("frame_rststream_zero_stream")
khenaidooac637102019-01-14 15:44:34 -05001255 return nil, ConnectionError(ErrCodeProtocol)
1256 }
1257 return &RSTStreamFrame{fh, ErrCode(binary.BigEndian.Uint32(p[:4]))}, nil
1258}
1259
1260// WriteRSTStream writes a RST_STREAM frame.
1261//
1262// It will perform exactly one Write to the underlying Writer.
1263// It is the caller's responsibility to not call other Write methods concurrently.
1264func (f *Framer) WriteRSTStream(streamID uint32, code ErrCode) error {
1265 if !validStreamID(streamID) && !f.AllowIllegalWrites {
1266 return errStreamID
1267 }
1268 f.startWrite(FrameRSTStream, 0, streamID)
1269 f.writeUint32(uint32(code))
1270 return f.endWrite()
1271}
1272
1273// A ContinuationFrame is used to continue a sequence of header block fragments.
mgouda64be8822025-05-30 10:44:00 +05301274// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.10
khenaidooac637102019-01-14 15:44:34 -05001275type ContinuationFrame struct {
1276 FrameHeader
1277 headerFragBuf []byte
1278}
1279
mgouda64be8822025-05-30 10:44:00 +05301280func parseContinuationFrame(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -05001281 if fh.StreamID == 0 {
mgouda64be8822025-05-30 10:44:00 +05301282 countError("frame_continuation_zero_stream")
khenaidooac637102019-01-14 15:44:34 -05001283 return nil, connError{ErrCodeProtocol, "CONTINUATION frame with stream ID 0"}
1284 }
1285 return &ContinuationFrame{fh, p}, nil
1286}
1287
1288func (f *ContinuationFrame) HeaderBlockFragment() []byte {
1289 f.checkValid()
1290 return f.headerFragBuf
1291}
1292
1293func (f *ContinuationFrame) HeadersEnded() bool {
1294 return f.FrameHeader.Flags.Has(FlagContinuationEndHeaders)
1295}
1296
1297// WriteContinuation writes a CONTINUATION frame.
1298//
1299// It will perform exactly one Write to the underlying Writer.
1300// It is the caller's responsibility to not call other Write methods concurrently.
1301func (f *Framer) WriteContinuation(streamID uint32, endHeaders bool, headerBlockFragment []byte) error {
1302 if !validStreamID(streamID) && !f.AllowIllegalWrites {
1303 return errStreamID
1304 }
1305 var flags Flags
1306 if endHeaders {
1307 flags |= FlagContinuationEndHeaders
1308 }
1309 f.startWrite(FrameContinuation, flags, streamID)
1310 f.wbuf = append(f.wbuf, headerBlockFragment...)
1311 return f.endWrite()
1312}
1313
1314// A PushPromiseFrame is used to initiate a server stream.
mgouda64be8822025-05-30 10:44:00 +05301315// See https://httpwg.org/specs/rfc7540.html#rfc.section.6.6
khenaidooac637102019-01-14 15:44:34 -05001316type PushPromiseFrame struct {
1317 FrameHeader
1318 PromiseID uint32
1319 headerFragBuf []byte // not owned
1320}
1321
1322func (f *PushPromiseFrame) HeaderBlockFragment() []byte {
1323 f.checkValid()
1324 return f.headerFragBuf
1325}
1326
1327func (f *PushPromiseFrame) HeadersEnded() bool {
1328 return f.FrameHeader.Flags.Has(FlagPushPromiseEndHeaders)
1329}
1330
mgouda64be8822025-05-30 10:44:00 +05301331func parsePushPromise(_ *frameCache, fh FrameHeader, countError func(string), p []byte) (_ Frame, err error) {
khenaidooac637102019-01-14 15:44:34 -05001332 pp := &PushPromiseFrame{
1333 FrameHeader: fh,
1334 }
1335 if pp.StreamID == 0 {
1336 // PUSH_PROMISE frames MUST be associated with an existing,
1337 // peer-initiated stream. The stream identifier of a
1338 // PUSH_PROMISE frame indicates the stream it is associated
1339 // with. If the stream identifier field specifies the value
1340 // 0x0, a recipient MUST respond with a connection error
1341 // (Section 5.4.1) of type PROTOCOL_ERROR.
mgouda64be8822025-05-30 10:44:00 +05301342 countError("frame_pushpromise_zero_stream")
khenaidooac637102019-01-14 15:44:34 -05001343 return nil, ConnectionError(ErrCodeProtocol)
1344 }
1345 // The PUSH_PROMISE frame includes optional padding.
1346 // Padding fields and flags are identical to those defined for DATA frames
1347 var padLength uint8
1348 if fh.Flags.Has(FlagPushPromisePadded) {
1349 if p, padLength, err = readByte(p); err != nil {
mgouda64be8822025-05-30 10:44:00 +05301350 countError("frame_pushpromise_pad_short")
khenaidooac637102019-01-14 15:44:34 -05001351 return
1352 }
1353 }
1354
1355 p, pp.PromiseID, err = readUint32(p)
1356 if err != nil {
mgouda64be8822025-05-30 10:44:00 +05301357 countError("frame_pushpromise_promiseid_short")
khenaidooac637102019-01-14 15:44:34 -05001358 return
1359 }
1360 pp.PromiseID = pp.PromiseID & (1<<31 - 1)
1361
1362 if int(padLength) > len(p) {
1363 // like the DATA frame, error out if padding is longer than the body.
mgouda64be8822025-05-30 10:44:00 +05301364 countError("frame_pushpromise_pad_too_big")
khenaidooac637102019-01-14 15:44:34 -05001365 return nil, ConnectionError(ErrCodeProtocol)
1366 }
1367 pp.headerFragBuf = p[:len(p)-int(padLength)]
1368 return pp, nil
1369}
1370
1371// PushPromiseParam are the parameters for writing a PUSH_PROMISE frame.
1372type PushPromiseParam struct {
1373 // StreamID is the required Stream ID to initiate.
1374 StreamID uint32
1375
1376 // PromiseID is the required Stream ID which this
1377 // Push Promises
1378 PromiseID uint32
1379
1380 // BlockFragment is part (or all) of a Header Block.
1381 BlockFragment []byte
1382
1383 // EndHeaders indicates that this frame contains an entire
1384 // header block and is not followed by any
1385 // CONTINUATION frames.
1386 EndHeaders bool
1387
1388 // PadLength is the optional number of bytes of zeros to add
1389 // to this frame.
1390 PadLength uint8
1391}
1392
1393// WritePushPromise writes a single PushPromise Frame.
1394//
1395// As with Header Frames, This is the low level call for writing
1396// individual frames. Continuation frames are handled elsewhere.
1397//
1398// It will perform exactly one Write to the underlying Writer.
1399// It is the caller's responsibility to not call other Write methods concurrently.
1400func (f *Framer) WritePushPromise(p PushPromiseParam) error {
1401 if !validStreamID(p.StreamID) && !f.AllowIllegalWrites {
1402 return errStreamID
1403 }
1404 var flags Flags
1405 if p.PadLength != 0 {
1406 flags |= FlagPushPromisePadded
1407 }
1408 if p.EndHeaders {
1409 flags |= FlagPushPromiseEndHeaders
1410 }
1411 f.startWrite(FramePushPromise, flags, p.StreamID)
1412 if p.PadLength != 0 {
1413 f.writeByte(p.PadLength)
1414 }
1415 if !validStreamID(p.PromiseID) && !f.AllowIllegalWrites {
1416 return errStreamID
1417 }
1418 f.writeUint32(p.PromiseID)
1419 f.wbuf = append(f.wbuf, p.BlockFragment...)
1420 f.wbuf = append(f.wbuf, padZeros[:p.PadLength]...)
1421 return f.endWrite()
1422}
1423
1424// WriteRawFrame writes a raw frame. This can be used to write
1425// extension frames unknown to this package.
1426func (f *Framer) WriteRawFrame(t FrameType, flags Flags, streamID uint32, payload []byte) error {
1427 f.startWrite(t, flags, streamID)
1428 f.writeBytes(payload)
1429 return f.endWrite()
1430}
1431
1432func readByte(p []byte) (remain []byte, b byte, err error) {
1433 if len(p) == 0 {
1434 return nil, 0, io.ErrUnexpectedEOF
1435 }
1436 return p[1:], p[0], nil
1437}
1438
1439func readUint32(p []byte) (remain []byte, v uint32, err error) {
1440 if len(p) < 4 {
1441 return nil, 0, io.ErrUnexpectedEOF
1442 }
1443 return p[4:], binary.BigEndian.Uint32(p[:4]), nil
1444}
1445
1446type streamEnder interface {
1447 StreamEnded() bool
1448}
1449
1450type headersEnder interface {
1451 HeadersEnded() bool
1452}
1453
1454type headersOrContinuation interface {
1455 headersEnder
1456 HeaderBlockFragment() []byte
1457}
1458
1459// A MetaHeadersFrame is the representation of one HEADERS frame and
1460// zero or more contiguous CONTINUATION frames and the decoding of
1461// their HPACK-encoded contents.
1462//
1463// This type of frame does not appear on the wire and is only returned
1464// by the Framer when Framer.ReadMetaHeaders is set.
1465type MetaHeadersFrame struct {
1466 *HeadersFrame
1467
1468 // Fields are the fields contained in the HEADERS and
1469 // CONTINUATION frames. The underlying slice is owned by the
1470 // Framer and must not be retained after the next call to
1471 // ReadFrame.
1472 //
1473 // Fields are guaranteed to be in the correct http2 order and
1474 // not have unknown pseudo header fields or invalid header
1475 // field names or values. Required pseudo header fields may be
1476 // missing, however. Use the MetaHeadersFrame.Pseudo accessor
1477 // method access pseudo headers.
1478 Fields []hpack.HeaderField
1479
1480 // Truncated is whether the max header list size limit was hit
1481 // and Fields is incomplete. The hpack decoder state is still
1482 // valid, however.
1483 Truncated bool
1484}
1485
1486// PseudoValue returns the given pseudo header field's value.
1487// The provided pseudo field should not contain the leading colon.
1488func (mh *MetaHeadersFrame) PseudoValue(pseudo string) string {
1489 for _, hf := range mh.Fields {
1490 if !hf.IsPseudo() {
1491 return ""
1492 }
1493 if hf.Name[1:] == pseudo {
1494 return hf.Value
1495 }
1496 }
1497 return ""
1498}
1499
1500// RegularFields returns the regular (non-pseudo) header fields of mh.
1501// The caller does not own the returned slice.
1502func (mh *MetaHeadersFrame) RegularFields() []hpack.HeaderField {
1503 for i, hf := range mh.Fields {
1504 if !hf.IsPseudo() {
1505 return mh.Fields[i:]
1506 }
1507 }
1508 return nil
1509}
1510
1511// PseudoFields returns the pseudo header fields of mh.
1512// The caller does not own the returned slice.
1513func (mh *MetaHeadersFrame) PseudoFields() []hpack.HeaderField {
1514 for i, hf := range mh.Fields {
1515 if !hf.IsPseudo() {
1516 return mh.Fields[:i]
1517 }
1518 }
1519 return mh.Fields
1520}
1521
1522func (mh *MetaHeadersFrame) checkPseudos() error {
1523 var isRequest, isResponse bool
1524 pf := mh.PseudoFields()
1525 for i, hf := range pf {
1526 switch hf.Name {
mgouda64be8822025-05-30 10:44:00 +05301527 case ":method", ":path", ":scheme", ":authority", ":protocol":
khenaidooac637102019-01-14 15:44:34 -05001528 isRequest = true
1529 case ":status":
1530 isResponse = true
1531 default:
1532 return pseudoHeaderError(hf.Name)
1533 }
1534 // Check for duplicates.
mgouda64be8822025-05-30 10:44:00 +05301535 // This would be a bad algorithm, but N is 5.
khenaidooac637102019-01-14 15:44:34 -05001536 // And this doesn't allocate.
1537 for _, hf2 := range pf[:i] {
1538 if hf.Name == hf2.Name {
1539 return duplicatePseudoHeaderError(hf.Name)
1540 }
1541 }
1542 }
1543 if isRequest && isResponse {
1544 return errMixPseudoHeaderTypes
1545 }
1546 return nil
1547}
1548
1549func (fr *Framer) maxHeaderStringLen() int {
mgouda64be8822025-05-30 10:44:00 +05301550 v := int(fr.maxHeaderListSize())
1551 if v < 0 {
1552 // If maxHeaderListSize overflows an int, use no limit (0).
1553 return 0
khenaidooac637102019-01-14 15:44:34 -05001554 }
mgouda64be8822025-05-30 10:44:00 +05301555 return v
khenaidooac637102019-01-14 15:44:34 -05001556}
1557
1558// readMetaFrame returns 0 or more CONTINUATION frames from fr and
1559// merge them into the provided hf and returns a MetaHeadersFrame
1560// with the decoded hpack values.
mgouda64be8822025-05-30 10:44:00 +05301561func (fr *Framer) readMetaFrame(hf *HeadersFrame) (Frame, error) {
khenaidooac637102019-01-14 15:44:34 -05001562 if fr.AllowIllegalReads {
1563 return nil, errors.New("illegal use of AllowIllegalReads with ReadMetaHeaders")
1564 }
1565 mh := &MetaHeadersFrame{
1566 HeadersFrame: hf,
1567 }
1568 var remainSize = fr.maxHeaderListSize()
1569 var sawRegular bool
1570
1571 var invalid error // pseudo header field errors
1572 hdec := fr.ReadMetaHeaders
1573 hdec.SetEmitEnabled(true)
1574 hdec.SetMaxStringLength(fr.maxHeaderStringLen())
1575 hdec.SetEmitFunc(func(hf hpack.HeaderField) {
1576 if VerboseLogs && fr.logReads {
1577 fr.debugReadLoggerf("http2: decoded hpack field %+v", hf)
1578 }
1579 if !httpguts.ValidHeaderFieldValue(hf.Value) {
mgouda64be8822025-05-30 10:44:00 +05301580 // Don't include the value in the error, because it may be sensitive.
1581 invalid = headerFieldValueError(hf.Name)
khenaidooac637102019-01-14 15:44:34 -05001582 }
1583 isPseudo := strings.HasPrefix(hf.Name, ":")
1584 if isPseudo {
1585 if sawRegular {
1586 invalid = errPseudoAfterRegular
1587 }
1588 } else {
1589 sawRegular = true
1590 if !validWireHeaderFieldName(hf.Name) {
1591 invalid = headerFieldNameError(hf.Name)
1592 }
1593 }
1594
1595 if invalid != nil {
1596 hdec.SetEmitEnabled(false)
1597 return
1598 }
1599
1600 size := hf.Size()
1601 if size > remainSize {
1602 hdec.SetEmitEnabled(false)
1603 mh.Truncated = true
mgouda64be8822025-05-30 10:44:00 +05301604 remainSize = 0
khenaidooac637102019-01-14 15:44:34 -05001605 return
1606 }
1607 remainSize -= size
1608
1609 mh.Fields = append(mh.Fields, hf)
1610 })
1611 // Lose reference to MetaHeadersFrame:
1612 defer hdec.SetEmitFunc(func(hf hpack.HeaderField) {})
1613
1614 var hc headersOrContinuation = hf
1615 for {
1616 frag := hc.HeaderBlockFragment()
mgouda64be8822025-05-30 10:44:00 +05301617
1618 // Avoid parsing large amounts of headers that we will then discard.
1619 // If the sender exceeds the max header list size by too much,
1620 // skip parsing the fragment and close the connection.
1621 //
1622 // "Too much" is either any CONTINUATION frame after we've already
1623 // exceeded the max header list size (in which case remainSize is 0),
1624 // or a frame whose encoded size is more than twice the remaining
1625 // header list bytes we're willing to accept.
1626 if int64(len(frag)) > int64(2*remainSize) {
1627 if VerboseLogs {
1628 log.Printf("http2: header list too large")
1629 }
1630 // It would be nice to send a RST_STREAM before sending the GOAWAY,
1631 // but the structure of the server's frame writer makes this difficult.
1632 return mh, ConnectionError(ErrCodeProtocol)
1633 }
1634
1635 // Also close the connection after any CONTINUATION frame following an
1636 // invalid header, since we stop tracking the size of the headers after
1637 // an invalid one.
1638 if invalid != nil {
1639 if VerboseLogs {
1640 log.Printf("http2: invalid header: %v", invalid)
1641 }
1642 // It would be nice to send a RST_STREAM before sending the GOAWAY,
1643 // but the structure of the server's frame writer makes this difficult.
1644 return mh, ConnectionError(ErrCodeProtocol)
1645 }
1646
khenaidooac637102019-01-14 15:44:34 -05001647 if _, err := hdec.Write(frag); err != nil {
mgouda64be8822025-05-30 10:44:00 +05301648 return mh, ConnectionError(ErrCodeCompression)
khenaidooac637102019-01-14 15:44:34 -05001649 }
1650
1651 if hc.HeadersEnded() {
1652 break
1653 }
1654 if f, err := fr.ReadFrame(); err != nil {
1655 return nil, err
1656 } else {
1657 hc = f.(*ContinuationFrame) // guaranteed by checkFrameOrder
1658 }
1659 }
1660
1661 mh.HeadersFrame.headerFragBuf = nil
1662 mh.HeadersFrame.invalidate()
1663
1664 if err := hdec.Close(); err != nil {
mgouda64be8822025-05-30 10:44:00 +05301665 return mh, ConnectionError(ErrCodeCompression)
khenaidooac637102019-01-14 15:44:34 -05001666 }
1667 if invalid != nil {
1668 fr.errDetail = invalid
1669 if VerboseLogs {
1670 log.Printf("http2: invalid header: %v", invalid)
1671 }
1672 return nil, StreamError{mh.StreamID, ErrCodeProtocol, invalid}
1673 }
1674 if err := mh.checkPseudos(); err != nil {
1675 fr.errDetail = err
1676 if VerboseLogs {
1677 log.Printf("http2: invalid pseudo headers: %v", err)
1678 }
1679 return nil, StreamError{mh.StreamID, ErrCodeProtocol, err}
1680 }
1681 return mh, nil
1682}
1683
1684func summarizeFrame(f Frame) string {
1685 var buf bytes.Buffer
1686 f.Header().writeDebug(&buf)
1687 switch f := f.(type) {
1688 case *SettingsFrame:
1689 n := 0
1690 f.ForeachSetting(func(s Setting) error {
1691 n++
1692 if n == 1 {
1693 buf.WriteString(", settings:")
1694 }
1695 fmt.Fprintf(&buf, " %v=%v,", s.ID, s.Val)
1696 return nil
1697 })
1698 if n > 0 {
1699 buf.Truncate(buf.Len() - 1) // remove trailing comma
1700 }
1701 case *DataFrame:
1702 data := f.Data()
1703 const max = 256
1704 if len(data) > max {
1705 data = data[:max]
1706 }
1707 fmt.Fprintf(&buf, " data=%q", data)
1708 if len(f.Data()) > max {
1709 fmt.Fprintf(&buf, " (%d bytes omitted)", len(f.Data())-max)
1710 }
1711 case *WindowUpdateFrame:
1712 if f.StreamID == 0 {
1713 buf.WriteString(" (conn)")
1714 }
1715 fmt.Fprintf(&buf, " incr=%v", f.Increment)
1716 case *PingFrame:
1717 fmt.Fprintf(&buf, " ping=%q", f.Data[:])
1718 case *GoAwayFrame:
1719 fmt.Fprintf(&buf, " LastStreamID=%v ErrCode=%v Debug=%q",
1720 f.LastStreamID, f.ErrCode, f.debugData)
1721 case *RSTStreamFrame:
1722 fmt.Fprintf(&buf, " ErrCode=%v", f.ErrCode)
1723 }
1724 return buf.String()
1725}