forked from antlinker/libmqtt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client_conn.go
387 lines (339 loc) · 10.3 KB
/
client_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
/*
* 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 (
"bufio"
"context"
"io"
"net"
"sync/atomic"
"time"
)
// clientConn is the wrapper of connection to server
// tend to actual packet send and receive
type clientConn struct {
protoVersion ProtoVersion // mqtt protocol version
parent Client // client which created this connection
name string // server addr info
conn net.Conn // connection to server
connRW *bufio.ReadWriter // make buffered connection
logicSendC chan Packet // logic send channel
netRecvC chan Packet // received packet from server
keepaliveC chan struct{} // keepalive packet
parentExit uint32
ctx context.Context // context for single connection
exit context.CancelFunc // terminate this connection if necessary
stopSig <-chan struct{}
}
func (c *clientConn) parentExiting() bool {
return atomic.LoadUint32(&c.parentExit) == 1
}
// start mqtt logic
func (c *clientConn) logic() {
defer func() {
err := c.conn.Close()
if err != nil {
notifyNetMsg(c.parent.msgCh, c.name, err)
} else {
notifyNetMsg(c.parent.msgCh, c.name, io.EOF)
}
c.parent.log.e("NET exit logic for server =", c.name)
}()
// start keepalive if required
if c.parent.options.keepalive > 0 {
c.parent.addWorker(c.keepalive)
}
for {
select {
case pkt, more := <-c.netRecvC:
if !more {
return
}
switch pkt.(type) {
case *SubAckPacket:
p := pkt.(*SubAckPacket)
c.parent.log.v("NET received SubAck, id =", p.PacketID)
if originPkt, ok := c.parent.idGen.getExtra(p.PacketID); ok {
switch originPkt.(type) {
case *SubscribePacket:
originSub := originPkt.(*SubscribePacket)
N := len(p.Codes)
for i, v := range originSub.Topics {
if i < N {
v.Qos = p.Codes[i]
}
}
c.parent.log.d("NET subscribed topics =", originSub.Topics)
notifySubMsg(c.parent.msgCh, originSub.Topics, nil)
c.parent.idGen.free(p.PacketID)
notifyPersistMsg(c.parent.msgCh, p, c.parent.persist.Delete(sendKey(p.PacketID)))
}
}
case *UnsubAckPacket:
p := pkt.(*UnsubAckPacket)
c.parent.log.v("NET received UnSubAck, id =", p.PacketID)
if originPkt, ok := c.parent.idGen.getExtra(p.PacketID); ok {
switch originPkt.(type) {
case *UnsubPacket:
originUnSub := originPkt.(*UnsubPacket)
c.parent.log.d("NET unsubscribed topics", originUnSub.TopicNames)
notifyUnSubMsg(c.parent.msgCh, originUnSub.TopicNames, nil)
c.parent.idGen.free(p.PacketID)
notifyPersistMsg(c.parent.msgCh, p, c.parent.persist.Delete(sendKey(p.PacketID)))
}
}
case *PublishPacket:
p := pkt.(*PublishPacket)
c.parent.log.v("NET received publish, topic =", p.TopicName, "id =", p.PacketID, "QoS =", p.Qos)
// received server publish, send to client
c.parent.recvCh <- p
// tend to QoS
switch p.Qos {
case Qos1:
c.parent.log.d("NET send PubAck for Publish, id =", p.PacketID)
c.send(&PubAckPacket{PacketID: p.PacketID})
notifyPersistMsg(c.parent.msgCh, p, c.parent.persist.Store(recvKey(p.PacketID), pkt))
case Qos2:
c.parent.log.d("NET send PubRecv for Publish, id =", p.PacketID)
c.send(&PubRecvPacket{PacketID: p.PacketID})
notifyPersistMsg(c.parent.msgCh, p, c.parent.persist.Store(recvKey(p.PacketID), pkt))
}
case *PubAckPacket:
p := pkt.(*PubAckPacket)
c.parent.log.v("NET received PubAck, id =", p.PacketID)
if originPkt, ok := c.parent.idGen.getExtra(p.PacketID); ok {
switch originPkt.(type) {
case *PublishPacket:
originPub := originPkt.(*PublishPacket)
if originPub.Qos == Qos1 {
c.parent.log.d("NET published qos1 packet, topic =", originPub.TopicName)
notifyPubMsg(c.parent.msgCh, originPub.TopicName, nil)
c.parent.idGen.free(p.PacketID)
notifyPersistMsg(c.parent.msgCh, p, c.parent.persist.Delete(sendKey(p.PacketID)))
}
}
}
case *PubRecvPacket:
p := pkt.(*PubRecvPacket)
c.parent.log.v("NET received PubRec, id =", p.PacketID)
if originPkt, ok := c.parent.idGen.getExtra(p.PacketID); ok {
switch originPkt.(type) {
case *PublishPacket:
originPub := originPkt.(*PublishPacket)
if originPub.Qos == Qos2 {
c.send(&PubRelPacket{PacketID: p.PacketID})
c.parent.log.d("NET send PubRel, id =", p.PacketID)
}
}
}
case *PubRelPacket:
p := pkt.(*PubRelPacket)
c.parent.log.v("NET send PubRel, id =", p.PacketID)
if originPkt, ok := c.parent.idGen.getExtra(p.PacketID); ok {
switch originPkt.(type) {
case *PublishPacket:
originPub := originPkt.(*PublishPacket)
if originPub.Qos == Qos2 {
c.send(&PubCompPacket{PacketID: p.PacketID})
c.parent.log.d("NET send PubComp, id =", p.PacketID)
notifyPersistMsg(c.parent.msgCh, p, c.parent.persist.Store(recvKey(p.PacketID), pkt))
}
}
}
case *PubCompPacket:
p := pkt.(*PubCompPacket)
c.parent.log.v("NET received PubComp, id =", p.PacketID)
if originPkt, ok := c.parent.idGen.getExtra(p.PacketID); ok {
switch originPkt.(type) {
case *PublishPacket:
originPub := originPkt.(*PublishPacket)
if originPub.Qos == Qos2 {
c.send(&PubRelPacket{PacketID: p.PacketID})
c.parent.log.d("NET send PubRel, id =", p.PacketID)
c.parent.log.d("NET published qos2 packet, topic =", originPub.TopicName)
notifyPubMsg(c.parent.msgCh, originPub.TopicName, nil)
c.parent.idGen.free(p.PacketID)
notifyPersistMsg(c.parent.msgCh, p, c.parent.persist.Delete(sendKey(p.PacketID)))
}
}
}
default:
c.parent.log.v("NET received packet, type =", pkt.Type())
}
case <-c.stopSig:
return
}
}
}
// keepalive with server
func (c *clientConn) keepalive() {
c.parent.log.d("NET start keepalive")
t := time.NewTicker(c.parent.options.keepalive * 3 / 4)
timeout := time.Duration(float64(c.parent.options.keepalive) * c.parent.options.keepaliveFactor)
timeoutTimer := time.NewTimer(timeout)
defer func() {
t.Stop()
timeoutTimer.Stop()
c.parent.log.d("NET stop keepalive for server =", c.name)
}()
for {
select {
case <-t.C:
c.send(PingReqPacket)
select {
case _, more := <-c.keepaliveC:
if !more {
return
}
timeoutTimer.Reset(timeout)
case <-timeoutTimer.C:
c.parent.log.i("NET keepalive timeout")
// exit client connection
c.exit()
return
case <-c.stopSig:
return
}
case <-c.stopSig:
return
}
}
}
const (
flushDelayInterval = 100 * time.Microsecond
)
// handle mqtt logic control packet send
func (c *clientConn) handleSend() {
c.parent.log.v("NET clientConn.handleSend() for server =", c.name)
flushSig := time.NewTimer(time.Hour)
defer func() {
c.parent.log.e("NET exit clientConn.handleSend() for server =", c.name)
flushSig.Stop()
}()
for {
select {
case <-c.stopSig:
return
case <-flushSig.C:
if err := c.connRW.Flush(); err != nil {
c.parent.log.e("NET flush error", err)
flushSig.Reset(time.Hour)
notifyNetMsg(c.parent.msgCh, c.name, err)
return
}
case pkt, more := <-c.parent.sendCh:
if !more {
return
}
pkt.SetVersion(c.protoVersion)
if err := pkt.WriteTo(c.connRW); err != nil {
c.parent.log.e("NET encode error", err)
return
}
flushSig.Reset(flushDelayInterval)
switch pkt.(type) {
case *PublishPacket:
p := pkt.(*PublishPacket)
if p.Qos == 0 {
c.parent.log.d("NET published qos0 packet, topic =", p.TopicName)
notifyPubMsg(c.parent.msgCh, p.TopicName, nil)
}
case *DisconnPacket:
// client exit with disconnect
if err := c.connRW.Flush(); err != nil {
c.parent.log.e("NET flush error", err)
notifyNetMsg(c.parent.msgCh, c.name, err)
}
_ = c.conn.Close()
c.exit()
return
}
case pkt, more := <-c.logicSendC:
if !more {
return
}
pkt.SetVersion(c.protoVersion)
if err := pkt.WriteTo(c.connRW); err != nil {
c.parent.log.e("NET encode error", err)
return
}
flushSig.Reset(flushDelayInterval)
switch pkt.(type) {
case *PubRelPacket:
notifyPersistMsg(c.parent.msgCh, pkt,
c.parent.persist.Store(sendKey(pkt.(*PubRelPacket).PacketID), pkt))
case *PubAckPacket:
notifyPersistMsg(c.parent.msgCh, pkt,
c.parent.persist.Delete(sendKey(pkt.(*PubAckPacket).PacketID)))
case *PubCompPacket:
notifyPersistMsg(c.parent.msgCh, pkt,
c.parent.persist.Delete(sendKey(pkt.(*PubCompPacket).PacketID)))
case *DisconnPacket:
// disconnect to server, no more action
if err := c.connRW.Flush(); err != nil {
c.parent.log.e("NET flush error", err)
notifyNetMsg(c.parent.msgCh, c.name, err)
}
_ = c.conn.Close()
c.exit()
return
}
}
}
}
// handle all message receive
func (c *clientConn) handleNetRecv() {
c.parent.log.v("NET clientConn.handleNetRecv() for server =", c.name)
defer func() {
c.parent.log.v("NET exit clientConn.handleNetRecv() for server =", c.name)
close(c.netRecvC)
close(c.keepaliveC)
}()
for {
pkt, err := Decode(c.protoVersion, c.connRW)
if err != nil {
c.parent.log.e("NET connection broken, server =", c.name, "err =", err)
// exit client connection
notifyNetMsg(c.parent.msgCh, c.name, err)
c.exit()
return
}
if pkt.Version() != c.protoVersion {
// protocol version not match, exit
c.exit()
return
}
if pkt.Type() == CtrlPingResp {
c.parent.log.d("NET received keepalive message")
select {
case c.keepaliveC <- struct{}{}:
case <-c.stopSig:
}
} else {
select {
case c.netRecvC <- pkt:
case <-c.stopSig:
}
}
}
}
// send mqtt logic packet
func (c *clientConn) send(pkt Packet) {
select {
case c.logicSendC <- pkt:
case <-c.stopSig:
}
}