-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathstartup.go
More file actions
110 lines (90 loc) · 2.11 KB
/
startup.go
File metadata and controls
110 lines (90 loc) · 2.11 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
package pgproto
import (
"bytes"
"fmt"
"io"
"sort"
)
const (
sslRequestVersion = 80877103
)
type StartupMessage struct {
SSLRequest bool
Options map[string][]byte
}
func (s *StartupMessage) client() {}
func ParseStartupMessage(r io.Reader) (*StartupMessage, error) {
b := newReadBuffer(r)
// [int32 - length] [int32 - protocol] [[string]\0[string\0]]\0
buf, err := b.ReadLength()
if err != nil {
return nil, err
}
s := &StartupMessage{
Options: make(map[string][]byte),
SSLRequest: false,
}
// Parse protocol version
p, err := buf.ReadInt()
if err != nil {
return nil, err
}
// Protocol version should either be protocol version 3.0 or an SSL request version
if p == sslRequestVersion {
s.SSLRequest = true
// Exit early, we don't have any options
return s, nil
} else if p != ProtocolVersion {
return nil, fmt.Errorf("unsupported protocol version")
}
// Parse the key/value pairs
for {
key, err := buf.ReadString(false)
if err == io.EOF {
break
} else if err != nil {
return nil, err
}
// This message ends in a single null terminator
if bytes.Equal(key, []byte{'\x00'}) {
break
}
// The key is [string] \0, we keep the \0 until now for the previous check
key = bytes.TrimRight(key, "\x00")
value, err := buf.ReadString(true)
if err != nil {
return nil, err
}
s.Options[string(bytes.ToLower(key))] = value
}
return s, nil
}
func (s *StartupMessage) Encode() []byte {
w := newWriteBuffer()
w.WriteInt(ProtocolVersion)
// Encode the options in sorted order
keys := []string{}
for k := range s.Options {
keys = append(keys, k)
}
sort.Strings(keys)
for _, k := range keys {
v := s.Options[k]
w.WriteString([]byte(k), true)
w.WriteString(v, true)
}
w.WriteByte('\x00')
w.PrependLength()
return w.Bytes()
}
func (s *StartupMessage) AsMap() map[string]interface{} {
return map[string]interface{}{
"Type": "StartupMessage",
"Payload": map[string]interface{}{
"SSLRequest": s.SSLRequest,
"Protocol": ProtocolVersion,
"Options": s.Options,
},
}
}
func (s *StartupMessage) String() string { return messageToString(s) }