sasl_initial_response.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. package pgproto3
  2. import (
  3. "bytes"
  4. "encoding/hex"
  5. "encoding/json"
  6. "errors"
  7. "github.com/jackc/pgx/v5/internal/pgio"
  8. )
  9. type SASLInitialResponse struct {
  10. AuthMechanism string
  11. Data []byte
  12. }
  13. // Frontend identifies this message as sendable by a PostgreSQL frontend.
  14. func (*SASLInitialResponse) Frontend() {}
  15. // Decode decodes src into dst. src must contain the complete message with the exception of the initial 1 byte message
  16. // type identifier and 4 byte message length.
  17. func (dst *SASLInitialResponse) Decode(src []byte) error {
  18. *dst = SASLInitialResponse{}
  19. rp := 0
  20. idx := bytes.IndexByte(src, 0)
  21. if idx < 0 {
  22. return errors.New("invalid SASLInitialResponse")
  23. }
  24. dst.AuthMechanism = string(src[rp:idx])
  25. rp = idx + 1
  26. rp += 4 // The rest of the message is data so we can just skip the size
  27. dst.Data = src[rp:]
  28. return nil
  29. }
  30. // Encode encodes src into dst. dst will include the 1 byte message type identifier and the 4 byte message length.
  31. func (src *SASLInitialResponse) Encode(dst []byte) ([]byte, error) {
  32. dst, sp := beginMessage(dst, 'p')
  33. dst = append(dst, []byte(src.AuthMechanism)...)
  34. dst = append(dst, 0)
  35. dst = pgio.AppendInt32(dst, int32(len(src.Data)))
  36. dst = append(dst, src.Data...)
  37. return finishMessage(dst, sp)
  38. }
  39. // MarshalJSON implements encoding/json.Marshaler.
  40. func (src SASLInitialResponse) MarshalJSON() ([]byte, error) {
  41. return json.Marshal(struct {
  42. Type string
  43. AuthMechanism string
  44. Data string
  45. }{
  46. Type: "SASLInitialResponse",
  47. AuthMechanism: src.AuthMechanism,
  48. Data: string(src.Data),
  49. })
  50. }
  51. // UnmarshalJSON implements encoding/json.Unmarshaler.
  52. func (dst *SASLInitialResponse) UnmarshalJSON(data []byte) error {
  53. // Ignore null, like in the main JSON package.
  54. if string(data) == "null" {
  55. return nil
  56. }
  57. var msg struct {
  58. AuthMechanism string
  59. Data string
  60. }
  61. if err := json.Unmarshal(data, &msg); err != nil {
  62. return err
  63. }
  64. dst.AuthMechanism = msg.AuthMechanism
  65. if msg.Data != "" {
  66. decoded, err := hex.DecodeString(msg.Data)
  67. if err != nil {
  68. return err
  69. }
  70. dst.Data = decoded
  71. }
  72. return nil
  73. }