-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcore_mqtt_serializer.c
2413 lines (2065 loc) · 85.2 KB
/
core_mqtt_serializer.c
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
/*
* coreMQTT v1.1.2
* Copyright (C) 2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* Permission is hereby granted, free of charge, to any person obtaining a copy of
* this software and associated documentation files (the "Software"), to deal in
* the Software without restriction, including without limitation the rights to
* use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
* the Software, and to permit persons to whom the Software is furnished to do so,
* subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
* IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* @file core_mqtt_serializer.c
* @brief Implements the user-facing functions in core_mqtt_serializer.h.
*/
#include <string.h>
#include <assert.h>
#include "core_mqtt_serializer.h"
/**
* @brief MQTT protocol version 3.1.1.
*/
#define MQTT_VERSION_3_1_1 ( ( uint8_t ) 4U )
/**
* @brief Size of the fixed and variable header of a CONNECT packet.
*/
#define MQTT_PACKET_CONNECT_HEADER_SIZE ( 10UL )
/* MQTT CONNECT flags. */
#define MQTT_CONNECT_FLAG_CLEAN ( 1 ) /**< @brief Clean session. */
#define MQTT_CONNECT_FLAG_WILL ( 2 ) /**< @brief Will present. */
#define MQTT_CONNECT_FLAG_WILL_QOS1 ( 3 ) /**< @brief Will QoS 1. */
#define MQTT_CONNECT_FLAG_WILL_QOS2 ( 4 ) /**< @brief Will QoS 2. */
#define MQTT_CONNECT_FLAG_WILL_RETAIN ( 5 ) /**< @brief Will retain. */
#define MQTT_CONNECT_FLAG_PASSWORD ( 6 ) /**< @brief Password present. */
#define MQTT_CONNECT_FLAG_USERNAME ( 7 ) /**< @brief User name present. */
/*
* Positions of each flag in the first byte of an MQTT PUBLISH packet's
* fixed header.
*/
#define MQTT_PUBLISH_FLAG_RETAIN ( 0 ) /**< @brief MQTT PUBLISH retain flag. */
#define MQTT_PUBLISH_FLAG_QOS1 ( 1 ) /**< @brief MQTT PUBLISH QoS1 flag. */
#define MQTT_PUBLISH_FLAG_QOS2 ( 2 ) /**< @brief MQTT PUBLISH QoS2 flag. */
#define MQTT_PUBLISH_FLAG_DUP ( 3 ) /**< @brief MQTT PUBLISH duplicate flag. */
/**
* @brief The size of MQTT DISCONNECT packets, per MQTT spec.
*/
#define MQTT_DISCONNECT_PACKET_SIZE ( 2UL )
/**
* @brief A PINGREQ packet is always 2 bytes in size, defined by MQTT 3.1.1 spec.
*/
#define MQTT_PACKET_PINGREQ_SIZE ( 2UL )
/**
* @brief The Remaining Length field of MQTT disconnect packets, per MQTT spec.
*/
#define MQTT_DISCONNECT_REMAINING_LENGTH ( ( uint8_t ) 0 )
/*
* Constants relating to CONNACK packets, defined by MQTT 3.1.1 spec.
*/
#define MQTT_PACKET_CONNACK_REMAINING_LENGTH ( ( uint8_t ) 2U ) /**< @brief A CONNACK packet always has a "Remaining length" of 2. */
#define MQTT_PACKET_CONNACK_SESSION_PRESENT_MASK ( ( uint8_t ) 0x01U ) /**< @brief The "Session Present" bit is always the lowest bit. */
/*
* UNSUBACK, PUBACK, PUBREC, PUBREL, and PUBCOMP always have a remaining length
* of 2.
*/
#define MQTT_PACKET_SIMPLE_ACK_REMAINING_LENGTH ( ( uint8_t ) 2 ) /**< @brief PUBACK, PUBREC, PUBREl, PUBCOMP, UNSUBACK Remaining length. */
#define MQTT_PACKET_PINGRESP_REMAINING_LENGTH ( 0U ) /**< @brief A PINGRESP packet always has a "Remaining length" of 0. */
/**
* @brief Per the MQTT 3.1.1 spec, the largest "Remaining Length" of an MQTT
* packet is this value, 256 MB.
*/
#define MQTT_MAX_REMAINING_LENGTH ( 268435455UL )
/**
* @brief Set a bit in an 8-bit unsigned integer.
*/
#define UINT8_SET_BIT( x, position ) ( ( x ) = ( uint8_t ) ( ( x ) | ( 0x01U << ( position ) ) ) )
/**
* @brief Macro for checking if a bit is set in a 1-byte unsigned int.
*
* @param[in] x The unsigned int to check.
* @param[in] position Which bit to check.
*/
#define UINT8_CHECK_BIT( x, position ) ( ( ( x ) & ( 0x01U << ( position ) ) ) == ( 0x01U << ( position ) ) )
/**
* @brief Get the high byte of a 16-bit unsigned integer.
*/
#define UINT16_HIGH_BYTE( x ) ( ( uint8_t ) ( ( x ) >> 8 ) )
/**
* @brief Get the low byte of a 16-bit unsigned integer.
*/
#define UINT16_LOW_BYTE( x ) ( ( uint8_t ) ( ( x ) & 0x00ffU ) )
/**
* @brief Macro for decoding a 2-byte unsigned int from a sequence of bytes.
*
* @param[in] ptr A uint8_t* that points to the high byte.
*/
#define UINT16_DECODE( ptr ) \
( uint16_t ) ( ( ( ( uint16_t ) ( *( ptr ) ) ) << 8 ) | \
( ( uint16_t ) ( *( ( ptr ) + 1 ) ) ) )
/**
* @brief A value that represents an invalid remaining length.
*
* This value is greater than what is allowed by the MQTT specification.
*/
#define MQTT_REMAINING_LENGTH_INVALID ( ( size_t ) 268435456 )
/**
* @brief The minimum remaining length for a QoS 0 PUBLISH.
*
* Includes two bytes for topic name length and one byte for topic name.
*/
#define MQTT_MIN_PUBLISH_REMAINING_LENGTH_QOS0 ( 3U )
/*-----------------------------------------------------------*/
/**
* @brief MQTT Subscription packet types.
*/
typedef enum MQTTSubscriptionType
{
MQTT_SUBSCRIBE, /**< @brief The type is a SUBSCRIBE packet. */
MQTT_UNSUBSCRIBE /**< @brief The type is a UNSUBSCRIBE packet. */
} MQTTSubscriptionType_t;
/*-----------------------------------------------------------*/
/**
* @brief Serializes MQTT PUBLISH packet into the buffer provided.
*
* This function serializes MQTT PUBLISH packet into #MQTTFixedBuffer_t.pBuffer.
* Copy of the payload into the buffer is done as part of the serialization
* only if @p serializePayload is true.
*
* @brief param[in] pPublishInfo Publish information.
* @brief param[in] remainingLength Remaining length of the PUBLISH packet.
* @brief param[in] packetIdentifier Packet identifier of PUBLISH packet.
* @brief param[in, out] pFixedBuffer Buffer to which PUBLISH packet will be
* serialized.
* @brief param[in] serializePayload Copy payload to the serialized buffer
* only if true. Only PUBLISH header will be serialized if false.
*
* @return Total number of bytes sent; -1 if there is an error.
*/
static void serializePublishCommon( const MQTTPublishInfo_t * pPublishInfo,
size_t remainingLength,
uint16_t packetIdentifier,
const MQTTFixedBuffer_t * pFixedBuffer,
bool serializePayload );
/**
* @brief Calculates the packet size and remaining length of an MQTT
* PUBLISH packet.
*
* @param[in] pPublishInfo MQTT PUBLISH packet parameters.
* @param[out] pRemainingLength The Remaining Length of the MQTT PUBLISH packet.
* @param[out] pPacketSize The total size of the MQTT PUBLISH packet.
*
* @return false if the packet would exceed the size allowed by the
* MQTT spec; true otherwise.
*/
static bool calculatePublishPacketSize( const MQTTPublishInfo_t * pPublishInfo,
size_t * pRemainingLength,
size_t * pPacketSize );
/**
* @brief Calculates the packet size and remaining length of an MQTT
* SUBSCRIBE or UNSUBSCRIBE packet.
*
* @param[in] pSubscriptionList List of MQTT subscription info.
* @param[in] subscriptionCount The number of elements in pSubscriptionList.
* @param[out] pRemainingLength The Remaining Length of the MQTT SUBSCRIBE or
* UNSUBSCRIBE packet.
* @param[out] pPacketSize The total size of the MQTT MQTT SUBSCRIBE or
* UNSUBSCRIBE packet.
* @param[in] subscriptionType #MQTT_SUBSCRIBE or #MQTT_UNSUBSCRIBE.
*
* #MQTTBadParameter if the packet would exceed the size allowed by the
* MQTT spec or a subscription is empty; #MQTTSuccess otherwise.
*/
static MQTTStatus_t calculateSubscriptionPacketSize( const MQTTSubscribeInfo_t * pSubscriptionList,
size_t subscriptionCount,
size_t * pRemainingLength,
size_t * pPacketSize,
MQTTSubscriptionType_t subscriptionType );
/**
* @brief Validates parameters of #MQTT_SerializeSubscribe or
* #MQTT_SerializeUnsubscribe.
*
* @param[in] pSubscriptionList List of MQTT subscription info.
* @param[in] subscriptionCount The number of elements in pSubscriptionList.
* @param[in] packetId Packet identifier.
* @param[in] remainingLength Remaining length of the packet.
* @param[in] pFixedBuffer Buffer for packet serialization.
*
* @return #MQTTNoMemory if pBuffer is too small to hold the MQTT packet;
* #MQTTBadParameter if invalid parameters are passed;
* #MQTTSuccess otherwise.
*/
static MQTTStatus_t validateSubscriptionSerializeParams( const MQTTSubscribeInfo_t * pSubscriptionList,
size_t subscriptionCount,
uint16_t packetId,
size_t remainingLength,
const MQTTFixedBuffer_t * pFixedBuffer );
/**
* @brief Serialize an MQTT CONNECT packet in the given buffer.
*
* @param[in] pConnectInfo MQTT CONNECT packet parameters.
* @param[in] pWillInfo Last Will and Testament. Pass NULL if not used.
* @param[in] remainingLength Remaining Length of MQTT CONNECT packet.
* @param[out] pFixedBuffer Buffer for packet serialization.
*/
static void serializeConnectPacket( const MQTTConnectInfo_t * pConnectInfo,
const MQTTPublishInfo_t * pWillInfo,
size_t remainingLength,
const MQTTFixedBuffer_t * pFixedBuffer );
/**
* @brief Prints the appropriate message for the CONNACK response code if logs
* are enabled.
*
* @param[in] responseCode MQTT standard CONNACK response code.
*/
static void logConnackResponse( uint8_t responseCode );
/**
* @brief Encodes the remaining length of the packet using the variable length
* encoding scheme provided in the MQTT v3.1.1 specification.
*
* @param[out] pDestination The destination buffer to store the encoded remaining
* length.
* @param[in] length The remaining length to encode.
*
* @return The location of the byte following the encoded value.
*/
static uint8_t * encodeRemainingLength( uint8_t * pDestination,
size_t length );
/**
* @brief Retrieve the size of the remaining length if it were to be encoded.
*
* @param[in] length The remaining length to be encoded.
*
* @return The size of the remaining length if it were to be encoded.
*/
static size_t remainingLengthEncodedSize( size_t length );
/**
* @brief Encode a string whose size is at maximum 16 bits in length.
*
* @param[out] pDestination Destination buffer for the encoding.
* @param[in] pSource The source string to encode.
* @param[in] sourceLength The length of the source string to encode.
*
* @return A pointer to the end of the encoded string.
*/
static uint8_t * encodeString( uint8_t * pDestination,
const char * pSource,
uint16_t sourceLength );
/**
* @brief Retrieves and decodes the Remaining Length from the network interface
* by reading a single byte at a time.
*
* @param[in] recvFunc Network interface receive function.
* @param[in] pNetworkContext Network interface context to the receive function.
*
* @return The Remaining Length of the incoming packet.
*/
static size_t getRemainingLength( TransportRecv_t recvFunc,
NetworkContext_t * pNetworkContext );
/**
* @brief Check if an incoming packet type is valid.
*
* @param[in] packetType The packet type to check.
*
* @return `true` if the packet type is valid; `false` otherwise.
*/
static bool incomingPacketValid( uint8_t packetType );
/**
* @brief Check the remaining length of an incoming PUBLISH packet against some
* value for QoS 0, or for QoS 1 and 2.
*
* The remaining length for a QoS 1 and 2 packet will always be two greater than
* for a QoS 0.
*
* @param[in] remainingLength Remaining length of the PUBLISH packet.
* @param[in] qos The QoS of the PUBLISH.
* @param[in] qos0Minimum Minimum possible remaining length for a QoS 0 PUBLISH.
*
* @return #MQTTSuccess or #MQTTBadResponse.
*/
static MQTTStatus_t checkPublishRemainingLength( size_t remainingLength,
MQTTQoS_t qos,
size_t qos0Minimum );
/**
* @brief Process the flags of an incoming PUBLISH packet.
*
* @param[in] publishFlags Flags of an incoming PUBLISH.
* @param[in, out] pPublishInfo Pointer to #MQTTPublishInfo_t struct where
* output will be written.
*
* @return #MQTTSuccess or #MQTTBadResponse.
*/
static MQTTStatus_t processPublishFlags( uint8_t publishFlags,
MQTTPublishInfo_t * pPublishInfo );
/**
* @brief Deserialize a CONNACK packet.
*
* Converts the packet from a stream of bytes to an #MQTTStatus_t.
*
* @param[in] pConnack Pointer to an MQTT packet struct representing a
* CONNACK.
* @param[out] pSessionPresent Whether a previous session was present.
*
* @return #MQTTSuccess if CONNACK specifies that CONNECT was accepted;
* #MQTTServerRefused if CONNACK specifies that CONNECT was rejected;
* #MQTTBadResponse if the CONNACK packet doesn't follow MQTT spec.
*/
static MQTTStatus_t deserializeConnack( const MQTTPacketInfo_t * pConnack,
bool * pSessionPresent );
/**
* @brief Decode the status bytes of a SUBACK packet to a #MQTTStatus_t.
*
* @param[in] statusCount Number of status bytes in the SUBACK.
* @param[in] pStatusStart The first status byte in the SUBACK.
*
* @return #MQTTSuccess, #MQTTServerRefused, or #MQTTBadResponse.
*/
static MQTTStatus_t readSubackStatus( size_t statusCount,
const uint8_t * pStatusStart );
/**
* @brief Deserialize a SUBACK packet.
*
* Converts the packet from a stream of bytes to an #MQTTStatus_t and extracts
* the packet identifier.
*
* @param[in] pSuback Pointer to an MQTT packet struct representing a SUBACK.
* @param[out] pPacketIdentifier Packet ID of the SUBACK.
*
* @return #MQTTSuccess if SUBACK is valid; #MQTTBadResponse if SUBACK packet
* doesn't follow the MQTT spec.
*/
static MQTTStatus_t deserializeSuback( const MQTTPacketInfo_t * pSuback,
uint16_t * pPacketIdentifier );
/**
* @brief Deserialize a PUBLISH packet received from the server.
*
* Converts the packet from a stream of bytes to an #MQTTPublishInfo_t and
* extracts the packet identifier. Also prints out debug log messages about the
* packet.
*
* @param[in] pIncomingPacket Pointer to an MQTT packet struct representing a
* PUBLISH.
* @param[out] pPacketId Packet identifier of the PUBLISH.
* @param[out] pPublishInfo Pointer to #MQTTPublishInfo_t where output is
* written.
*
* @return #MQTTSuccess if PUBLISH is valid; #MQTTBadResponse
* if the PUBLISH packet doesn't follow MQTT spec.
*/
static MQTTStatus_t deserializePublish( const MQTTPacketInfo_t * pIncomingPacket,
uint16_t * pPacketId,
MQTTPublishInfo_t * pPublishInfo );
/**
* @brief Deserialize an UNSUBACK, PUBACK, PUBREC, PUBREL, or PUBCOMP packet.
*
* Converts the packet from a stream of bytes to an #MQTTStatus_t and extracts
* the packet identifier.
*
* @param[in] pAck Pointer to the MQTT packet structure representing the packet.
* @param[out] pPacketIdentifier Packet ID of the ack type packet.
*
* @return #MQTTSuccess if UNSUBACK, PUBACK, PUBREC, PUBREL, or PUBCOMP is valid;
* #MQTTBadResponse if the packet doesn't follow the MQTT spec.
*/
static MQTTStatus_t deserializeSimpleAck( const MQTTPacketInfo_t * pAck,
uint16_t * pPacketIdentifier );
/**
* @brief Deserialize a PINGRESP packet.
*
* Converts the packet from a stream of bytes to an #MQTTStatus_t.
*
* @param[in] pPingresp Pointer to an MQTT packet struct representing a PINGRESP.
*
* @return #MQTTSuccess if PINGRESP is valid; #MQTTBadResponse if the PINGRESP
* packet doesn't follow MQTT spec.
*/
static MQTTStatus_t deserializePingresp( const MQTTPacketInfo_t * pPingresp );
/*-----------------------------------------------------------*/
static size_t remainingLengthEncodedSize( size_t length )
{
size_t encodedSize;
/* Determine how many bytes are needed to encode length.
* The values below are taken from the MQTT 3.1.1 spec. */
/* 1 byte is needed to encode lengths between 0 and 127. */
if( length < 128U )
{
encodedSize = 1U;
}
/* 2 bytes are needed to encode lengths between 128 and 16,383. */
else if( length < 16384U )
{
encodedSize = 2U;
}
/* 3 bytes are needed to encode lengths between 16,384 and 2,097,151. */
else if( length < 2097152U )
{
encodedSize = 3U;
}
/* 4 bytes are needed to encode lengths between 2,097,152 and 268,435,455. */
else
{
encodedSize = 4U;
}
LogDebug( ( "Encoded size for length %lu is %lu bytes.",
( unsigned long ) length,
( unsigned long ) encodedSize ) );
return encodedSize;
}
/*-----------------------------------------------------------*/
static uint8_t * encodeRemainingLength( uint8_t * pDestination,
size_t length )
{
uint8_t lengthByte;
uint8_t * pLengthEnd = NULL;
size_t remainingLength = length;
assert( pDestination != NULL );
pLengthEnd = pDestination;
/* This algorithm is copied from the MQTT v3.1.1 spec. */
do
{
lengthByte = ( uint8_t ) ( remainingLength % 128U );
remainingLength = remainingLength / 128U;
/* Set the high bit of this byte, indicating that there's more data. */
if( remainingLength > 0U )
{
UINT8_SET_BIT( lengthByte, 7 );
}
/* Output a single encoded byte. */
*pLengthEnd = lengthByte;
pLengthEnd++;
} while( remainingLength > 0U );
return pLengthEnd;
}
/*-----------------------------------------------------------*/
static uint8_t * encodeString( uint8_t * pDestination,
const char * pSource,
uint16_t sourceLength )
{
uint8_t * pBuffer = NULL;
/* Typecast const char * typed source buffer to const uint8_t *.
* This is to use same type buffers in memcpy. */
const uint8_t * pSourceBuffer = ( const uint8_t * ) pSource;
assert( pDestination != NULL );
pBuffer = pDestination;
/* The first byte of a UTF-8 string is the high byte of the string length. */
*pBuffer = UINT16_HIGH_BYTE( sourceLength );
pBuffer++;
/* The second byte of a UTF-8 string is the low byte of the string length. */
*pBuffer = UINT16_LOW_BYTE( sourceLength );
pBuffer++;
/* Copy the string into pBuffer. */
if( pSourceBuffer != NULL )
{
( void ) memcpy( pBuffer, pSourceBuffer, sourceLength );
}
/* Return the pointer to the end of the encoded string. */
pBuffer += sourceLength;
return pBuffer;
}
/*-----------------------------------------------------------*/
static bool calculatePublishPacketSize( const MQTTPublishInfo_t * pPublishInfo,
size_t * pRemainingLength,
size_t * pPacketSize )
{
bool status = true;
size_t packetSize = 0, payloadLimit = 0;
assert( pPublishInfo != NULL );
assert( pRemainingLength != NULL );
assert( pPacketSize != NULL );
/* The variable header of a PUBLISH packet always contains the topic name.
* The first 2 bytes of UTF-8 string contains length of the string.
*/
packetSize += pPublishInfo->topicNameLength + sizeof( uint16_t );
/* The variable header of a QoS 1 or 2 PUBLISH packet contains a 2-byte
* packet identifier. */
if( pPublishInfo->qos > MQTTQoS0 )
{
packetSize += sizeof( uint16_t );
}
/* Calculate the maximum allowed size of the payload for the given parameters.
* This calculation excludes the "Remaining length" encoding, whose size is not
* yet known. */
payloadLimit = MQTT_MAX_REMAINING_LENGTH - packetSize - 1U;
/* Ensure that the given payload fits within the calculated limit. */
if( pPublishInfo->payloadLength > payloadLimit )
{
LogError( ( "PUBLISH payload length of %lu cannot exceed "
"%lu so as not to exceed the maximum "
"remaining length of MQTT 3.1.1 packet( %lu ).",
( unsigned long ) pPublishInfo->payloadLength,
( unsigned long ) payloadLimit,
MQTT_MAX_REMAINING_LENGTH ) );
status = false;
}
else
{
/* Add the length of the PUBLISH payload. At this point, the "Remaining length"
* has been calculated. */
packetSize += pPublishInfo->payloadLength;
/* Now that the "Remaining length" is known, recalculate the payload limit
* based on the size of its encoding. */
payloadLimit -= remainingLengthEncodedSize( packetSize );
/* Check that the given payload fits within the size allowed by MQTT spec. */
if( pPublishInfo->payloadLength > payloadLimit )
{
LogError( ( "PUBLISH payload length of %lu cannot exceed "
"%lu so as not to exceed the maximum "
"remaining length of MQTT 3.1.1 packet( %lu ).",
( unsigned long ) pPublishInfo->payloadLength,
( unsigned long ) payloadLimit,
MQTT_MAX_REMAINING_LENGTH ) );
status = false;
}
else
{
/* Set the "Remaining length" output parameter and calculate the full
* size of the PUBLISH packet. */
*pRemainingLength = packetSize;
packetSize += 1U + remainingLengthEncodedSize( packetSize );
*pPacketSize = packetSize;
}
}
LogDebug( ( "PUBLISH packet remaining length=%lu and packet size=%lu.",
( unsigned long ) *pRemainingLength,
( unsigned long ) *pPacketSize ) );
return status;
}
/*-----------------------------------------------------------*/
static void serializePublishCommon( const MQTTPublishInfo_t * pPublishInfo,
size_t remainingLength,
uint16_t packetIdentifier,
const MQTTFixedBuffer_t * pFixedBuffer,
bool serializePayload )
{
uint8_t * pIndex = NULL;
const uint8_t * pPayloadBuffer = NULL;
/* The first byte of a PUBLISH packet contains the packet type and flags. */
uint8_t publishFlags = MQTT_PACKET_TYPE_PUBLISH;
assert( pPublishInfo != NULL );
assert( pFixedBuffer != NULL );
assert( pFixedBuffer->pBuffer != NULL );
/* Packet Id should be non zero for Qos 1 and Qos 2. */
assert( ( pPublishInfo->qos == MQTTQoS0 ) || ( packetIdentifier != 0U ) );
/* Duplicate flag should be set only for Qos 1 or Qos 2. */
assert( ( pPublishInfo->dup != true ) || ( pPublishInfo->qos != MQTTQoS0 ) );
/* Get the start address of the buffer. */
pIndex = pFixedBuffer->pBuffer;
if( pPublishInfo->qos == MQTTQoS1 )
{
LogDebug( ( "Adding QoS as QoS1 in PUBLISH flags." ) );
UINT8_SET_BIT( publishFlags, MQTT_PUBLISH_FLAG_QOS1 );
}
else if( pPublishInfo->qos == MQTTQoS2 )
{
LogDebug( ( "Adding QoS as QoS2 in PUBLISH flags." ) );
UINT8_SET_BIT( publishFlags, MQTT_PUBLISH_FLAG_QOS2 );
}
else
{
/* Empty else MISRA 15.7 */
}
if( pPublishInfo->retain == true )
{
LogDebug( ( "Adding retain bit in PUBLISH flags." ) );
UINT8_SET_BIT( publishFlags, MQTT_PUBLISH_FLAG_RETAIN );
}
if( pPublishInfo->dup == true )
{
LogDebug( ( "Adding dup bit in PUBLISH flags." ) );
UINT8_SET_BIT( publishFlags, MQTT_PUBLISH_FLAG_DUP );
}
*pIndex = publishFlags;
pIndex++;
/* The "Remaining length" is encoded from the second byte. */
pIndex = encodeRemainingLength( pIndex, remainingLength );
/* The topic name is placed after the "Remaining length". */
pIndex = encodeString( pIndex,
pPublishInfo->pTopicName,
pPublishInfo->topicNameLength );
/* A packet identifier is required for QoS 1 and 2 messages. */
if( pPublishInfo->qos > MQTTQoS0 )
{
LogDebug( ( "Adding packet Id in PUBLISH packet." ) );
/* Place the packet identifier into the PUBLISH packet. */
*pIndex = UINT16_HIGH_BYTE( packetIdentifier );
*( pIndex + 1 ) = UINT16_LOW_BYTE( packetIdentifier );
pIndex += 2;
}
/* The payload is placed after the packet identifier.
* Payload is copied over only if required by the flag serializePayload.
* This will help reduce an unnecessary copy of the payload into the buffer.
*/
if( ( pPublishInfo->payloadLength > 0U ) &&
( serializePayload == true ) )
{
LogDebug( ( "Copying PUBLISH payload of length =%lu to buffer",
( unsigned long ) pPublishInfo->payloadLength ) );
/* Typecast const void * typed payload buffer to const uint8_t *.
* This is to use same type buffers in memcpy. */
pPayloadBuffer = ( const uint8_t * ) pPublishInfo->pPayload;
( void ) memcpy( pIndex, pPayloadBuffer, pPublishInfo->payloadLength );
pIndex += pPublishInfo->payloadLength;
}
/* Ensure that the difference between the end and beginning of the buffer
* is less than the buffer size. */
assert( ( ( size_t ) ( pIndex - pFixedBuffer->pBuffer ) ) <= pFixedBuffer->size );
}
static size_t getRemainingLength( TransportRecv_t recvFunc,
NetworkContext_t * pNetworkContext )
{
size_t remainingLength = 0, multiplier = 1, bytesDecoded = 0, expectedSize = 0;
uint8_t encodedByte = 0;
int32_t bytesReceived = 0;
/* This algorithm is copied from the MQTT v3.1.1 spec. */
do
{
if( multiplier > 2097152U ) /* 128 ^ 3 */
{
remainingLength = MQTT_REMAINING_LENGTH_INVALID;
}
else
{
bytesReceived = recvFunc( pNetworkContext, &encodedByte, 1U );
if( bytesReceived == 1 )
{
remainingLength += ( ( size_t ) encodedByte & 0x7FU ) * multiplier;
multiplier *= 128U;
bytesDecoded++;
}
else
{
remainingLength = MQTT_REMAINING_LENGTH_INVALID;
}
}
if( remainingLength == MQTT_REMAINING_LENGTH_INVALID )
{
break;
}
} while( ( encodedByte & 0x80U ) != 0U );
/* Check that the decoded remaining length conforms to the MQTT specification. */
if( remainingLength != MQTT_REMAINING_LENGTH_INVALID )
{
expectedSize = remainingLengthEncodedSize( remainingLength );
if( bytesDecoded != expectedSize )
{
remainingLength = MQTT_REMAINING_LENGTH_INVALID;
}
}
return remainingLength;
}
/*-----------------------------------------------------------*/
static bool incomingPacketValid( uint8_t packetType )
{
bool status = false;
/* Check packet type. Mask out lower bits to ignore flags. */
switch( packetType & 0xF0U )
{
/* Valid incoming packet types. */
case MQTT_PACKET_TYPE_CONNACK:
case MQTT_PACKET_TYPE_PUBLISH:
case MQTT_PACKET_TYPE_PUBACK:
case MQTT_PACKET_TYPE_PUBREC:
case MQTT_PACKET_TYPE_PUBCOMP:
case MQTT_PACKET_TYPE_SUBACK:
case MQTT_PACKET_TYPE_UNSUBACK:
case MQTT_PACKET_TYPE_PINGRESP:
status = true;
break;
case ( MQTT_PACKET_TYPE_PUBREL & 0xF0U ):
/* The second bit of a PUBREL must be set. */
if( ( packetType & 0x02U ) > 0U )
{
status = true;
}
break;
/* Any other packet type is invalid. */
default:
LogWarn( ( "Incoming packet invalid: Packet type=%u.",
( unsigned int ) packetType ) );
break;
}
return status;
}
/*-----------------------------------------------------------*/
static MQTTStatus_t checkPublishRemainingLength( size_t remainingLength,
MQTTQoS_t qos,
size_t qos0Minimum )
{
MQTTStatus_t status = MQTTSuccess;
/* Sanity checks for "Remaining length". */
if( qos == MQTTQoS0 )
{
/* Check that the "Remaining length" is greater than the minimum. */
if( remainingLength < qos0Minimum )
{
LogDebug( ( "QoS 0 PUBLISH cannot have a remaining length less than %lu.",
( unsigned long ) qos0Minimum ) );
status = MQTTBadResponse;
}
}
else
{
/* Check that the "Remaining length" is greater than the minimum. For
* QoS 1 or 2, this will be two bytes greater than for QoS 0 due to the
* packet identifier. */
if( remainingLength < ( qos0Minimum + 2U ) )
{
LogDebug( ( "QoS 1 or 2 PUBLISH cannot have a remaining length less than %lu.",
( unsigned long ) ( qos0Minimum + 2U ) ) );
status = MQTTBadResponse;
}
}
return status;
}
/*-----------------------------------------------------------*/
static MQTTStatus_t processPublishFlags( uint8_t publishFlags,
MQTTPublishInfo_t * pPublishInfo )
{
MQTTStatus_t status = MQTTSuccess;
assert( pPublishInfo != NULL );
/* Check for QoS 2. */
if( UINT8_CHECK_BIT( publishFlags, MQTT_PUBLISH_FLAG_QOS2 ) )
{
/* PUBLISH packet is invalid if both QoS 1 and QoS 2 bits are set. */
if( UINT8_CHECK_BIT( publishFlags, MQTT_PUBLISH_FLAG_QOS1 ) )
{
LogDebug( ( "Bad QoS: 3." ) );
status = MQTTBadResponse;
}
else
{
pPublishInfo->qos = MQTTQoS2;
}
}
/* Check for QoS 1. */
else if( UINT8_CHECK_BIT( publishFlags, MQTT_PUBLISH_FLAG_QOS1 ) )
{
pPublishInfo->qos = MQTTQoS1;
}
/* If the PUBLISH isn't QoS 1 or 2, then it's QoS 0. */
else
{
pPublishInfo->qos = MQTTQoS0;
}
if( status == MQTTSuccess )
{
LogDebug( ( "QoS is %d.", ( int ) pPublishInfo->qos ) );
/* Parse the Retain bit. */
pPublishInfo->retain = ( UINT8_CHECK_BIT( publishFlags, MQTT_PUBLISH_FLAG_RETAIN ) ) ? true : false;
LogDebug( ( "Retain bit is %d.", ( int ) pPublishInfo->retain ) );
/* Parse the DUP bit. */
pPublishInfo->dup = ( UINT8_CHECK_BIT( publishFlags, MQTT_PUBLISH_FLAG_DUP ) ) ? true : false;
LogDebug( ( "DUP bit is %d.", ( int ) pPublishInfo->dup ) );
}
return status;
}
/*-----------------------------------------------------------*/
static void logConnackResponse( uint8_t responseCode )
{
const char * const pConnackResponses[ 6 ] =
{
"Connection accepted.", /* 0 */
"Connection refused: unacceptable protocol version.", /* 1 */
"Connection refused: identifier rejected.", /* 2 */
"Connection refused: server unavailable", /* 3 */
"Connection refused: bad user name or password.", /* 4 */
"Connection refused: not authorized." /* 5 */
};
/* Avoid unused parameter warning when assert and logs are disabled. */
( void ) responseCode;
( void ) pConnackResponses;
assert( responseCode <= 5 );
if( responseCode == 0u )
{
/* Log at Info level for a success CONNACK response. */
LogInfo( ( "%s", pConnackResponses[ 0 ] ) );
}
else
{
/* Log an error based on the CONNACK response code. */
LogError( ( "%s", pConnackResponses[ responseCode ] ) );
}
}
/*-----------------------------------------------------------*/
static MQTTStatus_t deserializeConnack( const MQTTPacketInfo_t * pConnack,
bool * pSessionPresent )
{
MQTTStatus_t status = MQTTSuccess;
const uint8_t * pRemainingData = NULL;
assert( pConnack != NULL );
assert( pSessionPresent != NULL );
pRemainingData = pConnack->pRemainingData;
/* According to MQTT 3.1.1, the second byte of CONNACK must specify a
* "Remaining length" of 2. */
if( pConnack->remainingLength != MQTT_PACKET_CONNACK_REMAINING_LENGTH )
{
LogError( ( "CONNACK does not have remaining length of %u.",
( unsigned int ) MQTT_PACKET_CONNACK_REMAINING_LENGTH ) );
status = MQTTBadResponse;
}
/* Check the reserved bits in CONNACK. The high 7 bits of the second byte
* in CONNACK must be 0. */
else if( ( pRemainingData[ 0 ] | 0x01U ) != 0x01U )
{
LogError( ( "Reserved bits in CONNACK incorrect." ) );
status = MQTTBadResponse;
}
else
{
/* Determine if the "Session Present" bit is set. This is the lowest bit of
* the second byte in CONNACK. */
if( ( pRemainingData[ 0 ] & MQTT_PACKET_CONNACK_SESSION_PRESENT_MASK )
== MQTT_PACKET_CONNACK_SESSION_PRESENT_MASK )
{
LogInfo( ( "CONNACK session present bit set." ) );
*pSessionPresent = true;
/* MQTT 3.1.1 specifies that the fourth byte in CONNACK must be 0 if the
* "Session Present" bit is set. */
if( pRemainingData[ 1 ] != 0U )
{
status = MQTTBadResponse;
}
}
else
{
LogInfo( ( "CONNACK session present bit not set." ) );
*pSessionPresent = false;
}
}
if( status == MQTTSuccess )
{
/* In MQTT 3.1.1, only values 0 through 5 are valid CONNACK response codes. */
if( pRemainingData[ 1 ] > 5U )
{
LogError( ( "CONNACK response %u is invalid.",
( unsigned int ) pRemainingData[ 1 ] ) );
status = MQTTBadResponse;
}
else
{
/* Print the appropriate message for the CONNACK response code if logs are
* enabled. */
logConnackResponse( pRemainingData[ 1 ] );
/* A nonzero CONNACK response code means the connection was refused. */
if( pRemainingData[ 1 ] > 0U )
{
status = MQTTServerRefused;
}
}
}
return status;
}