goaway.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586
  1. // Copyright 2019 The gRPC Authors
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. package http2interop
  15. import (
  16. "encoding/binary"
  17. "fmt"
  18. "io"
  19. )
  20. type GoAwayFrame struct {
  21. Header FrameHeader
  22. Reserved
  23. StreamID
  24. // TODO(carl-mastrangelo): make an enum out of this.
  25. Code uint32
  26. Data []byte
  27. }
  28. func (f *GoAwayFrame) GetHeader() *FrameHeader {
  29. return &f.Header
  30. }
  31. func (f *GoAwayFrame) ParsePayload(r io.Reader) error {
  32. raw := make([]byte, f.Header.Length)
  33. if _, err := io.ReadFull(r, raw); err != nil {
  34. return err
  35. }
  36. return f.UnmarshalPayload(raw)
  37. }
  38. func (f *GoAwayFrame) UnmarshalPayload(raw []byte) error {
  39. if f.Header.Length != len(raw) {
  40. return fmt.Errorf("Invalid Payload length %d != %d", f.Header.Length, len(raw))
  41. }
  42. if f.Header.Length < 8 {
  43. return fmt.Errorf("Invalid Payload length %d", f.Header.Length)
  44. }
  45. *f = GoAwayFrame{
  46. Reserved: Reserved(raw[0]>>7 == 1),
  47. StreamID: StreamID(binary.BigEndian.Uint32(raw[0:4]) & 0x7fffffff),
  48. Code: binary.BigEndian.Uint32(raw[4:8]),
  49. Data: []byte(string(raw[8:])),
  50. }
  51. return nil
  52. }
  53. func (f *GoAwayFrame) MarshalPayload() ([]byte, error) {
  54. raw := make([]byte, 8, 8+len(f.Data))
  55. binary.BigEndian.PutUint32(raw[:4], uint32(f.StreamID))
  56. binary.BigEndian.PutUint32(raw[4:8], f.Code)
  57. raw = append(raw, f.Data...)
  58. return raw, nil
  59. }
  60. func (f *GoAwayFrame) MarshalBinary() ([]byte, error) {
  61. payload, err := f.MarshalPayload()
  62. if err != nil {
  63. return nil, err
  64. }
  65. f.Header.Length = len(payload)
  66. f.Header.Type = GoAwayFrameType
  67. header, err := f.Header.MarshalBinary()
  68. if err != nil {
  69. return nil, err
  70. }
  71. header = append(header, payload...)
  72. return header, nil
  73. }