forked from hungnv038/broker
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathclient.go
671 lines (552 loc) · 14.3 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
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
// Copyright (c) 2014 The gomqtt 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://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 broker
import (
"errors"
"sync"
"time"
"github.com/gomqtt/packet"
"github.com/gomqtt/transport"
"gopkg.in/tomb.v2"
)
const (
clientConnecting byte = iota
clientConnected
clientDisconnected
)
// ErrExpectedConnect is returned when the first received packet is not a
// ConnectPacket.
var ErrExpectedConnect = errors.New("expected a ConnectPacket as the first packet")
// A Client represents a remote client that is connected to the broker.
type Client struct {
Context *Context
engine *Engine
conn transport.Conn
clientID string
cleanSession bool
session Session
out chan *packet.Message
state *state
tomb tomb.Tomb
mutex sync.Mutex
finish sync.Once
}
// newClient takes over a connection and returns a Client
func newClient(engine *Engine, conn transport.Conn) *Client {
c := &Client{
Context: NewContext(),
engine: engine,
conn: conn,
out: make(chan *packet.Message),
state: newState(clientConnecting),
}
// start processor
c.tomb.Go(c.processor)
return c
}
// Session returns the current Session used by the client.
func (c *Client) Session() Session {
return c.session
}
// CleanSession returns whether the client requested a clean session during connect.
func (c *Client) CleanSession() bool {
return c.cleanSession
}
// ClientID returns the supplied client id during connect.
func (c *Client) ClientID() string {
return c.clientID
}
// Publish will send a Message to the client and initiate QOS flows.
func (c *Client) Publish(msg *packet.Message) bool {
select {
case c.out <- msg:
return true
case <-c.tomb.Dying():
return false
}
}
// Close will immediately close the connection. When clean=true the client
// will be marked as cleanly disconnected, and the will messages will not
// get dispatched.
func (c *Client) Close(clean bool) {
if clean {
// mark client as cleanly disconnected
c.state.set(clientDisconnected)
}
// close underlying connection (triggers cleanup)
c.conn.Close()
}
/* processor goroutine */
// processes incoming packets
func (c *Client) processor() error {
first := true
c.log(NewConnection, c, nil, nil, nil)
// set initial read timeout
c.conn.SetReadTimeout(c.engine.ConnectTimeout)
for {
// get next packet from connection
pkt, err := c.conn.Receive()
if err != nil {
return c.die(TransportError, err, false)
}
c.log(PacketReceived, c, pkt, nil, nil)
if first {
// get connect
connect, ok := pkt.(*packet.ConnectPacket)
if !ok {
return c.die(ClientError, ErrExpectedConnect, true)
}
// process connect
err = c.processConnect(connect)
first = false
}
switch _pkt := pkt.(type) {
case *packet.SubscribePacket:
err = c.processSubscribe(_pkt)
case *packet.UnsubscribePacket:
err = c.processUnsubscribe(_pkt)
case *packet.PublishPacket:
err = c.processPublish(_pkt)
case *packet.PubackPacket:
err = c.processPubackAndPubcomp(_pkt.PacketID)
case *packet.PubcompPacket:
err = c.processPubackAndPubcomp(_pkt.PacketID)
case *packet.PubrecPacket:
err = c.processPubrec(_pkt.PacketID)
case *packet.PubrelPacket:
err = c.processPubrel(_pkt.PacketID)
case *packet.PingreqPacket:
err = c.processPingreq()
case *packet.DisconnectPacket:
err = c.processDisconnect()
}
// return eventual error
if err != nil {
return err // error has already been cleaned
}
}
}
// handle an incoming ConnackPacket
func (c *Client) processConnect(pkt *packet.ConnectPacket) error {
connack := packet.NewConnackPacket()
connack.ReturnCode = packet.ConnectionAccepted
connack.SessionPresent = false
// authenticate
ok, err := c.engine.Backend.Authenticate(c, pkt.Username, pkt.Password)
if err != nil {
c.die(BackendError, err, true)
}
// check authentication
if !ok {
// set return code
connack.ReturnCode = packet.ErrNotAuthorized
// send connack
err = c.send(connack, false)
if err != nil {
return c.die(TransportError, err, false)
}
// close client
return c.die(ClientError, nil, true)
}
// set state
c.state.set(clientConnected)
// add client to the brokers list
c.engine.add(c)
// set keep alive
if pkt.KeepAlive > 0 {
c.conn.SetReadTimeout(time.Duration(pkt.KeepAlive) * 1500 * time.Millisecond)
} else {
c.conn.SetReadTimeout(0)
}
// set values
c.cleanSession = pkt.CleanSession
c.clientID = pkt.ClientID
// retrieve session
s, resumed, err := c.engine.Backend.Setup(c, pkt.ClientID)
if err != nil {
return c.die(BackendError, err, true)
}
// reset the session if clean is requested
if pkt.CleanSession {
s.Reset()
}
// set session present
connack.SessionPresent = !pkt.CleanSession && resumed
// assign session
c.session = s
// save will if present
if pkt.Will != nil {
err = c.session.SaveWill(pkt.Will)
if err != nil {
return c.die(SessionError, err, true)
}
}
// send connack
err = c.send(connack, false)
if err != nil {
return c.die(TransportError, err, false)
}
// start sender
c.tomb.Go(c.sender)
// retrieve stored packets
packets, err := c.session.AllPackets(outgoing)
if err != nil {
return c.die(SessionError, err, true)
}
// resend stored packets
for _, pkt := range packets {
publish, ok := pkt.(*packet.PublishPacket)
if ok {
// set the dup flag on a publish packet
publish.Dup = true
}
err = c.send(pkt, true)
if err != nil {
return c.die(TransportError, err, false)
}
}
// attempt to restore client if not clean
if !pkt.CleanSession {
// get stored subscriptions
subs, err := s.AllSubscriptions()
if err != nil {
return c.die(SessionError, err, true)
}
// resubscribe subscriptions
for _, sub := range subs {
err = c.engine.Backend.Subscribe(c, sub.Topic)
if err != nil {
return c.die(BackendError, err, true)
}
}
// begin with queueing offline messages
err = c.engine.Backend.QueueOffline(c)
if err != nil {
return c.die(BackendError, err, true)
}
}
return nil
}
// handle an incoming PingreqPacket
func (c *Client) processPingreq() error {
err := c.send(packet.NewPingrespPacket(), true)
if err != nil {
return c.die(TransportError, err, false)
}
return nil
}
// handle an incoming SubscribePacket
func (c *Client) processSubscribe(pkt *packet.SubscribePacket) error {
suback := packet.NewSubackPacket()
suback.ReturnCodes = make([]byte, len(pkt.Subscriptions))
suback.PacketID = pkt.PacketID
// handle contained subscriptions
for i, subscription := range pkt.Subscriptions {
// save subscription in session
err := c.session.SaveSubscription(&subscription)
if err != nil {
return c.die(SessionError, err, true)
}
// subscribe client to queue
err = c.engine.Backend.Subscribe(c, subscription.Topic)
if err != nil {
return c.die(BackendError, err, true)
}
// save granted qos
suback.ReturnCodes[i] = subscription.QOS
}
// send suback
err := c.send(suback, true)
if err != nil {
return c.die(TransportError, err, false)
}
// queue retained messages
for _, sub := range pkt.Subscriptions {
err := c.engine.Backend.QueueRetained(c, sub.Topic)
if err != nil {
return c.die(BackendError, err, true)
}
}
return nil
}
// handle an incoming UnsubscribePacket
func (c *Client) processUnsubscribe(pkt *packet.UnsubscribePacket) error {
unsuback := packet.NewUnsubackPacket()
unsuback.PacketID = pkt.PacketID
for _, topic := range pkt.Topics {
// unsubscribe client from queue
err := c.engine.Backend.Unsubscribe(c, topic)
if err != nil {
return c.die(BackendError, err, true)
}
// remove subscription from session
err = c.session.DeleteSubscription(topic)
if err != nil {
return c.die(SessionError, err, true)
}
}
err := c.send(unsuback, true)
if err != nil {
return c.die(TransportError, err, false)
}
return nil
}
// handle an incoming PublishPacket
func (c *Client) processPublish(publish *packet.PublishPacket) error {
if publish.Message.QOS == 1 {
puback := packet.NewPubackPacket()
puback.PacketID = publish.PacketID
// acknowledge qos 1 publish
err := c.send(puback, true)
if err != nil {
return c.die(TransportError, err, false)
}
}
if publish.Message.QOS == 2 {
// store packet
err := c.session.SavePacket(incoming, publish)
if err != nil {
return c.die(SessionError, err, true)
}
pubrec := packet.NewPubrecPacket()
pubrec.PacketID = publish.PacketID
// signal qos 2 publish
err = c.send(pubrec, true)
if err != nil {
return c.die(TransportError, err, false)
}
}
if publish.Message.QOS <= 1 {
// publish packet to others
err := c.finishPublish(&publish.Message)
if err != nil {
return c.die(BackendError, err, true)
}
}
return nil
}
// handle an incoming PubackPacket or PubcompPacket
func (c *Client) processPubackAndPubcomp(packetID uint16) error {
// remove packet from store
c.session.DeletePacket(outgoing, packetID)
return nil
}
// handle an incoming PubrecPacket
func (c *Client) processPubrec(packetID uint16) error {
// allocate packet
pubrel := packet.NewPubrelPacket()
pubrel.PacketID = packetID
// overwrite stored PublishPacket with PubrelPacket
err := c.session.SavePacket(outgoing, pubrel)
if err != nil {
return c.die(SessionError, err, true)
}
// send packet
err = c.send(pubrel, true)
if err != nil {
return c.die(TransportError, err, false)
}
return nil
}
// handle an incoming PubrelPacket
func (c *Client) processPubrel(packetID uint16) error {
// get packet from store
pkt, err := c.session.LookupPacket(incoming, packetID)
if err != nil {
return c.die(SessionError, err, true)
}
// get packet from store
publish, ok := pkt.(*packet.PublishPacket)
if !ok {
return nil // ignore a wrongly sent PubrelPacket
}
pubcomp := packet.NewPubcompPacket()
pubcomp.PacketID = publish.PacketID
// acknowledge PublishPacket
err = c.send(pubcomp, true)
if err != nil {
return c.die(TransportError, err, false)
}
// remove packet from store
err = c.session.DeletePacket(incoming, packetID)
if err != nil {
return c.die(SessionError, err, true)
}
// publish packet to others
err = c.finishPublish(&publish.Message)
if err != nil {
return c.die(BackendError, err, true)
}
return nil
}
// handle an incoming DisconnectPacket
func (c *Client) processDisconnect() error {
// clear will
err := c.session.ClearWill()
if err != nil {
return c.die(SessionError, err, true)
}
// close client
c.Close(true)
return nil
}
/* sender goroutine */
// sends outgoing messages
func (c *Client) sender() error {
for {
select {
case <-c.tomb.Dying():
return tomb.ErrDying
case msg := <-c.out:
publish := packet.NewPublishPacket()
publish.Message = *msg
// get stored subscription
sub, err := c.session.LookupSubscription(publish.Message.Topic)
if err != nil {
return c.die(SessionError, err, true)
}
if sub != nil {
// respect maximum qos
if publish.Message.QOS > sub.QOS {
publish.Message.QOS = sub.QOS
}
}
// set packet id
if publish.Message.QOS > 0 {
publish.PacketID = c.session.PacketID()
}
// store packet if at least qos 1
if publish.Message.QOS > 0 {
err := c.session.SavePacket(outgoing, publish)
if err != nil {
return c.die(SessionError, err, true)
}
}
// send packet
err = c.send(publish, true)
if err != nil {
return c.die(TransportError, err, false)
}
c.log(MessageForwarded, c, nil, msg, nil)
}
}
}
/* helpers */
func (c *Client) finishPublish(msg *packet.Message) error {
// check retain flag
if msg.Retain {
if len(msg.Payload) > 0 {
err := c.engine.Backend.StoreRetained(c, msg)
if err != nil {
return err
}
} else {
err := c.engine.Backend.ClearRetained(c, msg.Topic)
if err != nil {
return err
}
}
}
// reset an existing retain flag
msg.Retain = false
// publish message to others
err := c.engine.Backend.Publish(c, msg)
if err != nil {
return err
}
c.log(MessagePublished, c, nil, msg, nil)
return nil
}
// will try to cleanup as many resources as possible
func (c *Client) cleanup(event LogEvent, err error, close bool) (LogEvent, error) {
// check session
if c.session != nil && c.state.get() == clientConnected {
// get will
will, _err := c.session.LookupWill()
if err == nil {
event = SessionError
err = _err
}
// publish will message
if will != nil {
_err = c.finishPublish(will)
if err == nil {
event = BackendError
err = _err
}
}
}
// remove client from the queue
if c.state.get() > clientConnecting {
_err := c.engine.Backend.Terminate(c)
if err == nil {
event = BackendError
err = _err
}
// reset the session if clean is requested
if c.cleanSession {
_err := c.session.Reset()
if err == nil {
event = SessionError
err = _err
}
}
}
// ensure that the connection gets closed
if close {
_err := c.conn.Close()
if err == nil {
event = TransportError
err = _err
}
}
c.log(LostConnection, c, nil, nil, nil)
// remove client from the brokers list if added
if c.state.get() > clientConnecting {
c.engine.remove(c)
}
return event, err
}
// used for closing and cleaning up from internal goroutines
func (c *Client) die(event LogEvent, err error, close bool) error {
c.finish.Do(func() {
event, err = c.cleanup(event, err, close)
// report error
if err != nil {
c.log(event, c, nil, nil, err)
}
})
return err
}
func (c *Client) send(pkt packet.Packet, buffered bool) error {
var err error
// send packet
if buffered {
err = c.conn.BufferedSend(pkt)
} else {
err = c.conn.Send(pkt)
}
// check error
if err != nil {
return err
}
c.log(PacketSent, c, pkt, nil, nil)
return nil
}
// log a message
func (c *Client) log(event LogEvent, client *Client, pkt packet.Packet, msg *packet.Message, err error) {
if c.engine.Logger != nil {
c.engine.Logger(event, client, pkt, msg, err)
}
}