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