/
client.go
1486 lines (1379 loc) · 40.7 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
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package server
import (
"bufio"
"bytes"
"context"
"crypto/md5"
"crypto/rand"
"encoding/binary"
"errors"
"fmt"
"io"
"math"
"net"
"os"
"reflect"
"sync"
"sync/atomic"
"time"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
"github.com/DrmagicE/gmqtt"
"github.com/DrmagicE/gmqtt/config"
"github.com/DrmagicE/gmqtt/persistence/queue"
"github.com/DrmagicE/gmqtt/persistence/subscription"
"github.com/DrmagicE/gmqtt/persistence/unack"
"github.com/DrmagicE/gmqtt/pkg/bitmap"
"github.com/DrmagicE/gmqtt/pkg/codes"
"github.com/DrmagicE/gmqtt/pkg/packets"
)
// Error
var (
ErrConnectTimeOut = errors.New("connect time out")
)
// Client status
const (
Connecting = iota
Connected
)
const (
readBufferSize = 1024
writeBufferSize = 1024
)
var (
bufioReaderPool sync.Pool
bufioWriterPool sync.Pool
)
func kvsToProperties(kvs []struct {
K []byte
V []byte
}) []packets.UserProperty {
u := make([]packets.UserProperty, len(kvs))
for k, v := range kvs {
u[k].K = v.K
u[k].V = v.V
}
return u
}
func newBufioReaderSize(r io.Reader, size int) *bufio.Reader {
if v := bufioReaderPool.Get(); v != nil {
br := v.(*bufio.Reader)
br.Reset(r)
return br
}
return bufio.NewReaderSize(r, size)
}
func putBufioReader(br *bufio.Reader) {
br.Reset(nil)
bufioReaderPool.Put(br)
}
func newBufioWriterSize(w io.Writer, size int) *bufio.Writer {
if v := bufioWriterPool.Get(); v != nil {
bw := v.(*bufio.Writer)
bw.Reset(w)
return bw
}
return bufio.NewWriterSize(w, size)
}
func putBufioWriter(bw *bufio.Writer) {
bw.Reset(nil)
bufioWriterPool.Put(bw)
}
func (client *client) ClientOptions() *ClientOptions {
return client.opts
}
// ClientOptions is the options which controls how the server interacts with the client.
// It will be set after the client has connected.
type ClientOptions struct {
// ClientID is the client id for the client.
ClientID string
// Username is the username for the client.
Username string
// KeepAlive is the keep alive time in seconds for the client.
// The server will close the client if no there is no packet has been received for 1.5 times the KeepAlive time.
KeepAlive uint16
// SessionExpiry is the session expiry interval in seconds.
// If the client version is v5, this value will be set into CONNACK Session Expiry Interval property.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901082
SessionExpiry uint32
// MaxInflight limits the number of QoS 1 and QoS 2 publications that the client is willing to process concurrently.
// For v3 client, it is default to config.MQTT.MaxInflight.
// For v5 client, it is the minimum of config.MQTT.MaxInflight and Receive Maximum property in CONNECT packet.
MaxInflight uint16
// ReceiveMax limits the number of QoS 1 and QoS 2 publications that the server is willing to process concurrently for the Client.
// If the client version is v5, this value will be set into Receive Maximum property in CONNACK packet.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901083
ReceiveMax uint16
// ClientMaxPacketSize is the maximum packet size that the client is willing to accept.
// The server will drop the packet if it exceeds ClientMaxPacketSize.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901050
ClientMaxPacketSize uint32
// ServerMaxPacketSize is the maximum packet size that the server is willing to accept from the client.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901086
ServerMaxPacketSize uint32
// ClientTopicAliasMax is highest value that the client will accept as a Topic Alias sent by the server.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901051
ClientTopicAliasMax uint16
// ServerTopicAliasMax is highest value that the server will accept as a Topic Alias sent by the client.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901088
ServerTopicAliasMax uint16
// RequestProblemInfo is the value to indicate whether the Reason String or User Properties should be sent in the case of failures.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901053
RequestProblemInfo bool
// UserProperties is the user properties provided by the client.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901090
UserProperties []*packets.UserProperty
// WildcardSubAvailable indicates whether the client is permitted to send retained messages.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901091
RetainAvailable bool
// WildcardSubAvailable indicates whether the client is permitted to subscribe Wildcard Subscriptions.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901091
WildcardSubAvailable bool
// SubIDAvailable indicates whether the client is permitted to set Subscription Identifiers.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901092
SubIDAvailable bool
// SharedSubAvailable indicates whether the client is permitted to subscribe Shared Subscriptions.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901093
SharedSubAvailable bool
// AuthMethod is the auth method send by the client.
// Only MQTT v5 client can set this value.
// See: https://docs.oasis-open.org/mqtt/mqtt/v5.0/os/mqtt-v5.0-os.html#_Toc3901055
AuthMethod []byte
}
// Client represent a mqtt client.
type Client interface {
// ClientOptions return a reference of ClientOptions. Do not edit.
// This is mainly used in hooks.
ClientOptions() *ClientOptions
// SessionInfo return a reference of session information of the client. Do not edit.
// Session info will be available after the client has passed OnSessionCreated or OnSessionResume.
SessionInfo() *gmqtt.Session
// Version return the protocol version of the used client.
Version() packets.Version
// ConnectedAt returns the connected time
ConnectedAt() time.Time
// Connection returns the raw net.Conn
Connection() net.Conn
// Close closes the client connection.
Close()
// Disconnect sends a disconnect packet to client, it is use to close v5 client.
Disconnect(disconnect *packets.Disconnect)
}
// client represents a MQTT client and implements the Client interface
type client struct {
connectedAt int64
server *server
wg sync.WaitGroup
rwc net.Conn //raw tcp connection
bufr *bufio.Reader
bufw *bufio.Writer
packetReader *packets.Reader
packetWriter *packets.Writer
in chan packets.Packet
out chan packets.Packet
close chan struct{}
closed chan struct{}
connected chan struct{}
status int32
// if 1, when client close, the session expiry interval will be ignored and the session will be removed.
forceRemoveSession int32
error chan error
errOnce sync.Once
err error
opts *ClientOptions //set up before OnConnect()
session *gmqtt.Session
cleanWillFlag bool // whether to remove will Msg
disconnect *packets.Disconnect
topicAliasManager TopicAliasManager
version packets.Version
aliasMapper [][]byte
// gard serverReceiveMaximumQuota
serverQuotaMu sync.Mutex
serverReceiveMaximumQuota uint16
config config.Config
queueStore queue.Store
unackStore unack.Store
pl *packetIDLimiter
queueNotifier *queueNotifier
// register requests the broker to add the client into the "active client list" before sending a positive CONNACK to the client.
register func(connect *packets.Connect, client *client) (sessionResume bool, err error)
// unregister requests the broker to remove the client from the "active client list" when the client is disconnected.
unregister func(client *client)
// deliverMessage
deliverMessage func(srcClientID string, msg *gmqtt.Message, options subscription.IterationOptions) (matched bool)
}
func (client *client) SessionInfo() *gmqtt.Session {
return client.session
}
func (client *client) Version() packets.Version {
return client.version
}
func (client *client) Disconnect(disconnect *packets.Disconnect) {
client.write(disconnect)
}
// ConnectedAt
func (client *client) ConnectedAt() time.Time {
return time.Unix(atomic.LoadInt64(&client.connectedAt), 0)
}
// Connection returns the raw net.Conn
func (client *client) Connection() net.Conn {
return client.rwc
}
func (client *client) setConnecting() {
atomic.StoreInt32(&client.status, Connecting)
}
func (client *client) setConnected(time time.Time) {
atomic.StoreInt64(&client.connectedAt, time.Unix())
atomic.StoreInt32(&client.status, Connected)
}
//Status returns client's status
func (client *client) Status() int32 {
return atomic.LoadInt32(&client.status)
}
// IsConnected returns whether the client is connected or not.
func (client *client) IsConnected() bool {
return client.Status() == Connected
}
func (client *client) setError(err error) {
client.errOnce.Do(func() {
if err != nil && err != io.EOF {
zaplog.Warn("connection lost",
zap.String("client_id", client.opts.ClientID),
zap.String("remote_addr", client.rwc.RemoteAddr().String()),
zap.Error(err))
client.err = err
if client.version == packets.Version5 {
if code, ok := err.(*codes.Error); ok {
if client.IsConnected() {
// send Disconnect
client.write(&packets.Disconnect{
Version: packets.Version5,
Code: code.Code,
Properties: &packets.Properties{
ReasonString: code.ReasonString,
User: kvsToProperties(code.UserProperties),
},
})
}
}
}
}
close(client.close)
})
}
func (client *client) writeLoop() {
var err error
srv := client.server
defer func() {
if re := recover(); re != nil {
err = errors.New(fmt.Sprint(re))
}
client.setError(err)
}()
for {
select {
case <-client.close:
return
case packet := <-client.out:
switch p := packet.(type) {
case *packets.Publish:
if client.version == packets.Version5 {
if client.opts.ClientTopicAliasMax > 0 {
// use alias if exist
if alias, ok := client.topicAliasManager.Check(p); ok {
p.TopicName = []byte{}
p.Properties.TopicAlias = &alias
} else {
// alias not exist
if alias != 0 {
p.Properties.TopicAlias = &alias
}
}
}
}
// OnDelivered hook
if srv.hooks.OnDelivered != nil {
srv.hooks.OnDelivered(context.Background(), client, gmqtt.MessageFromPublish(p))
}
srv.statsManager.messageSent(p.Qos, client.opts.ClientID)
case *packets.Puback, *packets.Pubcomp:
if client.version == packets.Version5 {
client.addServerQuota()
}
case *packets.Pubrec:
if client.version == packets.Version5 && p.Code >= codes.UnspecifiedError {
client.addServerQuota()
}
}
err = client.writePacket(packet)
if err != nil {
return
}
srv.statsManager.packetSent(packet, client.opts.ClientID)
if _, ok := packet.(*packets.Disconnect); ok {
_ = client.rwc.Close()
return
}
}
}
}
func (client *client) writePacket(packet packets.Packet) error {
if client.server.config.Log.DumpPacket {
if ce := zaplog.Check(zapcore.DebugLevel, "sending packet"); ce != nil {
ce.Write(
zap.String("packet", packet.String()),
zap.String("remote_addr", client.rwc.RemoteAddr().String()),
zap.String("client_id", client.opts.ClientID),
)
}
}
return client.packetWriter.WriteAndFlush(packet)
}
func (client *client) addServerQuota() {
client.serverQuotaMu.Lock()
if client.serverReceiveMaximumQuota < client.opts.ReceiveMax {
client.serverReceiveMaximumQuota++
}
client.serverQuotaMu.Unlock()
}
func (client *client) tryDecServerQuota() error {
client.serverQuotaMu.Lock()
defer client.serverQuotaMu.Unlock()
if client.serverReceiveMaximumQuota == 0 {
return codes.NewError(codes.RecvMaxExceeded)
}
client.serverReceiveMaximumQuota--
return nil
}
func (client *client) readLoop() {
var err error
srv := client.server
defer func() {
if re := recover(); re != nil {
err = errors.New(fmt.Sprint(re))
}
client.setError(err)
close(client.in)
}()
for {
var packet packets.Packet
if client.IsConnected() {
if keepAlive := client.opts.KeepAlive; keepAlive != 0 { //KeepAlive
_ = client.rwc.SetReadDeadline(time.Now().Add(time.Duration(keepAlive/2+keepAlive) * time.Second))
}
}
packet, err = client.packetReader.ReadPacket()
if err != nil {
if err != io.EOF && packet != nil {
zaplog.Error("read error", zap.String("packet_type", reflect.TypeOf(packet).String()))
}
return
}
if pub, ok := packet.(*packets.Publish); ok {
srv.statsManager.messageReceived(pub.Qos, client.opts.ClientID)
if client.version == packets.Version5 && pub.Qos > packets.Qos0 {
err = client.tryDecServerQuota()
if err != nil {
return
}
}
}
client.in <- packet
<-client.connected
srv.statsManager.packetReceived(packet, client.opts.ClientID)
if client.server.config.Log.DumpPacket {
if ce := zaplog.Check(zapcore.DebugLevel, "received packet"); ce != nil {
ce.Write(
zap.String("packet", packet.String()),
zap.String("remote_addr", client.rwc.RemoteAddr().String()),
zap.String("client_id", client.opts.ClientID),
)
}
}
}
}
// Close closes the client connection. The returned channel will be closed after unregisterClient process has been done
func (client *client) Close() {
if client.rwc != nil {
_ = client.rwc.Close()
}
}
var pid = os.Getpid()
var counter uint32
var machineID = readMachineID()
func readMachineID() []byte {
id := make([]byte, 3)
hostname, err1 := os.Hostname()
if err1 != nil {
_, err2 := io.ReadFull(rand.Reader, id)
if err2 != nil {
panic(fmt.Errorf("cannot get hostname: %v; %v", err1, err2))
}
return id
}
hw := md5.New()
hw.Write([]byte(hostname))
copy(id, hw.Sum(nil))
return id
}
func getRandomUUID() string {
var b [12]byte
// Timestamp, 4 bytes, big endian
binary.BigEndian.PutUint32(b[:], uint32(time.Now().Unix()))
// Machine, first 3 bytes of md5(hostname)
b[4] = machineID[0]
b[5] = machineID[1]
b[6] = machineID[2]
// Pid, 2 bytes, specs don't specify endianness, but we use big endian.
b[7] = byte(pid >> 8)
b[8] = byte(pid)
// Increment, 3 bytes, big endian
i := atomic.AddUint32(&counter, 1)
b[9] = byte(i >> 16)
b[10] = byte(i >> 8)
b[11] = byte(i)
return fmt.Sprintf(`%x`, string(b[:]))
}
func bool2Byte(bo bool) *byte {
var b byte
if bo {
b = 1
} else {
b = 0
}
return &b
}
func convertUint16(u *uint16, defaultValue uint16) uint16 {
if u == nil {
return defaultValue
}
return *u
}
func convertUint32(u *uint32, defaultValue uint32) uint32 {
if u == nil {
return defaultValue
}
return *u
}
func sendErrConnack(cli *client, err error) {
codeErr := converError(err)
// Override the error code if it is invalid for V3 client.
if packets.IsVersion3X(cli.version) && codeErr.Code > codes.V3NotAuthorized {
codeErr.Code = codes.NotAuthorized
}
cli.out <- &packets.Connack{
Version: cli.version,
Code: codeErr.Code,
Properties: getErrorProperties(cli, &codeErr.ErrorDetails),
}
}
func (client *client) connectWithTimeOut() (ok bool) {
// if any error occur, this function should set the error to the client and return false
var err error
defer func() {
if err != nil {
client.setError(err)
ok = false
} else {
ok = true
}
close(client.connected)
}()
timeout := time.NewTimer(5 * time.Second)
defer timeout.Stop()
var conn *packets.Connect
var authOpts *AuthOptions
// for enhanced auth
var onAuth OnAuth
for {
select {
case p := <-client.in:
if p == nil {
return
}
code := codes.Success
var authData []byte
switch p.(type) {
case *packets.Connect:
if conn != nil {
err = codes.ErrProtocol
break
}
conn = p.(*packets.Connect)
var resp *EnhancedAuthResponse
authOpts, resp, err = client.connectHandler(conn)
if err != nil {
break
}
if resp != nil && resp.Continue {
code = codes.ContinueAuthentication
authData = resp.AuthData
onAuth = resp.OnAuth
} else {
code = codes.Success
}
case *packets.Auth:
if conn == nil || packets.IsVersion3X(client.version) {
err = codes.ErrProtocol
break
}
if onAuth == nil {
err = codes.ErrProtocol
break
}
au := p.(*packets.Auth)
if au.Code != codes.ContinueAuthentication {
err = codes.ErrProtocol
break
}
var authResp *AuthResponse
authResp, err = client.authHandler(au, authOpts, onAuth)
if err != nil {
break
}
if authResp.Continue {
code = codes.ContinueAuthentication
authData = authResp.AuthData
} else {
code = codes.Success
}
default:
err = &codes.Error{
Code: codes.MalformedPacket,
}
break
}
// authentication fail
if err != nil {
sendErrConnack(client, err)
return
}
// continue authentication (ContinueAuthentication is introduced in V5)
if code == codes.ContinueAuthentication {
client.out <- &packets.Auth{
Code: code,
Properties: &packets.Properties{
AuthMethod: conn.Properties.AuthMethod,
AuthData: authData,
},
}
continue
}
// authentication success
client.opts.RetainAvailable = authOpts.RetainAvailable
client.opts.WildcardSubAvailable = authOpts.WildcardSubAvailable
client.opts.SubIDAvailable = authOpts.SubIDAvailable
client.opts.SharedSubAvailable = authOpts.SharedSubAvailable
client.opts.SessionExpiry = authOpts.SessionExpiry
client.opts.MaxInflight = authOpts.MaxInflight
client.opts.ReceiveMax = authOpts.ReceiveMax
client.opts.ClientMaxPacketSize = math.MaxUint32 // unlimited
client.opts.ServerMaxPacketSize = authOpts.MaxPacketSize
client.opts.ServerTopicAliasMax = authOpts.TopicAliasMax
client.opts.Username = string(conn.Username)
if len(conn.ClientID) == 0 {
if len(authOpts.AssignedClientID) != 0 {
client.opts.ClientID = string(authOpts.AssignedClientID)
} else {
client.opts.ClientID = getRandomUUID()
authOpts.AssignedClientID = []byte(client.opts.ClientID)
}
} else {
client.opts.ClientID = string(conn.ClientID)
}
var connackPpt *packets.Properties
if client.version == packets.Version5 {
client.opts.MaxInflight = convertUint16(conn.Properties.ReceiveMaximum, client.opts.MaxInflight)
client.opts.ClientMaxPacketSize = convertUint32(conn.Properties.MaximumPacketSize, client.opts.ClientMaxPacketSize)
client.opts.ClientTopicAliasMax = convertUint16(conn.Properties.TopicAliasMaximum, client.opts.ClientTopicAliasMax)
client.opts.AuthMethod = conn.Properties.AuthMethod
client.serverReceiveMaximumQuota = client.opts.ReceiveMax
client.aliasMapper = make([][]byte, client.opts.ReceiveMax+1)
client.opts.KeepAlive = authOpts.KeepAlive
var maxQoS byte
if authOpts.MaximumQoS >= 2 {
maxQoS = byte(1)
} else {
maxQoS = byte(0)
}
connackPpt = &packets.Properties{
SessionExpiryInterval: &authOpts.SessionExpiry,
ReceiveMaximum: &authOpts.ReceiveMax,
MaximumQoS: &maxQoS,
RetainAvailable: bool2Byte(authOpts.RetainAvailable),
TopicAliasMaximum: &authOpts.TopicAliasMax,
WildcardSubAvailable: bool2Byte(authOpts.WildcardSubAvailable),
SubIDAvailable: bool2Byte(authOpts.SubIDAvailable),
SharedSubAvailable: bool2Byte(authOpts.SharedSubAvailable),
MaximumPacketSize: &authOpts.MaxPacketSize,
ServerKeepAlive: &authOpts.KeepAlive,
AssignedClientID: authOpts.AssignedClientID,
ResponseInfo: authOpts.ResponseInfo,
}
} else {
client.opts.KeepAlive = conn.KeepAlive
}
if keepAlive := client.opts.KeepAlive; keepAlive != 0 { //KeepAlive
_ = client.rwc.SetReadDeadline(time.Now().Add(time.Duration(keepAlive/2+keepAlive) * time.Second))
}
client.newPacketIDLimiter(client.opts.MaxInflight)
var sessionResume bool
sessionResume, err = client.register(conn, client)
if err != nil {
sendErrConnack(client, err)
return
}
connack := conn.NewConnackPacket(codes.Success, sessionResume)
if conn.Version == packets.Version5 {
connack.Properties = connackPpt
}
client.write(connack)
return
case <-timeout.C:
err = ErrConnectTimeOut
return
}
}
}
func (client *client) basicAuth(conn *packets.Connect, authOpts *AuthOptions) (err error) {
srv := client.server
if srv.hooks.OnBasicAuth != nil {
err = srv.hooks.OnBasicAuth(context.Background(), client, &ConnectRequest{
Connect: conn,
Options: authOpts,
})
}
return err
}
func (client *client) enhancedAuth(conn *packets.Connect, authOpts *AuthOptions) (resp *EnhancedAuthResponse, err error) {
srv := client.server
if srv.hooks.OnEnhancedAuth == nil {
return nil, errors.New("OnEnhancedAuth hook is nil")
}
resp, err = srv.hooks.OnEnhancedAuth(context.Background(), client, &ConnectRequest{
Connect: conn,
Options: authOpts,
})
if err == nil && resp == nil {
err = errors.New("return nil response from OnEnhancedAuth hook")
}
return resp, err
}
func (client *client) connectHandler(conn *packets.Connect) (authOpts *AuthOptions, enhancedResp *EnhancedAuthResponse, err error) {
if !client.config.MQTT.AllowZeroLenClientID && len(conn.ClientID) == 0 {
err = &codes.Error{
Code: codes.ClientIdentifierNotValid,
}
return
}
client.version = conn.Version
// default auth options
authOpts = client.defaultAuthOptions(conn)
if packets.IsVersion3X(client.version) || (packets.IsVersion5(client.version) && conn.Properties.AuthMethod == nil) {
err = client.basicAuth(conn, authOpts)
}
if client.version == packets.Version5 && conn.Properties.AuthMethod != nil {
enhancedResp, err = client.enhancedAuth(conn, authOpts)
}
return
}
func (client *client) authHandler(auth *packets.Auth, authOpts *AuthOptions, onAuth OnAuth) (resp *AuthResponse, err error) {
authResp, err := onAuth(context.Background(), client, &AuthRequest{
Auth: auth,
Options: authOpts,
})
if err == nil && authResp == nil {
return nil, errors.New("return nil response from OnAuth hook")
}
return authResp, err
}
func getErrorProperties(client *client, errDetails *codes.ErrorDetails) *packets.Properties {
if client.version == packets.Version5 && client.opts.RequestProblemInfo && errDetails != nil {
return &packets.Properties{
ReasonString: errDetails.ReasonString,
User: kvsToProperties(errDetails.UserProperties),
}
}
return nil
}
func (client *client) defaultAuthOptions(connect *packets.Connect) *AuthOptions {
opts := &AuthOptions{
SessionExpiry: uint32(client.config.MQTT.SessionExpiry.Seconds()),
ReceiveMax: client.config.MQTT.ReceiveMax,
MaximumQoS: client.config.MQTT.MaximumQoS,
MaxPacketSize: client.config.MQTT.MaxPacketSize,
TopicAliasMax: client.config.MQTT.TopicAliasMax,
RetainAvailable: client.config.MQTT.RetainAvailable,
WildcardSubAvailable: client.config.MQTT.WildcardAvailable,
SubIDAvailable: client.config.MQTT.SubscriptionIDAvailable,
SharedSubAvailable: client.config.MQTT.SharedSubAvailable,
KeepAlive: client.config.MQTT.MaxKeepAlive,
MaxInflight: client.config.MQTT.MaxInflight,
}
if connect.KeepAlive < opts.KeepAlive {
opts.KeepAlive = connect.KeepAlive
}
if client.version == packets.Version5 {
if i := connect.Properties.SessionExpiryInterval; i == nil {
opts.SessionExpiry = 0
} else if *i < opts.SessionExpiry {
opts.SessionExpiry = *i
}
}
return opts
}
func (client *client) internalClose() {
if client.IsConnected() {
// OnClosed hooks
if client.server.hooks.OnClosed != nil {
client.server.hooks.OnClosed(context.Background(), client, client.err)
}
client.unregister(client)
client.server.statsManager.clientDisconnected(client.opts.ClientID)
}
putBufioReader(client.bufr)
putBufioWriter(client.bufw)
close(client.closed)
}
func (client *client) checkMaxPacketSize(msg *gmqtt.Message) (valid bool) {
totalBytes := msg.TotalBytes(packets.Version5)
if client.opts.ClientMaxPacketSize != 0 && totalBytes > client.opts.ClientMaxPacketSize {
return false
}
return true
}
func (client *client) write(packets packets.Packet) {
select {
case <-client.close:
return
case client.out <- packets:
}
}
func (client *client) subscribeHandler(sub *packets.Subscribe) *codes.Error {
srv := client.server
suback := &packets.Suback{
Version: sub.Version,
PacketID: sub.PacketID,
Properties: &packets.Properties{},
Payload: make([]codes.Code, len(sub.Topics)),
}
var subID uint32
now := time.Now()
if client.version == packets.Version5 {
if client.opts.SubIDAvailable && len(sub.Properties.SubscriptionIdentifier) != 0 {
subID = sub.Properties.SubscriptionIdentifier[0]
}
if !client.config.MQTT.SubscriptionIDAvailable && subID != 0 {
return &codes.Error{
Code: codes.SubIDNotSupported,
}
}
}
subReq := &SubscribeRequest{
Subscribe: sub,
Subscriptions: make(map[string]*struct {
Sub *gmqtt.Subscription
Error error
}),
ID: subID,
}
for _, v := range sub.Topics {
subReq.Subscriptions[v.Name] = &struct {
Sub *gmqtt.Subscription
Error error
}{Sub: subscription.FromTopic(v, subID), Error: nil}
}
if srv.hooks.OnSubscribe != nil {
err := srv.hooks.OnSubscribe(context.Background(), client, subReq)
if ce := converError(err); ce != nil {
suback.Properties = getErrorProperties(client, &ce.ErrorDetails)
for k := range suback.Payload {
if packets.IsVersion3X(client.version) {
suback.Payload[k] = packets.SubscribeFailure
} else {
suback.Payload[k] = ce.Code
}
}
client.write(suback)
return nil
}
}
for k, v := range sub.Topics {
sub := subReq.Subscriptions[v.Name].Sub
subErr := converError(subReq.Subscriptions[v.Name].Error)
var isShared bool
code := sub.QoS
if client.version == packets.Version5 {
if sub.ShareName != "" {
isShared = true
if !client.opts.SharedSubAvailable {
code = codes.SharedSubNotSupported
}
}
if !client.opts.SubIDAvailable && subID != 0 {
code = codes.SubIDNotSupported
}
if !client.opts.WildcardSubAvailable {
for _, c := range sub.TopicFilter {
if c == '+' || c == '#' {
code = codes.WildcardSubNotSupported
break
}
}
}
}
var subRs subscription.SubscribeResult
var err error
if subErr != nil {
code = subErr.Code
if packets.IsVersion3X(client.version) {
code = packets.SubscribeFailure
}
}
if code < packets.SubscribeFailure {
subRs, err = srv.subscriptionsDB.Subscribe(client.opts.ClientID, sub)
if err != nil {
zaplog.Error("failed to subscribe topic",
zap.String("topic", v.Name),
zap.Uint8("qos", v.Qos),
zap.String("client_id", client.opts.ClientID),
zap.String("remote_addr", client.rwc.RemoteAddr().String()),
zap.Error(err))
code = packets.SubscribeFailure
}
}
suback.Payload[k] = code
if code < packets.SubscribeFailure {
if srv.hooks.OnSubscribed != nil {
srv.hooks.OnSubscribed(context.Background(), client, sub)
}
zaplog.Info("subscribe succeeded",
zap.String("topic", sub.TopicFilter),
zap.Uint8("qos", sub.QoS),
zap.Uint8("retain_handling", sub.RetainHandling),
zap.Bool("retain_as_published", sub.RetainAsPublished),
zap.Bool("no_local", sub.NoLocal),
zap.Uint32("id", sub.ID),
zap.String("client_id", client.opts.ClientID),
zap.String("remote_addr", client.rwc.RemoteAddr().String()),
)
// The spec does not specify whether the retain message should follow the 'no-local' option rule.
// Gmqtt follows the mosquitto implementation which will send retain messages to no-local subscriptions.
// For details: https://github.com/eclipse/mosquitto/issues/1796
if !isShared && ((!subRs[0].AlreadyExisted && v.RetainHandling != 2) || v.RetainHandling == 0) {
msgs := srv.retainedDB.GetMatchedMessages(sub.TopicFilter)
for _, v := range msgs {
if v.QoS > subRs[0].Subscription.QoS {
v.QoS = subRs[0].Subscription.QoS
}
v.Dup = false
if !sub.RetainAsPublished {
v.Retained = false
}
var expiry time.Time
if v.MessageExpiry != 0 {
expiry = now.Add(time.Second * time.Duration(v.MessageExpiry))
}
err := client.queueStore.Add(&queue.Elem{
At: now,
Expiry: expiry,
MessageWithID: &queue.Publish{
Message: v,
},
})
if err != nil {
client.queueNotifier.notifyDropped(v, &queue.InternalError{Err: err})
if codesErr, ok := err.(*codes.Error); ok {
return codesErr
}
return &codes.Error{
Code: codes.UnspecifiedError,
}
}
}
}
} else {
zaplog.Info("subscribe failed",
zap.String("topic", sub.TopicFilter),
zap.Uint8("qos", suback.Payload[k]),
zap.String("client_id", client.opts.ClientID),
zap.String("remote_addr", client.rwc.RemoteAddr().String()),
)
}
}
client.write(suback)
return nil
}
func (client *client) publishHandler(pub *packets.Publish) *codes.Error {
srv := client.server
var dup bool
// check retain available
if !client.opts.RetainAvailable && pub.Retain {
return &codes.Error{
Code: codes.RetainNotSupported,
}
}
var msg *gmqtt.Message
msg = gmqtt.MessageFromPublish(pub)
if client.version == packets.Version5 && pub.Properties.TopicAlias != nil {
if *pub.Properties.TopicAlias >= client.opts.ServerTopicAliasMax {
return &codes.Error{