-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathproto.go
1382 lines (1226 loc) · 37.4 KB
/
proto.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 gobroke
import (
"bytes"
"encoding/binary"
"errors"
"fmt"
"time"
"unicode/utf8"
"github.com/RoanBrand/gobroke/internal/model"
"github.com/RoanBrand/gobroke/internal/queue"
log "github.com/sirupsen/logrus"
)
// MQTT packet parser states
const (
// Fixed header
controlAndFlags = iota
length
variableHeaderLen
variableHeader
propertiesLen
properties
payload
)
const maxVarLenMul = 128 * 128 * 128
var (
protoVersionToName = map[uint8][]byte{
3: {'M', 'Q', 'I', 's', 'd', 'p'},
4: {'M', 'Q', 'T', 'T'},
5: {'M', 'Q', 'T', 'T'},
}
pingRespPacket = []byte{model.PINGRESP, 0}
isSharedSub = []byte("$share")
// Close the connection normally. Do not send the Will Message.
errGotNormalDiscon = errors.New("Normal")
// The Client wishes to disconnect but requires
// that the Server also publishes its Will Message.
errGotDisconWithWill = errors.New("WithWill")
// Publish received with expiry == 0. Do not forward.
errPubExpired = errors.New("EOA")
)
func (s *Server) parseStream(ses *session, rx []byte) error {
p, l := &ses.packet, len(rx)
for i := 0; i < l; {
switch p.rxState {
case controlAndFlags:
p.controlType, p.flags = rx[i]&0xF0, rx[i]&0x0F
switch p.controlType { // [MQTT-2.2.2-1, 2-2]
case model.PUBLISH:
break
case model.PUBACK, model.PUBREC, model.PUBCOMP, model.PINGREQ:
if p.flags != 0 {
return errors.New("malformed packet: fixed header flags must be 0 (reserved)")
}
case model.PUBREL:
f := p.flags
if ses.protoVersion == 3 {
f &= 0x07
}
if f != 0x02 {
return errors.New("malformed PUBREL")
}
case model.SUBSCRIBE:
f := p.flags
if ses.protoVersion == 3 {
f &= 0x07
}
if f != 0x02 { // [MQTT-3.8.1-1]
return errors.New("malformed SUBSCRIBE: bad fixed header reserved flags")
}
case model.UNSUBSCRIBE:
f := p.flags
if ses.protoVersion == 3 {
f &= 0x07
}
if f != 0x02 { // [MQTT-3.10.1-1]
return errors.New("malformed UNSUBSCRIBE: bad fixed header reserved flags")
}
case model.DISCONNECT:
if p.flags != 0 { // [MQTT-3.14.1-1]
ses.disconnectReasonCode = model.MalformedPacket
return errors.New("malformed DISCONNECT: fixed header flags must be 0 (reserved)")
}
case model.CONNECT:
if ses.connectSent { // [MQTT-3.1.0-2]
return errors.New("second CONNECT packet received")
}
if p.flags != 0 {
return errors.New("malformed packet: fixed header flags must be 0 (reserved)")
}
default:
return errors.New("invalid MQTT Control Packet type")
}
p.rxState = length
p.lenMul = 1
i++
case length:
p.remainingLength += int(rx[i]&127) * p.lenMul
if p.lenMul > maxVarLenMul {
return errors.New("malformed packet: bad remaining length")
}
if rx[i]&128 == 0 {
switch p.controlType {
case model.PUBLISH:
p.vhToRead = 2
p.vhBuf = p.vhBuf[:0]
p.rxState = variableHeaderLen
case model.PUBACK, model.PUBREC, model.PUBREL, model.PUBCOMP:
p.vhToRead = 2
if ses.protoVersion == 5 && p.remainingLength > 2 {
p.vhToRead++ // Reason Code
}
p.vhBuf = p.vhBuf[:0]
p.rxState = variableHeader
case model.SUBSCRIBE:
// [MQTT-3.8.3-3]
if p.remainingLength < 5 || (ses.protoVersion == 5 && p.remainingLength < 6) {
return errors.New("malformed SUBSCRIBE: no Topic Filter present")
}
p.vhToRead = 2
p.vhBuf = p.vhBuf[:0]
p.rxState = variableHeader
case model.UNSUBSCRIBE:
if p.remainingLength < 4 || (ses.protoVersion == 5 && p.remainingLength < 5) { // [MQTT-3.10.3-2]
return errors.New("malformed UNSUBSCRIBE: no Topic Filter present")
}
p.vhToRead = 2
p.vhBuf = p.vhBuf[:0]
p.rxState = variableHeader
case model.PINGREQ:
if err := ses.writePacket(pingRespPacket); err != nil {
return err
}
ses.updateTimeout()
p.rxState = controlAndFlags
case model.CONNECT:
p.vhToRead = 2
p.vhBuf = p.vhBuf[:0]
p.rxState = variableHeaderLen
case model.DISCONNECT:
if p.remainingLength == 0 {
log.WithFields(log.Fields{
"ClientId": ses.clientId,
"Reason": "Normal disconnection",
}).Debug("DISCONNECT received")
return errGotNormalDiscon
} else if ses.protoVersion < 5 {
return errors.New("malformed DISCONNECT: proto < v5")
}
p.vhToRead = 1 // Reason Code
p.vhBuf = p.vhBuf[:0]
p.rxState = variableHeader
}
} else {
p.lenMul *= 128
}
i++
case variableHeaderLen:
toRead := p.vhToRead
if avail := l - i; avail < toRead {
toRead = avail
}
p.vhBuf = append(p.vhBuf, rx[i:i+toRead]...)
p.vhToRead -= toRead
p.remainingLength -= toRead
if p.vhToRead == 0 {
p.vhToRead = int(binary.BigEndian.Uint16(p.vhBuf))
if p.controlType == model.PUBLISH {
rawQoS := p.flags & 0x06
if rawQoS > 0 { // Qos > 0
if rawQoS == 6 { // [MQTT-3.3.1-4]
ses.disconnectReasonCode = model.MalformedPacket
return errors.New("malformed PUBLISH: no QoS3 allowed")
}
p.vhToRead += 2
} else if p.flags&0x08 > 0 { // [MQTT-3.3.1-2]
return errors.New("malformed PUBLISH: DUP set for QoS0")
}
} else { // CONNECT
p.vhToRead += 4 // ProtoVersion + ConnectFlags + KeepAlive
}
p.rxState = variableHeader
}
i += toRead
case variableHeader:
toRead := p.vhToRead
if avail := l - i; avail < toRead {
toRead = avail
}
p.vhBuf = append(p.vhBuf, rx[i:i+toRead]...)
p.remainingLength -= toRead
p.vhToRead -= toRead
if p.vhToRead == 0 {
c := ses.client
switch p.controlType {
case model.PUBLISH:
tLen := binary.BigEndian.Uint16(p.vhBuf)
if tLen > 0 {
if err := checkUTF8(p.vhBuf[2:2+tLen], true); err != nil { // [MQTT-3.3.2-1]
return errors.New("malformed PUBLISH: bad Topic Name: " + err.Error())
}
}
if p.flags&0x06 > 0 { // Qos > 0
p.pID = binary.BigEndian.Uint16(p.vhBuf[2+tLen:])
}
case model.PUBACK:
if p.remainingLength == 0 {
c.qos1Done(binary.BigEndian.Uint16(p.vhBuf))
}
c.session.incSendQuota()
if len(p.vhBuf) > 2 && ses.protoVersion == 5 && p.vhBuf[2] != 0 {
log.WithFields(log.Fields{
"ClientId": ses.clientId,
"Reason Code": p.vhBuf[2],
}).Debug("PUBACK received")
}
case model.PUBREC:
if p.remainingLength == 0 {
if err := ses.handlePubrec(); err != nil {
return err
}
}
if len(p.vhBuf) > 2 && ses.protoVersion == 5 && p.vhBuf[2] != 0 {
if p.vhBuf[2] >= model.UnspecifiedError {
c.session.incSendQuota()
}
log.WithFields(log.Fields{
"ClientId": ses.clientId,
"Reason Code": p.vhBuf[2],
}).Debug("PUBREC received")
}
case model.PUBREL: // [MQTT-4.3.3-2]
if p.remainingLength == 0 {
if err := ses.handlePubrel(); err != nil {
return err
}
}
if len(p.vhBuf) > 2 && ses.protoVersion == 5 && p.vhBuf[2] != 0 {
log.WithFields(log.Fields{
"ClientId": ses.clientId,
"Reason Code": p.vhBuf[2],
}).Debug("PUBREL received")
}
case model.PUBCOMP:
if p.remainingLength == 0 {
c.qos2Part2Done(binary.BigEndian.Uint16(p.vhBuf))
}
c.session.incSendQuota()
if len(p.vhBuf) > 2 && ses.protoVersion == 5 && p.vhBuf[2] != 0 {
log.WithFields(log.Fields{
"ClientId": ses.clientId,
"Reason Code": p.vhBuf[2],
}).Debug("PUBCOMP received")
}
case model.CONNECT:
pnLen := binary.BigEndian.Uint16(p.vhBuf)
ses.protoVersion = p.vhBuf[2+pnLen]
if !bytes.Equal(protoVersionToName[ses.protoVersion], p.vhBuf[2:2+pnLen]) { // [MQTT-3.1.2-1]
if ses.protoVersion < 5 {
ses.sendConnackFail(1) // [MQTT-3.1.2-2]
} else {
ses.sendConnackFail(model.UnsupportedProtocolVersion)
}
return errors.New("unsupported client protocol. Must be MQTT 3 (v3.1), 4 (v3.1.1) or 5 (v5)")
}
switch ses.protoVersion {
case 3:
if p.remainingLength < 3 {
return errors.New("invalid CONNECT: ClientId must be between 1-23 characters long for MQTT 3 (v3.1)")
}
case 4:
if p.remainingLength < 2 { // [MQTT-3.1.3-3]
return errors.New("malformed CONNECT: absent ClientId in payload")
}
case 5:
if p.remainingLength < 3 {
return errors.New("malformed CONNECT: too short (missing Properties Length or ClientId")
}
}
ses.connectFlags = p.vhBuf[3+pnLen]
if ses.connectFlags&0x01 > 0 { // [MQTT-3.1.2-3]
return errors.New("malformed CONNECT: reserved header flag must be 0")
}
ses.keepAlive = time.Duration(binary.BigEndian.Uint16(p.vhBuf[4+pnLen:]))
case model.DISCONNECT:
if p.remainingLength == 0 {
return ses.handleDisconnect()
}
}
//p.payload = p.payload[:0]
if p.remainingLength == 0 {
if p.controlType == model.PUBLISH {
p.payload = p.payload[:0]
if err := s.handlePublish(ses); err != nil {
return err
}
}
ses.updateTimeout()
p.rxState = controlAndFlags
} else if ses.protoVersion > 4 {
p.lenMul = 1
p.rxState = propertiesLen
} else {
p.payload = p.payload[:0]
p.rxState = payload
}
}
i += toRead
case payload:
toRead := p.remainingLength
if avail := l - i; avail < toRead {
toRead = avail
}
p.payload = append(p.payload, rx[i:i+toRead]...)
p.remainingLength -= toRead
if p.remainingLength == 0 {
var err error
switch p.controlType {
case model.PUBLISH:
err = s.handlePublish(ses)
case model.SUBSCRIBE:
err = s.handleSubscribe(ses)
case model.UNSUBSCRIBE:
err = s.handleUnsubscribe(ses)
case model.CONNECT:
err = s.handleConnect(ses)
}
if err != nil {
return err
}
ses.updateTimeout()
p.rxState = controlAndFlags
}
i += toRead
case propertiesLen:
p.vhPropToRead += int(rx[i]&127) * p.lenMul
if p.lenMul > maxVarLenMul {
return errors.New("malformed packet: bad Properties Length")
}
p.remainingLength--
if rx[i]&128 == 0 {
if p.vhPropToRead == 0 {
switch p.controlType {
case model.PUBLISH:
p.payload = p.payload[:0]
if p.remainingLength == 0 {
if err := s.handlePublish(ses); err != nil {
return err
}
ses.updateTimeout()
p.rxState = controlAndFlags
} else {
p.rxState = payload
}
case model.PUBACK:
ses.client.qos1Done(binary.BigEndian.Uint16(p.vhBuf))
p.rxState = controlAndFlags
case model.PUBREC:
if err := ses.handlePubrec(); err != nil {
return err
}
p.rxState = controlAndFlags
case model.PUBREL:
if err := ses.handlePubrel(); err != nil {
return err
}
p.rxState = controlAndFlags
case model.PUBCOMP:
ses.client.qos2Part2Done(binary.BigEndian.Uint16(p.vhBuf))
p.rxState = controlAndFlags
case model.DISCONNECT:
return ses.handleDisconnect()
default: // subscribe, unsubscribe, connect
p.payload = p.payload[:0]
p.rxState = payload
}
} else {
p.rxState = properties
}
} else {
p.lenMul *= 128
}
i++
case properties:
toRead := p.vhPropToRead
if avail := l - i; avail < toRead {
toRead = avail
}
p.vhBuf = append(p.vhBuf, rx[i:i+toRead]...)
p.remainingLength -= toRead
p.vhPropToRead -= toRead
if p.vhPropToRead == 0 {
switch p.controlType {
case model.PUBLISH:
p.payload = p.payload[:0]
if p.remainingLength == 0 {
if err := s.handlePublish(ses); err != nil {
return err
}
ses.updateTimeout()
p.rxState = controlAndFlags
} else {
p.rxState = payload
}
case model.PUBACK:
// TODO: handle PUBACK props
ses.client.qos1Done(binary.BigEndian.Uint16(p.vhBuf))
p.rxState = controlAndFlags
case model.PUBREC:
// TODO: handle PUBREC props
if err := ses.handlePubrec(); err != nil {
return err
}
p.rxState = controlAndFlags
case model.PUBREL:
// TODO: handle PUBREL props
if err := ses.handlePubrel(); err != nil {
return err
}
p.rxState = controlAndFlags
case model.PUBCOMP:
// TODO: handle PUBCOMP props
ses.client.qos2Part2Done(binary.BigEndian.Uint16(p.vhBuf))
p.rxState = controlAndFlags
case model.SUBSCRIBE:
/*if err := ses.handleSubscribeProperties(); err != nil {
return err
}*/
p.payload = p.payload[:0]
p.rxState = payload
case model.UNSUBSCRIBE:
if err := s.handleUnSubscribeProperties(ses); err != nil {
return err
}
p.payload = p.payload[:0]
p.rxState = payload
case model.CONNECT:
if err := s.handleConnectProperties(ses); err != nil {
return err
}
p.payload = p.payload[:0]
p.rxState = payload
case model.DISCONNECT:
return s.handleDisconnectProperties(ses)
}
}
i += toRead
}
}
return nil
}
func (s *Server) handleConnect(ses *session) error {
p := ses.packet.payload
pLen := len(p)
// ClientId
clientIdLen := int(binary.BigEndian.Uint16(p))
offs := 2 + clientIdLen
if pLen < offs {
return errors.New("malformed CONNECT: payload too short for ClientId")
}
if clientIdLen > 0 {
if ses.protoVersion == 3 && clientIdLen > 23 {
ses.sendConnackFail(2)
return errors.New("invalid CONNECT: ClientId must be between 1-23 characters long for MQTT 3 (v3.1)")
}
if err := checkUTF8(p[2:offs], false); err != nil { // [MQTT-3.1.3-4]
return errors.New("malformed CONNECT: bad ClientId: " + err.Error())
}
ses.clientId = string(p[2:offs])
} else {
if ses.protoVersion < 5 && !ses.cleanStart() { // [MQTT-3.1.3-7]
ses.sendConnackFail(2) // [MQTT-3.1.3-8]
return errors.New("malformed CONNECT: must have ClientId with CleanSession set to 0")
}
ses.clientId = "auto-" + string(generateRandomID())
ses.assignedCId = true
}
// Will Properties, Will Topic & Will Message/Payload
if ses.connectFlags&0x04 > 0 {
// Properties
if ses.protoVersion == 5 {
wpLen, vbLen, err := variableLengthDecode(p[offs:])
if err != nil {
return errors.New("malformed CONNECT: bad Will Properties Length")
}
// TODO: store and use Will Properties
offs += vbLen + wpLen
}
// Topic
if pLen < 2+offs {
return errors.New("malformed CONNECT: no Will Topic in payload")
}
wTopicUTFStart := offs
wTopicLen := int(binary.BigEndian.Uint16(p[offs:]))
offs += 2
if pLen < offs+wTopicLen {
return errors.New("malformed CONNECT: payload too short for Will Topic")
}
wTopicUTFEnd := offs + wTopicLen
offs += wTopicLen
if pLen < 2+offs {
return errors.New("malformed CONNECT: no Will Message in payload")
}
wTopicUTF8 := p[wTopicUTFStart:wTopicUTFEnd]
if err := checkUTF8(wTopicUTF8[2:], true); err != nil { // [MQTT-3.1.3-10]
return errors.New("malformed CONNECT: bad Will Topic: " + err.Error())
}
wMsgLen := int(binary.BigEndian.Uint16(p[offs:]))
offs += 2
if pLen < offs+wMsgLen {
return errors.New("malformed CONNECT: payload too short for Will Message")
}
wQoS := (ses.connectFlags & 0x18) >> 3
if wQoS > 2 { // [MQTT-3.1.2-14]
return errors.New("malformed CONNECT: invalid Will QoS level")
}
willPubFlags := wQoS << 1
if ses.connectFlags&0x20 > 0 {
willPubFlags |= 0x01 // retain
}
ses.will = model.NewPubOld(willPubFlags, wTopicUTF8, p[offs:offs+wMsgLen])
ses.will.Publisher = ses.clientId
offs += wMsgLen
} else if ses.connectFlags&0x38 > 0 { // [MQTT-3.1.2-11, 2-13, 2-15]
return errors.New("malformed CONNECT: bad Will Flags")
}
// Username & Password
var userName, password []byte
if ses.connectFlags&0x80 > 0 {
if pLen < 2+offs {
if ses.protoVersion < 5 {
ses.sendConnackFail(4)
}
return errors.New("malformed CONNECT: no User Name in payload")
}
userLen := int(binary.BigEndian.Uint16(p[offs:]))
offs += 2
if pLen < offs+userLen {
if ses.protoVersion < 5 {
ses.sendConnackFail(4)
}
return errors.New("malformed CONNECT: payload too short for User Name")
}
userName = p[offs : offs+userLen]
if err := checkUTF8(userName, false); err != nil { // [MQTT-3.1.3-11]
if ses.protoVersion < 5 {
ses.sendConnackFail(4)
}
return errors.New("malformed CONNECT: bad User Name: " + err.Error())
}
offs += userLen
if ses.connectFlags&0x40 > 0 {
if pLen < 2+offs {
if ses.protoVersion < 5 {
ses.sendConnackFail(4)
}
return errors.New("malformed CONNECT: no Password in payload")
}
passLen := int(binary.BigEndian.Uint16(p[offs:]))
offs += 2
if pLen < offs+passLen {
if ses.protoVersion < 5 {
ses.sendConnackFail(4)
}
return errors.New("malformed CONNECT: payload too short for Password")
}
password = p[offs : offs+passLen]
offs += passLen
}
} else if ses.connectFlags&0x40 > 0 {
return errors.New("malformed CONNECT: Password present without User Name")
}
if s.Auther != nil {
if err := s.Auther.AuthUser(ses.clientId, userName, password); err != nil {
if ses.protoVersion < 5 {
ses.sendConnackFail(5)
} else {
ses.sendConnackFail(model.NotAuthorized)
}
return errors.New("failed authentication for client " + ses.clientId + ": " + err.Error())
}
}
if offs != pLen {
return errors.New("malformed CONNECT: unexpected extra payload fields (Will Properties, Topic, Message, or User Name or Password)")
}
if err := ses.conn.SetReadDeadline(time.Time{}); err != nil { // CONNECT packet timeout cancel
return err
}
ses.connectSent = true
if ses.protoVersion > 4 {
ses.taFromClient = make(map[uint16][]byte)
}
sessionIsPresent := s.addSession(ses)
ses.ended.Add(1)
go ses.startWriter()
// [MQTT-3.2.2-1, 2-2, 2-3]
ses.sendConnackSuccess(&s.Config, sessionIsPresent)
ses.run(s.TimeoutQoS12MQTT34)
return nil
}
func (s *Server) handleConnectProperties(ses *session) error {
vh := ses.packet.vhBuf
pnLen := binary.BigEndian.Uint16(vh)
props := vh[pnLen+6:]
var gotSesExp, gotRxMax, gotMaxPSize, gotTopAlias, gotRRI, gotRPI bool
for i := 0; i < len(props); {
remain := len(props) - i
switch props[i] {
case model.SessionExpiryInterval:
if gotSesExp {
return errors.New("malformed CONNECT: Session Expiry Interval included more than once")
}
if remain < 5 {
return errors.New("malformed CONNECT: bad Session Expiry Interval")
}
ses.expiryInterval = binary.BigEndian.Uint32(props[i+1:])
gotSesExp = true
i += 5
case model.ReceiveMaximum:
if gotRxMax {
return errors.New("malformed CONNECT: Receive Maximum included more than once")
}
if remain < 3 {
return errors.New("malformed CONNECT: bad Receive Maximum")
}
ses.receiveMax = binary.BigEndian.Uint16(props[i+1:])
if ses.receiveMax == 0 {
return errors.New("malformed CONNECT: Receive Maximum 0 not allowed")
}
ses.sendQuota = make(chan struct{}, ses.receiveMax)
for i := 0; i < int(ses.receiveMax); i++ {
ses.sendQuota <- struct{}{}
}
gotRxMax = true
i += 3
case model.MaximumPacketSize:
if gotMaxPSize {
return errors.New("malformed CONNECT: Maximum Packet Size included more than once")
}
if remain < 5 {
return errors.New("malformed CONNECT: bad Maximum Packet Size")
}
ses.maxPacketSize = binary.BigEndian.Uint32(props[i+1:])
if ses.maxPacketSize == 0 {
return errors.New("malformed CONNECT: Maximum Packet Size 0 not allowed")
}
gotMaxPSize = true
i += 5
case model.TopicAliasMaximum:
if gotTopAlias {
return errors.New("malformed CONNECT: Topic Alias Maximum included more than once")
}
if remain < 3 {
return errors.New("malformed CONNECT: bad Topic Alias Maximum")
}
ses.topicAliasMax = binary.BigEndian.Uint16(props[i+1:])
if ses.topicAliasMax > 0 {
ses.taToClient.aliases = make(map[string]uint16, ses.topicAliasMax)
ses.taToClient.left = int32(ses.topicAliasMax)
}
gotTopAlias = true
i += 3
case model.RequestResponseInformation:
if gotRRI {
return errors.New("malformed CONNECT: Request Response Information included more than once")
}
if remain < 2 {
return errors.New("malformed CONNECT: bad Request Response Information")
}
if props[i+1] != 0 && props[i+1] != 1 {
return errors.New("malformed CONNECT: bad Request Response Information")
}
ses.reqRespInfo = props[i+1] == 1
gotRRI = true
i += 2
case model.RequestProblemInformation:
if gotRPI {
return errors.New("malformed CONNECT: Request Problem Information included more than once")
}
if remain < 2 {
return errors.New("malformed CONNECT: bad Request Problem Information")
}
if props[i+1] != 0 && props[i+1] != 1 {
return errors.New("malformed CONNECT: bad Request Problem Information")
}
ses.reqProblemInfo = props[i+1] == 1
gotRPI = true
i += 2
case model.UserProperty:
if remain < 5 {
return errors.New("malformed CONNECT: bad User Property")
}
kLen := int(binary.BigEndian.Uint16(props[i+1:]))
if remain < 5+kLen {
return errors.New("malformed CONNECT: bad User Property")
}
vLen := int(binary.BigEndian.Uint16(props[i+3+kLen:]))
expect := 5 + kLen + vLen
if remain < expect {
return errors.New("malformed CONNECT: bad User Property")
}
i += expect
case model.AuthenticationMethod:
if remain < 3 {
return errors.New("malformed CONNECT: bad Authentication Method Property")
}
l := int(binary.BigEndian.Uint16(props[i+1:]))
if remain < 3+l {
return errors.New("malformed CONNECT: bad Authentication Method Property")
}
i += 3 + l
case model.AuthenticationData:
if remain < 3 {
return errors.New("malformed CONNECT: bad Authentication Data Property")
}
l := int(binary.BigEndian.Uint16(props[i+1:]))
if remain < 3+l {
return errors.New("malformed CONNECT: bad Authentication Data Property")
}
i += 3 + l
default:
return fmt.Errorf("malformed CONNECT: unknown property %d (0x%x)", props[i], props[i])
}
}
return nil
}
func (s *Server) handlePublish(ses *session) error {
p := &ses.packet
topicLen := int(binary.BigEndian.Uint16(p.vhBuf))
var topicUTF8 []byte
// Topic Alias
if topicLen == 0 {
if p.topicAlias == 0 { // [MQTT-4.7.3-1]
return errors.New("malformed PUBLISH: empty Topic Name")
} else {
var ok bool
topicUTF8, ok = ses.taFromClient[p.topicAlias]
if !ok {
ses.disconnectReasonCode = model.ProtocolError
return errors.New("malformed PUBLISH: unknown Topic Alias")
}
p.topicAlias = 0
}
} else {
topicUTF8 = p.vhBuf[:topicLen+2]
if p.topicAlias != 0 {
t := make([]byte, len(topicUTF8))
copy(t, topicUTF8)
ses.taFromClient[p.topicAlias] = t
p.topicAlias = 0
}
}
if s.Auther != nil {
if err := s.Auther.AuthPublish(ses.clientId, topicUTF8[2:]); err != nil {
return errors.New("failed publish authorization for client " + ses.clientId + ": " + err.Error())
}
}
requiredLen := 1 + len(topicUTF8) + len(p.payload)
pub := model.NewPub(requiredLen)
pub.B[0] = p.flags
pub.B = append(pub.B, topicUTF8...)
pub.B = append(pub.B, p.payload...)
propsIdx := 2 + topicLen
if p.flags&0x06 > 0 { // Qos > 0
propsIdx += 2
}
props := p.vhBuf[propsIdx:]
if len(props) > 0 {
if cap(pub.Props) < len(props) {
pub.Props = make([]byte, 0, len(props))
} else {
pub.Props = pub.Props[:0]
}
var err error
pub.Props, err = ses.handlePublishProperties(pub.Props, props)
if err != nil {
pub.FreeIfLastUser()
if err == errPubExpired {
if qos := pub.RxQoS(); qos == 1 {
return ses.sendPuback(p.pID)
} else if qos == 2 {
return ses.sendPubrec(p.pID)
}
return nil
}
return err
}
if p.expiry != 0 {
pub.Expiry = time.Now().Add(time.Duration(p.expiry) * time.Second).Unix()
p.expiry = 0
}
}
pub.Publisher = ses.clientId
/*if log.IsLevelEnabled(log.DebugLevel) {
lf := log.Fields{
"ClientId": ses.clientId,
"Topic Name": string(p.vhBuf[2 : topicLen+2]),
"QoS": pub.RxQoS(),
}
if pub.Duplicate() {
lf["duplicate"] = true
}
if pub.ToRetain() {
lf["retain"] = true
}
log.WithFields(lf).Debug("PUBLISH received")
}*/
switch pub.RxQoS() {
case 0:
s.pubs.Add(queue.GetItem(pub))
case 1:
s.pubs.Add(queue.GetItem(pub))
return ses.sendPuback(p.pID)
case 2: // [MQTT-4.3.3-2]
if _, ok := ses.client.q2RxLookup[p.pID]; !ok {
ses.client.q2RxLookup[p.pID] = struct{}{}
s.pubs.Add(queue.GetItem(pub))
}
return ses.sendPubrec(p.pID)
}
return nil
}
func (s *session) handlePublishProperties(tx, rx []byte) ([]byte, error) {
var gotMEI, gotTA, gotRT, gotCD, gotCT bool
for i := 0; i < len(rx); {
remain := len(rx) - i
switch rx[i] {
case model.PayloadFormatIndicator:
if remain < 2 {
s.disconnectReasonCode = model.MalformedPacket
return nil, errors.New("malformed PUBLISH: bad Payload Format Indicator")
}
if rx[i+1] == 1 {
if err := checkUTF8(s.packet.payload, false); err != nil {
s.disconnectReasonCode = model.PayloadFormatInvalid
return nil, errors.New("malformed PUBLISH: payload not valid UTF8")
}
}
tx = append(tx, rx[i:i+2]...)
i += 2
case model.MessageExpiryInterval: // just use the last value
if remain < 5 {
s.disconnectReasonCode = model.MalformedPacket
return nil, errors.New("malformed PUBLISH: bad Message Expiry Interval")
}
s.packet.expiry = binary.BigEndian.Uint32(rx[i+1:])
gotMEI = true
i += 5
case model.TopicAlias:
if gotTA {
s.disconnectReasonCode = model.ProtocolError
return nil, errors.New("malformed PUBLISH: Topic Alias included more than once")
}
if remain < 3 {
s.disconnectReasonCode = model.MalformedPacket
return nil, errors.New("malformed PUBLISH: bad Topic Alias")
}
s.packet.topicAlias = binary.BigEndian.Uint16(rx[i+1:])
if s.packet.topicAlias == 0 {
s.disconnectReasonCode = model.ProtocolError
return nil, errors.New("malformed PUBLISH: bad Topic Alias")
}
gotTA = true
i += 3
case model.ResponseTopic:
if gotRT {
s.disconnectReasonCode = model.ProtocolError
return nil, errors.New("malformed PUBLISH: Response Topic included more than once")
}
if remain < 3 {
s.disconnectReasonCode = model.MalformedPacket
return nil, errors.New("malformed PUBLISH: bad Response Topic")
}
l := int(binary.BigEndian.Uint16(rx[i+1:]))
if remain < 3+l {
s.disconnectReasonCode = model.MalformedPacket
return nil, errors.New("malformed PUBLISH: bad Response Topic")
}
tx = append(tx, rx[i:i+3+l]...)
gotRT = true
i += 3 + l
case model.CorrelationData:
if gotCD {
s.disconnectReasonCode = model.ProtocolError
return nil, errors.New("malformed PUBLISH: Response Topic included more than once")
}
if remain < 3 {
s.disconnectReasonCode = model.MalformedPacket
return nil, errors.New("malformed PUBLISH: bad Response Topic")
}
l := int(binary.BigEndian.Uint16(rx[i+1:]))
if remain < 3+l {
s.disconnectReasonCode = model.MalformedPacket
return nil, errors.New("malformed PUBLISH: bad Response Topic")