-
Notifications
You must be signed in to change notification settings - Fork 15
/
MQTT.hpp
3172 lines (2862 loc) · 175 KB
/
MQTT.hpp
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
#ifndef hpp_CPP_MQTT_CPP_hpp
#define hpp_CPP_MQTT_CPP_hpp
// We need basic types
#include "../../Types.hpp"
// We need Platform code for allocations too
#include "../../Platform/Platform.hpp"
#if (MQTTDumpCommunication == 1)
// Because all projects are different, it's hard to give a generic method for dumping elements.
// So we end up with only limited dependencies:
// - a string class that concatenate with operator +=
// - the string class has MQTTStringGetData(MQTTString instance) method returning a pointer to the string array
// - the string class has MQTTStringGetLength(MQTTString instance) method returning the array size of the string
// - a hexadecimal dumping method
// - a printf-like formatting function
// Feel free to define the string class and method to use beforehand if you want to use your own.
// If none provided, we use's std::string class (or ClassPath's FastString depending on the environment)
#ifndef MQTTStringPrintf
static MQTTString MQTTStringPrintf(const char * format, ...)
{
va_list argp;
va_start(argp, format);
char buf[512];
// We use vasprintf extension to avoid dual parsing of the format string to find out the required length
int err = vsnprintf(buf, sizeof(buf), format, argp);
va_end(argp);
if (err <= 0) return MQTTString();
if (err >= (int)sizeof(buf)) err = (int)(sizeof(buf) - 1);
buf[err] = 0;
return MQTTString(buf, (size_t)err);
}
#endif
#ifndef MQTTHexDump
static void MQTTHexDump(MQTTString & out, const uint8* bytes, const uint32 length)
{
for (uint32 i = 0; i < length; i++)
out += MQTTStringPrintf("%02X", bytes[i]);
}
#endif
#endif
/** All network protocol specific structure or enumerations are declared here */
namespace Protocol
{
/** The MQTT specific enumeration or structures */
namespace MQTT
{
/** The types declared in this namespace are shared between the different versions */
namespace Common
{
/** This is the standard error code while reading an invalid value from hostile source */
enum LocalError
{
BadData = 0xFFFFFFFF, //!< Malformed data
NotEnoughData = 0xFFFFFFFE, //!< Not enough data
Shortcut = 0xFFFFFFFD, //!< Serialization shortcut used (not necessarly an error)
MinErrorCode = 0xFFFFFFFD,
};
/** Quickly check if the given code is an error */
static inline bool isError(uint32 value) { return value >= MinErrorCode; }
/** Check if serialization shortcut was used */
static inline bool isShortcut(uint32 value) { return value == Shortcut; }
/** The base interface all MQTT serializable structure must implement */
struct Serializable
{
/** We have a getSize() method that gives the number of bytes requires to serialize this object */
virtual uint32 getSize() const = 0;
/** Copy the value into the given buffer.
@param buffer A pointer to an allocated buffer that's at least getSize() bytes long
@return The number of bytes used in the buffer */
virtual uint32 copyInto(uint8 * buffer) const = 0;
/** Read the value from a buffer.
@param buffer A pointer to an allocated buffer
@param bufLength The length of the buffer in bytes
@return The number of bytes read from the buffer, or a LocalError upon error (use isError() to test for it) */
virtual uint32 readFrom(const uint8 * buffer, uint32 bufLength) = 0;
#if MQTTDumpCommunication == 1
/** Dump the serializable to the given string */
virtual void dump(MQTTString & out, const int indent = 0) = 0;
#endif
/** Check if this object is correct after deserialization */
virtual bool check() const { return true; }
/** Required destructor */
virtual ~Serializable() {}
};
/** Empty serializable used for generic code to avoid useless specific case in packet serialization */
struct EmptySerializable : public Serializable
{
uint32 getSize() const { return 0; }
uint32 copyInto(uint8 *) const { return 0; }
uint32 readFrom(const uint8 *, uint32) { return 0; }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*s%s\n", indent, "", "<none>"); }
#endif
bool check() const { return true; }
};
/** Invalid serialization used as an escape path */
struct Hidden InvalidData : public Serializable
{
uint32 getSize() const { return 0; }
uint32 copyInto(uint8 *) const { return 0; }
uint32 readFrom(const uint8 *, uint32) { return BadData; }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*s%s\n", indent, "", "<invalid>"); }
#endif
bool check() const { return false; }
};
/** A serializable with suicide characteristics
Typically, some structure are using list internally.
You can build list either by chaining items that are allocated with new or stack allocated.
In that case, you can't delete the next pointer inconditionnally, you need to got through a specialization
depending on the allocation type (heap or stack).
So instead call suicide and the stack based topic won't delete upon suiciding */
struct SerializableWithSuicide : public Serializable
{
/** Commit suicide. This is overloaded on stack allocated properties to avoid calling delete here */
virtual void suicide() { delete this; }
};
/** The visitor that'll be called with the relevant value */
struct MemMappedVisitor
{
/** Accept the given buffer */
virtual uint32 acceptBuffer(const uint8 * buffer, const uint32 bufLength) = 0;
// All visitor will have a getValue() method, but the returned type depends on the visitor and thus,
// can not be declared polymorphically
#if MQTTDumpCommunication == 1
virtual void dump(MQTTString & out, const int indent = 0)
{
out += MQTTStringPrintf("%*s", (int)indent, "");
// Voluntary incomplete
}
#endif
/** Default destructor */
virtual ~MemMappedVisitor() {}
};
/** Plumbing code for simple visitor pattern to avoid repetitive code in this file */
template <typename T>
struct SerializableVisitor : public MemMappedVisitor
{
T & getValue() { return *static_cast<T*>(this); }
operator T& () { return getValue(); }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0)
{
static_cast<T*>(this)->dump(out, indent);
}
#endif
uint32 acceptBuffer(const uint8 * buffer, const uint32 bufLength) { return static_cast<T*>(this)->readFrom(buffer, bufLength); }
};
/** Plumbing code for simple visitor pattern to avoid repetitive code in this file */
template <typename T>
struct PODVisitor : public MemMappedVisitor
{
T value;
T & getValue() { return value; }
operator T& () { return getValue(); }
PODVisitor(const T value = 0) : value(value) {}
uint32 acceptBuffer(const uint8 * buffer, const uint32 bufLength)
{
if (bufLength < sizeof(value)) return NotEnoughData;
memcpy(&value, buffer, sizeof(value));
return sizeof(value);
}
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0)
{
MemMappedVisitor::dump(out, indent);
out += getValue();
out += "\n";
}
#endif
};
/** Plumbing code for simple visitor pattern to avoid repetitive code in this file */
template <typename T>
struct LittleEndianPODVisitor : public MemMappedVisitor
{
T value;
T & getValue() { return value; }
operator T& () { return getValue(); }
LittleEndianPODVisitor(const T value = 0) : value(value) {}
uint32 acceptBuffer(const uint8 * buffer, const uint32 bufLength)
{
if (bufLength < sizeof(value)) return NotEnoughData;
memcpy(&value, buffer, sizeof(value));
value = BigEndian(value);
return sizeof(value);
}
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0)
{
MemMappedVisitor::dump(out, indent);
out += getValue();
out += "\n";
}
#endif
};
#pragma pack(push, 1)
/** A MQTT string is basically a string with a BigEndian size going first (section 1.5.4) */
struct String
{
/** The string length in bytes */
uint16 length;
char data[];
/** Call this method to read the structure when it's casted from the network buffer */
void fromNetwork() { length = ntohs(length); }
/** Call this method before sending the structure to the network */
void toNetwork() { length = htons(length); }
};
/** A string that's memory managed itself */
struct DynamicString Final : public Serializable
{
/** The string length in bytes */
uint16 length;
/** The data itself */
char * data;
/** For consistancy with the other structures, we have a getSize() method that gives the number of bytes requires to serialize this object */
uint32 getSize() const { return (uint32)length + 2; }
/** Copy the value into the given buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@return The number of bytes used in the buffer */
uint32 copyInto(uint8 * buffer) const { uint16 size = BigEndian(length); memcpy(buffer, &size, 2); memcpy(buffer+2, data, length); return (uint32)length + 2; }
/** Read the value from a buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@param bufLength The length of the buffer in bytes
@return The number of bytes read from the buffer, or BadData upon error */
uint32 readFrom(const uint8 * buffer, uint32 bufLength)
{
if (bufLength < 2) return NotEnoughData;
uint16 size = 0; memcpy(&size, buffer, 2); length = ntohs(size);
if (length+2 > bufLength) return NotEnoughData;
data = (char*)Platform::safeRealloc(data, length);
memcpy(data, buffer+2, length);
return (uint32)length+2;
}
/** Check if the value is correct */
bool check() const { return data ? length : length == 0; }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*sStr (%d bytes): %.*s\n", (int)indent, "", (int)length, length, data); }
#endif
/** Default constructor */
DynamicString() : length(0), data(0) {}
/** Construct from a text */
DynamicString(const char * text) : length(text ? strlen(text) : 0), data((char*)Platform::malloc(length)) { memcpy(data, text, length); }
/** Construct from a FastString */
DynamicString(const MQTTString & text) : length(MQTTStringGetLength(text)), data((char*)Platform::malloc(length)) { memcpy(data, MQTTStringGetData(text), length); }
/** Construct from a FastString */
DynamicString(const MQTTROString & text) : length(MQTTStringGetLength(text)), data((char*)Platform::malloc(length)) { memcpy(data, MQTTStringGetData(text), length); }
/** Copy constructor */
DynamicString(const DynamicString & other) : length(other.length), data((char*)Platform::malloc(length)) { memcpy(data, other.data, length); }
#if HasCPlusPlus11 == 1
/** Move constructor */
DynamicString(DynamicString && other) : length(std::move(other.length)), data(std::move(other.data)) { }
#endif
/** Destructor */
~DynamicString() { Platform::free(data); length = 0; }
/** Convert to a ReadOnlyString */
operator MQTTROString() const { return MQTTROString(data, length); }
/** Comparison operator */
bool operator != (const MQTTROString & other) const { return length != MQTTStringGetLength(other) || memcmp(data, MQTTStringGetData(other), length); }
/** Comparison operator */
bool operator == (const MQTTROString & other) const { return length == MQTTStringGetLength(other) && memcmp(data, MQTTStringGetData(other), length) == 0; }
/** Copy operator */
DynamicString & operator = (const DynamicString & other) { if (this != &other) { this->~DynamicString(); length = other.length; data = (char*)Platform::malloc(length); memcpy(data, other.data, length); } return *this; }
/** Copy operator */
void from(const char * str, const size_t len = 0) { this->~DynamicString(); length = len ? len : (strlen(str)+1); data = (char*)Platform::malloc(length); memcpy(data, str, length); data[length - 1] = 0; }
};
/** A dynamic string pair */
struct DynamicStringPair Final : public Serializable
{
/** The key used for the pair */
DynamicString key;
/** The value used for the pair */
DynamicString value;
/** For consistancy with the other structures, we have a getSize() method that gives the number of bytes requires to serialize this object */
uint32 getSize() const { return key.getSize() + value.getSize(); }
/** Copy the value into the given buffer.
@param buffer A pointer to an allocated buffer that's at least getSize() bytes long
@return The number of bytes used in the buffer */
uint32 copyInto(uint8 * buffer) const { uint32 o = key.copyInto(buffer); o += value.copyInto(buffer+o); return o; }
/** Read the value from a buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@param bufLength The length of the buffer in bytes
@return The number of bytes read from the buffer, or BadData upon error */
uint32 readFrom(const uint8 * buffer, uint32 bufLength)
{
uint32 o = key.readFrom(buffer, bufLength);
if (isError(o)) return o;
uint32 s = value.readFrom(buffer + o, bufLength - o);
if (isError(s)) return s;
return s+o;
}
/** Check if the value is correct */
bool check() const { return key.check() && value.check(); }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*sKV:\n", (int)indent, ""); key.dump(out, indent + 2); value.dump(out, indent + 2); }
#endif
/** Default constructor */
DynamicStringPair(const DynamicString & k = "", const DynamicString & v = "") : key(k), value(v) {}
/** Copy constructor */
DynamicStringPair(const DynamicStringPair & other) : key(other.key), value(other.value) {}
#if HasCPlusPlus11 == 1
/** Move constructor */
DynamicStringPair(DynamicStringPair && other) : key(std::move(other.key)), value(std::move(other.value)) { }
#endif
};
/** A MQTT binary data with a BigEndian size going first (section 1.5.6) */
struct BinaryData
{
/** The data length in bytes */
uint16 length;
uint8 data[];
/** Call this method to read the structure when it's casted from the network buffer */
void fromNetwork() { length = ntohs(length); }
/** Call this method before sending the structure to the network */
void toNetwork() { length = htons(length); }
};
/** A dynamic binary data, with self managed memory */
struct DynamicBinaryData Final : public Serializable
{
/** The string length in bytes */
uint16 length;
/** The data itself */
uint8 * data;
/** For consistancy with the other structures, we have a getSize() method that gives the number of bytes requires to serialize this object */
uint32 getSize() const { return (uint32)length + 2; }
/** Copy the value into the given buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@return The number of bytes used in the buffer */
uint32 copyInto(uint8 * buffer) const { uint16 size = htons(length); memcpy(buffer, &size, 2); memcpy(buffer+2, data, length); return (uint32)length + 2; }
/** Read the value from a buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@param bufLength The length of the buffer in bytes
@return The number of bytes read from the buffer, or BadData upon error */
uint32 readFrom(const uint8 * buffer, uint32 bufLength)
{
if (bufLength < 2) return NotEnoughData;
uint16 size = 0; memcpy(&size, buffer, 2); length = ntohs(size);
if (length+2 > bufLength) return NotEnoughData;
data = (uint8*)Platform::safeRealloc(data, length);
memcpy(data, buffer+2, length);
return (uint32)length + 2;
}
/** Check if the value is correct */
bool check() const { return data ? length : length == 0; }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*sBin (%d bytes):", (int)indent, "", (int)length); MQTTHexDump(out, data, length); out += "\n"; }
#endif
/** Construct from a memory block */
DynamicBinaryData(const uint16 length = 0, const uint8 * block = 0) : length(length), data(length ? (uint8*)Platform::malloc(length) : (uint8*)0) { memcpy(data, block, length); }
/** Copy constructor */
DynamicBinaryData(const DynamicBinaryData & other) : length(other.length), data(length ? (uint8*)Platform::malloc(length) : (uint8*)0) { memcpy(data, other.data, length); }
#if HasCPlusPlus11 == 1
/** Move constructor */
DynamicBinaryData(DynamicBinaryData && other) : length(std::move(other.length)), data(std::move(other.data)) { }
#endif
/** Destructor */
~DynamicBinaryData() { Platform::free(data); length = 0; }
};
/** A read only dynamic string view.
This is used to avoid copying a string buffer when only a pointer is required.
This string can be mutated to many buffer but no modification is done to the underlying array of chars */
struct DynamicStringView Final : public Serializable, public SerializableVisitor<DynamicStringView>
{
/** The string length in bytes */
uint16 length;
/** The data itself */
const char * data;
/** For consistancy with the other structures, we have a getSize() method that gives the number of bytes requires to serialize this object */
uint32 getSize() const { return (uint32)length + 2; }
/** Copy the value into the given buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@return The number of bytes used in the buffer */
uint32 copyInto(uint8 * buffer) const { uint16 size = htons(length); memcpy(buffer, &size, 2); memcpy(buffer+2, data, length); return (uint32)length + 2; }
/** Read the value from a buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@param bufLength The length of the buffer in bytes
@return The number of bytes read from the buffer, or BadData upon error
@warning This method capture a pointer on the given buffer so it must outlive this object when being called.
Don't use this method if buffer is a temporary data. */
uint32 readFrom(const uint8 * buffer, uint32 bufLength)
{
if (bufLength < 2) return NotEnoughData;
uint16 size = 0; memcpy(&size, buffer, 2); length = ntohs(size);
if (length+2 > bufLength) return NotEnoughData;
data = (const char*)&buffer[2];
return (uint32)length + 2;
}
/** Check if the value is correct */
bool check() const { return data ? length : length == 0; }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*sStr (%d bytes): %.*s\n", (int)indent, "", (int)length, length, data); }
#endif
/** Capture from a dynamic string here.
Beware of this method as the source must outlive this instance */
DynamicStringView & operator = (const DynamicString & source) { length = source.length; data = source.data; return *this; }
/** Capture from a dynamic string here.
Beware of this method as the source must outlive this instance */
DynamicStringView & operator = (const char * string) { length = strlen(string); data = string; return *this; }
/** Basic operator */
DynamicStringView & operator = (const DynamicStringView & source) { length = source.length; data = source.data; return *this; }
/** Comparison operator */
bool operator != (const DynamicStringView & other) const { return length != other.length || memcmp(data, other.data, length); }
/** Comparison operator */
bool operator == (const DynamicStringView & other) const { return length == other.length && memcmp(data, other.data, length) == 0; }
/** Comparison operator */
bool operator == (const char * other) const { return length == strlen(other) && memcmp(data, other, length) == 0; }
/** From a usual dynamic string */
DynamicStringView(const DynamicString & other) : length(other.length), data(other.data) {}
/** From a given C style buffer */
DynamicStringView(const char * string) : length(strlen(string)), data(string) {}
/** A null version */
DynamicStringView() : length(0), data(0) {}
};
/** A dynamic string pair view.
This is used to avoid copying a string buffer when only a pointer is required.
This string can be mutated to many buffer but no modification is done to the underlying array of chars */
struct DynamicStringPairView Final : public Serializable, public SerializableVisitor<DynamicStringPairView>
{
/** The key used for the pair */
DynamicStringView key;
/** The value used for the pair */
DynamicStringView value;
/** For consistancy with the other structures, we have a getSize() method that gives the number of bytes requires to serialize this object */
uint32 getSize() const { return key.getSize() + value.getSize(); }
/** Copy the value into the given buffer.
@param buffer A pointer to an allocated buffer that's at least getSize() bytes long
@return The number of bytes used in the buffer */
uint32 copyInto(uint8 * buffer) const { uint32 o = key.copyInto(buffer); o += value.copyInto(buffer+o); return o; }
/** Read the value from a buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@param bufLength The length of the buffer in bytes
@return The number of bytes read from the buffer, or BadData upon error */
uint32 readFrom(const uint8 * buffer, uint32 bufLength)
{
uint32 o = key.readFrom(buffer, bufLength);
if (isError(o)) return o;
uint32 s = value.readFrom(buffer + o, bufLength - o);
if (isError(s)) return s;
return s+o;
}
/** Check if the value is correct */
bool check() const { return key.check() && value.check(); }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*sKV:\n", (int)indent, ""); key.dump(out, indent + 2); value.dump(out, indent + 2); }
#endif
/** Default constructor */
DynamicStringPairView(const DynamicStringView & k = "", const DynamicStringView & v = "") : key(k), value(v) {}
/** Copy constructor */
DynamicStringPairView(const DynamicStringPairView & other) : key(other.key), value(other.value) {}
#if HasCPlusPlus11 == 1
/** Move constructor */
DynamicStringPairView(DynamicStringPair && other) : key(std::move(other.key)), value(std::move(other.value)) { }
#endif
};
/** A read only dynamic dynamic binary data, without self managed memory.
This is used to avoid copying a binary data buffer when only a pointer is required. */
struct DynamicBinDataView Final : public Serializable, public SerializableVisitor<DynamicBinDataView>
{
/** The string length in bytes */
uint16 length;
/** The data itself */
const uint8 * data;
/** For consistancy with the other structures, we have a getSize() method that gives the number of bytes requires to serialize this object */
uint32 getSize() const { return (uint32)length + 2; }
/** Copy the value into the given buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@return The number of bytes used in the buffer */
uint32 copyInto(uint8 * buffer) const { uint16 size = htons(length); memcpy(buffer, &size, 2); memcpy(buffer+2, data, length); return (uint32)length + 2; }
/** Read the value from a buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@param bufLength The length of the buffer in bytes
@return The number of bytes read from the buffer, or BadData upon error
@warning This method capture a pointer on the given buffer so it must outlive this object when being called.
Don't use this method if buffer is a temporary data. */
uint32 readFrom(const uint8 * buffer, uint32 bufLength)
{
if (bufLength < 2) return NotEnoughData;
uint16 size = 0; memcpy(&size, buffer, 2); length = ntohs(size);
if (length+2 > bufLength) return NotEnoughData;
data = &buffer[2];
return (uint32)length + 2;
}
/** Check if the value is correct */
bool check() const { return data ? length : length == 0; }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*sBin (%d bytes):", (int)indent, "", (int)length); MQTTHexDump(out, data, length); out += "\n"; }
#endif
/** Construct from a memory block */
DynamicBinDataView(const uint16 length = 0, const uint8 * block = 0) : length(length), data(block) { }
/** Copy constructor */
DynamicBinDataView(const DynamicBinaryData & other) : length(other.length), data(other.data) { }
/** Capture from a dynamic string here.
Beware of this method as the source must outlive this instance */
DynamicBinDataView & operator = (const DynamicBinaryData & source) { length = source.length; data = source.data; return *this; }
/** Basic operator */
DynamicBinDataView & operator = (const DynamicBinDataView & source) { length = source.length; data = source.data; return *this; }
};
#pragma pack(pop)
/** The variable byte integer encoding (section 1.5.5).
It's always stored encoded as a network version */
struct VBInt Final : public Serializable
{
enum
{
MaxSizeOn1Byte = 127,
MaxSizeOn2Bytes = 16383,
MaxSizeOn3Bytes = 2097151,
MaxPossibleSize = 268435455, //!< The maximum possible size
};
union
{
/** In the worst case, it's using 32 bits */
uint8 value[4];
/** The quick accessible word */
uint32 word;
};
/** The actual used size for transmitting the value, in bytes */
uint16 size;
/** Set the value. This algorithm is 26% faster compared to the basic method shown in the standard */
VBInt & operator = (uint32 other)
{
uint8 carry = 0;
uint8 pseudoLog = (other > 127) + (other > 16383) + (other > 2097151) + (other > 268435455);
size = pseudoLog+1;
switch (pseudoLog)
{
case 3: value[pseudoLog--] = (other >> 21); other &= 0x1FFFFF; carry = 0x80; // Intentionally no break here
// fall through
case 2: value[pseudoLog--] = (other >> 14) | carry; other &= 0x3FFF; carry = 0x80; // Same
// fall through
case 1: value[pseudoLog--] = (other >> 7) | carry; other &= 0x7F; carry = 0x80; // Ditto
// fall through
case 0: value[pseudoLog--] = other | carry; return *this;
default:
case 4: value[0] = value[1] = value[2] = value[3] = 0xFF; size = 0; return *this; // This is an error anyway
}
}
/** Get the value as an unsigned integer (decode)
@warning No check is made here to assert the encoding is good. Use check() to assert the encoding. */
operator uint32 () const
{
uint32 o = 0;
switch(size)
{
case 0: return 0; // This is an error anyway
case 4: o = value[3] << 21; // Intentionally no break here
// fall through
case 3: o |= (value[2] & 0x7F) << 14; // Same
// fall through
case 2: o |= (value[1] & 0x7F) << 7; // Ditto
// fall through
case 1: o |= value[0] & 0x7F; // Break is useless here too
}
return o;
}
/** Check if the value is correct */
bool check() const
{
return size > 0 && size < 5 && (value[size-1] & 0x80) == 0;
}
/** For consistancy with the other structures, we have a getSize() method that gives the number of bytes requires to serialize this object */
uint32 getSize() const { return size; }
/** Copy the value into the given buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@return The number of bytes used in the buffer */
uint32 copyInto(uint8 * buffer) const { memcpy(buffer, value, size); return size; }
/** Read the value from a buffer.
@param buffer A pointer to an allocated buffer that's at least 4 bytes long
@return The number of bytes read from the buffer, or BadData upon error */
uint32 readFrom(const uint8 * buffer, uint32 bufLength)
{
for (size = 0; size < 4;)
{
if (size+1 > bufLength) return NotEnoughData;
value[size] = buffer[size];
if (value[size++] < 0x80) break;
}
return size < 4 ? size : (uint32)BadData;
}
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*sVBInt: %u\n", (int)indent, "", (uint32)*this); }
#endif
/** Default constructor */
VBInt(uint32 value = 0) { this->operator=(value); }
/** Copy constructor */
VBInt(const VBInt & other) : word(other.word), size(other.size) { }
};
/** The variable byte integer encoding (section 1.5.5).
It's always stored encoded as a network version */
struct MappedVBInt Final : public PODVisitor<uint32>
{
/** Get the value from this mapped variable byte integer
@param buffer A pointer to the buffer to read from
@param bufLength The length of the buffer to read from
@return the number of bytes used in the buffer */
uint32 acceptBuffer(const uint8 * buffer, const uint32 bufLength)
{
uint32 size = 0; uint32 & o = getValue(); o = 0;
for (size = 0; size < 4 && size < bufLength; )
{
if (size+1 > bufLength) return NotEnoughData;
if (buffer[size++] < 0x80) break;
}
switch(size)
{
default:
case 0: return BadData; // This is an error anyway
case 4: o = buffer[3] << 21; // Intentionally no break here
// fall through
case 3: o |= (buffer[2] & 0x7F) << 14; // Same
// fall through
case 2: o |= (buffer[1] & 0x7F) << 7; // Ditto
// fall through
case 1: o |= buffer[0] & 0x7F; // Break is useless here too
}
return size;
}
};
/** The control packet type.
Src means the expected direction, C is for client to server, S for server to client and B for both direction. */
enum ControlPacketType
{
RESERVED = 0, //!< Src:Forbidden, it's reserved
CONNECT = 1, //!< Src:C Connection requested
CONNACK = 2, //!< Src:S Connection acknowledged
PUBLISH = 3, //!< Src:B Publish message
PUBACK = 4, //!< Src:B Publish acknowledged (QoS 1)
PUBREC = 5, //!< Src:B Publish received (QoS 2 delivery part 1)
PUBREL = 6, //!< Src:B Publish released (QoS 2 delivery part 2)
PUBCOMP = 7, //!< Src:B Publish completed (QoS 2 delivery part 3)
SUBSCRIBE = 8, //!< Src:C Subscribe requested
SUBACK = 9, //!< Src:S Subscribe acknowledged
UNSUBSCRIBE = 10, //!< Src:C Unsubscribe requested
UNSUBACK = 11, //!< Src:S Unsubscribe acknowledged
PINGREQ = 12, //!< Src:C Ping requested
PINGRESP = 13, //!< Src:S Ping answered
DISCONNECT = 14, //!< Src:B Disconnect notification
AUTH = 15, //!< Src:B Authentication exchanged
};
static const char * getControlPacketName(ControlPacketType type)
{
static const char * names[16] = { "RESERVED", "CONNECT", "CONNACK", "PUBLISH", "PUBACK", "PUBREC", "PUBREL", "PUBCOMP", "SUBSCRIBE", "SUBACK",
"UNSUBSCRIBE", "UNSUBACK", "PINGREQ", "PINGRESP", "DISCONNECT", "AUTH" };
return names[(int)type];
}
}
/** The version 5 for this protocol (OASIS MQTTv5 http://docs.oasis-open.org/mqtt/mqtt/v5.0/mqtt-v5.0.html ) */
namespace V5
{
// Bring shared types here
using namespace Protocol::MQTT::Common;
/** A generic type erasure class to minimize different code dealing with types */
struct Hidden GenericTypeBase
{
virtual uint32 typeSize() const = 0;
/** From network and To network are supposed to be called in succession
leading to the same state so they are both const even if individually, they modify the value */
virtual void fromNetwork() const = 0;
virtual void toNetwork() const = 0;
virtual void * raw() = 0;
bool check() const { return true; }
~GenericTypeBase() {}
};
/** A globally used GenericType that's there to minimize the number of generic code
that needs to be specialized by the compiler */
template <typename T>
struct Hidden GenericType : public GenericTypeBase
{
T value;
uint32 typeSize() const { return sizeof(T); }
void fromNetwork() const { const_cast<T&>(value) = BigEndian(value); }
void toNetwork() const { const_cast<T&>(value) = BigEndian(value); }
void * raw() { return &value; }
operator T & () { return value; }
GenericType & operator = (const T v) { value = v; return *this; }
GenericType(T v = 0) : value(v) {}
};
/** The reason codes */
enum ReasonCodes
{
Success = 0x00, //!< Success
NormalDisconnection = 0x00, //!< Normal disconnection
GrantedQoS0 = 0x00, //!< Granted QoS 0
GrantedQoS1 = 0x01, //!< Granted QoS 1
GrantedQoS2 = 0x02, //!< Granted QoS 2
DisconnectWithWillMessage = 0x04, //!< Disconnect with Will Message
NoMatchingSubscribers = 0x10, //!< No matching subscribers
NoSubscriptionExisted = 0x11, //!< No subscription existed
ContinueAuthentication = 0x18, //!< Continue authentication
ReAuthenticate = 0x19, //!< Re-authenticate
UnspecifiedError = 0x80, //!< Unspecified error
MalformedPacket = 0x81, //!< Malformed Packet
ProtocolError = 0x82, //!< Protocol Error
ImplementationSpecificError = 0x83, //!< Implementation specific error
UnsupportedProtocolVersion = 0x84, //!< Unsupported Protocol Version
ClientIdentifierNotValid = 0x85, //!< Client Identifier not valid
BadUserNameOrPassword = 0x86, //!< Bad User Name or Password
NotAuthorized = 0x87, //!< Not authorized
ServerUnavailable = 0x88, //!< Server unavailable
ServerBusy = 0x89, //!< Server busy
Banned = 0x8A, //!< Banned
ServerShuttingDown = 0x8B, //!< Server shutting down
BadAuthenticationMethod = 0x8C, //!< Bad authentication method
KeepAliveTimeout = 0x8D, //!< Keep Alive timeout
SessionTakenOver = 0x8E, //!< Session taken over
TopicFilterInvalid = 0x8F, //!< Topic Filter invalid
TopicNameInvalid = 0x90, //!< Topic Name invalid
PacketIdentifierInUse = 0x91, //!< Packet Identifier in use
PacketIdentifierNotFound = 0x92, //!< Packet Identifier not found
ReceiveMaximumExceeded = 0x93, //!< Receive Maximum exceeded
TopicAliasInvalid = 0x94, //!< Topic Alias invalid
PacketTooLarge = 0x95, //!< Packet too large
MessageRateTooHigh = 0x96, //!< Message rate too high
QuotaExceeded = 0x97, //!< Quota exceeded
AdministrativeAction = 0x98, //!< Administrative action
PayloadFormatInvalid = 0x99, //!< Payload format invalid
RetainNotSupported = 0x9A, //!< Retain not supported
QoSNotSupported = 0x9B, //!< QoS not supported
UseAnotherServer = 0x9C, //!< Use another server
ServerMoved = 0x9D, //!< Server moved
SharedSubscriptionsNotSupported = 0x9E, //!< Shared Subscriptions not supported
ConnectionRateExceeded = 0x9F, //!< Connection rate exceeded
MaximumConnectTime = 0xA0, //!< Maximum connect time
SubscriptionIdentifiersNotSupported = 0xA1, //!< Subscription Identifiers not supported
WildcardSubscriptionsNotSupported = 0xA2, //!< Wildcard Subscriptions not supported
};
/** The dynamic string class we prefer using depends on whether we are using client or server code */
#if MQTTClientOnlyImplementation == 1
typedef DynamicStringView DynString;
typedef DynamicBinDataView DynBinData;
#else
typedef DynamicString DynString;
typedef DynamicBinaryData DynBinData;
#endif
#pragma pack(push, 1)
/** A MQTT fixed header (section 2.1.1).
This is not used directly, but only to remember the expected format. Instead, each packet type is declared underneath, since it's faster to parse them directly */
struct FixedHeader
{
#if IsBigEndian == 1
union
{
uint8 raw : 8;
struct
{
/** The packet type */
uint8 type : 4;
uint8 dup : 1;
uint8 QoS : 2;
uint8 retain : 1;
};
};
#else
union
{
uint8 raw : 8;
struct
{
uint8 retain : 1;
uint8 QoS : 2;
uint8 dup : 1;
/** The packet type */
uint8 type : 4;
};
};
#endif
};
struct FixedHeaderBase
{
uint8 typeAndFlags;
virtual ControlPacketType getType() const { return (ControlPacketType)(typeAndFlags >> 4); }
virtual uint8 getFlags() const { return typeAndFlags & 0xF; }
virtual bool check() const { return true; }
#if MQTTDumpCommunication == 1
virtual void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*sHeader: (type %s, no flags)\n", (int)indent, "", getControlPacketName(getType())); }
#endif
FixedHeaderBase(const ControlPacketType type, const uint8 flags) : typeAndFlags(((uint8)type) << 4 | (flags & 0xF)) {}
virtual ~FixedHeaderBase() {}
};
/** The common format for the fixed header type */
template <ControlPacketType type, uint8 flags>
struct Hidden FixedHeaderType Final : public FixedHeaderBase
{
bool check() const { return getFlags() == flags; }
static bool check(const uint8 flag) { return flag == flags; }
FixedHeaderType() : FixedHeaderBase(type, flags) {}
};
/** The only header where flags have a meaning is for Publish operation */
template <>
struct Hidden FixedHeaderType<PUBLISH, 0> Final : public FixedHeaderBase
{
bool isDup() const { return typeAndFlags & 0x8; }
bool isRetain() const { return typeAndFlags & 0x1; }
uint8 getQoS() const { return (typeAndFlags & 0x6) >> 1; }
void setDup(const bool e) { typeAndFlags = (typeAndFlags & ~0x8) | (e ? 8 : 0); }
void setRetain(const bool e) { typeAndFlags = (typeAndFlags & ~0x1) | (e ? 1 : 0); }
void setQoS(const uint8 e) { typeAndFlags = (typeAndFlags & ~0x6) | (e < 3 ? (e << 1) : 0); }
static bool check(const uint8 flag) { return true; }
#if MQTTDumpCommunication == 1
void dump(MQTTString & out, const int indent = 0) { out += MQTTStringPrintf("%*sHeader: (type PUBLISH, retain %d, QoS %d, dup %d)\n", (int)indent, "", isRetain(), getQoS(), isDup()); }
#endif
FixedHeaderType(const uint8 flags = 0) : FixedHeaderBase(PUBLISH, flags) {}
FixedHeaderType(const bool dup, const uint8 QoS, const bool retain) : FixedHeaderBase(PUBLISH, (dup ? 8 : 0) | (retain ? 1 : 0) | (QoS < 3 ? (QoS << 1) : 0)) {}
};
/** The possible header types */
typedef FixedHeaderType<CONNECT, 0> ConnectHeader;
typedef FixedHeaderType<CONNACK, 0> ConnectACKHeader;
typedef FixedHeaderType<PUBLISH, 0> PublishHeader;
typedef FixedHeaderType<PUBACK, 0> PublishACKHeader;
typedef FixedHeaderType<PUBREC, 0> PublishReceivedHeader;
typedef FixedHeaderType<PUBREL, 2> PublishReleasedHeader;
typedef FixedHeaderType<PUBCOMP, 0> PublishCompletedHeader;
typedef FixedHeaderType<SUBSCRIBE, 2> SubscribeHeader;
typedef FixedHeaderType<SUBACK, 0> SubscribeACKHeader;
typedef FixedHeaderType<UNSUBSCRIBE,2> UnsubscribeHeader;
typedef FixedHeaderType<UNSUBACK, 0> UnsubscribeACKHeader;
typedef FixedHeaderType<PINGREQ, 0> PingRequestHeader;
typedef FixedHeaderType<PINGRESP, 0> PingACKHeader;
typedef FixedHeaderType<DISCONNECT, 0> DisconnectHeader;
typedef FixedHeaderType<AUTH, 0> AuthenticationHeader;
#pragma pack(pop)
/** Simple check header code and packet size.
@return error that will be detected with isError() or the number of bytes required for this packet */
static inline uint32 checkHeader(const uint8 * buffer, const uint32 size, ControlPacketType * type = 0)
{
if (size < 2) return NotEnoughData;
uint8 expectedFlags[] = { 0xF, 0, 0xF, 0, 0, 2, 0, 2, 0, 2, 0, 0, 0, 0, 0, 0};
if ((*buffer >> 4) != PUBLISH && ((*buffer & 0xF) ^ expectedFlags[(*buffer>>4)])) return BadData;
if (type) *type = (ControlPacketType)(*buffer >> 4);
// Then read the VB header
VBInt len;
uint32 s = len.readFrom(buffer + 1, size - 1);
if (isError(s)) return s;
return (uint32)len + s + 1;
}
/** The known property types (section 2.2.2.2) */
enum PropertyType
{
BadProperty = 0, //!< Does not exist in the standard, but useful to store a bad property type
PayloadFormat = 0x01, //!< Payload Format Indicator
MessageExpiryInterval = 0x02, //!< Message Expiry Interval
ContentType = 0x03, //!< Content Type
ResponseTopic = 0x08, //!< Response Topic
CorrelationData = 0x09, //!< Correlation Data
SubscriptionID = 0x0B, //!< Subscription Identifier
SessionExpiryInterval = 0x11, //!< Session Expiry Interval
AssignedClientID = 0x12, //!< Assigned Client Identifier
ServerKeepAlive = 0x13, //!< Server Keep Alive
AuthenticationMethod = 0x15, //!< Authentication Method
AuthenticationData = 0x16, //!< Authentication Data
RequestProblemInfo = 0x17, //!< Request Problem Information
WillDelayInterval = 0x18, //!< Will Delay Interval
RequestResponseInfo = 0x19, //!< Request Response Information
ResponseInfo = 0x1A, //!< Response Information
ServerReference = 0x1C, //!< Server Reference
ReasonString = 0x1F, //!< Reason String
ReceiveMax = 0x21, //!< Receive Maximum
TopicAliasMax = 0x22, //!< Topic Alias Maximum
TopicAlias = 0x23, //!< Topic Alias
QoSMax = 0x24, //!< Maximum QoS
RetainAvailable = 0x25, //!< Retain Available
UserProperty = 0x26, //!< User Property
PacketSizeMax = 0x27, //!< Maximum Packet Size
WildcardSubAvailable = 0x28, //!< Wildcard Subscription Available
SubIDAvailable = 0x29, //!< Subscription Identifier Available
SharedSubAvailable = 0x2A, //!< Shared Subscription Available
MaxUsedPropertyType, //!< Used as a gatekeeper for the knowing the maximum value for the properties
};
namespace PrivateRegistry
{
enum { PropertiesCount = 27 };
static const uint8 Hidden invPropertyMap[MaxUsedPropertyType] =
{
PropertiesCount, // BadProperty,
0, // PayloadFormat ,
1, // MessageExpiryInterval ,
2, // ContentType ,
PropertiesCount, // BadProperty,
PropertiesCount, // BadProperty,
PropertiesCount, // BadProperty,
PropertiesCount, // BadProperty,
3, // ResponseTopic ,
4, // CorrelationData ,
PropertiesCount, // BadProperty,
5, // SubscriptionID ,
PropertiesCount, // BadProperty,
PropertiesCount, // BadProperty,