-
Notifications
You must be signed in to change notification settings - Fork 492
/
client.go
423 lines (372 loc) · 11.8 KB
/
client.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
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
/*
* Copyright (c) 2017, The Easegress Authors
* All rights reserved.
*
* 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:https://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 mqttproxy
import (
"errors"
"net"
"reflect"
"sync"
"sync/atomic"
"time"
"github.com/easegress-io/easegress/v2/pkg/context"
"github.com/easegress-io/easegress/v2/pkg/logger"
"github.com/easegress-io/easegress/v2/pkg/protocols/mqttprot"
"github.com/eclipse/paho.mqtt.golang/packets"
)
const (
// Connected is MQTT client status of Connected
Connected = 1
// Disconnected is MQTT client status of Disconnected
Disconnected = 2
// QoS0 for "At most once"
QoS0 byte = 0
// QoS1 for "At least once
QoS1 byte = 1
// QoS2 for "Exactly once"
QoS2 byte = 2
)
type processFn func(*Client, packets.ControlPacket)
type processFnWithErr func(*Client, packets.ControlPacket) error
var processPacketMap = map[string]processFnWithErr{
"*packets.ConnectPacket": errorWrapper("double connect"),
"*packets.ConnackPacket": errorWrapper("client should not send connack"),
"*packets.PubrecPacket": errorWrapper("qos2 not support now"),
"*packets.PubrelPacket": errorWrapper("qos2 not support now"),
"*packets.PubcompPacket": errorWrapper("qos2 not support now"),
"*packets.SubackPacket": errorWrapper("broker not subscribe"),
"*packets.UnsubackPacket": errorWrapper("broker not unsubscribe"),
"*packets.PingrespPacket": errorWrapper("broker not ping"),
"*packets.SubscribePacket": pipelineWrapper(processSubscribe, Subscribe),
"*packets.UnsubscribePacket": pipelineWrapper(processUnsubscribe, Unsubscribe),
"*packets.PingreqPacket": nilErrWrapper(processPingreq),
"*packets.PubackPacket": nilErrWrapper(processPuback),
"*packets.PublishPacket": func(c *Client, packet packets.ControlPacket) error {
publish := packet.(*packets.PublishPacket)
logger.SpanDebugf(nil, "client %s process publish %v", c.info.cid, publish.TopicName)
if !c.checkPublishLimit(publish) {
logger.SpanErrorf(nil, "client %v publish limiter drop packet %v", c.info.cid, publish.TopicName)
return nil
}
return pipelineWrapper(processPublish, Publish)(c, packet)
},
}
type (
// ClientInfo is basic information for client
ClientInfo struct {
cid string
username string
password string
keepalive uint16
will *packets.PublishPacket
}
// Client represents a MQTT client connection in Broker
Client struct {
sync.Mutex
broker *Broker
session *Session
publishLimit *Limiter
conn net.Conn
info ClientInfo
statusFlag int32
writeCh chan packets.ControlPacket
done chan struct{}
// kv map is used for pipeline to share messages among filters during whole connection
kvMap sync.Map
}
)
var _ mqttprot.Client = (*Client)(nil)
// ClientID return client id of Client
func (c *Client) ClientID() string {
return c.info.cid
}
// Load load value keep in Client kv map
func (c *Client) Load(key interface{}) (value interface{}, ok bool) {
return c.kvMap.Load(key)
}
// Store store key-value pair in Client kv map
func (c *Client) Store(key interface{}, value interface{}) {
c.kvMap.Store(key, value)
}
// Delete delete key-value pair in Client kv map
func (c *Client) Delete(key interface{}) {
c.kvMap.Delete(key)
}
// UserName return username of Client
func (c *Client) UserName() string {
return c.info.username
}
func newClient(connect *packets.ConnectPacket, broker *Broker, conn net.Conn, limitSpec *RateLimit) *Client {
var will *packets.PublishPacket
if connect.WillFlag {
will = packets.NewControlPacket(packets.Publish).(*packets.PublishPacket)
will.Qos = connect.WillQos
will.TopicName = connect.WillTopic
will.Retain = connect.WillRetain
will.Payload = connect.WillMessage
will.Dup = connect.Dup
}
info := ClientInfo{
cid: connect.ClientIdentifier,
username: connect.Username,
password: string(connect.Password),
keepalive: connect.Keepalive,
will: will,
}
client := &Client{
broker: broker,
conn: conn,
info: info,
statusFlag: Connected,
writeCh: make(chan packets.ControlPacket, 50),
done: make(chan struct{}),
publishLimit: newLimiter(limitSpec),
}
return client
}
func (c *Client) readLoop() {
defer func() {
if c.info.will != nil {
c.runPipeline(c.info.will, Publish)
}
c.closeAndDelSession()
c.broker.removeClient(c.info.cid)
}()
keepAlive := time.Duration(c.info.keepalive) * time.Second
timeOut := keepAlive + keepAlive/2
for {
select {
case <-c.done:
return
default:
}
if keepAlive > 0 {
if err := c.conn.SetDeadline(time.Now().Add(timeOut)); err != nil {
logger.SpanErrorf(nil, "set read timeout failed: %s", c.info.cid)
}
}
logger.SpanDebugf(nil, "client %s readLoop read packet", c.info.cid)
packet, err := packets.ReadPacket(c.conn)
if err != nil {
logger.SpanErrorf(nil, "client %s read packet failed: %v", c.info.cid, err)
return
}
if _, ok := packet.(*packets.DisconnectPacket); ok {
c.info.will = nil
return
}
err = c.processPacket(packet)
if err != nil {
logger.SpanErrorf(nil, "client %s process packet failed: %v", c.info.cid, err)
return
}
}
}
func (c *Client) processPacket(packet packets.ControlPacket) error {
packetType := reflect.TypeOf(packet).String()
fn, ok := processPacketMap[packetType]
if !ok {
return errors.New("unknown packet")
}
return fn(c, packet)
}
func (c *Client) checkPublishLimit(publish *packets.PublishPacket) bool {
size := publish.RemainingLength + 8
return c.publishLimit.acquirePermission(size)
}
// runPipeline will run MQTT pipeline by using packet.
// it will return an error if MQTT pipline set MQTTContext to Disconnect or Drop.
func (c *Client) runPipeline(packet packets.ControlPacket, packetType PacketType) error {
pipelineName, ok := c.broker.pipelines[packetType]
if !ok {
return nil
}
pipe, ok := c.broker.muxMapper.GetHandler(pipelineName)
if !ok {
logger.SpanErrorf(nil, "get pipeline %v failed", pipelineName)
return nil
}
ctx := newContext(packet, c)
pipe.Handle(ctx)
resp := ctx.GetResponse(context.DefaultNamespace).(*mqttprot.Response)
if resp.Disconnect() {
c.close()
return errors.New("pipeline set disconnect")
}
if resp.Drop() {
return errors.New("pipeline set drop")
}
return nil
}
func (c *Client) writePacket(packet packets.ControlPacket) {
select {
case c.writeCh <- packet:
default:
logger.Warnf("writePacket: %s to client: %s failed: chan is full", packet.String(), c.ClientID())
}
}
func (c *Client) writeLoop() {
for {
select {
case p := <-c.writeCh:
err := p.Write(c.conn)
if err != nil {
logger.SpanErrorf(nil, "write packet %v to client %s failed: %s", p.String(), c.info.cid, err)
c.closeAndDelSession()
}
case <-c.done:
return
}
}
}
func (c *Client) close() {
c.Lock()
if c.disconnected() {
c.Unlock()
return
}
logger.SpanDebugf(nil, "client %v connection close", c.info.cid)
atomic.StoreInt32(&c.statusFlag, Disconnected)
close(c.done)
c.conn.SetReadDeadline(time.Now().Add(time.Second))
c.Unlock()
// pipeline
pipelineName, ok := c.broker.pipelines[Disconnect]
if !ok {
return
}
pipe, ok := c.broker.muxMapper.GetHandler(pipelineName)
if !ok {
logger.SpanErrorf(nil, "get pipeline %v failed", pipelineName)
} else {
disconnect := packets.NewControlPacket(packets.Disconnect).(*packets.DisconnectPacket)
ctx := newContext(disconnect, c)
pipe.Handle(ctx)
}
}
func (c *Client) disconnected() bool {
return atomic.LoadInt32(&c.statusFlag) == Disconnected
}
func (c *Client) closeAndDelSession() {
// session can be delete by kickOUt or closeAndDelSession
// only when session was delete by closeAndDelSession we should clean
// global store, otherwise it means that the device reconnect to
// the another broker, the current broker just disconnect connection.
// and clean local session information.
deleted := c.broker.sessMgr.delLocal(c.info.cid)
if c.session.cleanSession() && deleted {
c.broker.sessMgr.delDB(c.info.cid)
}
topics, _, _ := c.session.allSubscribes()
c.broker.topicMgr.unsubscribe(topics, c.info.cid)
c.close()
}
func errorWrapper(errMsg string) processFnWithErr {
return func(c *Client, p packets.ControlPacket) error {
return errors.New(errMsg)
}
}
func nilErrWrapper(fn processFn) processFnWithErr {
return func(c *Client, p packets.ControlPacket) error {
fn(c, p)
return nil
}
}
func pipelineWrapper(fn processFn, packetType PacketType) processFnWithErr {
return func(c *Client, p packets.ControlPacket) error {
err := c.runPipeline(p, packetType)
if err != nil {
logger.SpanDebugf(nil, "client process pipeline failed, %v", c.info.cid, err)
return nil
}
fn(c, p)
return nil
}
}
func processPublish(c *Client, packet packets.ControlPacket) {
publish := packet.(*packets.PublishPacket)
go c.broker.processBrokerModePublish(c.info.cid, publish)
switch publish.Qos {
case QoS0:
// do nothing
case QoS1:
puback := packets.NewControlPacket(packets.Puback).(*packets.PubackPacket)
puback.MessageID = publish.MessageID
c.writePacket(puback)
case QoS2:
// not support yet
}
}
func processPuback(c *Client, packet packets.ControlPacket) {
puback := packet.(*packets.PubackPacket)
c.session.puback(puback)
}
func processSubscribe(c *Client, p packets.ControlPacket) {
packet := p.(*packets.SubscribePacket)
logger.SpanDebugf(nil, "client %s subscribe %v with qos %v", c.info.cid, packet.Topics, packet.Qoss)
err := c.broker.topicMgr.subscribe(packet.Topics, packet.Qoss, c.info.cid)
if err != nil {
logger.SpanErrorf(nil, "client %v subscribe %v failed: %v", c.info.cid, packet.Topics, err)
return
}
c.session.subscribe(packet.Topics, packet.Qoss)
suback := packets.NewControlPacket(packets.Suback).(*packets.SubackPacket)
suback.MessageID = packet.MessageID
suback.ReturnCodes = make([]byte, len(packet.Topics))
for i := range packet.Topics {
suback.ReturnCodes[i] = packet.Qos
}
c.writePacket(suback)
}
func processUnsubscribe(c *Client, p packets.ControlPacket) {
packet := p.(*packets.UnsubscribePacket)
logger.SpanDebugf(nil, "client %s processUnsubscribe %v", c.info.cid, packet.Topics)
err := c.broker.topicMgr.unsubscribe(packet.Topics, c.info.cid)
if err != nil {
logger.SpanErrorf(nil, "client %v unsubscribe %v failed: %v", c.info.cid, packet.Topics, err)
}
c.session.unsubscribe(packet.Topics)
unsuback := packets.NewControlPacket(packets.Unsuback).(*packets.UnsubackPacket)
unsuback.MessageID = packet.MessageID
c.writePacket(unsuback)
}
func processPingreq(c *Client, packet packets.ControlPacket) {
resp := packets.NewControlPacket(packets.Pingresp).(*packets.PingrespPacket)
c.writePacket(resp)
}
// kickOUt kick out the connection of the client,
// it will recycle the session, unsbuscribe topic of the client.
// **IMPORT:**
// - DO NOT SCHEDULE THE DISCONNECT PIPELINE.
// - DO NOT CLEAN SESSION INFO IN THE GLOBAL STORE.
// So in the kickOUt, we don't call Client::close
func (c *Client) kickOut() {
// clean local session information, unsubscribe topic
// in the current broker
c.sessionCleanLocal()
// close connection, but don't schedule Disconnect Pipeline
c.Lock()
defer c.Unlock()
// Change the client status to Disconnected
atomic.StoreInt32(&c.statusFlag, Disconnected)
close(c.done)
c.conn.Close()
}
func (c *Client) sessionCleanLocal() {
c.broker.sessMgr.delLocal(c.info.cid)
topics, _, _ := c.session.allSubscribes()
c.broker.topicMgr.unsubscribe(topics, c.info.cid)
}