1package pgproto3
2
3import (
4	"encoding/binary"
5
6	"github.com/jackc/pgx/pgio"
7	"github.com/pkg/errors"
8)
9
10const (
11	AuthTypeOk                = 0
12	AuthTypeCleartextPassword = 3
13	AuthTypeMD5Password       = 5
14)
15
16type Authentication struct {
17	Type uint32
18
19	// MD5Password fields
20	Salt [4]byte
21}
22
23func (*Authentication) Backend() {}
24
25func (dst *Authentication) Decode(src []byte) error {
26	*dst = Authentication{Type: binary.BigEndian.Uint32(src[:4])}
27
28	switch dst.Type {
29	case AuthTypeOk:
30	case AuthTypeCleartextPassword:
31	case AuthTypeMD5Password:
32		copy(dst.Salt[:], src[4:8])
33	default:
34		return errors.Errorf("unknown authentication type: %d", dst.Type)
35	}
36
37	return nil
38}
39
40func (src *Authentication) Encode(dst []byte) []byte {
41	dst = append(dst, 'R')
42	sp := len(dst)
43	dst = pgio.AppendInt32(dst, -1)
44	dst = pgio.AppendUint32(dst, src.Type)
45
46	switch src.Type {
47	case AuthTypeMD5Password:
48		dst = append(dst, src.Salt[:]...)
49	}
50
51	pgio.SetInt32(dst[sp:], int32(len(dst[sp:])))
52
53	return dst
54}
55