forked from antlinker/libmqtt
-
Notifications
You must be signed in to change notification settings - Fork 1
/
client_conn.go
350 lines (306 loc) · 9.27 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
/*
* 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"
"net"
"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 int // keepalive packet
ctx context.Context // context for single connection
exit context.CancelFunc // terminate this connection if necessary
}
// start mqtt logic
func (c *clientConn) logic() {
defer func() {
c.conn.Close()
c.parent.log.e("NET exit logic for server =", c.name)
}()
// start keepalive if required
if c.parent.options.keepalive > 0 {
c.parent.workers.Add(1)
go c.keepalive()
}
for {
select {
case <-c.ctx.Done():
return
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, 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, 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, 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, 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, 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, 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, c.parent.persist.Delete(sendKey(p.PacketID)))
}
}
}
default:
c.parent.log.v("NET received packet, type =", pkt.Type())
}
}
}
}
// 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)
c.parent.workers.Done()
}()
for {
select {
case <-c.ctx.Done():
return
case <-t.C:
c.send(PingReqPacket)
select {
case <-c.ctx.Done():
return
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
}
}
}
}
// handle mqtt logic control packet send
func (c *clientConn) handleSend() {
c.parent.log.v("NET start send handle for server = ", c.name)
defer func() {
c.parent.workers.Done()
c.parent.log.e("NET exit send handler for server =", c.name)
}()
for {
select {
case <-c.ctx.Done():
return
case pkt, more := <-c.parent.sendCh:
if !more {
return
}
if err := pkt.WriteTo(c.connRW); err != nil {
c.parent.log.e("NET encode error", err)
return
}
if err := c.connRW.Flush(); err != nil {
c.parent.log.e("NET flush error", err)
return
}
switch pkt.Type() {
case CtrlPublish:
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 CtrlDisConn:
// client exit with disconnect
c.parent.exit()
return
}
case pkt, more := <-c.logicSendC:
if !more {
return
}
if err := pkt.WriteTo(c.connRW); err != nil {
c.parent.log.e("NET encode error", err)
return
}
if err := c.connRW.Flush(); err != nil {
c.parent.log.e("NET flush error", err)
return
}
switch pkt.Type() {
case CtrlPubRel:
notifyPersistMsg(c.parent.msgCh,
c.parent.persist.Store(sendKey(pkt.(*PubRelPacket).PacketID), pkt))
case CtrlPubAck:
notifyPersistMsg(c.parent.msgCh,
c.parent.persist.Delete(sendKey(pkt.(*PubAckPacket).PacketID)))
case CtrlPubComp:
notifyPersistMsg(c.parent.msgCh,
c.parent.persist.Delete(sendKey(pkt.(*PubCompPacket).PacketID)))
case CtrlDisConn:
// disconnect to server
c.conn.Close()
return
}
}
}
}
// handle all message receive
func (c *clientConn) handleRecv() {
defer func() {
c.parent.log.e("NET exit recv handler for server =", c.name)
close(c.netRecvC)
close(c.keepaliveC)
c.parent.workers.Done()
}()
for {
select {
case <-c.ctx.Done():
return
default:
pkt, err := Decode(c.protoVersion, c.connRW)
if err != nil {
c.parent.log.e("NET connection broken, server =", c.name, "err =", err)
// TODO send proper net error to net handler
// exit client connection
c.exit()
return
}
if pkt == PingRespPacket {
c.parent.log.d("NET received keepalive message")
c.keepaliveC <- 1
} else {
c.netRecvC <- pkt
}
}
}
}
// send mqtt logic packet
func (c *clientConn) send(pkt Packet) {
if c.parent.isClosing() {
return
}
c.logicSendC <- pkt
}