-
Notifications
You must be signed in to change notification settings - Fork 11
/
connection.go
294 lines (229 loc) · 6.04 KB
/
connection.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
package yagnats
import (
"bufio"
"crypto/tls"
"crypto/x509"
"errors"
"net"
"sync"
"time"
)
type Connection struct {
conn net.Conn
addr string
user string
pass string
dial func(network, address string) (net.Conn, error)
writeLock *sync.Mutex
pongs chan *PongPacket
oks chan *OKPacket
errs chan error
onMessage func(*MsgPacket)
Disconnected chan bool
logger Logger
loggerMutex *sync.RWMutex
}
type ConnectionProvider interface {
ProvideConnection() (*Connection, error)
}
func NewConnection(addr, user, pass string) *Connection {
return &Connection{
addr: addr,
user: user,
pass: pass,
dial: func(network, address string) (net.Conn, error) {
return net.DialTimeout(network, address, 5*time.Second)
},
writeLock: &sync.Mutex{},
logger: &DefaultLogger{},
loggerMutex: &sync.RWMutex{},
pongs: make(chan *PongPacket),
oks: make(chan *OKPacket),
// buffer size of 1 to account for fatal unexpected errors
// from the server (i.e. slow consumer)
errs: make(chan error, 1),
Disconnected: make(chan bool),
}
}
func NewTLSConnection(addr, user, pass string, certPool *x509.CertPool, clientCert *tls.Certificate, verifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error) *Connection {
connection := NewConnection(addr, user, pass)
connection.dial = func(network, address string) (net.Conn, error) {
conn, err := net.DialTimeout(network, address, 5*time.Second)
if err != nil {
return nil, err
}
br := bufio.NewReaderSize(conn, 32768)
_, err = Parse(br)
if err != nil {
return nil, err
}
hostname, _, err := net.SplitHostPort(address)
if err != nil {
return nil, err
}
config := tls.Config{
RootCAs: certPool,
ServerName: hostname,
VerifyPeerCertificate: verifyPeerCertificate,
}
// When client certificate is provided, we are expecting mutual TLS.
if clientCert != nil {
config.Certificates = []tls.Certificate{*clientCert}
}
conn = tls.Client(conn, &config)
tlsConn := conn.(*tls.Conn)
err = tlsConn.Handshake()
return tlsConn, err
}
return connection
}
type ConnectionInfo struct {
Addr string
Username string
Password string
Dial func(network, address string) (net.Conn, error)
TLSInfo *ConnectionTLSInfo
}
type ConnectionTLSInfo struct {
CertPool *x509.CertPool
ClientCert *tls.Certificate
VerifyPeerCertificate func(rawCerts [][]byte, verifiedChains [][]*x509.Certificate) error
}
func (c *ConnectionInfo) ProvideConnection() (*Connection, error) {
var conn *Connection
if c.TLSInfo == nil {
conn = NewConnection(c.Addr, c.Username, c.Password)
} else {
conn = NewTLSConnection(c.Addr, c.Username, c.Password, c.TLSInfo.CertPool, c.TLSInfo.ClientCert, c.TLSInfo.VerifyPeerCertificate)
}
if c.Dial != nil {
conn.dial = c.Dial
}
var err error
err = conn.Dial()
if err != nil {
return nil, err
}
err = conn.Handshake()
if err != nil {
return nil, err
}
return conn, nil
}
type ConnectionCluster struct {
Members []ConnectionProvider
}
func (c *ConnectionCluster) ProvideConnection() (conn *Connection, err error) {
for _, cp := range c.Members {
conn, err = cp.ProvideConnection()
if err == nil {
return conn, nil
}
}
return nil, err
}
func (c *Connection) Dial() error {
conn, err := c.dial("tcp", c.addr)
if err != nil {
return err
}
c.conn = conn
go c.receivePackets()
return nil
}
func (c *Connection) OnMessage(callback func(*MsgPacket)) {
c.onMessage = callback
}
func (c *Connection) Handshake() error {
c.Send(&ConnectPacket{User: c.user, Pass: c.pass})
return c.ErrOrOK()
}
func (c *Connection) Disconnect() {
c.conn.Close()
}
func (c *Connection) ErrOrOK() error {
c.Logger().Debug("connection.err-or-ok.wait")
select {
case err := <-c.errs:
c.Logger().Warnd(map[string]interface{}{"error": err.Error()}, "connection.err-or-ok.err")
return err
case <-c.oks:
c.Logger().Debug("connection.err-or-ok.ok")
return nil
}
}
func (c *Connection) Send(packet Packet) {
c.Logger().Debugd(map[string]interface{}{"packet": packet}, "connection.packet.send")
c.writeLock.Lock()
defer c.writeLock.Unlock()
// ignore write errors; readPackets will notice connection being interrupted
_, err := c.conn.Write(packet.Encode())
if err != nil {
c.Logger().Errord(map[string]interface{}{"error": err.Error()}, "connection.packet.write-error")
}
return
}
func (c *Connection) Ping() bool {
c.Send(&PingPacket{})
select {
case _, ok := <-c.pongs:
return ok
case <-time.After(500 * time.Millisecond):
return false
}
}
func (c *Connection) SetLogger(logger Logger) {
c.loggerMutex.Lock()
c.logger = logger
c.loggerMutex.Unlock()
}
func (c *Connection) Logger() Logger {
c.loggerMutex.RLock()
defer c.loggerMutex.RUnlock()
return c.logger
}
func (c *Connection) receivePackets() {
io := bufio.NewReader(c.conn)
for {
c.Logger().Debug("connection.packet.read")
packet, err := Parse(io)
if err != nil {
c.Logger().Errord(map[string]interface{}{"error": err.Error()}, "connection.packet.read-error")
c.Disconnect()
c.disconnected()
break
}
switch packet.(type) {
case *PongPacket:
c.Logger().Debug("connection.packet.pong-received")
select {
case c.pongs <- packet.(*PongPacket):
c.Logger().Debug("connection.packet.pong-served")
default:
c.Logger().Debug("connection.packet.pong-unhandled")
}
case *PingPacket:
c.Logger().Debug("connection.packet.ping-received")
c.Send(&PongPacket{})
case *OKPacket:
c.Logger().Debug("connection.packet.ok-received")
c.oks <- packet.(*OKPacket)
case *ERRPacket:
c.Logger().Debug("connection.packet.err-received")
c.errs <- errors.New(packet.(*ERRPacket).Message)
case *InfoPacket:
c.Logger().Debug("connection.packet.info-received")
// noop
case *MsgPacket:
c.Logger().Debugd(
map[string]interface{}{"packet": packet},
"connection.packet.msg-received",
)
c.onMessage(packet.(*MsgPacket))
}
}
}
func (c *Connection) disconnected() {
c.Disconnected <- true
c.errs <- errors.New("disconnected")
}