-
Notifications
You must be signed in to change notification settings - Fork 57
/
protocol.go
276 lines (233 loc) · 5.73 KB
/
protocol.go
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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
// Copyright 2018 The go-zeromq Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.
package zmq4
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"io"
"strings"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
var (
errGreeting = errors.New("zmq4: invalid greeting received")
errSecMech = errors.New("zmq4: invalid security mechanism")
errBadSec = errors.New("zmq4: invalid or unsupported security mechanism")
ErrBadCmd = errors.New("zmq4: invalid command name")
ErrBadFrame = errors.New("zmq4: invalid frame")
errOverflow = errors.New("zmq4: overflow")
errEmptyAppMDKey = errors.New("zmq4: empty application metadata key")
errDupAppMDKey = errors.New("zmq4: duplicate application metadata key")
errBoolCnv = errors.New("zmq4: invalid byte to bool conversion")
)
const (
sigHeader = 0xFF
sigFooter = 0x7F
majorVersion uint8 = 3
minorVersion uint8 = 0
hasMoreBitFlag = 0x1
isLongBitFlag = 0x2
isCommandBitFlag = 0x4
zmtpMsgLen = 64
)
var (
defaultVersion = [2]uint8{
majorVersion,
minorVersion,
}
)
const (
maxUint = ^uint(0)
maxInt = int(maxUint >> 1)
maxUint64 = ^uint64(0)
maxInt64 = int64(maxUint64 >> 1)
)
func asString(slice []byte) string {
i := bytes.IndexByte(slice, 0)
if i < 0 {
i = len(slice)
}
return string(slice[:i])
}
func asBool(b byte) (bool, error) {
switch b {
case 0x00:
return false, nil
case 0x01:
return true, nil
}
return false, errBoolCnv
}
type greeting struct {
Sig struct {
Header byte
_ [8]byte
Footer byte
}
Version [2]uint8
Mechanism [20]byte
Server byte
_ [31]byte
}
func (g *greeting) read(r io.Reader) error {
var data [zmtpMsgLen]byte
_, err := io.ReadFull(r, data[:])
if err != nil {
return fmt.Errorf("could not read ZMTP greeting: %w", err)
}
g.unmarshal(data[:])
if g.Sig.Header != sigHeader {
return fmt.Errorf("invalid ZMTP signature header: %w", errGreeting)
}
if g.Sig.Footer != sigFooter {
return fmt.Errorf("invalid ZMTP signature footer: %w", errGreeting)
}
if !g.validate(defaultVersion) {
return fmt.Errorf(
"invalid ZMTP version (got=%v, want=%v): %w",
g.Version, defaultVersion, errGreeting,
)
}
return nil
}
func (g *greeting) unmarshal(data []byte) {
_ = data[:zmtpMsgLen]
g.Sig.Header = data[0]
g.Sig.Footer = data[9]
g.Version[0] = data[10]
g.Version[1] = data[11]
copy(g.Mechanism[:], data[12:32])
g.Server = data[32]
}
func (g *greeting) write(w io.Writer) error {
_, err := w.Write(g.marshal())
return err
}
func (g *greeting) marshal() []byte {
var buf [zmtpMsgLen]byte
buf[0] = g.Sig.Header
// padding 1 ignored
buf[9] = g.Sig.Footer
buf[10] = g.Version[0]
buf[11] = g.Version[1]
copy(buf[12:32], g.Mechanism[:])
buf[32] = g.Server
// padding 2 ignored
return buf[:]
}
func (g *greeting) validate(ref [2]uint8) bool {
switch {
case g.Version == ref:
return true
case g.Version[0] > ref[0] ||
g.Version[0] == ref[0] && g.Version[1] > ref[1]:
// accept higher protocol values
return true
case g.Version[0] < ref[0] ||
g.Version[0] == ref[0] && g.Version[1] < ref[1]:
// FIXME(sbinet): handle version negotiations as per
// https://rfc.zeromq.org/spec:23/ZMTP/#version-negotiation
return false
default:
return false
}
}
const (
sysSockType = "Socket-Type"
sysSockID = "Identity"
)
// Metadata is describing a Conn's metadata information.
type Metadata map[string]string
// MarshalZMTP marshals MetaData to ZMTP encoded data.
func (md Metadata) MarshalZMTP() ([]byte, error) {
buf := new(bytes.Buffer)
keys := make(map[string]struct{})
for k, v := range md {
if len(k) == 0 {
return nil, errEmptyAppMDKey
}
key := strings.ToLower(k)
if _, dup := keys[key]; dup {
return nil, errDupAppMDKey
}
keys[key] = struct{}{}
switch k {
case sysSockID, sysSockType:
if _, err := io.Copy(buf, Property{K: k, V: v}); err != nil {
return nil, err
}
default:
if _, err := io.Copy(buf, Property{K: "X-" + key, V: v}); err != nil {
return nil, err
}
}
}
return buf.Bytes(), nil
}
// UnmarshalZMTP unmarshals MetaData from a ZMTP encoded data.
func (md *Metadata) UnmarshalZMTP(p []byte) error {
i := 0
for i < len(p) {
var kv Property
n, err := kv.Write(p[i:])
if err != nil {
return err
}
i += n
name := toTitle(kv.K)
(*md)[name] = kv.V
}
return nil
}
// Property describes a Conn metadata's entry.
// The on-wire respresentation of Property is specified by:
//
// https://rfc.zeromq.org/spec:23/ZMTP/
type Property struct {
K string
V string
}
func (prop Property) Read(data []byte) (n int, err error) {
klen := len(prop.K)
vlen := len(prop.V)
size := 1 + klen + 4 + vlen
_ = data[:size] // help with bound check elision
data[n] = byte(klen)
n++
n += copy(data[n:n+klen], toTitle(prop.K))
binary.BigEndian.PutUint32(data[n:n+4], uint32(vlen))
n += 4
n += copy(data[n:n+vlen], prop.V)
return n, io.EOF
}
func (prop *Property) Write(data []byte) (n int, err error) {
klen := int(data[n])
n++
if klen > len(data) {
return n, io.ErrUnexpectedEOF
}
prop.K = toTitle(string(data[n : n+klen]))
n += klen
v := binary.BigEndian.Uint32(data[n : n+4])
n += 4
if uint64(v) > uint64(maxInt) {
return n, errOverflow
}
vlen := int(v)
if n+vlen > len(data) {
return n, io.ErrUnexpectedEOF
}
prop.V = string(data[n : n+vlen])
n += vlen
return n, nil
}
type flag byte
func (fl flag) hasMore() bool { return fl&hasMoreBitFlag == hasMoreBitFlag }
func (fl flag) isLong() bool { return fl&isLongBitFlag == isLongBitFlag }
func (fl flag) isCommand() bool { return fl&isCommandBitFlag == isCommandBitFlag }
func toTitle(s string) string {
return cases.Title(language.Und, cases.NoLower).String(s)
}