startup_message.go 2.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. package pgproto3
  2. import (
  3. "bytes"
  4. "encoding/binary"
  5. "encoding/json"
  6. "errors"
  7. "fmt"
  8. "github.com/jackc/pgx/v5/internal/pgio"
  9. )
  10. const ProtocolVersionNumber = 196608 // 3.0
  11. type StartupMessage struct {
  12. ProtocolVersion uint32
  13. Parameters map[string]string
  14. }
  15. // Frontend identifies this message as sendable by a PostgreSQL frontend.
  16. func (*StartupMessage) Frontend() {}
  17. // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
  18. // type identifier and 4 byte message length.
  19. func (dst *StartupMessage) Decode(src []byte) error {
  20. if len(src) < 4 {
  21. return errors.New("startup message too short")
  22. }
  23. dst.ProtocolVersion = binary.BigEndian.Uint32(src)
  24. rp := 4
  25. if dst.ProtocolVersion != ProtocolVersionNumber {
  26. return fmt.Errorf("Bad startup message version number. Expected %d, got %d", ProtocolVersionNumber, dst.ProtocolVersion)
  27. }
  28. dst.Parameters = make(map[string]string)
  29. for {
  30. idx := bytes.IndexByte(src[rp:], 0)
  31. if idx < 0 {
  32. return &invalidMessageFormatErr{messageType: "StartupMessage"}
  33. }
  34. key := string(src[rp : rp+idx])
  35. rp += idx + 1
  36. idx = bytes.IndexByte(src[rp:], 0)
  37. if idx < 0 {
  38. return &invalidMessageFormatErr{messageType: "StartupMessage"}
  39. }
  40. value := string(src[rp : rp+idx])
  41. rp += idx + 1
  42. dst.Parameters[key] = value
  43. if len(src[rp:]) == 1 {
  44. if src[rp] != 0 {
  45. return fmt.Errorf("Bad startup message last byte. Expected 0, got %d", src[rp])
  46. }
  47. break
  48. }
  49. }
  50. return nil
  51. }
  52. // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
  53. func (src *StartupMessage) Encode(dst []byte) ([]byte, error) {
  54. sp := len(dst)
  55. dst = pgio.AppendInt32(dst, -1)
  56. dst = pgio.AppendUint32(dst, src.ProtocolVersion)
  57. for k, v := range src.Parameters {
  58. dst = append(dst, k...)
  59. dst = append(dst, 0)
  60. dst = append(dst, v...)
  61. dst = append(dst, 0)
  62. }
  63. dst = append(dst, 0)
  64. return finishMessage(dst, sp)
  65. }
  66. // MarshalJSON implements encoding/json.Marshaler.
  67. func (src StartupMessage) MarshalJSON() ([]byte, error) {
  68. return json.Marshal(struct {
  69. Type string
  70. ProtocolVersion uint32
  71. Parameters map[string]string
  72. }{
  73. Type: "StartupMessage",
  74. ProtocolVersion: src.ProtocolVersion,
  75. Parameters: src.Parameters,
  76. })
  77. }