forked from antlinker/libmqtt
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient_options.go
312 lines (276 loc) · 8.24 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
/*
* 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"
"io"
"io/ioutil"
"time"
)
var (
ErrNotSupportedVersion = errors.New("mqtt version not supported ")
)
// Option is client option for connection options
type Option func(*AsyncClient) error
// WithCleanSession will set clean flag in connect packet
func WithCleanSession(f bool) Option {
return func(c *AsyncClient) error {
c.options.cleanSession = f
return nil
}
}
// WithIdentity for username and password
func WithIdentity(username, password string) Option {
return func(c *AsyncClient) error {
c.options.username = username
c.options.password = password
return nil
}
}
// WithKeepalive set the keepalive interval (time in second)
func WithKeepalive(keepalive uint16, factor float64) Option {
return func(c *AsyncClient) error {
c.options.keepalive = time.Duration(keepalive) * time.Second
if factor > 1 {
c.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) error {
c.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) error {
if firstDelay < time.Millisecond {
firstDelay = time.Millisecond
}
if maxDelay < firstDelay {
maxDelay = firstDelay
}
if factor < 1 {
factor = 1
}
c.options.firstDelay = firstDelay
c.options.maxDelay = maxDelay
c.options.backOffFactor = factor
return nil
}
}
// WithClientID set the client id for connection
func WithClientID(clientID string) Option {
return func(c *AsyncClient) error {
c.options.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) error {
c.options.isWill = true
c.options.willTopic = topic
c.options.willQos = qos
c.options.willRetain = retain
c.options.willPayload = payload
return nil
}
}
// WithSecureServer use server certificate for verification
// won't apply `WithTLS`, `WithCustomTLS`, `WithTLSReader` options
// when connecting to these servers
func WithSecureServer(servers ...string) Option {
return func(c *AsyncClient) error {
c.options.secureServers = append(c.options.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
func WithServer(servers ...string) Option {
return func(c *AsyncClient) error {
c.options.servers = append(c.options.servers, servers...)
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) 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
}
c.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) 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
}
c.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) error {
c.options.tlsConfig = config
return nil
}
}
// WithDialTimeout for connection time out (time in second)
func WithDialTimeout(timeout uint16) Option {
return func(c *AsyncClient) error {
c.options.dialTimeout = time.Duration(timeout) * time.Second
return nil
}
}
// WithBuf is the alias of WithBufSize
var WithBuf = WithBufSize
// WithBufSize designate the channel size of send and recv
func WithBufSize(sendBuf, recvBuf int) Option {
return func(c *AsyncClient) error {
if sendBuf < 1 {
sendBuf = 1
}
if recvBuf < 1 {
recvBuf = 1
}
c.options.sendChanSize = sendBuf
c.options.recvChanSize = recvBuf
return nil
}
}
// WithLog will create basic logger for the client
func WithLog(l LogLevel) Option {
return func(c *AsyncClient) error {
c.log = newLogger(l)
return nil
}
}
// WithVersion defines the mqtt protocol ProtoVersion in use
func WithVersion(version ProtoVersion, compromise bool) Option {
return func(c *AsyncClient) error {
switch version {
case V311, V5:
c.options.protoVersion = version
c.options.protoCompromise = compromise
return nil
}
return ErrNotSupportedVersion
}
}
// WithRouter set the router for topic dispatch
func WithRouter(r TopicRouter) Option {
return func(c *AsyncClient) error {
if r != nil {
c.router = r
}
return nil
}
}
// WithPersist defines the persist method to be used
func WithPersist(method PersistMethod) Option {
return func(c *AsyncClient) error {
if method != nil {
c.persist = method
}
return nil
}
}
// clientOptions is the options for client to connect, reconnect, disconnect
type clientOptions struct {
protoVersion ProtoVersion // mqtt protocol ProtoVersion
protoCompromise bool // compromise to server protocol ProtoVersion
sendChanSize int // send channel size
recvChanSize int // recv channel size
servers []string // server address strings
secureServers []string // servers with valid tls certificates
dialTimeout time.Duration // dial timeout in second
clientID string // used by ConnPacket
username string // used by ConnPacket
password string // used by ConnPacket
keepalive time.Duration // used by ConnPacket (time in second)
keepaliveFactor float64 // used for reasonable amount time to close conn if no ping resp
cleanSession bool // used by ConnPacket
isWill bool // used by ConnPacket
willTopic string // used by ConnPacket
willPayload []byte // used by ConnPacket
willQos byte // used by ConnPacket
willRetain bool // used by ConnPacket
tlsConfig *tls.Config // tls config with client side cert
maxDelay time.Duration
firstDelay time.Duration
backOffFactor float64
autoReconnect bool
defaultTlsConfig *tls.Config
}