-
Notifications
You must be signed in to change notification settings - Fork 23
/
mqttpacket.cpp
2527 lines (2018 loc) · 90.3 KB
/
mqttpacket.cpp
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
/*
This file is part of FlashMQ (https://www.flashmq.org)
Copyright (C) 2021-2023 Wiebe Cazemier
FlashMQ is free software: you can redistribute it and/or modify
it under the terms of The Open Software License 3.0 (OSL-3.0).
See LICENSE for license details.
*/
#include "mqttpacket.h"
#include <cstring>
#include <iostream>
#include <list>
#include <cassert>
#include "utils.h"
#include "threadglobals.h"
#include "subscriptionstore.h"
#include "mainapp.h"
#include "exceptions.h"
#include "acksender.h"
// constructor for parsing incoming packets
MqttPacket::MqttPacket(CirBuf &buf, size_t packet_len, size_t fixed_header_length, std::shared_ptr<Client> &sender) :
bites(packet_len),
fixed_header_length(fixed_header_length),
sender(sender)
{
assert(packet_len > 0);
if (packet_len > sender->getMaxIncomingPacketSize())
{
throw ProtocolError("Incoming packet size exceeded.", ReasonCodes::PacketTooLarge);
}
buf.read(bites.data(), packet_len);
protocolVersion = sender->getProtocolVersion();
first_byte = bites[0];
unsigned char _packetType = (first_byte & 0xF0) >> 4;
packetType = (PacketType)_packetType;
pos += fixed_header_length;
externallyReceived = true;
}
MqttPacket::MqttPacket(const ConnAck &connAck) :
bites(connAck.getLengthWithoutFixedHeader())
{
packetType = PacketType::CONNACK;
first_byte = static_cast<char>(packetType) << 4;
writeByte(connAck.session_present & 0b00000001); // all connect-ack flags are 0, except session-present. [MQTT-3.2.2.1]
writeByte(connAck.return_code);
if (connAck.protocol_version >= ProtocolVersion::Mqtt5)
{
// TODO: don't include the reason string and user properties when it would increase the CONACK packet beyond the max packet size as determined by client.
// We don't send those at all momentarily, so there is no logic to prevent it.
writeProperties(connAck.propertyBuilder);
}
calculateRemainingLength();
}
MqttPacket::MqttPacket(const SubAck &subAck) :
bites(subAck.getLengthWithoutFixedHeader())
{
packetType = PacketType::SUBACK;
first_byte = static_cast<char>(packetType) << 4;
writeUint16(subAck.packet_id);
if (subAck.protocol_version >= ProtocolVersion::Mqtt5)
{
// TODO: don't include the reason string and user properties when it would increase the SUBACK packet beyond the max packet size as determined by client.
// We don't send those at all momentarily, so there is no logic to prevent it.
writeProperties(subAck.propertyBuilder);
}
std::vector<char> returnList;
returnList.reserve(subAck.responses.size());
for (ReasonCodes code : subAck.responses)
{
returnList.push_back(static_cast<char>(code));
}
writeBytes(&returnList[0], returnList.size());
calculateRemainingLength();
}
MqttPacket::MqttPacket(const UnsubAck &unsubAck) :
bites(unsubAck.getLengthWithoutFixedHeader())
{
packetType = PacketType::UNSUBACK;
first_byte = static_cast<char>(packetType) << 4;
writeUint16(unsubAck.packet_id);
if (unsubAck.protocol_version >= ProtocolVersion::Mqtt5)
{
writeProperties(unsubAck.propertyBuilder);
for(const ReasonCodes &rc : unsubAck.reasonCodes)
{
writeByte(static_cast<uint8_t>(rc));
}
}
calculateRemainingLength();
}
MqttPacket::MqttPacket(const ProtocolVersion protocolVersion, const Publish &_publish) :
MqttPacket(protocolVersion, _publish, _publish.qos, _publish.topicAlias, _publish.skipTopic)
{
}
/**
* @brief Construct a packet for a specific protocol version.
* @param protocolVersion is required here, and not on the Publish object, because publishes don't have a protocol until they are for a specific client.
* @param _publish
*
* Important to note here is that there are two concepts here: writing the byte array for sending to clients, and setting the data in publishData. The latter
* will only have stuff important for internal logic. In other words, it won't contain the payload.
*
* The extra parameters are for overriding certain properties of the publish, because the receiving client wants it differently. Use the other overload
* if you just want the publish object's data.
*/
MqttPacket::MqttPacket(const ProtocolVersion protocolVersion, const Publish &_publish, const uint8_t _qos, const uint16_t _topic_alias, const bool _skip_topic)
{
if (_publish.topic.length() > 0xFFFF)
{
throw ProtocolError("Topic path too long.", ReasonCodes::ProtocolError);
}
this->protocolVersion = protocolVersion;
this->publishData.client_id = _publish.client_id;
this->publishData.username = _publish.username;
this->publishData.skipTopic = _skip_topic;
this->publishData.qos = _qos;
this->publishData.retain = _publish.retain;
this->publishData.topicAlias = _topic_alias;
this->packetType = PacketType::PUBLISH;
if (!this->publishData.skipTopic)
this->publishData.topic = _publish.topic;
first_byte = static_cast<char>(packetType) << 4;
first_byte |= (this->publishData.qos << 1);
first_byte |= (static_cast<char>(publishData.retain) & 0b00000001);
std::optional<Mqtt5PropertyBuilder> property_builder;
if (protocolVersion >= ProtocolVersion::Mqtt5)
{
if (_publish.expireInfo)
this->publishData.setExpireAfter(_publish.expireInfo->getCurrentTimeToExpire().count());
this->publishData.correlationData = _publish.correlationData;
this->publishData.responseTopic = _publish.responseTopic;
this->publishData.contentType = _publish.contentType;
this->publishData.payloadUtf8 = _publish.payloadUtf8;
this->publishData.userProperties = _publish.userProperties;
property_builder = this->publishData.getPropertyBuilder();
}
size_t len = 0;
// Calculate length
{
len += 2; // topic string length field
if (!this->publishData.skipTopic)
len += this->publishData.topic.length();
len += _publish.payload.length();
if (this->publishData.qos)
len += 2;
if (protocolVersion >= ProtocolVersion::Mqtt5)
len += property_builder ? property_builder->getLength() : 1;
}
bites.resize(len);
writeString(publishData.topic);
if (publishData.qos)
{
// Reserve the space for the packet id, which will be assigned later.
packet_id_pos = pos;
char zero[2] = {0,0};
writeBytes(zero, 2);
}
if (protocolVersion >= ProtocolVersion::Mqtt5)
writeProperties(property_builder);
payloadStart = pos;
payloadLen = _publish.payload.length();
writeBytes(_publish.payload.c_str(), _publish.payload.length());
calculateRemainingLength();
assert(pos == bites.size());
}
MqttPacket::MqttPacket(const PubResponse &pubAck) :
bites(pubAck.getLengthIncludingFixedHeader())
{
this->protocolVersion = pubAck.protocol_version;
fixed_header_length = 2;
const uint8_t firstByteDefaultBits = pubAck.packet_type == PacketType::PUBREL ? 0b0010 : 0;
this->first_byte = (static_cast<uint8_t>(pubAck.packet_type) << 4) | firstByteDefaultBits;
writeByte(first_byte);
writeByte(pubAck.getRemainingLength());
this->packet_id_pos = this->pos;
writeUint16(pubAck.packet_id);
if (pubAck.needsReasonCode())
{
// TODO: don't include the reason string and user properties when it would increase the PUBACK/PUBREL/PUBCOMP packet beyond the max packet size as determined by client.
// We don't send those at all momentarily, so there is no logic to prevent it.
writeByte(static_cast<uint8_t>(pubAck.reason_code));
}
}
/**
* @brief Constructor to create a disconnect packet. In normal server mode, only MQTT5 is supposed to do that (MQTT3 has no concept of server-initiated
* disconnect packet). But, we also use it in the test client.
* @param disconnect
*/
MqttPacket::MqttPacket(const Disconnect &disconnect) :
bites(disconnect.getLengthWithoutFixedHeader())
{
this->protocolVersion = disconnect.protocolVersion;
packetType = PacketType::DISCONNECT;
first_byte = static_cast<char>(packetType) << 4;
if (this->protocolVersion >= ProtocolVersion::Mqtt5)
{
writeByte(static_cast<uint8_t>(disconnect.reasonCode));
writeProperties(disconnect.propertyBuilder);
}
calculateRemainingLength();
}
MqttPacket::MqttPacket(const Auth &auth) :
bites(auth.getLengthWithoutFixedHeader()),
protocolVersion(ProtocolVersion::Mqtt5),
packetType(PacketType::AUTH)
{
first_byte = static_cast<char>(packetType) << 4;
writeByte(static_cast<uint8_t>(auth.reasonCode));
writeProperties(auth.propertyBuilder);
calculateRemainingLength();
}
MqttPacket::MqttPacket(const Connect &connect) :
protocolVersion(connect.protocolVersion),
packetType(PacketType::CONNECT)
{
first_byte = static_cast<char>(packetType) << 4;
const std::string_view magicString = connect.getMagicString();
std::optional<Mqtt5PropertyBuilder> will_properties;
if (connect.will && this->protocolVersion >= ProtocolVersion::Mqtt5)
will_properties = connect.will->getPropertyBuilder();
size_t len = 0;
// Calculate length
{
len += connect.clientid.length() + 2;
len += magicString.length();
len += 6; // header stuff, lengths, keep-alive
if (this->protocolVersion >= ProtocolVersion::Mqtt5)
len += connect.propertyBuilder ? connect.propertyBuilder->getLength() : 1;
if (connect.will)
{
if (this->protocolVersion >= ProtocolVersion::Mqtt5)
len += will_properties ? will_properties->getLength() : 1;
len += connect.will->topic.length() + 2;
len += connect.will->payload.length() + 2;
}
if (connect.username.has_value())
len += connect.username->size() + 2;
if (connect.password.has_value())
len += connect.password->size() + 2;
}
bites.resize(len);
writeString(magicString);
uint8_t protocolVersionByte = static_cast<uint8_t>(protocolVersion);
if (connect.bridgeProtocolBit && protocolVersion <= ProtocolVersion::Mqtt311) // MQTT5 uses subscription options for it.
protocolVersionByte |= 0x80;
writeByte(protocolVersionByte);
uint8_t flags = connect.clean_start << 1;
flags |= static_cast<unsigned int>(connect.username.has_value()) << 7;
flags |= static_cast<unsigned int>(connect.password.has_value()) << 6;
if (connect.will)
{
flags |= 4;
flags |= (connect.will->qos << 3);
flags |= (connect.will->retain << 5);
}
writeByte(flags);
writeUint16(connect.keepalive);
if (connect.protocolVersion >= ProtocolVersion::Mqtt5)
{
writeProperties(connect.propertyBuilder);
}
writeString(connect.clientid);
if (connect.will)
{
if (connect.protocolVersion >= ProtocolVersion::Mqtt5)
{
writeProperties(will_properties);
}
writeString(connect.will->topic);
writeString(connect.will->payload);
}
if (connect.username.has_value())
writeString(connect.username.value());
if (connect.password.has_value())
writeString(connect.password.value());
calculateRemainingLength();
assert(pos == bites.size());
}
MqttPacket::MqttPacket(const Subscribe &subscribe) :
bites(subscribe.getLengthWithoutFixedHeader()),
packetType(PacketType::SUBSCRIBE)
{
first_byte = static_cast<char>(packetType) << 4;
first_byte |= 2; // required reserved bit
writeUint16(subscribe.packetId);
if (subscribe.protocolVersion >= ProtocolVersion::Mqtt5)
{
writeProperties(subscribe.propertyBuilder);
}
writeString(subscribe.topic);
if (subscribe.protocolVersion < ProtocolVersion::Mqtt5)
{
writeByte(subscribe.qos);
}
else
{
SubscriptionOptionsByte options(subscribe.qos, subscribe.noLocal, subscribe.retainAsPublished);
writeByte(options.b);
}
calculateRemainingLength();
}
MqttPacket::MqttPacket(const Unsubscribe &unsubscribe) :
bites(unsubscribe.getLengthWithoutFixedHeader()),
packetType(PacketType::UNSUBSCRIBE)
{
#ifndef TESTING
throw NotImplementedException("Code is only for testing.");
#endif
first_byte = static_cast<char>(packetType) << 4;
first_byte |= 2; // required reserved bit
writeUint16(unsubscribe.packetId);
if (unsubscribe.protocolVersion >= ProtocolVersion::Mqtt5)
{
writeProperties(unsubscribe.propertyBuilder);
}
writeString(unsubscribe.topic);
calculateRemainingLength();
}
void MqttPacket::bufferToMqttPackets(CirBuf &buf, std::vector<MqttPacket> &packetQueueIn, std::shared_ptr<Client> &sender)
{
while (buf.usedBytes() >= MQTT_HEADER_LENGH)
{
// Determine the packet length by decoding the variable length
int remaining_length_i = 1; // index of 'remaining length' field is one after start.
uint fixed_header_length = 1;
size_t multiplier = 1;
size_t packet_length = 0;
unsigned char encodedByte = 0;
do
{
fixed_header_length++;
if (fixed_header_length > 5)
throw ProtocolError("Packet signifies more than 5 bytes in variable length header. Invalid.", ReasonCodes::MalformedPacket);
// This happens when you only don't have all the bytes that specify the remaining length.
if (fixed_header_length > buf.usedBytes())
return;
encodedByte = buf.peakAhead(remaining_length_i++);
packet_length += (encodedByte & 127) * multiplier;
multiplier *= 128;
if (multiplier > 128*128*128*128)
throw ProtocolError("Malformed Remaining Length.", ReasonCodes::MalformedPacket);
}
while ((encodedByte & 128) != 0);
packet_length += fixed_header_length;
if (sender && !sender->getAuthenticated() && packet_length >= 1024*1024)
{
throw ProtocolError("An unauthenticated client sends a packet of 1 MB or bigger? Probably it's just random bytes.", ReasonCodes::ProtocolError);
}
const uint32_t size_limit = std::min<uint32_t>(sender->getMaxIncomingPacketSize(), ABSOLUTE_MAX_PACKET_SIZE);
if (packet_length > size_limit)
{
std::ostringstream oss;
oss << "Packet size " << packet_length << " exceeds the server limit of " << size_limit << " bytes";
throw ProtocolError(oss.str(), ReasonCodes::PacketTooLarge);
}
if (packet_length <= buf.usedBytes())
{
packetQueueIn.emplace_back(buf, packet_length, fixed_header_length, sender);
}
else
break;
}
}
void MqttPacket::handle()
{
// For clients that send packets before they even receive a connack.
if (protocolVersion == ProtocolVersion::None)
protocolVersion = sender->getProtocolVersion();
// It may be a stale client. This is especially important for when a session is picked up by another client. The old client
// may still have stale data in the buffer, causing action on the session otherwise.
if (sender->getDisconnectStage() > DisconnectStage::NotInitiated)
return;
if (packetType == PacketType::Reserved)
throw ProtocolError("Packet type 0 specified, which is reserved and invalid.", ReasonCodes::MalformedPacket);
if (!sender->getAuthenticated())
{
if (packetType == PacketType::AUTH && sender->getExtendedAuthenticationMethod().empty())
{
throw ProtocolError("You can't initiate first (extended) authentication with an AUTH packet.", ReasonCodes::ProtocolError);
}
if (!(packetType == PacketType::CONNECT || packetType == PacketType::AUTH || packetType == PacketType::DISCONNECT ||
packetType == PacketType::CONNACK))
{
exceptionOnNonMqtt(this->bites);
if (sender->preAuthPacketCounter++ > 200)
throw ProtocolError("Too many pre-auth packets dropped", ReasonCodes::ProtocolError);
logger->log(LOG_WARNING) << "Unapproved packet type (" << packetTypeToString(packetType)
<< ") from non-authenticated client " << sender->repr() << ". Dropping packet.";
return;
}
}
if (packetType == PacketType::PUBLISH)
handlePublish();
else if (packetType == PacketType::PUBACK)
handlePubAck();
else if (packetType == PacketType::PUBREC)
handlePubRec();
else if (packetType == PacketType::PUBREL)
handlePubRel();
else if (packetType == PacketType::PUBCOMP)
handlePubComp();
else if (packetType == PacketType::PINGREQ)
sender->writePingResp();
else if (packetType == PacketType::SUBSCRIBE)
handleSubscribe();
else if (packetType == PacketType::UNSUBSCRIBE)
handleUnsubscribe();
else if (packetType == PacketType::SUBACK)
handleSubAck();
else if (packetType == PacketType::CONNECT)
handleConnect();
else if (packetType == PacketType::DISCONNECT)
handleDisconnect();
else if (packetType == PacketType::CONNACK)
handleConnAck();
else if (packetType == PacketType::AUTH)
handleExtendedAuth();
}
ConnectData MqttPacket::parseConnectData()
{
if (this->packetType != PacketType::CONNECT)
throw std::runtime_error("Packet must be connect packet.");
setPosToDataStart();
ConnectData result;
uint16_t variable_header_length = readTwoBytesToUInt16();
if (!(variable_header_length == 4 || variable_header_length == 6))
{
throw ProtocolError("Invalid variable header length. Garbage?", ReasonCodes::MalformedPacket);
}
const Settings &settings = *ThreadGlobals::getSettings();
const char *c = readBytes(variable_header_length);
const std::string magic_marker(c, variable_header_length);
const uint8_t protocolVersionByte = readUint8();
result.protocol_level_byte = protocolVersionByte & 0x7F;
result.bridge = protocolVersionByte & 0x80; // Unofficial, defacto, way of specifying that. MQTT5 uses subscription options for it.
if (magic_marker == "MQTT")
{
if (result.protocol_level_byte == 0x04)
protocolVersion = ProtocolVersion::Mqtt311;
if (result.protocol_level_byte == 0x05)
protocolVersion = ProtocolVersion::Mqtt5;
}
else if (magic_marker == "MQIsdp" && result.protocol_level_byte == 0x03)
{
protocolVersion = ProtocolVersion::Mqtt31;
}
else
{
throw ProtocolError("Packet contains invalid MQTT marker.", ReasonCodes::MalformedPacket);
}
// Even though we're still parsing, setting this helps the exception handler to make decisions.
sender->setProtocolVersion(this->protocolVersion);
char flagByte = readByte();
bool reserved = !!(flagByte & 0b00000001);
if (reserved)
throw ProtocolError("Protocol demands reserved flag in CONNECT is 0", ReasonCodes::MalformedPacket);
bool user_name_flag = static_cast<bool>(flagByte & 0b10000000);
result.password_flag = !!(flagByte & 0b01000000);
result.will_retain = !!(flagByte & 0b00100000);
result.will_qos = (flagByte & 0b00011000) >> 3;
result.will_flag = !!(flagByte & 0b00000100);
result.clean_start = !!(flagByte & 0b00000010);
if (result.will_qos > 2)
throw ProtocolError("Invalid QoS for will.", ReasonCodes::MalformedPacket);
result.keep_alive = readTwoBytesToUInt16();
if (protocolVersion == ProtocolVersion::Mqtt5)
{
/*
* MQTT5: "If the Session Expiry Interval is absent the value 0 is used. If it is set to 0, or is absent,
* the Session ends when the Network Connection is closed."
*/
result.session_expire = 0;
result.keep_alive = std::max<uint16_t>(result.keep_alive, 5);
const size_t proplen = decodeVariableByteIntAtPos();
const size_t prop_end_at = pos + proplen;
std::array<uint8_t, 8> pcounts;
pcounts.fill(0);
while (pos < prop_end_at)
{
const Mqtt5Properties prop = static_cast<Mqtt5Properties>(readUint8());
switch (prop)
{
case Mqtt5Properties::SessionExpiryInterval:
if (pcounts[0]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.session_expire = std::min<uint32_t>(readFourBytesToUint32(), settings.getExpireSessionAfterSeconds());
break;
case Mqtt5Properties::ReceiveMaximum:
if (pcounts[1]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.client_receive_max = std::min<int16_t>(readTwoBytesToUInt16(), result.client_receive_max);
break;
case Mqtt5Properties::MaximumPacketSize:
if (pcounts[2]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.max_outgoing_packet_size = std::min<uint32_t>(readFourBytesToUint32(), result.max_outgoing_packet_size);
break;
case Mqtt5Properties::TopicAliasMaximum:
if (pcounts[3]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.max_outgoing_topic_aliases = std::min<uint16_t>(readTwoBytesToUInt16(), settings.maxOutgoingTopicAliasValue);
break;
case Mqtt5Properties::RequestResponseInformation:
{
if (pcounts[4]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
const uint8_t x = readUint8();
if (x > 1)
throw ProtocolError(propertyToString(prop) + " must be 0 or 1", ReasonCodes::ProtocolError);
result.request_response_information = static_cast<bool>(x);
break;
}
case Mqtt5Properties::RequestProblemInformation:
{
if (pcounts[5]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
const uint8_t x = readUint8();
if (x > 1)
throw ProtocolError(propertyToString(prop) + " must be 0 or 1", ReasonCodes::ProtocolError);
result.request_problem_information = static_cast<bool>(x);
break;
}
case Mqtt5Properties::UserProperty:
{
// We (ab)use the publishData for the user properties, because it's there.
std::string key = readBytesToString();
std::string val = readBytesToString();
this->publishData.addUserProperty(std::move(key), std::move(val));
break;
}
case Mqtt5Properties::AuthenticationMethod:
{
if (pcounts[6]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.authenticationMethod = readBytesToString();
break;
}
case Mqtt5Properties::AuthenticationData:
{
if (pcounts[7]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.authenticationData = readBytesToString(false);
break;
}
default:
throw ProtocolError("Invalid connect property.", ReasonCodes::ProtocolError);
}
}
}
if (result.authenticationMethod.empty() && !result.authenticationData.empty())
throw ProtocolError("Including authentication data when there is no authentication method is not allowed", ReasonCodes::ProtocolError);
if (result.client_receive_max == 0 || result.max_outgoing_packet_size == 0)
{
throw ProtocolError("Receive max or max outgoing packet size can't be 0.", ReasonCodes::ProtocolError);
}
result.client_id = readBytesToString();
if (result.will_flag)
{
result.willpublish.qos = result.will_qos;
result.willpublish.retain = result.will_retain;
if (result.will_retain)
{
if (settings.retainedMessagesMode == RetainedMessagesMode::DisconnectWithError)
throw ProtocolError("Option 'retained_messages_mode' set to 'disconnect_with_error' and received a will with retain.", ReasonCodes::RetainNotSupported);
else if (settings.retainedMessagesMode == RetainedMessagesMode::Downgrade)
{
result.willpublish.retain = false;
result.will_retain = false;
}
else if (settings.retainedMessagesMode == RetainedMessagesMode::Drop)
result.will_flag = false; // This will make us not pick up later, and we still parse the bytes from the packet.
}
result.willpublish.client_id = result.client_id;
if (protocolVersion == ProtocolVersion::Mqtt5)
{
const size_t proplen = decodeVariableByteIntAtPos();
const size_t prop_end_at = pos + proplen;
std::array<uint8_t, 8> pcounts;
pcounts.fill(0);
while (pos < prop_end_at)
{
const Mqtt5Properties prop = static_cast<Mqtt5Properties>(readUint8());
switch (prop)
{
case Mqtt5Properties::WillDelayInterval:
if (pcounts[0]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.willpublish.will_delay = readFourBytesToUint32();
break;
case Mqtt5Properties::PayloadFormatIndicator:
if (pcounts[1]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.willpublish.payloadUtf8 = true;
break;
case Mqtt5Properties::ContentType:
{
if (pcounts[2]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.willpublish.contentType = readBytesToString();
break;
}
case Mqtt5Properties::ResponseTopic:
{
if (pcounts[3]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.willpublish.responseTopic = readBytesToString(true, true);
if (result.willpublish.responseTopic->empty())
throw ProtocolError("Response topic in will cannot be empty", ReasonCodes::ProtocolError);
break;
}
case Mqtt5Properties::MessageExpiryInterval:
{
if (pcounts[4]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
const uint32_t expiresAfter = readFourBytesToUint32();
result.willpublish.setExpireAfter(expiresAfter);
break;
}
case Mqtt5Properties::CorrelationData:
{
if (pcounts[5]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.willpublish.correlationData = readBytesToString(false);
break;
}
case Mqtt5Properties::UserProperty:
{
std::string key = readBytesToString();
std::string val = readBytesToString();
result.willpublish.addUserProperty(std::move(key), std::move(val));
break;
}
default:
throw ProtocolError("Invalid will property in connect.", ReasonCodes::ProtocolError);
}
}
}
result.willpublish.topic = readBytesToString(true, true);
if (result.willpublish.topic.empty())
{
logger->log(LOG_WARNING) << "Empty will topic is not allowed. Dropping will for client " << sender->repr() << ".";
result.will_flag = false;
}
uint16_t will_payload_length = readTwoBytesToUInt16();
result.willpublish.payload = std::string(readBytes(will_payload_length), will_payload_length);
if (result.willpublish.payloadUtf8 && !isValidUtf8Generic(result.willpublish.payload))
{
throw ProtocolError("Will payload announced as UTF8, but it's not valid.", ReasonCodes::PayloadFormatInvalid);
}
}
else
{
if (result.will_retain)
throw ProtocolError("Will retain bit can't be set without will.", ReasonCodes::ProtocolError);
if (result.will_qos != 0)
throw ProtocolError("Will QoS must be 0 when there is no will.", ReasonCodes::ProtocolError);
}
if (user_name_flag)
{
// Usernames must be UTF-8, but we defer that check so we can give proper a CONNACK, and continue parsing.
result.username = readBytesToString(false);
if (result.username.value().empty())
{
if (settings.zeroByteUsernameIsAnonymous)
result.username.reset();
else
throw ProtocolError("Attempting anonymous login with zero byte username. See config option 'zero_byte_username_is_anonymous'.",
ReasonCodes::BadUserNameOrPassword);
}
}
if (result.username)
{
result.willpublish.username = result.username.value();
if (!settings.allowUnsafeUsernameChars && containsDangerousCharacters(result.username.value()))
throw ProtocolError(formatString("Username '%s' contains unsafe characters and 'allow_unsafe_username_chars' is false.", result.username.value().c_str()),
ReasonCodes::BadUserNameOrPassword);
}
if (result.password_flag)
{
if (this->protocolVersion <= ProtocolVersion::Mqtt311 && !user_name_flag)
{
throw ProtocolError("MQTT 3.1.1: If the User Name Flag is set to 0, the Password Flag MUST be set to 0.", ReasonCodes::MalformedPacket);
}
result.password = readBytesToString(false);
}
return result;
}
ConnAckData MqttPacket::parseConnAckData()
{
if (this->packetType != PacketType::CONNACK)
throw std::runtime_error("Packet must be connack packet.");
const Settings &settings = *ThreadGlobals::getSettings();
setPosToDataStart();
ConnAckData result;
const uint8_t flagByte = readByte();
result.sessionPresent = flagByte & 0x01;
result.reasonCode = static_cast<ReasonCodes>(readUint8());
if (protocolVersion == ProtocolVersion::Mqtt5)
{
const size_t proplen = decodeVariableByteIntAtPos();
const size_t prop_end_at = pos + proplen;
std::array<uint8_t, 16> pcounts;
pcounts.fill(0);
while (pos < prop_end_at)
{
const Mqtt5Properties prop = static_cast<Mqtt5Properties>(readUint8());
switch (prop)
{
case Mqtt5Properties::SessionExpiryInterval:
if (pcounts[0]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.session_expire = std::min<uint32_t>(readFourBytesToUint32(), result.session_expire);
break;
case Mqtt5Properties::ReceiveMaximum:
if (pcounts[1]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.client_receive_max = std::min<int16_t>(readTwoBytesToUInt16(), result.client_receive_max);
break;
case Mqtt5Properties::MaximumQoS:
if (pcounts[2]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.max_qos = std::min<uint8_t>(readUint8(), result.max_qos);
break;
case Mqtt5Properties::RetainAvailable:
if (pcounts[3]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.retained_available = static_cast<bool>(readByte());
break;
case Mqtt5Properties::MaximumPacketSize:
if (pcounts[4]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.max_outgoing_packet_size = std::min<uint32_t>(readFourBytesToUint32(), result.max_outgoing_packet_size);
break;
case Mqtt5Properties::AssignedClientIdentifier:
if (pcounts[5]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.assigned_client_id = readBytesToString();
break;
case Mqtt5Properties::TopicAliasMaximum:
if (pcounts[6]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.max_outgoing_topic_aliases = std::min<uint16_t>(readTwoBytesToUInt16(), settings.maxOutgoingTopicAliasValue);
break;
case Mqtt5Properties::ReasonString:
{
if (pcounts[7]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
const std::string reason = readBytesToString();
logger->logf(LOG_NOTICE, "ConnAck reason string: %s", reason.c_str());
break;
}
case Mqtt5Properties::UserProperty:
{
std::string key = readBytesToString();
std::string value = readBytesToString();
break;
}
case Mqtt5Properties::WildcardSubscriptionAvailable:
if (pcounts[8]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
readByte();
break;
case Mqtt5Properties::SubscriptionIdentifierAvailable:
if (pcounts[9]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
readByte();
break;
case Mqtt5Properties::SharedSubscriptionAvailable:
if (pcounts[10]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.shared_subscriptions_available = !!readByte();
break;
case Mqtt5Properties::ServerKeepAlive:
if (pcounts[11]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.keep_alive = readTwoBytesToUInt16();
break;
case Mqtt5Properties::ResponseInformation:
if (pcounts[12]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.response_information = readBytesToString();
break;
case Mqtt5Properties::ServerReference:
if (pcounts[13]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.server_reference = readBytesToString();
break;
case Mqtt5Properties::AuthenticationMethod:
if (pcounts[14]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.authMethod = readBytesToString();
break;
case Mqtt5Properties::AuthenticationData:
if (pcounts[15]++ > 0)
throw ProtocolError("Can't specify " + propertyToString(prop) + " more than once", ReasonCodes::ProtocolError);
result.authData = readBytesToString();
break;
default:
throw ProtocolError("Invalid connack property.", ReasonCodes::ProtocolError);
}
}
}
return result;
}
void MqttPacket::handleConnect()
{
if (sender->hasConnectPacketSeen())
throw ProtocolError("Client already sent a CONNECT.", ReasonCodes::ProtocolError);
std::shared_ptr<SubscriptionStore> subscriptionStore = MainApp::getMainApp()->getSubscriptionStore();
Authentication &authentication = *ThreadGlobals::getAuth();