-
Notifications
You must be signed in to change notification settings - Fork 103
/
core_mqtt.c
3384 lines (2896 loc) · 123 KB
/
core_mqtt.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 v2.1.0
* Copyright (C) 2022 Amazon.com, Inc. or its affiliates. All Rights Reserved.
*
* SPDX-License-Identifier: MIT
*
* 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.c
* @brief Implements the user-facing functions in core_mqtt.h.
*/
#include <string.h>
#include <assert.h>
#include "core_mqtt.h"
#include "core_mqtt_state.h"
/* Include config defaults header to get default values of configs. */
#include "core_mqtt_config_defaults.h"
#include "core_mqtt_default_logging.h"
#ifndef MQTT_PRE_SEND_HOOK
/**
* @brief Hook called before a 'send' operation is executed.
*/
#define MQTT_PRE_SEND_HOOK( pContext )
#endif /* !MQTT_PRE_SEND_HOOK */
#ifndef MQTT_POST_SEND_HOOK
/**
* @brief Hook called after the 'send' operation is complete.
*/
#define MQTT_POST_SEND_HOOK( pContext )
#endif /* !MQTT_POST_SEND_HOOK */
#ifndef MQTT_PRE_STATE_UPDATE_HOOK
/**
* @brief Hook called just before an update to the MQTT state is made.
*/
#define MQTT_PRE_STATE_UPDATE_HOOK( pContext )
#endif /* !MQTT_PRE_STATE_UPDATE_HOOK */
#ifndef MQTT_POST_STATE_UPDATE_HOOK
/**
* @brief Hook called just after an update to the MQTT state has
* been made.
*/
#define MQTT_POST_STATE_UPDATE_HOOK( pContext )
#endif /* !MQTT_POST_STATE_UPDATE_HOOK */
/**
* @brief Bytes required to encode any string length in an MQTT packet header.
* Length is always encoded in two bytes according to the MQTT specification.
*/
#define CORE_MQTT_SERIALIZED_LENGTH_FIELD_BYTES ( 2U )
/**
* @brief Number of vectors required to encode one topic filter in a subscribe
* request. Three vectors are required as there are three fields in the
* subscribe request namely:
* 1. Topic filter length; 2. Topic filter; and 3. QoS in this order.
*/
#define CORE_MQTT_SUBSCRIBE_PER_TOPIC_VECTOR_LENGTH ( 3U )
/**
* @brief Number of vectors required to encode one topic filter in an
* unsubscribe request. Two vectors are required as there are two fields in the
* unsubscribe request namely:
* 1. Topic filter length; and 2. Topic filter in this order.
*/
#define CORE_MQTT_UNSUBSCRIBE_PER_TOPIC_VECTOR_LENGTH ( 2U )
/*-----------------------------------------------------------*/
/**
* @brief Sends provided buffer to network using transport send.
*
* @brief param[in] pContext Initialized MQTT context.
* @brief param[in] pBufferToSend Buffer to be sent to network.
* @brief param[in] bytesToSend Number of bytes to be sent.
*
* @note This operation may call the transport send function
* repeatedly to send bytes over the network until either:
* 1. The requested number of bytes @a bytesToSend have been sent.
* OR
* 2. MQTT_SEND_TIMEOUT_MS milliseconds have gone by since entering this
* function.
* OR
* 3. There is an error in sending data over the network.
*
* @return Total number of bytes sent, or negative value on network error.
*/
static int32_t sendBuffer( MQTTContext_t * pContext,
const uint8_t * pBufferToSend,
size_t bytesToSend );
/**
* @brief Sends MQTT connect without copying the users data into any buffer.
*
* @brief param[in] pContext Initialized MQTT context.
* @brief param[in] pConnectInfo MQTT CONNECT packet information.
* @brief param[in] pWillInfo Last Will and Testament. Pass NULL if Last Will and
* Testament is not used.
* @brief param[in] remainingLength the length of the connect packet.
*
* @note This operation may call the transport send function
* repeatedly to send bytes over the network until either:
* 1. The requested number of bytes @a remainingLength have been sent.
* OR
* 2. MQTT_SEND_TIMEOUT_MS milliseconds have gone by since entering this
* function.
* OR
* 3. There is an error in sending data over the network.
*
* @return #MQTTSendFailed or #MQTTSuccess.
*/
static MQTTStatus_t sendConnectWithoutCopy( MQTTContext_t * pContext,
const MQTTConnectInfo_t * pConnectInfo,
const MQTTPublishInfo_t * pWillInfo,
size_t remainingLength );
/**
* @brief Sends the vector array passed through the parameters over the network.
*
* @note The preference is given to 'writev' function if it is present in the
* transport interface. Otherwise, a send call is made repeatedly to achieve the
* result.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] pIoVec The vector array to be sent.
* @param[in] ioVecCount The number of elements in the array.
*
* @note This operation may call the transport send or writev functions
* repeatedly to send bytes over the network until either:
* 1. The requested number of bytes have been sent.
* OR
* 2. MQTT_SEND_TIMEOUT_MS milliseconds have gone by since entering this
* function.
* OR
* 3. There is an error in sending data over the network.
*
* @return The total number of bytes sent or the error code as received from the
* transport interface.
*/
static int32_t sendMessageVector( MQTTContext_t * pContext,
TransportOutVector_t * pIoVec,
size_t ioVecCount );
/**
* @brief Add a string and its length after serializing it in a manner outlined by
* the MQTT specification.
*
* @param[in] serializedLength Array of two bytes to which the vector will point.
* The array must remain in scope until the message has been sent.
* @param[in] string The string to be serialized.
* @param[in] length The length of the string to be serialized.
* @param[in] iterator The iterator pointing to the first element in the
* transport interface IO array.
* @param[out] updatedLength This parameter will be added to with the number of
* bytes added to the vector.
*
* @return The number of vectors added.
*/
static size_t addEncodedStringToVector( uint8_t serializedLength[ CORE_MQTT_SERIALIZED_LENGTH_FIELD_BYTES ],
const char * const string,
uint16_t length,
TransportOutVector_t * iterator,
size_t * updatedLength );
/**
* @brief Send MQTT SUBSCRIBE message without copying the user data into a buffer and
* directly sending it.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] pSubscriptionList List of MQTT subscription info.
* @param[in] subscriptionCount The count of elements in the list.
* @param[in] packetId The packet ID of the subscribe packet
* @param[in] remainingLength The remaining length of the subscribe packet.
*
* @return #MQTTSuccess or #MQTTSendFailed.
*/
static MQTTStatus_t sendSubscribeWithoutCopy( MQTTContext_t * pContext,
const MQTTSubscribeInfo_t * pSubscriptionList,
size_t subscriptionCount,
uint16_t packetId,
size_t remainingLength );
/**
* @brief Send MQTT UNSUBSCRIBE message without copying the user data into a buffer and
* directly sending it.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] pSubscriptionList MQTT subscription info.
* @param[in] subscriptionCount The count of elements in the list.
* @param[in] packetId The packet ID of the unsubscribe packet.
* @param[in] remainingLength The remaining length of the unsubscribe packet.
*
* @return #MQTTSuccess or #MQTTSendFailed.
*/
static MQTTStatus_t sendUnsubscribeWithoutCopy( MQTTContext_t * pContext,
const MQTTSubscribeInfo_t * pSubscriptionList,
size_t subscriptionCount,
uint16_t packetId,
size_t remainingLength );
/**
* @brief Calculate the interval between two millisecond timestamps, including
* when the later value has overflowed.
*
* @note In C, the operands are promoted to signed integers in subtraction.
* Using this function avoids the need to cast the result of subtractions back
* to uint32_t.
*
* @param[in] later The later time stamp, in milliseconds.
* @param[in] start The earlier time stamp, in milliseconds.
*
* @return later - start.
*/
static uint32_t calculateElapsedTime( uint32_t later,
uint32_t start );
/**
* @brief Convert a byte indicating a publish ack type to an #MQTTPubAckType_t.
*
* @param[in] packetType First byte of fixed header.
*
* @return Type of ack.
*/
static MQTTPubAckType_t getAckFromPacketType( uint8_t packetType );
/**
* @brief Receive bytes into the network buffer.
*
* @param[in] pContext Initialized MQTT Context.
* @param[in] bytesToRecv Number of bytes to receive.
*
* @note This operation calls the transport receive function
* repeatedly to read bytes from the network until either:
* 1. The requested number of bytes @a bytesToRecv are read.
* OR
* 2. No data is received from the network for MQTT_RECV_POLLING_TIMEOUT_MS duration.
*
* OR
* 3. There is an error in reading from the network.
*
*
* @return Number of bytes received, or negative number on network error.
*/
static int32_t recvExact( const MQTTContext_t * pContext,
size_t bytesToRecv );
/**
* @brief Discard a packet from the transport interface.
*
* @param[in] pContext MQTT Connection context.
* @param[in] remainingLength Remaining length of the packet to dump.
* @param[in] timeoutMs Time remaining to discard the packet.
*
* @return #MQTTRecvFailed or #MQTTNoDataAvailable.
*/
static MQTTStatus_t discardPacket( const MQTTContext_t * pContext,
size_t remainingLength,
uint32_t timeoutMs );
/**
* @brief Discard a packet from the MQTT buffer and the transport interface.
*
* @param[in] pContext MQTT Connection context.
* @param[in] pPacketInfo Information struct of the packet to be discarded.
*
* @return #MQTTRecvFailed or #MQTTNoDataAvailable.
*/
static MQTTStatus_t discardStoredPacket( MQTTContext_t * pContext,
const MQTTPacketInfo_t * pPacketInfo );
/**
* @brief Receive a packet from the transport interface.
*
* @param[in] pContext MQTT Connection context.
* @param[in] incomingPacket packet struct with remaining length.
* @param[in] remainingTimeMs Time remaining to receive the packet.
*
* @return #MQTTSuccess or #MQTTRecvFailed.
*/
static MQTTStatus_t receivePacket( const MQTTContext_t * pContext,
MQTTPacketInfo_t incomingPacket,
uint32_t remainingTimeMs );
/**
* @brief Get the correct ack type to send.
*
* @param[in] state Current state of publish.
*
* @return Packet Type byte of PUBACK, PUBREC, PUBREL, or PUBCOMP if one of
* those should be sent, else 0.
*/
static uint8_t getAckTypeToSend( MQTTPublishState_t state );
/**
* @brief Send acks for received QoS 1/2 publishes.
*
* @param[in] pContext MQTT Connection context.
* @param[in] packetId packet ID of original PUBLISH.
* @param[in] publishState Current publish state in record.
*
* @return #MQTTSuccess, #MQTTIllegalState or #MQTTSendFailed.
*/
static MQTTStatus_t sendPublishAcks( MQTTContext_t * pContext,
uint16_t packetId,
MQTTPublishState_t publishState );
/**
* @brief Send a keep alive PINGREQ if the keep alive interval has elapsed.
*
* @param[in] pContext Initialized MQTT Context.
*
* @return #MQTTKeepAliveTimeout if a PINGRESP is not received in time,
* #MQTTSendFailed if the PINGREQ cannot be sent, or #MQTTSuccess.
*/
static MQTTStatus_t handleKeepAlive( MQTTContext_t * pContext );
/**
* @brief Handle received MQTT PUBLISH packet.
*
* @param[in] pContext MQTT Connection context.
* @param[in] pIncomingPacket Incoming packet.
*
* @return MQTTSuccess, MQTTIllegalState or deserialization error.
*/
static MQTTStatus_t handleIncomingPublish( MQTTContext_t * pContext,
MQTTPacketInfo_t * pIncomingPacket );
/**
* @brief Handle received MQTT publish acks.
*
* @param[in] pContext MQTT Connection context.
* @param[in] pIncomingPacket Incoming packet.
*
* @return MQTTSuccess, MQTTIllegalState, or deserialization error.
*/
static MQTTStatus_t handlePublishAcks( MQTTContext_t * pContext,
MQTTPacketInfo_t * pIncomingPacket );
/**
* @brief Handle received MQTT ack.
*
* @param[in] pContext MQTT Connection context.
* @param[in] pIncomingPacket Incoming packet.
* @param[in] manageKeepAlive Flag indicating if PINGRESPs should not be given
* to the application
*
* @return MQTTSuccess, MQTTIllegalState, or deserialization error.
*/
static MQTTStatus_t handleIncomingAck( MQTTContext_t * pContext,
MQTTPacketInfo_t * pIncomingPacket,
bool manageKeepAlive );
/**
* @brief Run a single iteration of the receive loop.
*
* @param[in] pContext MQTT Connection context.
* @param[in] manageKeepAlive Flag indicating if keep alive should be handled.
*
* @return #MQTTRecvFailed if a network error occurs during reception;
* #MQTTSendFailed if a network error occurs while sending an ACK or PINGREQ;
* #MQTTBadResponse if an invalid packet is received;
* #MQTTKeepAliveTimeout if the server has not sent a PINGRESP before
* #MQTT_PINGRESP_TIMEOUT_MS milliseconds;
* #MQTTIllegalState if an incoming QoS 1/2 publish or ack causes an
* invalid transition for the internal state machine;
* #MQTTSuccess on success.
*/
static MQTTStatus_t receiveSingleIteration( MQTTContext_t * pContext,
bool manageKeepAlive );
/**
* @brief Validates parameters of #MQTT_Subscribe or #MQTT_Unsubscribe.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] pSubscriptionList List of MQTT subscription info.
* @param[in] subscriptionCount The number of elements in pSubscriptionList.
* @param[in] packetId Packet identifier.
*
* @return #MQTTBadParameter if invalid parameters are passed;
* #MQTTSuccess otherwise.
*/
static MQTTStatus_t validateSubscribeUnsubscribeParams( const MQTTContext_t * pContext,
const MQTTSubscribeInfo_t * pSubscriptionList,
size_t subscriptionCount,
uint16_t packetId );
/**
* @brief Receives a CONNACK MQTT packet.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] timeoutMs Timeout for waiting for CONNACK packet.
* @param[in] cleanSession Clean session flag set by application.
* @param[out] pIncomingPacket List of MQTT subscription info.
* @param[out] pSessionPresent Whether a previous session was present.
* Only relevant if not establishing a clean session.
*
* @return #MQTTBadResponse if a bad response is received;
* #MQTTNoDataAvailable if no data available for transport recv;
* ##MQTTRecvFailed if transport recv failed;
* #MQTTSuccess otherwise.
*/
static MQTTStatus_t receiveConnack( const MQTTContext_t * pContext,
uint32_t timeoutMs,
bool cleanSession,
MQTTPacketInfo_t * pIncomingPacket,
bool * pSessionPresent );
/**
* @brief Resends pending acks for a re-established MQTT session, or
* clears existing state records for a clean session.
*
* @param[in] pContext Initialized MQTT context.
* @param[in] sessionPresent Session present flag received from the MQTT broker.
*
* @return #MQTTSendFailed if transport send during resend failed;
* #MQTTSuccess otherwise.
*/
static MQTTStatus_t handleSessionResumption( MQTTContext_t * pContext,
bool sessionPresent );
/**
* @brief Send the publish packet without copying the topic string and payload in
* the buffer.
*
* @brief param[in] pContext Initialized MQTT context.
* @brief param[in] pPublishInfo MQTT PUBLISH packet parameters.
* @brief param[in] pMqttHeader the serialized MQTT header with the header byte;
* the encoded length of the packet; and the encoded length of the topic string.
* @brief param[in] headerSize Size of the serialized PUBLISH header.
* @brief param[in] packetId Packet Id of the publish packet.
*
* @return #MQTTSendFailed if transport send during resend failed;
* #MQTTSuccess otherwise.
*/
static MQTTStatus_t sendPublishWithoutCopy( MQTTContext_t * pContext,
const MQTTPublishInfo_t * pPublishInfo,
const uint8_t * pMqttHeader,
size_t headerSize,
uint16_t packetId );
/**
* @brief Function to validate #MQTT_Publish parameters.
*
* @brief param[in] pContext Initialized MQTT context.
* @brief param[in] pPublishInfo MQTT PUBLISH packet parameters.
* @brief param[in] packetId Packet Id for the MQTT PUBLISH packet.
*
* @return #MQTTBadParameter if invalid parameters are passed;
* #MQTTSuccess otherwise.
*/
static MQTTStatus_t validatePublishParams( const MQTTContext_t * pContext,
const MQTTPublishInfo_t * pPublishInfo,
uint16_t packetId );
/**
* @brief Performs matching for special cases when a topic filter ends
* with a wildcard character.
*
* When the topic name has been consumed but there are remaining characters to
* to match in topic filter, this function handles the following 2 cases:
* - When the topic filter ends with "/+" or "/#" characters, but the topic
* name only ends with '/'.
* - When the topic filter ends with "/#" characters, but the topic name
* ends at the parent level.
*
* @note This function ASSUMES that the topic name been consumed in linear
* matching with the topic filer, but the topic filter has remaining characters
* to be matched.
*
* @param[in] pTopicFilter The topic filter containing the wildcard.
* @param[in] topicFilterLength Length of the topic filter being examined.
* @param[in] filterIndex Index of the topic filter being examined.
*
* @return Returns whether the topic filter and the topic name match.
*/
static bool matchEndWildcardsSpecialCases( const char * pTopicFilter,
uint16_t topicFilterLength,
uint16_t filterIndex );
/**
* @brief Attempt to match topic name with a topic filter starting with a wildcard.
*
* If the topic filter starts with a '+' (single-level) wildcard, the function
* advances the @a pNameIndex by a level in the topic name.
* If the topic filter starts with a '#' (multi-level) wildcard, the function
* concludes that both the topic name and topic filter match.
*
* @param[in] pTopicName The topic name to match.
* @param[in] topicNameLength Length of the topic name.
* @param[in] pTopicFilter The topic filter to match.
* @param[in] topicFilterLength Length of the topic filter.
* @param[in,out] pNameIndex Current index in the topic name being examined. It is
* advanced by one level for `+` wildcards.
* @param[in, out] pFilterIndex Current index in the topic filter being examined.
* It is advanced to position of '/' level separator for '+' wildcard.
* @param[out] pMatch Whether the topic filter and topic name match.
*
* @return `true` if the caller of this function should exit; `false` if the
* caller should continue parsing the topics.
*/
static bool matchWildcards( const char * pTopicName,
uint16_t topicNameLength,
const char * pTopicFilter,
uint16_t topicFilterLength,
uint16_t * pNameIndex,
uint16_t * pFilterIndex,
bool * pMatch );
/**
* @brief Match a topic name and topic filter allowing the use of wildcards.
*
* @param[in] pTopicName The topic name to check.
* @param[in] topicNameLength Length of the topic name.
* @param[in] pTopicFilter The topic filter to check.
* @param[in] topicFilterLength Length of topic filter.
*
* @return `true` if the topic name and topic filter match; `false` otherwise.
*/
static bool matchTopicFilter( const char * pTopicName,
uint16_t topicNameLength,
const char * pTopicFilter,
uint16_t topicFilterLength );
/*-----------------------------------------------------------*/
static bool matchEndWildcardsSpecialCases( const char * pTopicFilter,
uint16_t topicFilterLength,
uint16_t filterIndex )
{
bool matchFound = false;
assert( pTopicFilter != NULL );
assert( topicFilterLength != 0U );
/* Check if the topic filter has 2 remaining characters and it ends in
* "/#". This check handles the case to match filter "sport/#" with topic
* "sport". The reason is that the '#' wildcard represents the parent and
* any number of child levels in the topic name.*/
if( ( topicFilterLength >= 3U ) &&
( filterIndex == ( topicFilterLength - 3U ) ) &&
( pTopicFilter[ filterIndex + 1U ] == '/' ) &&
( pTopicFilter[ filterIndex + 2U ] == '#' ) )
{
matchFound = true;
}
/* Check if the next character is "#" or "+" and the topic filter ends in
* "/#" or "/+". This check handles the cases to match:
*
* - Topic filter "sport/+" with topic "sport/".
* - Topic filter "sport/#" with topic "sport/".
*/
if( ( filterIndex == ( topicFilterLength - 2U ) ) &&
( pTopicFilter[ filterIndex ] == '/' ) )
{
/* Check that the last character is a wildcard. */
matchFound = ( pTopicFilter[ filterIndex + 1U ] == '+' ) ||
( pTopicFilter[ filterIndex + 1U ] == '#' );
}
return matchFound;
}
/*-----------------------------------------------------------*/
static bool matchWildcards( const char * pTopicName,
uint16_t topicNameLength,
const char * pTopicFilter,
uint16_t topicFilterLength,
uint16_t * pNameIndex,
uint16_t * pFilterIndex,
bool * pMatch )
{
bool shouldStopMatching = false;
bool locationIsValidForWildcard;
assert( pTopicName != NULL );
assert( topicNameLength != 0U );
assert( pTopicFilter != NULL );
assert( topicFilterLength != 0U );
assert( pNameIndex != NULL );
assert( pFilterIndex != NULL );
assert( pMatch != NULL );
/* Wild card in a topic filter is only valid either at the starting position
* or when it is preceded by a '/'.*/
locationIsValidForWildcard = ( *pFilterIndex == 0u ) ||
( pTopicFilter[ *pFilterIndex - 1U ] == '/' );
if( ( pTopicFilter[ *pFilterIndex ] == '+' ) && ( locationIsValidForWildcard == true ) )
{
bool nextLevelExistsInTopicName = false;
bool nextLevelExistsinTopicFilter = false;
/* Move topic name index to the end of the current level. The end of the
* current level is identified by the last character before the next level
* separator '/'. */
while( *pNameIndex < topicNameLength )
{
/* Exit the loop if we hit the level separator. */
if( pTopicName[ *pNameIndex ] == '/' )
{
nextLevelExistsInTopicName = true;
break;
}
( *pNameIndex )++;
}
/* Determine if the topic filter contains a child level after the current level
* represented by the '+' wildcard. */
if( ( *pFilterIndex < ( topicFilterLength - 1U ) ) &&
( pTopicFilter[ *pFilterIndex + 1U ] == '/' ) )
{
nextLevelExistsinTopicFilter = true;
}
/* If the topic name contains a child level but the topic filter ends at
* the current level, then there does not exist a match. */
if( ( nextLevelExistsInTopicName == true ) &&
( nextLevelExistsinTopicFilter == false ) )
{
*pMatch = false;
shouldStopMatching = true;
}
/* If the topic name and topic filter have child levels, then advance the
* filter index to the level separator in the topic filter, so that match
* can be performed in the next level.
* Note: The name index already points to the level separator in the topic
* name. */
else if( nextLevelExistsInTopicName == true )
{
( *pFilterIndex )++;
}
else
{
/* If we have reached here, the the loop terminated on the
* ( *pNameIndex < topicNameLength) condition, which means that have
* reached past the end of the topic name, and thus, we decrement the
* index to the last character in the topic name.*/
( *pNameIndex )--;
}
}
/* '#' matches everything remaining in the topic name. It must be the
* last character in a topic filter. */
else if( ( pTopicFilter[ *pFilterIndex ] == '#' ) &&
( *pFilterIndex == ( topicFilterLength - 1U ) ) &&
( locationIsValidForWildcard == true ) )
{
/* Subsequent characters don't need to be checked for the
* multi-level wildcard. */
*pMatch = true;
shouldStopMatching = true;
}
else
{
/* Any character mismatch other than '+' or '#' means the topic
* name does not match the topic filter. */
*pMatch = false;
shouldStopMatching = true;
}
return shouldStopMatching;
}
/*-----------------------------------------------------------*/
static bool matchTopicFilter( const char * pTopicName,
uint16_t topicNameLength,
const char * pTopicFilter,
uint16_t topicFilterLength )
{
bool matchFound = false, shouldStopMatching = false;
uint16_t nameIndex = 0, filterIndex = 0;
assert( pTopicName != NULL );
assert( topicNameLength != 0 );
assert( pTopicFilter != NULL );
assert( topicFilterLength != 0 );
while( ( nameIndex < topicNameLength ) && ( filterIndex < topicFilterLength ) )
{
/* Check if the character in the topic name matches the corresponding
* character in the topic filter string. */
if( pTopicName[ nameIndex ] == pTopicFilter[ filterIndex ] )
{
/* If the topic name has been consumed but the topic filter has not
* been consumed, match for special cases when the topic filter ends
* with wildcard character. */
if( nameIndex == ( topicNameLength - 1U ) )
{
matchFound = matchEndWildcardsSpecialCases( pTopicFilter,
topicFilterLength,
filterIndex );
}
}
else
{
/* Check for matching wildcards. */
shouldStopMatching = matchWildcards( pTopicName,
topicNameLength,
pTopicFilter,
topicFilterLength,
&nameIndex,
&filterIndex,
&matchFound );
}
if( ( matchFound == true ) || ( shouldStopMatching == true ) )
{
break;
}
/* Increment indexes. */
nameIndex++;
filterIndex++;
}
if( matchFound == false )
{
/* If the end of both strings has been reached, they match. This represents the
* case when the topic filter contains the '+' wildcard at a non-starting position.
* For example, when matching either of "sport/+/player" OR "sport/hockey/+" topic
* filters with "sport/hockey/player" topic name. */
matchFound = ( nameIndex == topicNameLength ) &&
( filterIndex == topicFilterLength );
}
return matchFound;
}
/*-----------------------------------------------------------*/
static int32_t sendMessageVector( MQTTContext_t * pContext,
TransportOutVector_t * pIoVec,
size_t ioVecCount )
{
int32_t sendResult;
uint32_t startTime;
TransportOutVector_t * pIoVectIterator;
size_t vectorsToBeSent = ioVecCount;
size_t bytesToSend = 0U;
int32_t bytesSentOrError = 0;
assert( pContext != NULL );
assert( pIoVec != NULL );
assert( pContext->getTime != NULL );
/* Send must always be defined */
assert( pContext->transportInterface.send != NULL );
/* Count the total number of bytes to be sent as outlined in the vector. */
for( pIoVectIterator = pIoVec; pIoVectIterator <= &( pIoVec[ ioVecCount - 1U ] ); pIoVectIterator++ )
{
bytesToSend += pIoVectIterator->iov_len;
}
/* Reset the iterator to point to the first entry in the array. */
pIoVectIterator = pIoVec;
/* Note the start time. */
startTime = pContext->getTime();
while( ( bytesSentOrError < ( int32_t ) bytesToSend ) && ( bytesSentOrError >= 0 ) )
{
if( pContext->transportInterface.writev != NULL )
{
sendResult = pContext->transportInterface.writev( pContext->transportInterface.pNetworkContext,
pIoVectIterator,
vectorsToBeSent );
}
else
{
sendResult = pContext->transportInterface.send( pContext->transportInterface.pNetworkContext,
pIoVectIterator->iov_base,
pIoVectIterator->iov_len );
}
if( sendResult > 0 )
{
/* It is a bug in the application's transport send implementation if
* more bytes than expected are sent. */
assert( sendResult <= ( ( int32_t ) bytesToSend - bytesSentOrError ) );
bytesSentOrError += sendResult;
/* Set last transmission time. */
pContext->lastPacketTxTime = pContext->getTime();
LogDebug( ( "sendMessageVector: Bytes Sent=%ld, Bytes Remaining=%lu",
( long int ) sendResult,
( unsigned long ) ( bytesToSend - ( size_t ) bytesSentOrError ) ) );
}
else if( sendResult < 0 )
{
bytesSentOrError = sendResult;
LogError( ( "sendMessageVector: Unable to send packet: Network Error." ) );
}
else
{
/* MISRA Empty body */
}
/* Check for timeout. */
if( calculateElapsedTime( pContext->getTime(), startTime ) > MQTT_SEND_TIMEOUT_MS )
{
LogError( ( "sendMessageVector: Unable to send packet: Timed out." ) );
break;
}
/* Update the send pointer to the correct vector and offset. */
while( ( pIoVectIterator <= &( pIoVec[ ioVecCount - 1U ] ) ) &&
( sendResult >= ( int32_t ) pIoVectIterator->iov_len ) )
{
sendResult -= ( int32_t ) pIoVectIterator->iov_len;
pIoVectIterator++;
/* Update the number of vector which are yet to be sent. */
vectorsToBeSent--;
}
/* Some of the bytes from this vector were sent as well, update the length
* and the pointer to data in this vector. */
if( ( sendResult > 0 ) &&
( pIoVectIterator <= &( pIoVec[ ioVecCount - 1U ] ) ) )
{
pIoVectIterator->iov_base = ( const void * ) &( ( ( const uint8_t * ) pIoVectIterator->iov_base )[ sendResult ] );
pIoVectIterator->iov_len -= ( size_t ) sendResult;
}
}
return bytesSentOrError;
}
static int32_t sendBuffer( MQTTContext_t * pContext,
const uint8_t * pBufferToSend,
size_t bytesToSend )
{
int32_t sendResult;
uint32_t timeoutMs;
int32_t bytesSentOrError = 0;
const uint8_t * pIndex = pBufferToSend;
assert( pContext != NULL );
assert( pContext->getTime != NULL );
assert( pContext->transportInterface.send != NULL );
assert( pIndex != NULL );
/* Set the timeout. */
timeoutMs = pContext->getTime() + MQTT_SEND_TIMEOUT_MS;
while( ( bytesSentOrError < ( int32_t ) bytesToSend ) && ( bytesSentOrError >= 0 ) )
{
sendResult = pContext->transportInterface.send( pContext->transportInterface.pNetworkContext,
pIndex,
bytesToSend - ( size_t ) bytesSentOrError );
if( sendResult > 0 )
{
/* It is a bug in the application's transport send implementation if
* more bytes than expected are sent. */
assert( sendResult <= ( ( int32_t ) bytesToSend - bytesSentOrError ) );
bytesSentOrError += sendResult;
pIndex = &pIndex[ sendResult ];
/* Set last transmission time. */
pContext->lastPacketTxTime = pContext->getTime();
LogDebug( ( "sendBuffer: Bytes Sent=%ld, Bytes Remaining=%lu",
( long int ) sendResult,
( unsigned long ) ( bytesToSend - ( size_t ) bytesSentOrError ) ) );
}
else if( sendResult < 0 )
{
bytesSentOrError = sendResult;
LogError( ( "sendBuffer: Unable to send packet: Network Error." ) );
}
else
{
/* MISRA Empty body */
}
/* Check for timeout. */
if( pContext->getTime() >= timeoutMs )
{
LogError( ( "sendBuffer: Unable to send packet: Timed out." ) );
break;
}
}
return bytesSentOrError;
}
/*-----------------------------------------------------------*/
static uint32_t calculateElapsedTime( uint32_t later,
uint32_t start )
{
return later - start;
}
/*-----------------------------------------------------------*/
static MQTTPubAckType_t getAckFromPacketType( uint8_t packetType )
{
MQTTPubAckType_t ackType = MQTTPuback;
switch( packetType )
{
case MQTT_PACKET_TYPE_PUBACK:
ackType = MQTTPuback;
break;
case MQTT_PACKET_TYPE_PUBREC:
ackType = MQTTPubrec;
break;
case MQTT_PACKET_TYPE_PUBREL:
ackType = MQTTPubrel;
break;
case MQTT_PACKET_TYPE_PUBCOMP:
default:
/* This function is only called after checking the type is one of
* the above four values, so packet type must be PUBCOMP here. */
assert( packetType == MQTT_PACKET_TYPE_PUBCOMP );
ackType = MQTTPubcomp;
break;
}
return ackType;
}
/*-----------------------------------------------------------*/
static int32_t recvExact( const MQTTContext_t * pContext,
size_t bytesToRecv )
{
uint8_t * pIndex = NULL;
size_t bytesRemaining = bytesToRecv;
int32_t totalBytesRecvd = 0, bytesRecvd;
uint32_t lastDataRecvTimeMs = 0U, timeSinceLastRecvMs = 0U;
TransportRecv_t recvFunc = NULL;
MQTTGetCurrentTimeFunc_t getTimeStampMs = NULL;
bool receiveError = false;
assert( pContext != NULL );
assert( bytesToRecv <= pContext->networkBuffer.size );
assert( pContext->getTime != NULL );
assert( pContext->transportInterface.recv != NULL );
assert( pContext->networkBuffer.pBuffer != NULL );
pIndex = pContext->networkBuffer.pBuffer;
recvFunc = pContext->transportInterface.recv;
getTimeStampMs = pContext->getTime;
/* Part of the MQTT packet has been read before calling this function. */
lastDataRecvTimeMs = getTimeStampMs();
while( ( bytesRemaining > 0U ) && ( receiveError == false ) )
{
bytesRecvd = recvFunc( pContext->transportInterface.pNetworkContext,
pIndex,
bytesRemaining );
if( bytesRecvd < 0 )
{
LogError( ( "Network error while receiving packet: ReturnCode=%ld.",
( long int ) bytesRecvd ) );