-
Notifications
You must be signed in to change notification settings - Fork 737
/
Copy pathiothubtransport_mqtt_common.c
4134 lines (3826 loc) · 156 KB
/
iothubtransport_mqtt_common.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
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
#include <stdlib.h>
#include <ctype.h>
#include "azure_c_shared_utility/optimize_size.h"
#include "azure_c_shared_utility/gballoc.h"
#include "azure_c_shared_utility/xlogging.h"
#include "azure_c_shared_utility/strings.h"
#include "azure_c_shared_utility/doublylinkedlist.h"
#include "azure_c_shared_utility/crt_abstractions.h"
#include "azure_c_shared_utility/agenttime.h"
#include "azure_c_shared_utility/threadapi.h"
#include "azure_c_shared_utility/sastoken.h"
#include "azure_c_shared_utility/tickcounter.h"
#include "azure_c_shared_utility/tlsio.h"
#include "azure_c_shared_utility/platform.h"
#include "azure_c_shared_utility/safe_math.h"
#include "azure_c_shared_utility/string_tokenizer.h"
#include "azure_c_shared_utility/shared_util_options.h"
#include "azure_c_shared_utility/urlencode.h"
#include "internal/iothub_client_private.h"
#include "internal/iothub_client_retry_control.h"
#include "internal/iothub_transport_ll_private.h"
#include "internal/iothubtransport_mqtt_common.h"
#include "internal/iothubtransport.h"
#include "internal/iothub_internal_consts.h"
#include "internal/iothub_message_private.h"
#include "azure_umqtt_c/mqtt_client.h"
#include "iothub_message.h"
#include "iothub_client_options.h"
#include "iothub_client_version.h"
#include <stdarg.h>
#include <stdio.h>
#include <limits.h>
#include <inttypes.h>
#define SAS_REFRESH_MULTIPLIER .8
#define EPOCH_TIME_T_VALUE 0
#define DEFAULT_MQTT_KEEPALIVE 4*60 // 4 min
#define DEFAULT_CONNACK_TIMEOUT 30 // 30 seconds
#define BUILD_CONFIG_USERNAME 24
#define SAS_TOKEN_DEFAULT_LEN 10
#define RESEND_TIMEOUT_VALUE_MIN 1*60
#define TELEMETRY_MSG_TIMEOUT_MIN 2*60
#define MQTT_MESSAGE_DUP_FLAG_TRUE true
#define MQTT_MESSAGE_DUP_FLAG_FALSE false
#define DEFAULT_CONNECTION_INTERVAL 30
#define FAILED_CONN_BACKOFF_VALUE 5
#define STATUS_CODE_FAILURE_VALUE 500
#define STATUS_CODE_TIMEOUT_VALUE 408
#define DEFAULT_RETRY_POLICY IOTHUB_CLIENT_RETRY_EXPONENTIAL_BACKOFF_WITH_JITTER
#define DEFAULT_RETRY_TIMEOUT_IN_SECONDS 0
#define MAX_DISCONNECT_VALUE 50
#define ON_DEMAND_GET_TWIN_REQUEST_TIMEOUT_SECS 60
#define TWIN_REPORT_UPDATE_TIMEOUT_SECS (60*5)
#define MESSAGE_REPUBLISH_TIMEOUT_SECS 3
static const char TOPIC_DEVICE_TWIN_PREFIX[] = "$iothub/twin";
static const char TOPIC_DEVICE_METHOD_PREFIX[] = "$iothub/methods";
static const char* TOPIC_GET_DESIRED_STATE = "$iothub/twin/res/#";
static const char* TOPIC_NOTIFICATION_STATE = "$iothub/twin/PATCH/properties/desired/#";
static const char* TOPIC_DEVICE_MSG = "devices/%s/messages/devicebound/#";
static const char* TOPIC_DEVICE_EVENTS = "devices/%s/messages/events/";
static const char* TOPIC_MODULE_EVENTS = "devices/%s/modules/%s/messages/events/";
static const char* TOPIC_INPUT_QUEUE_NAME = "devices/%s/modules/%s/#";
static const char* TOPIC_DEVICE_METHOD_SUBSCRIBE = "$iothub/methods/POST/#";
static const char* PROPERTY_SEPARATOR = "&";
static const char PROPERTY_EQUALS = '=';
static const char TOPIC_SLASH = '/';
static const char* REPORTED_PROPERTIES_TOPIC = "$iothub/twin/PATCH/properties/reported/?$rid=%"PRIu16;
static const char* GET_PROPERTIES_TOPIC = "$iothub/twin/GET/?$rid=%"PRIu16;
static const char* DEVICE_METHOD_RESPONSE_TOPIC = "$iothub/methods/res/%d/?$rid=%s";
#ifdef RUN_SFC_TESTS
static const char* FAULT_OPERATION_TYPE = "AzIoTHub_FaultOperationType";
#endif //RUN_SFC_TESTS
static const char SYS_TOPIC_STRING_FORMAT[] = "%s%%24.%s=%s";
static const char REQUEST_ID_PROPERTY[] = "?$rid=";
static size_t REQUEST_ID_PROPERTY_LEN = sizeof(REQUEST_ID_PROPERTY) - 1;
#define SYS_PROP_MESSAGE_ID "mid"
#define SYS_PROP_MESSAGE_CREATION_TIME_UTC "ctime"
#define SYS_PROP_USER_ID "uid"
#define SYS_PROP_CORRELATION_ID "cid"
#define SYS_PROP_CONTENT_TYPE "ct"
#define SYS_PROP_CONTENT_ENCODING "ce"
#define SYS_PROP_DIAGNOSTIC_ID "diagid"
#define SYS_PROP_DIAGNOSTIC_CONTEXT "diagctx"
#define SYS_PROP_CONNECTION_DEVICE_ID "cdid"
#define SYS_PROP_CONNECTION_MODULE_ID "cmid"
#define SYS_PROP_ON "on"
#define SYS_PROP_EXP "exp"
#define SYS_PROP_TO "to"
#define SYS_COMPONENT_NAME "sub"
static const char* DIAGNOSTIC_CONTEXT_CREATION_TIME_UTC_PROPERTY = "creationtimeutc";
static const char DT_MODEL_ID_TOKEN[] = "model-id";
static const char DEFAULT_IOTHUB_PRODUCT_IDENTIFIER[] = CLIENT_DEVICE_TYPE_PREFIX "/" IOTHUB_SDK_VERSION;
#define TOLOWER(c) (((c>='A') && (c<='Z'))?c-'A'+'a':c)
#define UNSUBSCRIBE_FROM_TOPIC 0x0000
#define SUBSCRIBE_GET_REPORTED_STATE_TOPIC 0x0001
#define SUBSCRIBE_NOTIFICATION_STATE_TOPIC 0x0002
#define SUBSCRIBE_TELEMETRY_TOPIC 0x0004
#define SUBSCRIBE_DEVICE_METHOD_TOPIC 0x0008
#define SUBSCRIBE_INPUT_QUEUE_TOPIC 0x0010
#define SUBSCRIBE_TOPIC_COUNT 5
MU_DEFINE_ENUM_STRINGS_WITHOUT_INVALID(MQTT_CLIENT_EVENT_ERROR, MQTT_CLIENT_EVENT_ERROR_VALUES);
// "System" property that a given MQTT property maps to, which can be used when building IOTHUB_MESSAGE_HANDLE that
// we will pass into application callback.
typedef enum IOTHUB_SYSTEM_PROPERTY_TYPE_TAG
{
// Property that the application custom defined and will go into the propertyMap of IOTHUB_MESSAGE_HANDLE
IOTHUB_SYSTEM_PROPERTY_TYPE_APPLICATION_CUSTOM,
// A "system" property we should silently ignore. There are many %24.<property> that previous versions of the
// SDK parsed out but did NOT add to the application custom list. To maintain backward compat, and because
// the %24 implies a system property, we will parse these out but otherwise ignore them.
IOTHUB_SYSTEM_PROPERTY_TYPE_SILENTLY_IGNORE,
// Properties from this point on map to system properties that have accessors in IOTHUB_MESSAGE_HANDLE
IOTHUB_SYSTEM_PROPERTY_TYPE_MESSAGE_ID,
IOTHUB_SYSTEM_PROPERTY_TYPE_CREATION_TIME,
IOTHUB_SYSTEM_PROPERTY_TYPE_CONNECTION_DEVICE_ID,
IOTHUB_SYSTEM_PROPERTY_TYPE_CONNECTION_MODULE_ID,
IOTHUB_SYSTEM_PROPERTY_TYPE_CORRELATION_ID,
IOTHUB_SYSTEM_PROPERTY_TYPE_MESSAGE_USER_ID,
IOTHUB_SYSTEM_PROPERTY_TYPE_CONTENT_TYPE,
IOTHUB_SYSTEM_PROPERTY_TYPE_CONTENT_ENCODING
} IOTHUB_SYSTEM_PROPERTY_TYPE;
typedef struct SYSTEM_PROPERTY_INFO_TAG
{
const char* propName;
IOTHUB_SYSTEM_PROPERTY_TYPE propertyType;
} SYSTEM_PROPERTY_INFO;
// Encoding of a $ followed by ., which is how MQTT "system" properties are sent to us
#define URL_ENCODED_PERCENT_SIGN_DOT "%24."
const size_t URL_ENCODED_PERCENT_SIGN_DOT_LEN = sizeof(URL_ENCODED_PERCENT_SIGN_DOT) / sizeof(URL_ENCODED_PERCENT_SIGN_DOT[0]) - 1;
// Helper to build up system properties, which MUST start with "%24." string
#define DEFINE_MQTT_SYSTEM_PROPERTY(token) URL_ENCODED_PERCENT_SIGN_DOT token
static SYSTEM_PROPERTY_INFO sysPropList[] = {
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_MESSAGE_ID), IOTHUB_SYSTEM_PROPERTY_TYPE_MESSAGE_ID},
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_USER_ID), IOTHUB_SYSTEM_PROPERTY_TYPE_MESSAGE_USER_ID },
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_CORRELATION_ID), IOTHUB_SYSTEM_PROPERTY_TYPE_CORRELATION_ID },
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_CONTENT_TYPE), IOTHUB_SYSTEM_PROPERTY_TYPE_CONTENT_TYPE },
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_CONTENT_ENCODING), IOTHUB_SYSTEM_PROPERTY_TYPE_CONTENT_ENCODING },
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_CONNECTION_DEVICE_ID), IOTHUB_SYSTEM_PROPERTY_TYPE_CONNECTION_DEVICE_ID},
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_CONNECTION_MODULE_ID), IOTHUB_SYSTEM_PROPERTY_TYPE_CONNECTION_MODULE_ID },
// "System" properties the SDK previously ignored and will continue to do so for compat.
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_MESSAGE_CREATION_TIME_UTC), IOTHUB_SYSTEM_PROPERTY_TYPE_CREATION_TIME},
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_ON), IOTHUB_SYSTEM_PROPERTY_TYPE_SILENTLY_IGNORE },
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_EXP), IOTHUB_SYSTEM_PROPERTY_TYPE_SILENTLY_IGNORE },
{ DEFINE_MQTT_SYSTEM_PROPERTY(SYS_PROP_TO), IOTHUB_SYSTEM_PROPERTY_TYPE_SILENTLY_IGNORE },
// even though they don't start with %24, previous versions of SDK parsed and ignored these. Keep same behavior.
{ "devices/", IOTHUB_SYSTEM_PROPERTY_TYPE_SILENTLY_IGNORE },
{ "iothub-operation", IOTHUB_SYSTEM_PROPERTY_TYPE_SILENTLY_IGNORE },
{ "iothub-ack" , IOTHUB_SYSTEM_PROPERTY_TYPE_SILENTLY_IGNORE }
};
static const size_t sysPropListLength = sizeof(sysPropList) / sizeof(sysPropList[0]);
typedef enum DEVICE_TWIN_MSG_TYPE_TAG
{
REPORTED_STATE,
RETRIEVE_PROPERTIES
} DEVICE_TWIN_MSG_TYPE;
typedef enum MQTT_TRANSPORT_CREDENTIAL_TYPE_TAG
{
CREDENTIAL_NOT_BUILD,
X509,
SAS_TOKEN_FROM_USER,
DEVICE_KEY,
} MQTT_TRANSPORT_CREDENTIAL_TYPE;
typedef enum MQTT_CLIENT_STATUS_TAG
{
MQTT_CLIENT_STATUS_NOT_CONNECTED,
MQTT_CLIENT_STATUS_CONNECTING,
MQTT_CLIENT_STATUS_CONNECTED,
MQTT_CLIENT_STATUS_PENDING_CLOSE,
MQTT_CLIENT_STATUS_EXECUTE_DISCONNECT
} MQTT_CLIENT_STATUS;
typedef struct MQTTTRANSPORT_HANDLE_DATA_TAG
{
// Topic control
STRING_HANDLE topic_MqttEvent;
STRING_HANDLE topic_MqttMessage;
STRING_HANDLE topic_GetState;
STRING_HANDLE topic_NotifyState;
STRING_HANDLE topic_InputQueue;
STRING_HANDLE topic_DeviceMethods;
uint32_t topics_ToSubscribe;
// Connection related constants
STRING_HANDLE hostAddress;
STRING_HANDLE device_id;
STRING_HANDLE module_id;
STRING_HANDLE devicesAndModulesPath;
int portNum;
// conn_attempted indicates whether a connection has *ever* been attempted on the lifetime
// of this handle. Even if a given xio transport is added/removed, this always stays true.
bool conn_attempted;
MQTT_GET_IO_TRANSPORT get_io_transport;
// The current mqtt iothub implementation requires that the hub name and the domain suffix be passed as the first of a series of segments
// passed through the username portion of the connection frame.
// The second segment will contain the device id. The two segments are delimited by a "/".
// The first segment can be a maximum 256 characters.
// The second segment can be a maximum 128 characters.
// With the / delimeter you have 384 chars (Plus a terminator of 0).
STRING_HANDLE configPassedThroughUsername;
// Protocol
MQTT_CLIENT_HANDLE mqttClient;
XIO_HANDLE xioTransport;
// Session - connection
uint16_t packetId;
uint16_t twin_resp_packet_id;
// Connection state control
bool isRegistered;
MQTT_CLIENT_STATUS mqttClientStatus;
bool isDestroyCalled;
bool isRetryExpiredCallbackCalled;
bool device_twin_get_sent;
bool twin_resp_sub_recv;
bool isRecoverableError;
uint16_t keepAliveValue;
uint16_t connect_timeout_in_sec;
tickcounter_ms_t mqtt_connect_time;
size_t connectFailCount;
tickcounter_ms_t connectTick;
bool log_trace;
bool raw_trace;
TICK_COUNTER_HANDLE msgTickCounter;
OPTIONHANDLER_HANDLE saved_tls_options; // Here are the options from the xio layer if any is saved.
// Internal lists for message tracking
PDLIST_ENTRY waitingToSend;
DLIST_ENTRY ack_waiting_queue;
DLIST_ENTRY pending_get_twin_queue;
// Message tracking
CONTROL_PACKET_TYPE currPacketState;
// Telemetry specific
DLIST_ENTRY telemetry_waitingForAck;
bool auto_url_encode_decode;
// Controls frequency of reconnection logic.
RETRY_CONTROL_HANDLE retry_control_handle;
// Auth module used to generating handle authorization
// with either SAS Token, x509 Certs, and Device SAS Token
IOTHUB_AUTHORIZATION_HANDLE authorization_module;
TRANSPORT_CALLBACKS_INFO transport_callbacks;
void* transport_ctx;
char* http_proxy_hostname;
int http_proxy_port;
char* http_proxy_username;
char* http_proxy_password;
bool isConnectUsernameSet;
int disconnect_recv_flag;
} MQTTTRANSPORT_HANDLE_DATA, *PMQTTTRANSPORT_HANDLE_DATA;
typedef struct MQTT_DEVICE_TWIN_ITEM_TAG
{
tickcounter_ms_t msgCreationTime;
tickcounter_ms_t msgPublishTime;
size_t retryCount;
uint16_t packet_id;
uint32_t iothub_msg_id;
IOTHUB_DEVICE_TWIN* device_twin_data;
DEVICE_TWIN_MSG_TYPE device_twin_msg_type;
DLIST_ENTRY entry;
IOTHUB_CLIENT_DEVICE_TWIN_CALLBACK userCallback;
void* userContext;
} MQTT_DEVICE_TWIN_ITEM;
typedef struct MQTT_MESSAGE_DETAILS_LIST_TAG
{
tickcounter_ms_t msgCreationTime;
tickcounter_ms_t msgPublishTime;
IOTHUB_MESSAGE_LIST* iotHubMessageEntry;
void* context;
uint16_t packet_id;
DLIST_ENTRY entry;
} MQTT_MESSAGE_DETAILS_LIST, *PMQTT_MESSAGE_DETAILS_LIST;
typedef struct DEVICE_METHOD_INFO_TAG
{
STRING_HANDLE request_id;
} DEVICE_METHOD_INFO;
typedef struct MESSAGE_DISPOSITION_CONTEXT_TAG
{
uint16_t packet_id;
QOS_VALUE qos_value;
} MESSAGE_DISPOSITION_CONTEXT;
//
// InternStrnicmp implements strnicmp. strnicmp isn't available on all platforms.
//
static int InternStrnicmp(const char* s1, const char* s2, size_t n)
{
int result;
if (s1 == NULL)
{
result = -1;
}
else if (s2 == NULL)
{
result = 1;
}
else
{
result = 0;
while (n-- && result == 0)
{
if (*s1 == 0) result = -1;
else if (*s2 == 0) result = 1;
else
{
result = TOLOWER(*s1) - TOLOWER(*s2);
++s1;
++s2;
}
}
}
return result;
}
//
// freeProxyData free()'s and resets proxy related settings of the mqtt_transport_instance.
//
static void freeProxyData(MQTTTRANSPORT_HANDLE_DATA* transport_data)
{
if (transport_data->http_proxy_hostname != NULL)
{
free(transport_data->http_proxy_hostname);
transport_data->http_proxy_hostname = NULL;
}
if (transport_data->http_proxy_username != NULL)
{
free(transport_data->http_proxy_username);
transport_data->http_proxy_username = NULL;
}
if (transport_data->http_proxy_password != NULL)
{
free(transport_data->http_proxy_password);
transport_data->http_proxy_password = NULL;
}
}
//
// DestroyXioTransport frees resources associated with MQTT handle and resets appropriate state
//
static void DestroyXioTransport(PMQTTTRANSPORT_HANDLE_DATA transport_data)
{
mqtt_client_clear_xio(transport_data->mqttClient);
xio_destroy(transport_data->xioTransport);
transport_data->xioTransport = NULL;
}
//
// setSavedTlsOptions saves off TLS specific options. This is used
// so that during a disconnection, we have these values available for next reconnection.
//
static void setSavedTlsOptions(PMQTTTRANSPORT_HANDLE_DATA transport, OPTIONHANDLER_HANDLE new_options)
{
if (transport->saved_tls_options != NULL)
{
OptionHandler_Destroy(transport->saved_tls_options);
}
transport->saved_tls_options = new_options;
}
//
// freeTransportHandleData free()'s 'the transport_data and all members that were allocated by it.
//
static void freeTransportHandleData(MQTTTRANSPORT_HANDLE_DATA* transport_data)
{
if (transport_data->mqttClient != NULL)
{
mqtt_client_deinit(transport_data->mqttClient);
transport_data->mqttClient = NULL;
}
if (transport_data->retry_control_handle != NULL)
{
retry_control_destroy(transport_data->retry_control_handle);
}
setSavedTlsOptions(transport_data, NULL);
tickcounter_destroy(transport_data->msgTickCounter);
freeProxyData(transport_data);
STRING_delete(transport_data->devicesAndModulesPath);
STRING_delete(transport_data->topic_MqttEvent);
STRING_delete(transport_data->topic_MqttMessage);
STRING_delete(transport_data->device_id);
STRING_delete(transport_data->module_id);
STRING_delete(transport_data->hostAddress);
STRING_delete(transport_data->configPassedThroughUsername);
STRING_delete(transport_data->topic_GetState);
STRING_delete(transport_data->topic_NotifyState);
STRING_delete(transport_data->topic_DeviceMethods);
STRING_delete(transport_data->topic_InputQueue);
DestroyXioTransport(transport_data);
free(transport_data);
}
//
// getNextPacketId gets the next Packet Id to use and increments internal counter.
//
static uint16_t getNextPacketId(PMQTTTRANSPORT_HANDLE_DATA transport_data)
{
if (transport_data->packetId + 1 >= USHRT_MAX)
{
transport_data->packetId = 1;
}
else
{
transport_data->packetId++;
}
return transport_data->packetId;
}
#ifndef NO_LOGGING
//
// retrieveMqttReturnCodes returns friendly representation of connection code for logging purposes.
//
static const char* retrieveMqttReturnCodes(CONNECT_RETURN_CODE rtn_code)
{
switch (rtn_code)
{
case CONNECTION_ACCEPTED:
return "Accepted";
case CONN_REFUSED_UNACCEPTABLE_VERSION:
return "Unacceptable Version";
case CONN_REFUSED_ID_REJECTED:
return "Id Rejected";
case CONN_REFUSED_SERVER_UNAVAIL:
return "Server Unavailable";
case CONN_REFUSED_BAD_USERNAME_PASSWORD:
return "Bad Username/Password";
case CONN_REFUSED_NOT_AUTHORIZED:
return "Not Authorized";
case CONN_REFUSED_UNKNOWN:
default:
return "Unknown";
}
}
#endif // NO_LOGGING
//
// retrieveDeviceMethodRidInfo parses an incoming MQTT topic for a device method and retrieves the request ID it specifies.
//
static int retrieveDeviceMethodRidInfo(const char* resp_topic, STRING_HANDLE method_name, STRING_HANDLE request_id)
{
int result;
STRING_TOKENIZER_HANDLE token_handle = STRING_TOKENIZER_create_from_char(resp_topic);
if (token_handle == NULL)
{
LogError("Failed creating token from device twin topic.");
result = MU_FAILURE;
}
else
{
STRING_HANDLE token_value;
if ((token_value = STRING_new()) == NULL)
{
LogError("Failed allocating new string .");
result = MU_FAILURE;
}
else
{
size_t token_index = 0;
size_t request_id_length = strlen(REQUEST_ID_PROPERTY);
result = MU_FAILURE;
while (STRING_TOKENIZER_get_next_token(token_handle, token_value, "/") == 0)
{
if (token_index == 3)
{
if (STRING_concat_with_STRING(method_name, token_value) != 0)
{
LogError("Failed STRING_concat_with_STRING.");
result = MU_FAILURE;
break;
}
}
else if (token_index == 4)
{
if (STRING_length(token_value) >= request_id_length)
{
const char* request_id_value = STRING_c_str(token_value);
if (memcmp(request_id_value, REQUEST_ID_PROPERTY, request_id_length) == 0)
{
if (STRING_concat(request_id, request_id_value + request_id_length) != 0)
{
LogError("Failed STRING_concat failed.");
result = MU_FAILURE;
}
else
{
result = 0;
}
break;
}
}
}
token_index++;
}
STRING_delete(token_value);
}
STRING_TOKENIZER_destroy(token_handle);
}
return result;
}
//
// parseDeviceTwinTopicInfo parses information about a topic PUBLISH'd to this device/module.
//
static int parseDeviceTwinTopicInfo(const char* resp_topic, bool* patch_msg, size_t* request_id, int* status_code)
{
int result;
STRING_TOKENIZER_HANDLE token_handle = STRING_TOKENIZER_create_from_char(resp_topic);
if (token_handle == NULL)
{
LogError("Failed creating token from device twin topic.");
result = MU_FAILURE;
*status_code = 0;
*request_id = 0;
*patch_msg = false;
}
else
{
STRING_HANDLE token_value;
if ((token_value = STRING_new()) == NULL)
{
LogError("Failed allocating new string .");
result = MU_FAILURE;
*status_code = 0;
*request_id = 0;
*patch_msg = false;
}
else
{
result = MU_FAILURE;
size_t token_count = 0;
while (STRING_TOKENIZER_get_next_token(token_handle, token_value, "/") == 0)
{
if (token_count == 2)
{
if (strcmp(STRING_c_str(token_value), "PATCH") == 0)
{
*patch_msg = true;
*status_code = 0;
*request_id = 0;
result = 0;
break;
}
*patch_msg = false;
}
else if (token_count == 3)
{
*status_code = (int)atol(STRING_c_str(token_value));
}
else if (token_count == 4)
{
const char* request_id_string = STRING_c_str(token_value);
if (strncmp(request_id_string, REQUEST_ID_PROPERTY, REQUEST_ID_PROPERTY_LEN) != 0)
{
LogError("requestId does not begin with string format %s", REQUEST_ID_PROPERTY);
*request_id = 0;
result = MU_FAILURE;
}
else
{
*request_id = (size_t)atol(request_id_string + REQUEST_ID_PROPERTY_LEN);
result = 0;
}
break;
}
token_count++;
}
STRING_delete(token_value);
}
STRING_TOKENIZER_destroy(token_handle);
}
return result;
}
//
// retrieveTopicType translates an MQTT topic PUBLISH'd to this device/module into what type (e.g. twin, method, etc.) it represents.
//
static int retrieveTopicType(PMQTTTRANSPORT_HANDLE_DATA transportData, const char* topicName, IOTHUB_IDENTITY_TYPE* type)
{
int result;
const char* mqtt_message_queue_topic;
const char* input_queue_topic;
if (InternStrnicmp(topicName, TOPIC_DEVICE_TWIN_PREFIX, sizeof(TOPIC_DEVICE_TWIN_PREFIX) - 1) == 0)
{
*type = IOTHUB_TYPE_DEVICE_TWIN;
result = 0;
}
else if (InternStrnicmp(topicName, TOPIC_DEVICE_METHOD_PREFIX, sizeof(TOPIC_DEVICE_METHOD_PREFIX) - 1) == 0)
{
*type = IOTHUB_TYPE_DEVICE_METHODS;
result = 0;
}
// mqtt_message_queue_topic contains additional "#" from subscribe, which we strip off on comparing incoming.
else if (((mqtt_message_queue_topic = STRING_c_str(transportData->topic_MqttMessage)) != NULL) && (InternStrnicmp(topicName, mqtt_message_queue_topic, strlen(mqtt_message_queue_topic) - 1) == 0))
{
*type = IOTHUB_TYPE_TELEMETRY;
result = 0;
}
// input_queue_topic contains additional "#" from subscribe, which we strip off on comparing incoming.
else if (((input_queue_topic = STRING_c_str(transportData->topic_InputQueue)) != NULL) && (InternStrnicmp(topicName, input_queue_topic, strlen(input_queue_topic) - 1) == 0))
{
*type = IOTHUB_TYPE_EVENT_QUEUE;
result = 0;
}
else
{
LogError("Topic %s does not match any client is subscribed to", topicName);
result = MU_FAILURE;
}
return result;
}
//
// notifyApplicationOfSendMessageComplete lets application know that messages in the iothubMsgList have completed (or should be considered failed) with confirmResult status.
//
static void notifyApplicationOfSendMessageComplete(IOTHUB_MESSAGE_LIST* iothubMsgList, PMQTTTRANSPORT_HANDLE_DATA transport_data, IOTHUB_CLIENT_CONFIRMATION_RESULT confirmResult)
{
DLIST_ENTRY messageCompleted;
DList_InitializeListHead(&messageCompleted);
DList_InsertTailList(&messageCompleted, &(iothubMsgList->entry));
transport_data->transport_callbacks.send_complete_cb(&messageCompleted, confirmResult, transport_data->transport_ctx);
}
//
// addUserPropertiesTouMqttMessage translates application properties in iothub_message_handle (set by the application with IoTHubMessage_SetProperty e.g.)
// into a representation in the MQTT TOPIC topic_string.
//
static int addUserPropertiesTouMqttMessage(IOTHUB_MESSAGE_HANDLE iothub_message_handle, STRING_HANDLE topic_string, size_t* index_ptr, bool urlencode)
{
int result = 0;
const char* const* propertyKeys;
const char* const* propertyValues;
size_t propertyCount;
size_t index = *index_ptr;
MAP_HANDLE properties_map = IoTHubMessage_Properties(iothub_message_handle);
if (properties_map != NULL)
{
if (Map_GetInternals(properties_map, &propertyKeys, &propertyValues, &propertyCount) != MAP_OK)
{
LogError("Failed to get the internals of the property map.");
result = MU_FAILURE;
}
else
{
if (propertyCount != 0)
{
for (index = 0; index < propertyCount && result == 0; index++)
{
if (urlencode)
{
STRING_HANDLE property_key = URL_EncodeString(propertyKeys[index]);
STRING_HANDLE property_value = URL_EncodeString(propertyValues[index]);
if ((property_key == NULL) || (property_value == NULL))
{
LogError("Failed URL Encoding properties");
result = MU_FAILURE;
}
else if (STRING_sprintf(topic_string, "%s=%s%s", STRING_c_str(property_key), STRING_c_str(property_value), propertyCount - 1 == index ? "" : PROPERTY_SEPARATOR) != 0)
{
LogError("Failed constructing property string.");
result = MU_FAILURE;
}
STRING_delete(property_key);
STRING_delete(property_value);
}
else
{
if (STRING_sprintf(topic_string, "%s=%s%s", propertyKeys[index], propertyValues[index], propertyCount - 1 == index ? "" : PROPERTY_SEPARATOR) != 0)
{
LogError("Failed constructing property string.");
result = MU_FAILURE;
}
}
}
}
}
}
*index_ptr = index;
return result;
}
#ifdef RUN_SFC_TESTS
//
// isMqttMessageSfcType checks to see if the message is a service-fault-control message.
//
static bool isMqttMessageSfcType(IOTHUB_MESSAGE_HANDLE iothub_message_handle)
{
bool result = false;
const char* const* propertyKeys;
const char* const* propertyValues;
size_t propertyCount;
size_t index;
MAP_HANDLE properties_map = IoTHubMessage_Properties(iothub_message_handle);
if (properties_map != NULL)
{
if (Map_GetInternals(properties_map, &propertyKeys, &propertyValues, &propertyCount) != MAP_OK)
{
LogError("Failed to get the internals of the property map.");
}
else
{
for (index = 0; index < propertyCount; index++)
{
if (strncmp(propertyKeys[index], FAULT_OPERATION_TYPE , strlen(FAULT_OPERATION_TYPE )) == 0)
{
result = true;
break;
}
}
}
}
return result;
}
#endif //RUN_SFC_TESTS
//
// addSystemPropertyToTopicString appends a given "system" property from iothub_message_handle (set by the application with APIs such as IoTHubMessage_SetMessageId,
// IoTHubMessage_SetContentTypeSystemProperty, etc.) onto the MQTT TOPIC topic_string.
//
static int addSystemPropertyToTopicString(STRING_HANDLE topic_string, size_t index, const char* property_key, const char* property_value, bool urlencode)
{
int result = 0;
if (urlencode)
{
STRING_HANDLE encoded_property_value = URL_EncodeString(property_value);
if (encoded_property_value == NULL)
{
LogError("Failed URL encoding %s.", property_key);
result = MU_FAILURE;
}
else if (STRING_sprintf(topic_string, SYS_TOPIC_STRING_FORMAT, index == 0 ? "" : PROPERTY_SEPARATOR, property_key, STRING_c_str(encoded_property_value)) != 0)
{
LogError("Failed setting %s.", property_key);
result = MU_FAILURE;
}
STRING_delete(encoded_property_value);
}
else
{
if (STRING_sprintf(topic_string, SYS_TOPIC_STRING_FORMAT, index == 0 ? "" : PROPERTY_SEPARATOR, property_key, property_value) != 0)
{
LogError("Failed setting %s.", property_key);
result = MU_FAILURE;
}
}
return result;
}
//
// addSystemPropertyToTopicString appends all "system" property from iothub_message_handle (set by the application with APIs such as IoTHubMessage_SetMessageId,
// IoTHubMessage_SetContentTypeSystemProperty, etc.) onto the MQTT TOPIC topic_string.
//
static int addSystemPropertiesTouMqttMessage(IOTHUB_MESSAGE_HANDLE iothub_message_handle, STRING_HANDLE topic_string, size_t* index_ptr, bool urlencode)
{
int result = 0;
size_t index = *index_ptr;
bool is_security_msg = IoTHubMessage_IsSecurityMessage(iothub_message_handle);
const char* correlation_id = IoTHubMessage_GetCorrelationId(iothub_message_handle);
if (correlation_id != NULL)
{
result = addSystemPropertyToTopicString(topic_string, index, SYS_PROP_CORRELATION_ID, correlation_id, urlencode);
index++;
}
if (result == 0)
{
const char* msg_id = IoTHubMessage_GetMessageId(iothub_message_handle);
if (msg_id != NULL)
{
result = addSystemPropertyToTopicString(topic_string, index, SYS_PROP_MESSAGE_ID, msg_id, urlencode);
index++;
}
}
if (result == 0)
{
const char* content_type = IoTHubMessage_GetContentTypeSystemProperty(iothub_message_handle);
if (content_type != NULL)
{
result = addSystemPropertyToTopicString(topic_string, index, SYS_PROP_CONTENT_TYPE, content_type, urlencode);
index++;
}
}
if (result == 0)
{
const char* content_encoding = IoTHubMessage_GetContentEncodingSystemProperty(iothub_message_handle);
if (content_encoding != NULL)
{
// Security message require content encoding
result = addSystemPropertyToTopicString(topic_string, index, SYS_PROP_CONTENT_ENCODING, content_encoding, is_security_msg ? true : urlencode);
index++;
}
}
if (result == 0)
{
const char* message_creation_time_utc = IoTHubMessage_GetMessageCreationTimeUtcSystemProperty(iothub_message_handle);
if (message_creation_time_utc != NULL)
{
result = addSystemPropertyToTopicString(topic_string, index, SYS_PROP_MESSAGE_CREATION_TIME_UTC, message_creation_time_utc, urlencode);
index++;
}
}
if (result == 0)
{
if (is_security_msg)
{
// The Security interface Id value must be encoded
if (addSystemPropertyToTopicString(topic_string, index++, SECURITY_INTERFACE_ID_MQTT, SECURITY_INTERFACE_ID_VALUE, true) != 0)
{
LogError("Failed setting Security interface id");
result = MU_FAILURE;
}
else
{
result = 0;
}
}
}
if (result == 0)
{
const char* output_name = IoTHubMessage_GetOutputName(iothub_message_handle);
if (output_name != NULL)
{
// Encode the output name if encoding is on
if (addSystemPropertyToTopicString(topic_string, index++, SYS_PROP_ON, output_name, urlencode) != 0)
{
LogError("Failed setting output name");
result = MU_FAILURE;
}
else
{
result = 0;
}
}
}
if (result == 0)
{
const char* component_name = IoTHubMessage_GetComponentName(iothub_message_handle);
if (component_name != NULL)
{
// Encode the component name if encoding is on
if (addSystemPropertyToTopicString(topic_string, index++, SYS_COMPONENT_NAME, component_name, urlencode) != 0)
{
LogError("Failed setting component name");
result = MU_FAILURE;
}
else
{
result = 0;
}
}
}
*index_ptr = index;
return result;
}
//
// addDiagnosticPropertiesTouMqttMessage appends diagnostic data (as specified by IoTHubMessage_SetDiagnosticPropertyData) onto
// the MQTT topic topic_string.
//
static int addDiagnosticPropertiesTouMqttMessage(IOTHUB_MESSAGE_HANDLE iothub_message_handle, STRING_HANDLE topic_string, size_t* index_ptr)
{
int result = 0;
size_t index = *index_ptr;
const IOTHUB_MESSAGE_DIAGNOSTIC_PROPERTY_DATA* diagnosticData = IoTHubMessage_GetDiagnosticPropertyData(iothub_message_handle);
if (diagnosticData != NULL)
{
const char* diag_id = diagnosticData->diagnosticId;
const char* creation_time_utc = diagnosticData->diagnosticCreationTimeUtc;
//diagid and creationtimeutc must be present/unpresent simultaneously
if (diag_id != NULL && creation_time_utc != NULL)
{
if (STRING_sprintf(topic_string, SYS_TOPIC_STRING_FORMAT, index == 0 ? "" : PROPERTY_SEPARATOR, SYS_PROP_DIAGNOSTIC_ID, diag_id) != 0)
{
LogError("Failed setting diagnostic id");
result = MU_FAILURE;
}
index++;
if (result == 0)
{
//construct diagnostic context, it should be urlencode(key1=value1,key2=value2)
STRING_HANDLE diagContextHandle = STRING_construct_sprintf("%s=%s", DIAGNOSTIC_CONTEXT_CREATION_TIME_UTC_PROPERTY, creation_time_utc);
if (diagContextHandle == NULL)
{
LogError("Failed constructing diagnostic context");
result = MU_FAILURE;
}
else
{
//Add other diagnostic context properties here if have more
STRING_HANDLE encodedContextValueHandle = URL_Encode(diagContextHandle);
const char* encodedContextValueString = NULL;
if (encodedContextValueHandle != NULL &&
(encodedContextValueString = STRING_c_str(encodedContextValueHandle)) != NULL)
{
if (STRING_sprintf(topic_string, SYS_TOPIC_STRING_FORMAT, index == 0 ? "" : PROPERTY_SEPARATOR, SYS_PROP_DIAGNOSTIC_CONTEXT, encodedContextValueString) != 0)
{
LogError("Failed setting diagnostic context");
result = MU_FAILURE;
}
STRING_delete(encodedContextValueHandle);
encodedContextValueHandle = NULL;
}
else
{
LogError("Failed encoding diagnostic context value");
result = MU_FAILURE;
}
STRING_delete(diagContextHandle);
diagContextHandle = NULL;
index++;
}
}
}
else if (diag_id != NULL || creation_time_utc != NULL)
{
LogError("diagid and diagcreationtimeutc must be present simultaneously.");
result = MU_FAILURE;
}
}
return result;
}
//
// addPropertiesTouMqttMessage adds user, "system", and diagnostic messages onto MQTT topic string. Note that "system" properties is a
// construct of the SDK and IoT Hub. The MQTT protocol itself does not assign any significance to system and user properties (as opposed to AMQP).
// The IOTHUB_MESSAGE_HANDLE structure however does have well-known properties (e.g. IoTHubMessage_SetMessageId) that the SDK treats as system
// properties where we can automatically fill in the key value for in the key=value list.
//
static STRING_HANDLE addPropertiesTouMqttMessage(IOTHUB_MESSAGE_HANDLE iothub_message_handle, const char* eventTopic, bool urlencode)
{