forked from antlinker/libmqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
client_options.go
369 lines (322 loc) · 9.37 KB
/
client_options.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
/*
* Copyright Go-IIoT (https://github.com/goiiot)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package libmqtt
import (
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"io/ioutil"
"time"
)
var (
ErrNotSupportedVersion = errors.New("mqtt version not supported ")
)
// Option is client option for connection options
type Option func(*AsyncClient, *connectOptions) error
// WithSecureServer use server certificate for verification
// won't apply `WithTLS`, `WithCustomTLS`, `WithTLSReader` options
// when connecting to these servers
//
// Deprecated: use Client.ConnectServer instead (will be removed in v1.0)
func WithSecureServer(servers ...string) Option {
return func(c *AsyncClient, options *connectOptions) error {
if c == nil {
return errors.New("global option can not be applied to ConnectServer")
}
c.secureServers = append(c.secureServers, servers...)
return nil
}
}
// WithServer set client servers
// addresses should be in form of `ip:port` or `domain.name:port`,
// only TCP connection supported for now
//
// Deprecated: use Client.ConnectServer instead (will be removed in v1.0)
func WithServer(servers ...string) Option {
return func(c *AsyncClient, options *connectOptions) error {
c.servers = append(c.servers, servers...)
return nil
}
}
// WithBuf is the alias of WithBufSize
//
// Deprecated: use WithBufSize instead (will be removed in v1.0)
var WithBuf = WithBufSize
// WithBufSize designate the channel size of send and recv
func WithBufSize(sendBufSize, recvBufSize int) Option {
return func(c *AsyncClient, options *connectOptions) error {
if sendBufSize < 1 {
sendBufSize = 1
}
if recvBufSize < 1 {
recvBufSize = 1
}
c.sendCh = make(chan Packet, sendBufSize)
c.recvCh = make(chan *PublishPacket, recvBufSize)
return nil
}
}
func WithConnHandleFunc(handler ConnHandleFunc) Option {
return func(client *AsyncClient, options *connectOptions) error {
options.connHandler = handler
return nil
}
}
func WithPubHandleFunc(handler PubHandleFunc) Option {
return func(client *AsyncClient, options *connectOptions) error {
if client.pubHandler == nil {
client.pubHandler = handler
}
return nil
}
}
func WithSubHandleFunc(handler SubHandleFunc) Option {
return func(client *AsyncClient, options *connectOptions) error {
if client.subHandler == nil {
client.subHandler = handler
}
return nil
}
}
func WithUnsubHandleFunc(handler UnsubHandleFunc) Option {
return func(client *AsyncClient, options *connectOptions) error {
if client.unsubHandler == nil {
client.unsubHandler = handler
}
return nil
}
}
func WithNetHandleFunc(handler NetHandleFunc) Option {
return func(client *AsyncClient, options *connectOptions) error {
if client.netHandler == nil {
client.netHandler = handler
}
return nil
}
}
func WithPersistHandleFunc(handler PersistHandleFunc) Option {
return func(client *AsyncClient, options *connectOptions) error {
if client.persistHandler == nil {
client.persistHandler = handler
}
return nil
}
}
// WithLog will create basic logger for the client
func WithLog(l LogLevel) Option {
return func(c *AsyncClient, options *connectOptions) error {
c.log = newLogger(l)
return nil
}
}
// WithPersist defines the persist method to be used
func WithPersist(method PersistMethod) Option {
return func(c *AsyncClient, options *connectOptions) error {
if method != nil {
c.persist = method
}
return nil
}
}
// WithCleanSession will set clean flag in connect packet
func WithCleanSession(f bool) Option {
return func(c *AsyncClient, options *connectOptions) error {
options.connPacket.CleanSession = f
return nil
}
}
// WithIdentity for username and password
func WithIdentity(username, password string) Option {
return func(c *AsyncClient, options *connectOptions) error {
options.connPacket.Username = username
options.connPacket.Password = password
return nil
}
}
// WithKeepalive set the keepalive interval (time in second)
func WithKeepalive(keepalive uint16, factor float64) Option {
return func(c *AsyncClient, options *connectOptions) error {
if keepalive <= 0 {
return fmt.Errorf("keepalive provided must be greater than 0")
}
options.connPacket.Keepalive = keepalive
options.keepalive = time.Duration(keepalive) * time.Second
if factor > 1 {
options.keepaliveFactor = factor
} else {
factor = 1.2
}
return nil
}
}
// WithAutoReconnect set client to auto reconnect to server when connection failed
func WithAutoReconnect(autoReconnect bool) Option {
return func(c *AsyncClient, options *connectOptions) error {
options.autoReconnect = autoReconnect
return nil
}
}
// WithBackoffStrategy will set reconnect backoff strategy
// firstDelay is the time to wait before retrying after the first failure
// maxDelay defines the upper bound of backoff delay
// factor is applied to the backoff after each retry.
//
// e.g. FirstDelay = 1s and Factor = 2
// then the SecondDelay is 2s, the ThirdDelay is 4s
func WithBackoffStrategy(firstDelay, maxDelay time.Duration, factor float64) Option {
return func(c *AsyncClient, options *connectOptions) error {
if firstDelay < time.Millisecond {
firstDelay = time.Millisecond
}
if maxDelay < firstDelay {
maxDelay = firstDelay
}
if factor < 1 {
factor = 1
}
options.firstDelay = firstDelay
options.maxDelay = maxDelay
options.backOffFactor = factor
return nil
}
}
// WithClientID set the client id for connection
func WithClientID(clientID string) Option {
return func(c *AsyncClient, options *connectOptions) error {
options.connPacket.ClientID = clientID
return nil
}
}
// WithWill mark this connection as a will teller
func WithWill(topic string, qos QosLevel, retain bool, payload []byte) Option {
return func(c *AsyncClient, options *connectOptions) error {
options.connPacket.IsWill = true
options.connPacket.WillTopic = topic
options.connPacket.WillQos = qos
options.connPacket.WillRetain = retain
options.connPacket.WillMessage = payload
return nil
}
}
// WithTLSReader set tls from client cert, key, ca reader, apply to all servers
// listed in `WithServer` Option
func WithTLSReader(certReader, keyReader, caReader io.Reader, serverNameOverride string, skipVerify bool) Option {
return func(c *AsyncClient, options *connectOptions) error {
b, err := ioutil.ReadAll(certReader)
if err != nil {
return err
}
cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM(b) {
return err
}
// load cert-key pair
certBytes, err := ioutil.ReadAll(certReader)
if err != nil {
return err
}
keyBytes, err := ioutil.ReadAll(keyReader)
if err != nil {
return err
}
cert, err := tls.X509KeyPair(certBytes, keyBytes)
if err != nil {
return err
}
options.tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: skipVerify,
ClientCAs: cp,
ServerName: serverNameOverride,
}
return nil
}
}
// WithTLS set client tls from cert, key and ca file, apply to all servers
// listed in `WithServer` Option
func WithTLS(certFile, keyFile, caCert, serverNameOverride string, skipVerify bool) Option {
return func(c *AsyncClient, options *connectOptions) error {
b, err := ioutil.ReadFile(caCert)
if err != nil {
return err
}
cp := x509.NewCertPool()
if !cp.AppendCertsFromPEM(b) {
return err
}
cert, err := tls.LoadX509KeyPair(certFile, keyFile)
if err != nil {
return err
}
options.tlsConfig = &tls.Config{
Certificates: []tls.Certificate{cert},
InsecureSkipVerify: skipVerify,
ClientCAs: cp,
ServerName: serverNameOverride,
}
return nil
}
}
// WithCustomTLS replaces the TLS options with a custom tls.Config
func WithCustomTLS(config *tls.Config) Option {
return func(c *AsyncClient, options *connectOptions) error {
if config == nil {
options.tlsConfig = nil
} else {
options.tlsConfig = config.Clone()
}
return nil
}
}
// WithDialTimeout for connection time out (time in second)
func WithDialTimeout(timeout uint16) Option {
return func(c *AsyncClient, options *connectOptions) error {
options.dialTimeout = time.Duration(timeout) * time.Second
return nil
}
}
// WithVersion defines the mqtt protocol ProtoVersion in use
func WithVersion(version ProtoVersion, compromise bool) Option {
return func(c *AsyncClient, options *connectOptions) error {
switch version {
case V311, V5:
options.protoVersion = version
options.protoCompromise = compromise
return nil
}
return ErrNotSupportedVersion
}
}
// WithRouter set the router for topic dispatch
func WithRouter(r TopicRouter) Option {
return func(c *AsyncClient, options *connectOptions) error {
if r != nil {
c.router = r
}
return nil
}
}
func WithConnPacket(pkt ConnPacket) Option {
return func(c *AsyncClient, options *connectOptions) error {
options.connPacket = &pkt
if pkt.Keepalive > 0 {
options.keepalive = time.Duration(pkt.Keepalive) * time.Second
}
return nil
}
}