-
Notifications
You must be signed in to change notification settings - Fork 37
Expand file tree
/
Copy pathclient.c
More file actions
3833 lines (3157 loc) · 149 KB
/
client.c
File metadata and controls
3833 lines (3157 loc) · 149 KB
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 Amazon.com, Inc. or its affiliates. All Rights Reserved.
* SPDX-License-Identifier: Apache-2.0.
*/
#include <aws/mqtt/client.h>
#include <aws/mqtt/private/client_impl.h>
#include <aws/mqtt/private/mqtt_client_test_helper.h>
#include <aws/mqtt/private/mqtt_iot_metrics.h>
#include <aws/mqtt/private/packets.h>
#include <aws/mqtt/private/shared.h>
#include <aws/mqtt/private/topic_tree.h>
#include <aws/http/proxy.h>
#include <aws/http/request_response.h>
#include <aws/http/websocket.h>
#include <aws/io/channel_bootstrap.h>
#include <aws/io/event_loop.h>
#include <aws/io/socket.h>
#include <aws/io/tls_channel_handler.h>
#include <aws/io/uri.h>
#include <aws/common/clock.h>
#include <aws/common/task_scheduler.h>
#include <inttypes.h>
#ifdef _MSC_VER
# pragma warning(disable : 4204)
# pragma warning(disable : 4996) /* allow strncpy() */
#endif
/* 3 seconds */
static const uint64_t s_default_ping_timeout_ns = 3000000000;
/* 20 minutes - This is the default (and max) for AWS IoT as of 2020.02.18 */
static const uint16_t s_default_keep_alive_sec = 1200;
#define DEFAULT_MQTT311_OPERATION_TABLE_SIZE 100
static int s_mqtt_client_connect(
struct aws_mqtt_client_connection_311_impl *connection,
aws_mqtt_client_on_connection_complete_fn *on_connection_complete,
void *userdata);
/*******************************************************************************
* Helper functions
******************************************************************************/
void mqtt_connection_lock_synced_data(struct aws_mqtt_client_connection_311_impl *connection) {
int err = aws_mutex_lock(&connection->synced_data.lock);
AWS_ASSERT(!err);
(void)err;
}
void mqtt_connection_unlock_synced_data(struct aws_mqtt_client_connection_311_impl *connection) {
ASSERT_SYNCED_DATA_LOCK_HELD(connection);
int err = aws_mutex_unlock(&connection->synced_data.lock);
AWS_ASSERT(!err);
(void)err;
}
/* To configure the connection, ensure the state is DISCONNECTED or CONNECTED. The function should be wrapped by
* connection synced_data lock.
*/
static bool s_is_valid_connection_state_for_configuration(struct aws_mqtt_client_connection_311_impl *connection) {
return connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTED ||
connection->synced_data.state == AWS_MQTT_CLIENT_STATE_CONNECTED;
}
static void s_aws_mqtt_schedule_reconnect_task(struct aws_mqtt_client_connection_311_impl *connection) {
uint64_t next_attempt_ns = 0;
aws_high_res_clock_get_ticks(&next_attempt_ns);
next_attempt_ns += aws_timestamp_convert(
connection->reconnect_timeouts.current_sec, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
aws_event_loop_schedule_task_future(connection->loop, &connection->reconnect_task->task, next_attempt_ns);
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT,
"id=%p: Scheduling reconnect, for %" PRIu64 " on event-loop %p",
(void *)connection,
next_attempt_ns,
(void *)connection->loop);
}
static void s_aws_mqtt_client_destroy(void *user_data) {
struct aws_mqtt_client *client = user_data;
AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "client=%p: Cleaning up MQTT client", (void *)client);
aws_client_bootstrap_release(client->bootstrap);
aws_mem_release(client->allocator, client);
}
void mqtt_connection_set_state(
struct aws_mqtt_client_connection_311_impl *connection,
enum aws_mqtt_client_connection_state state) {
ASSERT_SYNCED_DATA_LOCK_HELD(connection);
if (connection->synced_data.state == state) {
AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: MQTT connection already in state %d", (void *)connection, state);
return;
}
connection->synced_data.state = state;
}
static void s_request_timeout(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
(void)channel_task;
struct request_timeout_task_arg *timeout_task_arg = arg;
struct aws_mqtt_client_connection_311_impl *connection = timeout_task_arg->connection;
if (status == AWS_TASK_STATUS_RUN_READY) {
if (timeout_task_arg->task_arg_wrapper != NULL) {
mqtt_request_complete(connection, AWS_ERROR_MQTT_TIMEOUT, timeout_task_arg->packet_id);
}
}
/*
* Whether cancelled or run, if we have a back pointer to the operation's task arg, we must zero it out
* so that when it completes it does not try to cancel us, because we will already be freed.
*
* If we don't have a back pointer to the operation's task arg, that means it already ran and completed.
*/
if (timeout_task_arg->task_arg_wrapper != NULL) {
timeout_task_arg->task_arg_wrapper->timeout_task_arg = NULL;
timeout_task_arg->task_arg_wrapper = NULL;
}
aws_mem_release(connection->allocator, timeout_task_arg);
}
static struct request_timeout_task_arg *s_schedule_timeout_task(
struct aws_mqtt_client_connection_311_impl *connection,
uint16_t packet_id,
uint64_t timeout_duration_in_ns) {
if (timeout_duration_in_ns == UINT64_MAX || timeout_duration_in_ns == 0 || packet_id == 0) {
return NULL;
}
/* schedule a timeout task to run, in case server never sends us an ack */
struct aws_channel_task *request_timeout_task = NULL;
struct request_timeout_task_arg *timeout_task_arg = NULL;
if (!aws_mem_acquire_many(
connection->allocator,
2,
&timeout_task_arg,
sizeof(struct request_timeout_task_arg),
&request_timeout_task,
sizeof(struct aws_channel_task))) {
return NULL;
}
aws_channel_task_init(request_timeout_task, s_request_timeout, timeout_task_arg, "mqtt_request_timeout");
AWS_ZERO_STRUCT(*timeout_task_arg);
timeout_task_arg->connection = connection;
timeout_task_arg->packet_id = packet_id;
uint64_t timestamp = 0;
if (aws_channel_current_clock_time(connection->slot->channel, ×tamp)) {
aws_mem_release(connection->allocator, timeout_task_arg);
return NULL;
}
timestamp = aws_add_u64_saturating(timestamp, timeout_duration_in_ns);
aws_channel_schedule_task_future(connection->slot->channel, request_timeout_task, timestamp);
return timeout_task_arg;
}
static void s_init_statistics(struct aws_mqtt_connection_operation_statistics_impl *stats) {
aws_atomic_store_int(&stats->incomplete_operation_count_atomic, 0);
aws_atomic_store_int(&stats->incomplete_operation_size_atomic, 0);
aws_atomic_store_int(&stats->unacked_operation_count_atomic, 0);
aws_atomic_store_int(&stats->unacked_operation_size_atomic, 0);
}
static bool s_is_topic_shared_topic(struct aws_byte_cursor *input) {
char *input_str = (char *)input->ptr;
if (strncmp("$share/", input_str, strlen("$share/")) == 0) {
return true;
}
return false;
}
static struct aws_string *s_get_normal_topic_from_shared_topic(struct aws_string *input) {
const char *input_char_str = aws_string_c_str(input);
size_t input_char_length = strlen(input_char_str);
size_t split_position = 7; // Start at '$share/' since we know it has to exist
while (split_position < input_char_length) {
split_position += 1;
if (input_char_str[split_position] == '/') {
break;
}
}
// If we got all the way to the end, OR there is not at least a single character
// after the second /, then it's invalid input.
if (split_position + 1 >= input_char_length) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "Cannot parse shared subscription topic: Topic is not formatted correctly");
return NULL;
}
const size_t split_delta = input_char_length - split_position;
if (split_delta > 0) {
// Annoyingly, we cannot just use 'char result_char[split_delta];' because
// MSVC doesn't support it.
char *result_char = aws_mem_calloc(input->allocator, split_delta, sizeof(char));
strncpy(result_char, input_char_str + split_position + 1, split_delta);
struct aws_string *result_string = aws_string_new_from_c_str(input->allocator, (const char *)result_char);
aws_mem_release(input->allocator, result_char);
return result_string;
}
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "Cannot parse shared subscription topic: Topic is not formatted correctly");
return NULL;
}
/*******************************************************************************
* Client Init
******************************************************************************/
struct aws_mqtt_client *aws_mqtt_client_new(struct aws_allocator *allocator, struct aws_client_bootstrap *bootstrap) {
aws_mqtt_fatal_assert_library_initialized();
struct aws_mqtt_client *client = aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt_client));
if (client == NULL) {
return NULL;
}
AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "client=%p: Initalizing MQTT client", (void *)client);
client->allocator = allocator;
client->bootstrap = aws_client_bootstrap_acquire(bootstrap);
aws_ref_count_init(&client->ref_count, client, (aws_simple_completion_callback *)s_aws_mqtt_client_destroy);
return client;
}
struct aws_mqtt_client *aws_mqtt_client_acquire(struct aws_mqtt_client *client) {
if (client != NULL) {
aws_ref_count_acquire(&client->ref_count);
}
return client;
}
void aws_mqtt_client_release(struct aws_mqtt_client *client) {
if (client != NULL) {
aws_ref_count_release(&client->ref_count);
}
}
#define AWS_RESET_RECONNECT_BACKOFF_DELAY_SECONDS 10
/* At this point, the channel for the MQTT connection has completed its shutdown */
static void s_mqtt_client_shutdown(
struct aws_client_bootstrap *bootstrap,
int error_code,
struct aws_channel *channel,
void *user_data) {
(void)bootstrap;
(void)channel;
struct aws_mqtt_client_connection_311_impl *connection = user_data;
AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(connection->loop));
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT, "id=%p: Channel has been shutdown with error code %d", (void *)connection, error_code);
enum aws_mqtt_client_connection_state prev_state;
struct aws_linked_list cancelling_requests;
aws_linked_list_init(&cancelling_requests);
bool disconnected_state = false;
{ /* BEGIN CRITICAL SECTION */
mqtt_connection_lock_synced_data(connection);
/*
* On a channel that represents a valid connection (successful connack received),
* channel_successful_connack_timestamp_ns will be the time the connack was received. Otherwise it will be
* zero.
*
* Use that fact to determine whether or not we should reset the current reconnect backoff delay.
*
* We reset the reconnect backoff if either of:
* 1) the user called disconnect()
* 2) a successful connection had lasted longer than our minimum reset time (10s at the moment)
*/
uint64_t now = 0;
aws_high_res_clock_get_ticks(&now);
uint64_t time_diff = now - connection->reconnect_timeouts.channel_successful_connack_timestamp_ns;
bool was_user_disconnect = connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING;
bool was_sufficiently_long_connection =
(connection->reconnect_timeouts.channel_successful_connack_timestamp_ns != 0) &&
(time_diff >=
aws_timestamp_convert(
AWS_RESET_RECONNECT_BACKOFF_DELAY_SECONDS, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL));
if (was_user_disconnect || was_sufficiently_long_connection) {
connection->reconnect_timeouts.current_sec = connection->reconnect_timeouts.min_sec;
}
connection->reconnect_timeouts.channel_successful_connack_timestamp_ns = 0;
/* Move all the ongoing requests to the pending requests list, because the response they are waiting for will
* never arrives. Sad. But, we will retry. */
if (connection->clean_session) {
/* For a clean session, the Session lasts as long as the Network Connection. Thus, discard the previous
* session */
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT,
"id=%p: Discard ongoing requests and pending requests when a clean session connection lost.",
(void *)connection);
aws_linked_list_move_all_back(&cancelling_requests, &connection->thread_data.ongoing_requests_list);
aws_linked_list_move_all_back(&cancelling_requests, &connection->synced_data.pending_requests_list);
} else {
aws_linked_list_move_all_back(
&connection->synced_data.pending_requests_list, &connection->thread_data.ongoing_requests_list);
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT,
"id=%p: All subscribe/unsubscribe and publish QoS>0 have been move to pending list",
(void *)connection);
}
prev_state = connection->synced_data.state;
switch (connection->synced_data.state) {
case AWS_MQTT_CLIENT_STATE_CONNECTED:
/* unexpected hangup from broker, try to reconnect */
mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_RECONNECTING);
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: connection was unexpected interrupted, switch state to RECONNECTING.",
(void *)connection);
break;
case AWS_MQTT_CLIENT_STATE_DISCONNECTING:
/* disconnect requested by user */
/* Successfully shutdown, if cleansession is set, ongoing and pending requests will be cleared */
disconnected_state = true;
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: disconnect finished, switch state to DISCONNECTED.",
(void *)connection);
break;
case AWS_MQTT_CLIENT_STATE_CONNECTING:
/* failed to connect */
disconnected_state = true;
break;
case AWS_MQTT_CLIENT_STATE_RECONNECTING:
/* reconnect failed, schedule the next attempt later, no need to change the state. */
break;
default:
/* AWS_MQTT_CLIENT_STATE_DISCONNECTED */
break;
}
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT, "id=%p: current state is %d", (void *)connection, (int)connection->synced_data.state);
/* Always clear slot, as that's what's been shutdown */
if (connection->slot) {
aws_channel_slot_remove(connection->slot);
AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: slot is removed successfully", (void *)connection);
connection->slot = NULL;
}
mqtt_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
if (!aws_linked_list_empty(&cancelling_requests)) {
struct aws_linked_list_node *current = aws_linked_list_front(&cancelling_requests);
const struct aws_linked_list_node *end = aws_linked_list_end(&cancelling_requests);
while (current != end) {
struct aws_mqtt_request *request = AWS_CONTAINER_OF(current, struct aws_mqtt_request, list_node);
if (request->on_complete) {
request->on_complete(
&connection->base,
request->packet_id,
AWS_ERROR_MQTT_CANCELLED_FOR_CLEAN_SESSION,
request->on_complete_ud);
}
current = current->next;
}
{ /* BEGIN CRITICAL SECTION */
mqtt_connection_lock_synced_data(connection);
while (!aws_linked_list_empty(&cancelling_requests)) {
struct aws_linked_list_node *node = aws_linked_list_pop_front(&cancelling_requests);
struct aws_mqtt_request *request = AWS_CONTAINER_OF(node, struct aws_mqtt_request, list_node);
aws_hash_table_remove(
&connection->synced_data.outstanding_requests_table, &request->packet_id, NULL, NULL);
aws_memory_pool_release(&connection->synced_data.requests_pool, request);
}
mqtt_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
}
/* If there's no error code and this wasn't user-requested, set the error code to something useful */
if (error_code == AWS_ERROR_SUCCESS) {
if (prev_state != AWS_MQTT_CLIENT_STATE_DISCONNECTING && prev_state != AWS_MQTT_CLIENT_STATE_DISCONNECTED) {
error_code = AWS_ERROR_MQTT_UNEXPECTED_HANGUP;
}
}
switch (prev_state) {
case AWS_MQTT_CLIENT_STATE_RECONNECTING: {
/* If reconnect attempt failed, schedule the next attempt */
AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Reconnect failed, retrying", (void *)connection);
s_aws_mqtt_schedule_reconnect_task(connection);
break;
}
case AWS_MQTT_CLIENT_STATE_CONNECTED: {
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: Connection interrupted, calling callback and attempting reconnect",
(void *)connection);
MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_interrupted, error_code);
aws_mqtt311_callback_set_manager_on_connection_interrupted(&connection->callback_manager, error_code);
/* In case user called disconnect from the on_interrupted callback */
bool stop_reconnect;
{ /* BEGIN CRITICAL SECTION */
mqtt_connection_lock_synced_data(connection);
stop_reconnect = connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING;
if (stop_reconnect) {
disconnected_state = true;
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: disconnect finished, switch state to DISCONNECTED.",
(void *)connection);
}
mqtt_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
if (!stop_reconnect) {
s_aws_mqtt_schedule_reconnect_task(connection);
}
break;
}
default:
break;
}
if (disconnected_state) {
{ /* BEGIN CRITICAL SECTION */
mqtt_connection_lock_synced_data(connection);
mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_DISCONNECTED);
mqtt_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
switch (prev_state) {
case AWS_MQTT_CLIENT_STATE_CONNECTED:
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT,
"id=%p: Caller requested disconnect from on_interrupted callback, aborting reconnect",
(void *)connection);
MQTT_CLIENT_CALL_CALLBACK(connection, on_disconnect);
MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_closed, NULL);
aws_mqtt311_callback_set_manager_on_disconnect(&connection->callback_manager);
break;
case AWS_MQTT_CLIENT_STATE_DISCONNECTING:
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: Disconnect completed, clearing request queue and calling callback",
(void *)connection);
MQTT_CLIENT_CALL_CALLBACK(connection, on_disconnect);
MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_closed, NULL);
aws_mqtt311_callback_set_manager_on_disconnect(&connection->callback_manager);
break;
case AWS_MQTT_CLIENT_STATE_CONNECTING:
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT,
"id=%p: Initial connection attempt failed, calling callback",
(void *)connection);
MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_connection_complete, error_code, 0, false);
MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_connection_failure, error_code);
break;
default:
break;
}
/* The connection can die now. Release the refcount */
aws_mqtt_client_connection_release(&connection->base);
}
}
/*******************************************************************************
* Connection New
******************************************************************************/
/* The assumption here is that a connection always outlives its channels, and the channel this task was scheduled on
* always outlives this task, so all we need to do is check the connection state. If we are in a state that waits
* for a CONNACK, kill it off. In the case that the connection died between scheduling this task and it being executed
* the status will always be CANCELED because this task will be canceled when the owning channel goes away. */
static void s_connack_received_timeout(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
struct aws_mqtt_client_connection_311_impl *connection = arg;
if (status == AWS_TASK_STATUS_RUN_READY) {
bool time_out = false;
{ /* BEGIN CRITICAL SECTION */
mqtt_connection_lock_synced_data(connection);
time_out =
(connection->synced_data.state == AWS_MQTT_CLIENT_STATE_CONNECTING ||
connection->synced_data.state == AWS_MQTT_CLIENT_STATE_RECONNECTING);
mqtt_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
if (time_out) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: mqtt CONNACK response timeout detected", (void *)connection);
aws_channel_shutdown(connection->slot->channel, AWS_ERROR_MQTT_TIMEOUT);
}
}
aws_mem_release(connection->allocator, channel_task);
}
/**
* Channel has been initialized callback. Sets up channel handler and sends out CONNECT packet.
* The on_connack callback is called with the CONNACK packet is received from the server.
*/
static void s_mqtt_client_init(
struct aws_client_bootstrap *bootstrap,
int error_code,
struct aws_channel *channel,
void *user_data) {
(void)bootstrap;
struct aws_io_message *message = NULL;
/* Setup callback contract is: if error_code is non-zero then channel is NULL. */
AWS_FATAL_ASSERT((error_code != 0) == (channel == NULL));
struct aws_mqtt_client_connection_311_impl *connection = user_data;
struct aws_byte_buf username_with_metrics_buf;
AWS_ZERO_STRUCT(username_with_metrics_buf);
if (error_code != AWS_OP_SUCCESS) {
/* client shutdown already handles this case, so just call that. */
s_mqtt_client_shutdown(bootstrap, error_code, channel, user_data);
return;
}
AWS_FATAL_ASSERT(aws_channel_get_event_loop(channel) == connection->loop);
/* user requested disconnect before the channel has been set up. Stop installing the slot and sending CONNECT. */
bool failed_create_slot = false;
{ /* BEGIN CRITICAL SECTION */
mqtt_connection_lock_synced_data(connection);
if (connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING) {
/* It only happens when the user request disconnect during reconnecting, we don't need to fire any callback.
* The on_disconnect will be invoked as channel finish shutting down. */
mqtt_connection_unlock_synced_data(connection);
aws_channel_shutdown(channel, AWS_ERROR_SUCCESS);
return;
}
/* Create the slot */
connection->slot = aws_channel_slot_new(channel);
if (!connection->slot) {
failed_create_slot = true;
}
mqtt_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
/* install the slot and handler */
if (failed_create_slot) {
AWS_LOGF_ERROR(
AWS_LS_MQTT_CLIENT,
"id=%p: Failed to create new slot, something has gone horribly wrong, error %d (%s).",
(void *)connection,
aws_last_error(),
aws_error_name(aws_last_error()));
goto handle_error;
}
if (aws_channel_slot_insert_end(channel, connection->slot)) {
AWS_LOGF_ERROR(
AWS_LS_MQTT_CLIENT,
"id=%p: Failed to insert slot into channel %p, error %d (%s).",
(void *)connection,
(void *)channel,
aws_last_error(),
aws_error_name(aws_last_error()));
goto handle_error;
}
if (aws_channel_slot_set_handler(connection->slot, &connection->handler)) {
AWS_LOGF_ERROR(
AWS_LS_MQTT_CLIENT,
"id=%p: Failed to set MQTT handler into slot on channel %p, error %d (%s).",
(void *)connection,
(void *)channel,
aws_last_error(),
aws_error_name(aws_last_error()));
goto handle_error;
}
aws_mqtt311_decoder_reset_for_new_connection(&connection->thread_data.decoder);
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT, "id=%p: Connection successfully opened, sending CONNECT packet", (void *)connection);
struct aws_channel_task *connack_task = aws_mem_calloc(connection->allocator, 1, sizeof(struct aws_channel_task));
if (!connack_task) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to allocate timeout task.", (void *)connection);
goto handle_error;
}
aws_channel_task_init(connack_task, s_connack_received_timeout, connection, "mqtt_connack_timeout");
uint64_t now = 0;
if (aws_channel_current_clock_time(channel, &now)) {
AWS_LOGF_ERROR(
AWS_LS_MQTT_CLIENT,
"static: Failed to setting MQTT handler into slot on channel %p, error %d (%s).",
(void *)channel,
aws_last_error(),
aws_error_name(aws_last_error()));
goto handle_error;
}
now += connection->ping_timeout_ns;
aws_channel_schedule_task_future(channel, connack_task, now);
struct aws_byte_cursor client_id_cursor = aws_byte_cursor_from_buf(&connection->client_id);
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: MQTT Connection initializing CONNECT packet for client-id '" PRInSTR "'",
(void *)connection,
AWS_BYTE_CURSOR_PRI(client_id_cursor));
/* Send the connect packet */
struct aws_mqtt_packet_connect connect;
aws_mqtt_packet_connect_init(
&connect, client_id_cursor, connection->clean_session, connection->keep_alive_time_secs);
if (connection->will.topic.buffer) {
/* Add will if present */
struct aws_byte_cursor topic_cur = aws_byte_cursor_from_buf(&connection->will.topic);
struct aws_byte_cursor payload_cur = aws_byte_cursor_from_buf(&connection->will.payload);
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: Adding will to connection on " PRInSTR " with payload " PRInSTR,
(void *)connection,
AWS_BYTE_CURSOR_PRI(topic_cur),
AWS_BYTE_CURSOR_PRI(payload_cur));
aws_mqtt_packet_connect_add_will(
&connect, topic_cur, connection->will.qos, connection->will.retain, payload_cur);
}
if (connection->username || connection->metrics_storage) {
struct aws_byte_cursor username_cur;
AWS_ZERO_STRUCT(username_cur);
if (connection->username) {
username_cur = aws_byte_cursor_from_string(connection->username);
}
/* Apply metrics to username if configured */
if (connection->metrics_storage) {
if (aws_mqtt_append_sdk_metrics_to_username(
connection->allocator,
&username_cur,
&connection->metrics_storage->storage_view,
&username_with_metrics_buf,
NULL) == AWS_OP_SUCCESS) {
username_cur = aws_byte_cursor_from_buf(&username_with_metrics_buf);
} else {
AWS_LOGF_WARN(
AWS_LS_MQTT_CLIENT,
"id=%p: Failed to apply metrics to username, using original",
(void *)connection);
}
}
if (aws_byte_cursor_is_valid(&username_cur) && username_cur.len > 0) {
struct aws_byte_cursor password_cur;
AWS_ZERO_STRUCT(password_cur);
if (connection->password) {
password_cur = aws_byte_cursor_from_string(connection->password);
}
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: Adding username " PRInSTR " to connection",
(void *)connection,
AWS_BYTE_CURSOR_PRI(username_cur));
aws_mqtt_packet_connect_add_credentials(&connect, username_cur, password_cur);
} else {
AWS_LOGF_INFO(
AWS_LS_MQTT_CLIENT,
"id=%p: Failed to set username and password. Most likely there is an issue in metrics. (e.x.: username "
"is empty and metrics string exceed the size limit). ",
(void *)connection);
}
}
message = mqtt_get_message_for_packet(connection, &connect.fixed_header);
if (!message) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to get message from pool", (void *)connection);
goto handle_error;
}
if (aws_mqtt_packet_connect_encode(&message->message_data, &connect)) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to encode CONNECT packet", (void *)connection);
goto handle_error;
}
if (aws_channel_slot_send_message(connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to send encoded CONNECT packet upstream", (void *)connection);
goto handle_error;
}
aws_byte_buf_clean_up(&username_with_metrics_buf);
return;
handle_error:
MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_connection_complete, aws_last_error(), 0, false);
MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_connection_failure, aws_last_error());
aws_channel_shutdown(channel, aws_last_error());
aws_byte_buf_clean_up(&username_with_metrics_buf);
if (message) {
aws_mem_release(message->allocator, message);
}
}
static void s_attempt_reconnect(struct aws_task *task, void *userdata, enum aws_task_status status) {
(void)task;
struct aws_mqtt_reconnect_task *reconnect = userdata;
struct aws_mqtt_client_connection_311_impl *connection = aws_atomic_load_ptr(&reconnect->connection_ptr);
/* If the task is not cancelled and a connection has not succeeded, attempt reconnect */
if (status == AWS_TASK_STATUS_RUN_READY && connection) {
mqtt_connection_lock_synced_data(connection);
/**
* Check the state and if we are disconnecting (AWS_MQTT_CLIENT_STATE_DISCONNECTING) then we want to skip it
* and abort the reconnect task (or rather, just do not try to reconnect)
*/
if (connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING) {
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT, "id=%p: Skipping reconnect: Client is trying to disconnect", (void *)connection);
/**
* There is the nasty world where the disconnect task/function is called right when we are "reconnecting" as
* our state but we have not reconnected. When this happens, the disconnect function doesn't do anything
* beyond setting the state to AWS_MQTT_CLIENT_STATE_DISCONNECTING (aws_mqtt_client_connection_disconnect),
* meaning the disconnect callback will NOT be called nor will we release memory.
* For this reason, we have to do the callback and release of the connection here otherwise the code
* will DEADLOCK forever and that is bad.
*/
bool perform_full_destroy = false;
if (!connection->slot) {
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT,
"id=%p: Reconnect task called but client is disconnecting and has no slot. Finishing disconnect",
(void *)connection);
mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_DISCONNECTED);
perform_full_destroy = true;
}
aws_mem_release(reconnect->allocator, reconnect);
connection->reconnect_task = NULL;
/* Unlock the synced data, then potentially call the disconnect callback and release the connection */
mqtt_connection_unlock_synced_data(connection);
if (perform_full_destroy) {
MQTT_CLIENT_CALL_CALLBACK(connection, on_disconnect);
MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_closed, NULL);
aws_mqtt_client_connection_release(&connection->base);
}
return;
}
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT,
"id=%p: Attempting reconnect, if it fails next attempt will be in %" PRIu64 " seconds",
(void *)connection,
connection->reconnect_timeouts.current_sec);
/* Check before multiplying to avoid potential overflow */
if (connection->reconnect_timeouts.current_sec > connection->reconnect_timeouts.max_sec / 2) {
connection->reconnect_timeouts.current_sec = connection->reconnect_timeouts.max_sec;
} else {
connection->reconnect_timeouts.current_sec *= 2;
}
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT,
"id=%p: Attempting reconnect, if it fails next attempt will be in %" PRIu64 " seconds",
(void *)connection,
connection->reconnect_timeouts.current_sec);
mqtt_connection_unlock_synced_data(connection);
if (s_mqtt_client_connect(
connection, connection->on_connection_complete, connection->on_connection_complete_ud)) {
/* If reconnect attempt failed, schedule the next attempt */
s_aws_mqtt_schedule_reconnect_task(connection);
} else {
/* Ideally, it would be nice to move this inside the lock, but I'm unsure of the correctness */
connection->reconnect_task->task.timestamp = 0;
}
} else {
aws_mem_release(reconnect->allocator, reconnect);
}
}
void aws_create_reconnect_task(struct aws_mqtt_client_connection_311_impl *connection) {
if (connection->reconnect_task == NULL) {
connection->reconnect_task = aws_mem_calloc(connection->allocator, 1, sizeof(struct aws_mqtt_reconnect_task));
AWS_FATAL_ASSERT(connection->reconnect_task != NULL);
aws_atomic_init_ptr(&connection->reconnect_task->connection_ptr, connection);
connection->reconnect_task->allocator = connection->allocator;
aws_task_init(
&connection->reconnect_task->task, s_attempt_reconnect, connection->reconnect_task, "mqtt_reconnect");
}
}
static void s_mqtt_client_connection_destroy_final(struct aws_mqtt_client_connection *base_connection) {
struct aws_mqtt_client_connection_311_impl *connection = base_connection->impl;
AWS_PRECONDITION(!connection || connection->allocator);
if (!connection) {
return;
}
/* If the slot is not NULL, the connection is still connected, which should be prevented from calling this function
*/
AWS_ASSERT(!connection->slot);
AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Destroying connection", (void *)connection);
aws_mqtt_client_on_connection_termination_fn *termination_handler = NULL;
void *termination_handler_user_data = NULL;
if (connection->on_termination != NULL) {
termination_handler = connection->on_termination;
termination_handler_user_data = connection->on_termination_ud;
}
aws_mqtt311_callback_set_manager_clean_up(&connection->callback_manager);
/* If the reconnect_task isn't freed, free it */
if (connection->reconnect_task) {
aws_mem_release(connection->reconnect_task->allocator, connection->reconnect_task);
}
aws_string_destroy(connection->host_name);
/* Clear the credentials */
if (connection->username) {
aws_string_destroy_secure(connection->username);
}
if (connection->password) {
aws_string_destroy_secure(connection->password);
}
/* Clean up the will */
aws_byte_buf_clean_up(&connection->will.topic);
aws_byte_buf_clean_up(&connection->will.payload);
/* Clear the client_id */
aws_byte_buf_clean_up(&connection->client_id);
/* Free all of the active subscriptions */
aws_mqtt_topic_tree_clean_up(&connection->thread_data.subscriptions);
aws_mqtt311_decoder_clean_up(&connection->thread_data.decoder);
aws_hash_table_clean_up(&connection->synced_data.outstanding_requests_table);
/* clean up the pending_requests if it's not empty */
while (!aws_linked_list_empty(&connection->synced_data.pending_requests_list)) {
struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->synced_data.pending_requests_list);
struct aws_mqtt_request *request = AWS_CONTAINER_OF(node, struct aws_mqtt_request, list_node);
/* Fire the callback and clean up the memory, as the connection get destroyed. */
if (request->on_complete) {
request->on_complete(
&connection->base, request->packet_id, AWS_ERROR_MQTT_CONNECTION_DESTROYED, request->on_complete_ud);
}
aws_memory_pool_release(&connection->synced_data.requests_pool, request);
}
aws_memory_pool_clean_up(&connection->synced_data.requests_pool);
aws_mutex_clean_up(&connection->synced_data.lock);
aws_rw_lock_clean_up(&connection->callback_lock);
aws_tls_connection_options_clean_up(&connection->tls_options);
/* Clean up the websocket proxy options */
if (connection->http_proxy_config) {
aws_http_proxy_config_destroy(connection->http_proxy_config);
connection->http_proxy_config = NULL;
}
/* Clean up metrics */
if (connection->metrics_storage) {
aws_mqtt_iot_metrics_storage_destroy(connection->metrics_storage);
connection->metrics_storage = NULL;
}
aws_mqtt_client_release(connection->client);
/* Frees all allocated memory */
aws_mem_release(connection->allocator, connection);
if (termination_handler != NULL) {
(*termination_handler)(termination_handler_user_data);
}
}
static void s_on_final_disconnect(struct aws_mqtt_client_connection *connection, void *userdata) {
(void)userdata;
s_mqtt_client_connection_destroy_final(connection);
}
static void s_mqtt_client_connection_start_destroy(void *user_data) {
struct aws_mqtt_client_connection_311_impl *connection = user_data;
bool call_destroy_final = false;
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: Last refcount on connection has been released, start destroying the connection.",
(void *)connection);
{ /* BEGIN CRITICAL SECTION */
mqtt_connection_lock_synced_data(connection);
if (connection->synced_data.state != AWS_MQTT_CLIENT_STATE_DISCONNECTED) {
/*
* We don't call the on_disconnect callback until we've transitioned to the DISCONNECTED state. So it's
* safe to change it now while we hold the lock since we know we're not DISCONNECTED yet.
*/
connection->on_disconnect = s_on_final_disconnect;
if (connection->synced_data.state != AWS_MQTT_CLIENT_STATE_DISCONNECTING) {
mqtt_disconnect_impl(connection, AWS_ERROR_SUCCESS);
AWS_LOGF_DEBUG(
AWS_LS_MQTT_CLIENT,
"id=%p: final refcount has been released, switch state to DISCONNECTING.",
(void *)connection);
mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_DISCONNECTING);
}
} else {
call_destroy_final = true;
}
mqtt_connection_unlock_synced_data(connection);
} /* END CRITICAL SECTION */
if (call_destroy_final) {
s_mqtt_client_connection_destroy_final(&connection->base);
}
}
/*******************************************************************************
* Connection Configuration
******************************************************************************/
static int s_aws_mqtt_client_connection_311_set_will(
void *impl,
const struct aws_byte_cursor *topic,
enum aws_mqtt_qos qos,
bool retain,
const struct aws_byte_cursor *payload) {
struct aws_mqtt_client_connection_311_impl *connection = impl;
AWS_PRECONDITION(connection);
AWS_PRECONDITION(topic);
if (!aws_mqtt_is_valid_topic(topic)) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Will topic is invalid", (void *)connection);
return aws_raise_error(AWS_ERROR_MQTT_INVALID_TOPIC);
}
if (qos > AWS_MQTT_QOS_EXACTLY_ONCE) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Will qos is invalid", (void *)connection);
return aws_raise_error(AWS_ERROR_MQTT_INVALID_QOS);
}
int result = AWS_OP_ERR;
AWS_LOGF_TRACE(
AWS_LS_MQTT_CLIENT,
"id=%p: Setting last will with topic \"" PRInSTR "\"",
(void *)connection,
AWS_BYTE_CURSOR_PRI(*topic));
struct aws_byte_buf local_topic_buf;
struct aws_byte_buf local_payload_buf;
AWS_ZERO_STRUCT(local_topic_buf);
AWS_ZERO_STRUCT(local_payload_buf);
struct aws_byte_buf topic_buf = aws_byte_buf_from_array(topic->ptr, topic->len);
if (aws_byte_buf_init_copy(&local_topic_buf, connection->allocator, &topic_buf)) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to copy will topic", (void *)connection);
goto cleanup;
}
struct aws_byte_buf payload_buf = aws_byte_buf_from_array(payload->ptr, payload->len);
if (aws_byte_buf_init_copy(&local_payload_buf, connection->allocator, &payload_buf)) {
AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to copy will body", (void *)connection);
goto cleanup;
}
{ /* BEGIN CRITICAL SECTION */
mqtt_connection_lock_synced_data(connection);