-
Notifications
You must be signed in to change notification settings - Fork 56
/
conn.go
501 lines (425 loc) · 9.91 KB
/
conn.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
// 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"
"net"
"strings"
"sync"
"sync/atomic"
)
var ErrClosedConn = errors.New("zmq4: read/write on closed connection")
// Conn implements the ZeroMQ Message Transport Protocol as defined
// in https://rfc.zeromq.org/spec:23/ZMTP/.
type Conn struct {
typ SocketType
id SocketIdentity
rw net.Conn
sec Security
Server bool
Meta Metadata
Peer struct {
Server bool
Meta Metadata
}
mu sync.RWMutex
topics map[string]struct{} // set of subscribed topics
closed int32
onCloseErrorCB func(c *Conn)
}
func (c *Conn) Close() error {
return c.rw.Close()
}
func (c *Conn) Read(p []byte) (int, error) {
if c.Closed() {
return 0, ErrClosedConn
}
n, err := io.ReadFull(c.rw, p)
c.checkIO(err)
return n, err
}
func (c *Conn) Write(p []byte) (int, error) {
if c.Closed() {
return 0, ErrClosedConn
}
n, err := c.rw.Write(p)
c.checkIO(err)
return n, err
}
// Open opens a ZMTP connection over rw with the given security, socket type and identity.
// An optional onCloseErrorCB can be provided to inform the caller when this Conn is closed.
// Open performs a complete ZMTP handshake.
func Open(rw net.Conn, sec Security, sockType SocketType, sockID SocketIdentity, server bool, onCloseErrorCB func(c *Conn)) (*Conn, error) {
if rw == nil {
return nil, fmt.Errorf("zmq4: invalid nil read-writer")
}
if sec == nil {
return nil, fmt.Errorf("zmq4: invalid nil security")
}
conn := &Conn{
typ: sockType,
id: sockID,
rw: rw,
sec: sec,
Server: server,
Meta: make(Metadata),
topics: make(map[string]struct{}),
onCloseErrorCB: onCloseErrorCB,
}
conn.Meta[sysSockType] = string(conn.typ)
conn.Meta[sysSockID] = conn.id.String()
conn.Peer.Meta = make(Metadata)
err := conn.init(sec)
if err != nil {
return nil, fmt.Errorf("zmq4: could not initialize ZMTP connection: %w", err)
}
return conn, nil
}
// init performs a ZMTP handshake over an io.ReadWriter
func (conn *Conn) init(sec Security) error {
var err error
err = conn.greet(conn.Server)
if err != nil {
return fmt.Errorf("zmq4: could not exchange greetings: %w", err)
}
err = conn.sec.Handshake(conn, conn.Server)
if err != nil {
return fmt.Errorf("zmq4: could not perform security handshake: %w", err)
}
peer := SocketType(conn.Peer.Meta[sysSockType])
if !peer.IsCompatible(conn.typ) {
return fmt.Errorf("zmq4: peer=%q not compatible with %q", peer, conn.typ)
}
// FIXME(sbinet): if security mechanism does not define a client/server
// topology, enforce that p.server == p.peer.server == 0
// as per:
// https://rfc.zeromq.org/spec:23/ZMTP/#topology
return nil
}
func (conn *Conn) greet(server bool) error {
var err error
send := greeting{Version: defaultVersion}
send.Sig.Header = sigHeader
send.Sig.Footer = sigFooter
kind := string(conn.sec.Type())
if len(kind) > len(send.Mechanism) {
return errSecMech
}
copy(send.Mechanism[:], kind)
err = send.write(conn.rw)
if err != nil {
conn.checkIO(err)
return fmt.Errorf("zmq4: could not send greeting: %w", err)
}
var recv greeting
err = recv.read(conn.rw)
if err != nil {
conn.checkIO(err)
return fmt.Errorf("zmq4: could not recv greeting: %w", err)
}
peerKind := asString(recv.Mechanism[:])
if peerKind != kind {
return errBadSec
}
conn.Peer.Server, err = asBool(recv.Server)
if err != nil {
return fmt.Errorf("zmq4: could not get peer server flag: %w", err)
}
return nil
}
// SendCmd sends a ZMTP command over the wire.
func (c *Conn) SendCmd(name string, body []byte) error {
if c.Closed() {
return ErrClosedConn
}
cmd := Cmd{Name: name, Body: body}
buf, err := cmd.marshalZMTP()
if err != nil {
return err
}
return c.send(true, buf, 0)
}
// SendMsg sends a ZMTP message over the wire.
func (c *Conn) SendMsg(msg Msg) error {
if c.Closed() {
return ErrClosedConn
}
if msg.multipart {
return c.sendMulti(msg)
}
nframes := len(msg.Frames)
for i, frame := range msg.Frames {
var flag byte
if i < nframes-1 {
flag ^= hasMoreBitFlag
}
err := c.send(false, frame, flag)
if err != nil {
return fmt.Errorf("zmq4: error sending frame %d/%d: %w", i+1, nframes, err)
}
}
return nil
}
// RecvMsg receives a ZMTP message from the wire.
func (c *Conn) RecvMsg() (Msg, error) {
if c.Closed() {
return Msg{}, ErrClosedConn
}
msg := c.read()
if msg.err != nil {
return msg, fmt.Errorf("zmq4: could not read recv msg: %w", msg.err)
}
if !msg.isCmd() {
return msg, nil
}
switch len(msg.Frames) {
case 0:
msg.err = fmt.Errorf("zmq4: empty command")
return msg, msg.err
case 1:
// ok
default:
msg.err = fmt.Errorf("zmq4: invalid length command")
return msg, msg.err
}
var cmd Cmd
msg.err = cmd.unmarshalZMTP(msg.Frames[0])
if msg.err != nil {
return msg, fmt.Errorf("zmq4: could not unmarshal ZMTP recv msg: %w", msg.err)
}
switch cmd.Name {
case CmdPing:
// send back a PONG immediately.
msg.err = c.SendCmd(CmdPong, nil)
if msg.err != nil {
return msg, msg.err
}
}
switch len(cmd.Body) {
case 0:
msg.Frames = nil
default:
msg.Frames = msg.Frames[:1]
msg.Frames[0] = cmd.Body
}
return msg, nil
}
func (c *Conn) RecvCmd() (Cmd, error) {
var cmd Cmd
if c.Closed() {
return cmd, ErrClosedConn
}
msg := c.read()
if msg.err != nil {
return cmd, fmt.Errorf("zmq4: could not read recv cmd: %w", msg.err)
}
if !msg.isCmd() {
return cmd, ErrBadFrame
}
switch len(msg.Frames) {
case 0:
msg.err = fmt.Errorf("zmq4: empty command")
return cmd, msg.err
case 1:
// ok
default:
msg.err = fmt.Errorf("zmq4: invalid length command")
return cmd, msg.err
}
err := cmd.unmarshalZMTP(msg.Frames[0])
if err != nil {
return cmd, fmt.Errorf("zmq4: could not unmarshal ZMTP recv cmd: %w", err)
}
return cmd, nil
}
func (c *Conn) sendMulti(msg Msg) error {
var buffers net.Buffers
nframes := len(msg.Frames)
for i, frame := range msg.Frames {
var flag byte
if i < nframes-1 {
flag ^= hasMoreBitFlag
}
size := len(frame)
isLong := size > 255
if isLong {
flag ^= isLongBitFlag
}
var (
hdr = [8 + 1]byte{flag}
hsz int
)
if isLong {
hsz = 9
binary.BigEndian.PutUint64(hdr[1:], uint64(size))
} else {
hsz = 2
hdr[1] = uint8(size)
}
switch c.sec.Type() {
case NullSecurity:
buffers = append(buffers, hdr[:hsz], frame)
default:
var secBuf bytes.Buffer
if _, err := c.sec.Encrypt(&secBuf, frame); err != nil {
return err
}
buffers = append(buffers, hdr[:hsz], secBuf.Bytes())
}
}
if _, err := buffers.WriteTo(c.rw); err != nil {
c.checkIO(err)
return err
}
return nil
}
func (c *Conn) send(isCommand bool, body []byte, flag byte) error {
// Long flag
size := len(body)
isLong := size > 255
if isLong {
flag ^= isLongBitFlag
}
if isCommand {
flag ^= isCommandBitFlag
}
var (
hdr = [8 + 1]byte{flag}
hsz int
)
// Write out the message itself
if isLong {
hsz = 9
binary.BigEndian.PutUint64(hdr[1:], uint64(size))
} else {
hsz = 2
hdr[1] = uint8(size)
}
if _, err := c.rw.Write(hdr[:hsz]); err != nil {
c.checkIO(err)
return err
}
if _, err := c.sec.Encrypt(c.rw, body); err != nil {
c.checkIO(err)
return err
}
return nil
}
// read returns the isCommand flag, the body of the message, and optionally an error
func (c *Conn) read() Msg {
var (
header [2]byte
longHdr [8]byte
msg Msg
hasMore = true
isCmd = false
)
for hasMore {
// Read out the header
_, msg.err = io.ReadFull(c.rw, header[:])
if msg.err != nil {
c.checkIO(msg.err)
return msg
}
fl := flag(header[0])
hasMore = fl.hasMore()
isCmd = isCmd || fl.isCommand()
// Determine the actual length of the body
size := uint64(header[1])
if fl.isLong() {
// We read 2 bytes of the header already
// In case of a long message, the length is bytes 2-8 of the header
// We already have the first byte, so assign it, and then read the rest
longHdr[0] = header[1]
_, msg.err = io.ReadFull(c.rw, longHdr[1:])
if msg.err != nil {
c.checkIO(msg.err)
return msg
}
size = binary.BigEndian.Uint64(longHdr[:])
}
if size > uint64(maxInt64) {
msg.err = errOverflow
return msg
}
body := make([]byte, size)
_, msg.err = io.ReadFull(c.rw, body)
if msg.err != nil {
c.checkIO(msg.err)
return msg
}
// fast path for NULL security: we bypass the bytes.Buffer allocation.
switch c.sec.Type() {
case NullSecurity: // FIXME(sbinet): also do that for non-encrypted PLAIN?
msg.Frames = append(msg.Frames, body)
continue
}
buf := new(bytes.Buffer)
if _, msg.err = c.sec.Decrypt(buf, body); msg.err != nil {
return msg
}
msg.Frames = append(msg.Frames, buf.Bytes())
}
if isCmd {
msg.Type = CmdMsg
}
return msg
}
func (conn *Conn) subscribe(msg Msg) {
conn.mu.Lock()
v := msg.Frames[0]
k := string(v[1:])
switch v[0] {
case 0:
delete(conn.topics, k)
case 1:
conn.topics[k] = struct{}{}
}
conn.mu.Unlock()
}
func (conn *Conn) subscribed(topic string) bool {
conn.mu.RLock()
defer conn.mu.RUnlock()
for k := range conn.topics {
switch {
case k == "":
// subscribed to everything
return true
case strings.HasPrefix(topic, k):
return true
}
}
return false
}
func (conn *Conn) SetClosed() {
if wasClosed := atomic.CompareAndSwapInt32(&conn.closed, 0, 1); wasClosed {
conn.notifyOnCloseError()
}
}
func (conn *Conn) Closed() bool {
return atomic.LoadInt32(&conn.closed) == 1
}
func (conn *Conn) checkIO(err error) {
if err == nil {
return
}
if err == io.EOF || errors.Is(err, io.EOF) {
conn.SetClosed()
return
}
var e net.Error
if errors.As(err, &e); e != nil && !e.Timeout() {
conn.SetClosed()
}
}
func (conn *Conn) notifyOnCloseError() {
if conn.onCloseErrorCB == nil {
return
}
conn.onCloseErrorCB(conn)
}