Debian Codegraph @

crt/aws-c-mqtt/source/client.c

raw symbols SCIP
1 /**
2 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
3 * SPDX-License-Identifier: Apache-2.0.
4 */
5 #include <aws/mqtt/client.h>
6
7 #include <aws/mqtt/private/client_impl.h>
8 #include <aws/mqtt/private/mqtt_client_test_helper.h>
9 #include <aws/mqtt/private/mqtt_iot_metrics.h>
10 #include <aws/mqtt/private/packets.h>
11 #include <aws/mqtt/private/shared.h>
12 #include <aws/mqtt/private/topic_tree.h>
13
14 #include <aws/http/proxy.h>
15 #include <aws/http/request_response.h>
16 #include <aws/http/websocket.h>
17
18 #include <aws/io/channel_bootstrap.h>
19 #include <aws/io/event_loop.h>
20 #include <aws/io/socket.h>
21 #include <aws/io/tls_channel_handler.h>
22 #include <aws/io/uri.h>
23
24 #include <aws/common/clock.h>
25 #include <aws/common/task_scheduler.h>
26
27 #include <inttypes.h>
28
29 #ifdef _MSC_VER
30 # pragma warning(disable : 4204)
31 # pragma warning(disable : 4996) /* allow strncpy() */
32 #endif
33
34 /* 3 seconds */
35 static const uint64_t s_default_ping_timeout_ns = 3000000000;
36
37 /* 20 minutes - This is the default (and max) for AWS IoT as of 2020.02.18 */
38 static const uint16_t s_default_keep_alive_sec = 1200;
39
40 #define DEFAULT_MQTT311_OPERATION_TABLE_SIZE 100
41
42 static int s_mqtt_client_connect(
43 struct aws_mqtt_client_connection_311_impl *connection,
44 aws_mqtt_client_on_connection_complete_fn *on_connection_complete,
45 void *userdata);
46 /*******************************************************************************
47 * Helper functions
48 ******************************************************************************/
49
50 void mqtt_connection_lock_synced_data(struct aws_mqtt_client_connection_311_impl *connection) {
51 int err = aws_mutex_lock(&connection->synced_data.lock);
52 AWS_ASSERT(!err);
53 (void)err;
54 }
55
56 void mqtt_connection_unlock_synced_data(struct aws_mqtt_client_connection_311_impl *connection) {
57 ASSERT_SYNCED_DATA_LOCK_HELD(connection);
58
59 int err = aws_mutex_unlock(&connection->synced_data.lock);
60 AWS_ASSERT(!err);
61 (void)err;
62 }
63
64 /* To configure the connection, ensure the state is DISCONNECTED or CONNECTED. The function should be wrapped by
65 * connection synced_data lock.
66 */
67 static bool s_is_valid_connection_state_for_configuration(struct aws_mqtt_client_connection_311_impl *connection) {
68
69 return connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTED ||
70 connection->synced_data.state == AWS_MQTT_CLIENT_STATE_CONNECTED;
71 }
72
73 static void s_aws_mqtt_schedule_reconnect_task(struct aws_mqtt_client_connection_311_impl *connection) {
74 uint64_t next_attempt_ns = 0;
75 aws_high_res_clock_get_ticks(&next_attempt_ns);
76 next_attempt_ns += aws_timestamp_convert(
77 connection->reconnect_timeouts.current_sec, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
78 aws_event_loop_schedule_task_future(connection->loop, &connection->reconnect_task->task, next_attempt_ns);
79 AWS_LOGF_TRACE(
80 AWS_LS_MQTT_CLIENT,
81 "id=%p: Scheduling reconnect, for %" PRIu64 " on event-loop %p",
82 (void *)connection,
83 next_attempt_ns,
84 (void *)connection->loop);
85 }
86
87 static void s_aws_mqtt_client_destroy(struct aws_mqtt_client *client) {
88
89 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "client=%p: Cleaning up MQTT client", (void *)client);
90 aws_client_bootstrap_release(client->bootstrap);
91
92 aws_mem_release(client->allocator, client);
93 }
94
95 void mqtt_connection_set_state(
96 struct aws_mqtt_client_connection_311_impl *connection,
97 enum aws_mqtt_client_connection_state state) {
98 ASSERT_SYNCED_DATA_LOCK_HELD(connection);
99 if (connection->synced_data.state == state) {
100 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: MQTT connection already in state %d", (void *)connection, state);
101 return;
102 }
103 connection->synced_data.state = state;
104 }
105
106 static void s_request_timeout(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
107 (void)channel_task;
108 struct request_timeout_task_arg *timeout_task_arg = arg;
109 struct aws_mqtt_client_connection_311_impl *connection = timeout_task_arg->connection;
110
111 if (status == AWS_TASK_STATUS_RUN_READY) {
112 if (timeout_task_arg->task_arg_wrapper != NULL) {
113 mqtt_request_complete(connection, AWS_ERROR_MQTT_TIMEOUT, timeout_task_arg->packet_id);
114 }
115 }
116
117 /*
118 * Whether cancelled or run, if we have a back pointer to the operation's task arg, we must zero it out
119 * so that when it completes it does not try to cancel us, because we will already be freed.
120 *
121 * If we don't have a back pointer to the operation's task arg, that means it already ran and completed.
122 */
123 if (timeout_task_arg->task_arg_wrapper != NULL) {
124 timeout_task_arg->task_arg_wrapper->timeout_task_arg = NULL;
125 timeout_task_arg->task_arg_wrapper = NULL;
126 }
127
128 aws_mem_release(connection->allocator, timeout_task_arg);
129 }
130
131 static struct request_timeout_task_arg *s_schedule_timeout_task(
132 struct aws_mqtt_client_connection_311_impl *connection,
133 uint16_t packet_id,
134 uint64_t timeout_duration_in_ns) {
135
136 if (timeout_duration_in_ns == UINT64_MAX || timeout_duration_in_ns == 0 || packet_id == 0) {
137 return NULL;
138 }
139
140 /* schedule a timeout task to run, in case server never sends us an ack */
141 struct aws_channel_task *request_timeout_task = NULL;
142 struct request_timeout_task_arg *timeout_task_arg = NULL;
143 if (!aws_mem_acquire_many(
144 connection->allocator,
145 2,
146 &timeout_task_arg,
147 sizeof(struct request_timeout_task_arg),
148 &request_timeout_task,
149 sizeof(struct aws_channel_task))) {
150 return NULL;
151 }
152 aws_channel_task_init(request_timeout_task, s_request_timeout, timeout_task_arg, "mqtt_request_timeout");
153 AWS_ZERO_STRUCT(*timeout_task_arg);
154 timeout_task_arg->connection = connection;
155 timeout_task_arg->packet_id = packet_id;
156 uint64_t timestamp = 0;
157 if (aws_channel_current_clock_time(connection->slot->channel, &timestamp)) {
158 aws_mem_release(connection->allocator, timeout_task_arg);
159 return NULL;
160 }
161 timestamp = aws_add_u64_saturating(timestamp, timeout_duration_in_ns);
162 aws_channel_schedule_task_future(connection->slot->channel, request_timeout_task, timestamp);
163 return timeout_task_arg;
164 }
165
166 static void s_init_statistics(struct aws_mqtt_connection_operation_statistics_impl *stats) {
167 aws_atomic_store_int(&stats->incomplete_operation_count_atomic, 0);
168 aws_atomic_store_int(&stats->incomplete_operation_size_atomic, 0);
169 aws_atomic_store_int(&stats->unacked_operation_count_atomic, 0);
170 aws_atomic_store_int(&stats->unacked_operation_size_atomic, 0);
171 }
172
173 static bool s_is_topic_shared_topic(struct aws_byte_cursor *input) {
174 char *input_str = (char *)input->ptr;
175 if (strncmp("$share/", input_str, strlen("$share/")) == 0) {
176 return true;
177 }
178 return false;
179 }
180
181 static struct aws_string *s_get_normal_topic_from_shared_topic(struct aws_string *input) {
182 const char *input_char_str = aws_string_c_str(input);
183 size_t input_char_length = strlen(input_char_str);
184 size_t split_position = 7; // Start at '$share/' since we know it has to exist
185 while (split_position < input_char_length) {
186 split_position += 1;
187 if (input_char_str[split_position] == '/') {
188 break;
189 }
190 }
191 // If we got all the way to the end, OR there is not at least a single character
192 // after the second /, then it's invalid input.
193 if (split_position + 1 >= input_char_length) {
194 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "Cannot parse shared subscription topic: Topic is not formatted correctly");
195 return NULL;
196 }
197 const size_t split_delta = input_char_length - split_position;
198 if (split_delta > 0) {
199 // Annoyingly, we cannot just use 'char result_char[split_delta];' because
200 // MSVC doesn't support it.
201 char *result_char = aws_mem_calloc(input->allocator, split_delta, sizeof(char));
202 strncpy(result_char, input_char_str + split_position + 1, split_delta);
203 struct aws_string *result_string = aws_string_new_from_c_str(input->allocator, (const char *)result_char);
204 aws_mem_release(input->allocator, result_char);
205 return result_string;
206 }
207 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "Cannot parse shared subscription topic: Topic is not formatted correctly");
208 return NULL;
209 }
210
211 /*******************************************************************************
212 * Client Init
213 ******************************************************************************/
214 struct aws_mqtt_client *aws_mqtt_client_new(struct aws_allocator *allocator, struct aws_client_bootstrap *bootstrap) {
215
216 aws_mqtt_fatal_assert_library_initialized();
217
218 struct aws_mqtt_client *client = aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt_client));
219 if (client == NULL) {
220 return NULL;
221 }
222
223 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "client=%p: Initalizing MQTT client", (void *)client);
224
225 client->allocator = allocator;
226 client->bootstrap = aws_client_bootstrap_acquire(bootstrap);
227 aws_ref_count_init(&client->ref_count, client, (aws_simple_completion_callback *)s_aws_mqtt_client_destroy);
228
229 return client;
230 }
231
232 struct aws_mqtt_client *aws_mqtt_client_acquire(struct aws_mqtt_client *client) {
233 if (client != NULL) {
234 aws_ref_count_acquire(&client->ref_count);
235 }
236
237 return client;
238 }
239
240 void aws_mqtt_client_release(struct aws_mqtt_client *client) {
241 if (client != NULL) {
242 aws_ref_count_release(&client->ref_count);
243 }
244 }
245
246 #define AWS_RESET_RECONNECT_BACKOFF_DELAY_SECONDS 10
247
248 /* At this point, the channel for the MQTT connection has completed its shutdown */
249 static void s_mqtt_client_shutdown(
250 struct aws_client_bootstrap *bootstrap,
251 int error_code,
252 struct aws_channel *channel,
253 void *user_data) {
254
255 (void)bootstrap;
256 (void)channel;
257
258 struct aws_mqtt_client_connection_311_impl *connection = user_data;
259 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(connection->loop));
260
261 AWS_LOGF_TRACE(
262 AWS_LS_MQTT_CLIENT, "id=%p: Channel has been shutdown with error code %d", (void *)connection, error_code);
263
264 enum aws_mqtt_client_connection_state prev_state;
265 struct aws_linked_list cancelling_requests;
266 aws_linked_list_init(&cancelling_requests);
267 bool disconnected_state = false;
268 { /* BEGIN CRITICAL SECTION */
269 mqtt_connection_lock_synced_data(connection);
270
271 /*
272 * On a channel that represents a valid connection (successful connack received),
273 * channel_successful_connack_timestamp_ns will be the time the connack was received. Otherwise it will be
274 * zero.
275 *
276 * Use that fact to determine whether or not we should reset the current reconnect backoff delay.
277 *
278 * We reset the reconnect backoff if either of:
279 * 1) the user called disconnect()
280 * 2) a successful connection had lasted longer than our minimum reset time (10s at the moment)
281 */
282 uint64_t now = 0;
283 aws_high_res_clock_get_ticks(&now);
284 uint64_t time_diff = now - connection->reconnect_timeouts.channel_successful_connack_timestamp_ns;
285
286 bool was_user_disconnect = connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING;
287 bool was_sufficiently_long_connection =
288 (connection->reconnect_timeouts.channel_successful_connack_timestamp_ns != 0) &&
289 (time_diff >=
290 aws_timestamp_convert(
291 AWS_RESET_RECONNECT_BACKOFF_DELAY_SECONDS, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL));
292
293 if (was_user_disconnect || was_sufficiently_long_connection) {
294 connection->reconnect_timeouts.current_sec = connection->reconnect_timeouts.min_sec;
295 }
296 connection->reconnect_timeouts.channel_successful_connack_timestamp_ns = 0;
297
298 /* Move all the ongoing requests to the pending requests list, because the response they are waiting for will
299 * never arrives. Sad. But, we will retry. */
300 if (connection->clean_session) {
301 /* For a clean session, the Session lasts as long as the Network Connection. Thus, discard the previous
302 * session */
303 AWS_LOGF_TRACE(
304 AWS_LS_MQTT_CLIENT,
305 "id=%p: Discard ongoing requests and pending requests when a clean session connection lost.",
306 (void *)connection);
307 aws_linked_list_move_all_back(&cancelling_requests, &connection->thread_data.ongoing_requests_list);
308 aws_linked_list_move_all_back(&cancelling_requests, &connection->synced_data.pending_requests_list);
309 } else {
310 aws_linked_list_move_all_back(
311 &connection->synced_data.pending_requests_list, &connection->thread_data.ongoing_requests_list);
312 AWS_LOGF_TRACE(
313 AWS_LS_MQTT_CLIENT,
314 "id=%p: All subscribe/unsubscribe and publish QoS>0 have been move to pending list",
315 (void *)connection);
316 }
317 prev_state = connection->synced_data.state;
318 switch (connection->synced_data.state) {
319 case AWS_MQTT_CLIENT_STATE_CONNECTED:
320 /* unexpected hangup from broker, try to reconnect */
321 mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_RECONNECTING);
322 AWS_LOGF_DEBUG(
323 AWS_LS_MQTT_CLIENT,
324 "id=%p: connection was unexpected interrupted, switch state to RECONNECTING.",
325 (void *)connection);
326 break;
327 case AWS_MQTT_CLIENT_STATE_DISCONNECTING:
328 /* disconnect requested by user */
329 /* Successfully shutdown, if cleansession is set, ongoing and pending requests will be cleared */
330 disconnected_state = true;
331 AWS_LOGF_DEBUG(
332 AWS_LS_MQTT_CLIENT,
333 "id=%p: disconnect finished, switch state to DISCONNECTED.",
334 (void *)connection);
335 break;
336 case AWS_MQTT_CLIENT_STATE_CONNECTING:
337 /* failed to connect */
338 disconnected_state = true;
339 break;
340 case AWS_MQTT_CLIENT_STATE_RECONNECTING:
341 /* reconnect failed, schedule the next attempt later, no need to change the state. */
342 break;
343 default:
344 /* AWS_MQTT_CLIENT_STATE_DISCONNECTED */
345 break;
346 }
347 AWS_LOGF_TRACE(
348 AWS_LS_MQTT_CLIENT, "id=%p: current state is %d", (void *)connection, (int)connection->synced_data.state);
349 /* Always clear slot, as that's what's been shutdown */
350 if (connection->slot) {
351 aws_channel_slot_remove(connection->slot);
352 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: slot is removed successfully", (void *)connection);
353 connection->slot = NULL;
354 }
355
356 mqtt_connection_unlock_synced_data(connection);
357 } /* END CRITICAL SECTION */
358
359 if (!aws_linked_list_empty(&cancelling_requests)) {
360 struct aws_linked_list_node *current = aws_linked_list_front(&cancelling_requests);
361 const struct aws_linked_list_node *end = aws_linked_list_end(&cancelling_requests);
362 while (current != end) {
363 struct aws_mqtt_request *request = AWS_CONTAINER_OF(current, struct aws_mqtt_request, list_node);
364 if (request->on_complete) {
365 request->on_complete(
366 &connection->base,
367 request->packet_id,
368 AWS_ERROR_MQTT_CANCELLED_FOR_CLEAN_SESSION,
369 request->on_complete_ud);
370 }
371 current = current->next;
372 }
373 { /* BEGIN CRITICAL SECTION */
374 mqtt_connection_lock_synced_data(connection);
375 while (!aws_linked_list_empty(&cancelling_requests)) {
376 struct aws_linked_list_node *node = aws_linked_list_pop_front(&cancelling_requests);
377 struct aws_mqtt_request *request = AWS_CONTAINER_OF(node, struct aws_mqtt_request, list_node);
378 aws_hash_table_remove(
379 &connection->synced_data.outstanding_requests_table, &request->packet_id, NULL, NULL);
380 aws_memory_pool_release(&connection->synced_data.requests_pool, request);
381 }
382 mqtt_connection_unlock_synced_data(connection);
383 } /* END CRITICAL SECTION */
384 }
385
386 /* If there's no error code and this wasn't user-requested, set the error code to something useful */
387 if (error_code == AWS_ERROR_SUCCESS) {
388 if (prev_state != AWS_MQTT_CLIENT_STATE_DISCONNECTING && prev_state != AWS_MQTT_CLIENT_STATE_DISCONNECTED) {
389 error_code = AWS_ERROR_MQTT_UNEXPECTED_HANGUP;
390 }
391 }
392 switch (prev_state) {
393 case AWS_MQTT_CLIENT_STATE_RECONNECTING: {
394 /* If reconnect attempt failed, schedule the next attempt */
395 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Reconnect failed, retrying", (void *)connection);
396 s_aws_mqtt_schedule_reconnect_task(connection);
397 break;
398 }
399 case AWS_MQTT_CLIENT_STATE_CONNECTED: {
400 AWS_LOGF_DEBUG(
401 AWS_LS_MQTT_CLIENT,
402 "id=%p: Connection interrupted, calling callback and attempting reconnect",
403 (void *)connection);
404 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_interrupted, error_code);
405 aws_mqtt311_callback_set_manager_on_connection_interrupted(&connection->callback_manager, error_code);
406
407 /* In case user called disconnect from the on_interrupted callback */
408 bool stop_reconnect;
409 { /* BEGIN CRITICAL SECTION */
410 mqtt_connection_lock_synced_data(connection);
411 stop_reconnect = connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING;
412 if (stop_reconnect) {
413 disconnected_state = true;
414 AWS_LOGF_DEBUG(
415 AWS_LS_MQTT_CLIENT,
416 "id=%p: disconnect finished, switch state to DISCONNECTED.",
417 (void *)connection);
418 }
419 mqtt_connection_unlock_synced_data(connection);
420 } /* END CRITICAL SECTION */
421
422 if (!stop_reconnect) {
423 s_aws_mqtt_schedule_reconnect_task(connection);
424 }
425 break;
426 }
427 default:
428 break;
429 }
430 if (disconnected_state) {
431 { /* BEGIN CRITICAL SECTION */
432 mqtt_connection_lock_synced_data(connection);
433 mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_DISCONNECTED);
434 mqtt_connection_unlock_synced_data(connection);
435 } /* END CRITICAL SECTION */
436 switch (prev_state) {
437 case AWS_MQTT_CLIENT_STATE_CONNECTED:
438 AWS_LOGF_TRACE(
439 AWS_LS_MQTT_CLIENT,
440 "id=%p: Caller requested disconnect from on_interrupted callback, aborting reconnect",
441 (void *)connection);
442 MQTT_CLIENT_CALL_CALLBACK(connection, on_disconnect);
443 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_closed, NULL);
444 aws_mqtt311_callback_set_manager_on_disconnect(&connection->callback_manager);
445 break;
446 case AWS_MQTT_CLIENT_STATE_DISCONNECTING:
447 AWS_LOGF_DEBUG(
448 AWS_LS_MQTT_CLIENT,
449 "id=%p: Disconnect completed, clearing request queue and calling callback",
450 (void *)connection);
451 MQTT_CLIENT_CALL_CALLBACK(connection, on_disconnect);
452 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_closed, NULL);
453 aws_mqtt311_callback_set_manager_on_disconnect(&connection->callback_manager);
454 break;
455 case AWS_MQTT_CLIENT_STATE_CONNECTING:
456 AWS_LOGF_TRACE(
457 AWS_LS_MQTT_CLIENT,
458 "id=%p: Initial connection attempt failed, calling callback",
459 (void *)connection);
460 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_connection_complete, error_code, 0, false);
461 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_connection_failure, error_code);
462 break;
463 default:
464 break;
465 }
466 /* The connection can die now. Release the refcount */
467 aws_mqtt_client_connection_release(&connection->base);
468 }
469 }
470
471 /*******************************************************************************
472 * Connection New
473 ******************************************************************************/
474 /* The assumption here is that a connection always outlives its channels, and the channel this task was scheduled on
475 * always outlives this task, so all we need to do is check the connection state. If we are in a state that waits
476 * for a CONNACK, kill it off. In the case that the connection died between scheduling this task and it being executed
477 * the status will always be CANCELED because this task will be canceled when the owning channel goes away. */
478 static void s_connack_received_timeout(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
479 struct aws_mqtt_client_connection_311_impl *connection = arg;
480
481 if (status == AWS_TASK_STATUS_RUN_READY) {
482 bool time_out = false;
483 { /* BEGIN CRITICAL SECTION */
484 mqtt_connection_lock_synced_data(connection);
485 time_out =
486 (connection->synced_data.state == AWS_MQTT_CLIENT_STATE_CONNECTING ||
487 connection->synced_data.state == AWS_MQTT_CLIENT_STATE_RECONNECTING);
488 mqtt_connection_unlock_synced_data(connection);
489 } /* END CRITICAL SECTION */
490 if (time_out) {
491 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: mqtt CONNACK response timeout detected", (void *)connection);
492 aws_channel_shutdown(connection->slot->channel, AWS_ERROR_MQTT_TIMEOUT);
493 }
494 }
495
496 aws_mem_release(connection->allocator, channel_task);
497 }
498
499 /**
500 * Channel has been initialized callback. Sets up channel handler and sends out CONNECT packet.
501 * The on_connack callback is called with the CONNACK packet is received from the server.
502 */
503 static void s_mqtt_client_init(
504 struct aws_client_bootstrap *bootstrap,
505 int error_code,
506 struct aws_channel *channel,
507 void *user_data) {
508
509 (void)bootstrap;
510 struct aws_io_message *message = NULL;
511
512 /* Setup callback contract is: if error_code is non-zero then channel is NULL. */
513 AWS_FATAL_ASSERT((error_code != 0) == (channel == NULL));
514
515 struct aws_mqtt_client_connection_311_impl *connection = user_data;
516 struct aws_byte_buf username_with_metrics_buf;
517 AWS_ZERO_STRUCT(username_with_metrics_buf);
518
519 if (error_code != AWS_OP_SUCCESS) {
520 /* client shutdown already handles this case, so just call that. */
521 s_mqtt_client_shutdown(bootstrap, error_code, channel, user_data);
522 return;
523 }
524
525 AWS_FATAL_ASSERT(aws_channel_get_event_loop(channel) == connection->loop);
526
527 /* user requested disconnect before the channel has been set up. Stop installing the slot and sending CONNECT. */
528 bool failed_create_slot = false;
529
530 { /* BEGIN CRITICAL SECTION */
531 mqtt_connection_lock_synced_data(connection);
532
533 if (connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING) {
534 /* It only happens when the user request disconnect during reconnecting, we don't need to fire any callback.
535 * The on_disconnect will be invoked as channel finish shutting down. */
536 mqtt_connection_unlock_synced_data(connection);
537 aws_channel_shutdown(channel, AWS_ERROR_SUCCESS);
538 return;
539 }
540 /* Create the slot */
541 connection->slot = aws_channel_slot_new(channel);
542 if (!connection->slot) {
543 failed_create_slot = true;
544 }
545 mqtt_connection_unlock_synced_data(connection);
546 } /* END CRITICAL SECTION */
547
548 /* install the slot and handler */
549 if (failed_create_slot) {
550
551 AWS_LOGF_ERROR(
552 AWS_LS_MQTT_CLIENT,
553 "id=%p: Failed to create new slot, something has gone horribly wrong, error %d (%s).",
554 (void *)connection,
555 aws_last_error(),
556 aws_error_name(aws_last_error()));
557 goto handle_error;
558 }
559
560 if (aws_channel_slot_insert_end(channel, connection->slot)) {
561 AWS_LOGF_ERROR(
562 AWS_LS_MQTT_CLIENT,
563 "id=%p: Failed to insert slot into channel %p, error %d (%s).",
564 (void *)connection,
565 (void *)channel,
566 aws_last_error(),
567 aws_error_name(aws_last_error()));
568 goto handle_error;
569 }
570
571 if (aws_channel_slot_set_handler(connection->slot, &connection->handler)) {
572 AWS_LOGF_ERROR(
573 AWS_LS_MQTT_CLIENT,
574 "id=%p: Failed to set MQTT handler into slot on channel %p, error %d (%s).",
575 (void *)connection,
576 (void *)channel,
577 aws_last_error(),
578 aws_error_name(aws_last_error()));
579
580 goto handle_error;
581 }
582
583 aws_mqtt311_decoder_reset_for_new_connection(&connection->thread_data.decoder);
584
585 AWS_LOGF_DEBUG(
586 AWS_LS_MQTT_CLIENT, "id=%p: Connection successfully opened, sending CONNECT packet", (void *)connection);
587
588 struct aws_channel_task *connack_task = aws_mem_calloc(connection->allocator, 1, sizeof(struct aws_channel_task));
589 if (!connack_task) {
590 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to allocate timeout task.", (void *)connection);
591 goto handle_error;
592 }
593
594 aws_channel_task_init(connack_task, s_connack_received_timeout, connection, "mqtt_connack_timeout");
595
596 uint64_t now = 0;
597 if (aws_channel_current_clock_time(channel, &now)) {
598 AWS_LOGF_ERROR(
599 AWS_LS_MQTT_CLIENT,
600 "static: Failed to setting MQTT handler into slot on channel %p, error %d (%s).",
601 (void *)channel,
602 aws_last_error(),
603 aws_error_name(aws_last_error()));
604
605 goto handle_error;
606 }
607 now += connection->ping_timeout_ns;
608 aws_channel_schedule_task_future(channel, connack_task, now);
609
610 struct aws_byte_cursor client_id_cursor = aws_byte_cursor_from_buf(&connection->client_id);
611 AWS_LOGF_DEBUG(
612 AWS_LS_MQTT_CLIENT,
613 "id=%p: MQTT Connection initializing CONNECT packet for client-id '" PRInSTR "'",
614 (void *)connection,
615 AWS_BYTE_CURSOR_PRI(client_id_cursor));
616
617 /* Send the connect packet */
618 struct aws_mqtt_packet_connect connect;
619 aws_mqtt_packet_connect_init(
620 &connect, client_id_cursor, connection->clean_session, connection->keep_alive_time_secs);
621
622 if (connection->will.topic.buffer) {
623 /* Add will if present */
624
625 struct aws_byte_cursor topic_cur = aws_byte_cursor_from_buf(&connection->will.topic);
626 struct aws_byte_cursor payload_cur = aws_byte_cursor_from_buf(&connection->will.payload);
627
628 AWS_LOGF_DEBUG(
629 AWS_LS_MQTT_CLIENT,
630 "id=%p: Adding will to connection on " PRInSTR " with payload " PRInSTR,
631 (void *)connection,
632 AWS_BYTE_CURSOR_PRI(topic_cur),
633 AWS_BYTE_CURSOR_PRI(payload_cur));
634 aws_mqtt_packet_connect_add_will(
635 &connect, topic_cur, connection->will.qos, connection->will.retain, payload_cur);
636 }
637
638 struct aws_byte_cursor username_cur;
639 AWS_ZERO_STRUCT(username_cur);
640 if (connection->username) {
641 username_cur = aws_byte_cursor_from_string(connection->username);
642 }
643
644 if (aws_mqtt_has_non_empty_username(&username_cur, connection->metrics_storage)) {
645
646 /* Apply metrics to username if configured */
647 if (connection->metrics_storage) {
648 if (aws_mqtt_append_sdk_metrics_to_username(
649 connection->allocator,
650 &username_cur,
651 &connection->metrics_storage->storage_view,
652 &username_with_metrics_buf,
653 NULL) == AWS_OP_SUCCESS) {
654 username_cur = aws_byte_cursor_from_buf(&username_with_metrics_buf);
655 } else {
656 AWS_LOGF_WARN(
657 AWS_LS_MQTT_CLIENT,
658 "id=%p: Failed to apply metrics to username, using original",
659 (void *)connection);
660 }
661 }
662
663 if (aws_byte_cursor_is_valid(&username_cur) && username_cur.len > 0) {
664
665 struct aws_byte_cursor password_cur;
666 AWS_ZERO_STRUCT(password_cur);
667
668 if (connection->password) {
669 password_cur = aws_byte_cursor_from_string(connection->password);
670 }
671
672 AWS_LOGF_DEBUG(
673 AWS_LS_MQTT_CLIENT,
674 "id=%p: Adding username " PRInSTR " to connection",
675 (void *)connection,
676 AWS_BYTE_CURSOR_PRI(username_cur));
677
678 aws_mqtt_packet_connect_add_credentials(&connect, username_cur, password_cur);
679 } else {
680 AWS_LOGF_INFO(
681 AWS_LS_MQTT_CLIENT,
682 "id=%p: Failed to set username and password. Most likely there is an issue in metrics. (e.x.: username "
683 "is empty and metrics string exceed the size limit). ",
684 (void *)connection);
685 }
686 }
687
688 message = mqtt_get_message_for_packet(connection, &connect.fixed_header);
689 if (!message) {
690
691 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to get message from pool", (void *)connection);
692 goto handle_error;
693 }
694
695 if (aws_mqtt_packet_connect_encode(&message->message_data, &connect)) {
696
697 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to encode CONNECT packet", (void *)connection);
698 goto handle_error;
699 }
700
701 if (aws_channel_slot_send_message(connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
702
703 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to send encoded CONNECT packet upstream", (void *)connection);
704 goto handle_error;
705 }
706
707 aws_byte_buf_clean_up(&username_with_metrics_buf);
708 return;
709
710 handle_error:
711 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_connection_complete, aws_last_error(), 0, false);
712 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_connection_failure, aws_last_error());
713 aws_channel_shutdown(channel, aws_last_error());
714
715 aws_byte_buf_clean_up(&username_with_metrics_buf);
716
717 if (message) {
718 aws_mem_release(message->allocator, message);
719 }
720 }
721
722 static void s_attempt_reconnect(struct aws_task *task, void *userdata, enum aws_task_status status) {
723
724 (void)task;
725
726 struct aws_mqtt_reconnect_task *reconnect = userdata;
727 struct aws_mqtt_client_connection_311_impl *connection = aws_atomic_load_ptr(&reconnect->connection_ptr);
728
729 /* If the task is not cancelled and a connection has not succeeded, attempt reconnect */
730 if (status == AWS_TASK_STATUS_RUN_READY && connection) {
731 mqtt_connection_lock_synced_data(connection);
732
733 /**
734 * Check the state and if we are disconnecting (AWS_MQTT_CLIENT_STATE_DISCONNECTING) then we want to skip it
735 * and abort the reconnect task (or rather, just do not try to reconnect)
736 */
737 if (connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING) {
738 AWS_LOGF_TRACE(
739 AWS_LS_MQTT_CLIENT, "id=%p: Skipping reconnect: Client is trying to disconnect", (void *)connection);
740
741 /**
742 * There is the nasty world where the disconnect task/function is called right when we are "reconnecting" as
743 * our state but we have not reconnected. When this happens, the disconnect function doesn't do anything
744 * beyond setting the state to AWS_MQTT_CLIENT_STATE_DISCONNECTING (aws_mqtt_client_connection_disconnect),
745 * meaning the disconnect callback will NOT be called nor will we release memory.
746 * For this reason, we have to do the callback and release of the connection here otherwise the code
747 * will DEADLOCK forever and that is bad.
748 */
749 bool perform_full_destroy = false;
750 if (!connection->slot) {
751 AWS_LOGF_TRACE(
752 AWS_LS_MQTT_CLIENT,
753 "id=%p: Reconnect task called but client is disconnecting and has no slot. Finishing disconnect",
754 (void *)connection);
755 mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_DISCONNECTED);
756 perform_full_destroy = true;
757 }
758
759 aws_mem_release(reconnect->allocator, reconnect);
760 connection->reconnect_task = NULL;
761
762 /* Unlock the synced data, then potentially call the disconnect callback and release the connection */
763 mqtt_connection_unlock_synced_data(connection);
764 if (perform_full_destroy) {
765 MQTT_CLIENT_CALL_CALLBACK(connection, on_disconnect);
766 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_closed, NULL);
767 aws_mqtt_client_connection_release(&connection->base);
768 }
769 return;
770 }
771
772 AWS_LOGF_TRACE(
773 AWS_LS_MQTT_CLIENT,
774 "id=%p: Attempting reconnect, if it fails next attempt will be in %" PRIu64 " seconds",
775 (void *)connection,
776 connection->reconnect_timeouts.current_sec);
777
778 /* Check before multiplying to avoid potential overflow */
779 if (connection->reconnect_timeouts.current_sec > connection->reconnect_timeouts.max_sec / 2) {
780 connection->reconnect_timeouts.current_sec = connection->reconnect_timeouts.max_sec;
781 } else {
782 connection->reconnect_timeouts.current_sec *= 2;
783 }
784
785 AWS_LOGF_TRACE(
786 AWS_LS_MQTT_CLIENT,
787 "id=%p: Attempting reconnect, if it fails next attempt will be in %" PRIu64 " seconds",
788 (void *)connection,
789 connection->reconnect_timeouts.current_sec);
790
791 mqtt_connection_unlock_synced_data(connection);
792
793 if (s_mqtt_client_connect(
794 connection, connection->on_connection_complete, connection->on_connection_complete_ud)) {
795 /* If reconnect attempt failed, schedule the next attempt */
796 s_aws_mqtt_schedule_reconnect_task(connection);
797 } else {
798 /* Ideally, it would be nice to move this inside the lock, but I'm unsure of the correctness */
799 connection->reconnect_task->task.timestamp = 0;
800 }
801 } else {
802 aws_mem_release(reconnect->allocator, reconnect);
803 }
804 }
805
806 void aws_create_reconnect_task(struct aws_mqtt_client_connection_311_impl *connection) {
807 if (connection->reconnect_task == NULL) {
808 connection->reconnect_task = aws_mem_calloc(connection->allocator, 1, sizeof(struct aws_mqtt_reconnect_task));
809 AWS_FATAL_ASSERT(connection->reconnect_task != NULL);
810
811 aws_atomic_init_ptr(&connection->reconnect_task->connection_ptr, connection);
812 connection->reconnect_task->allocator = connection->allocator;
813 aws_task_init(
814 &connection->reconnect_task->task, s_attempt_reconnect, connection->reconnect_task, "mqtt_reconnect");
815 }
816 }
817
818 static void s_mqtt_client_connection_destroy_final(struct aws_mqtt_client_connection *base_connection) {
819
820 struct aws_mqtt_client_connection_311_impl *connection = base_connection->impl;
821 AWS_PRECONDITION(!connection || connection->allocator);
822 if (!connection) {
823 return;
824 }
825
826 /* If the slot is not NULL, the connection is still connected, which should be prevented from calling this function
827 */
828 AWS_ASSERT(!connection->slot);
829
830 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Destroying connection", (void *)connection);
831
832 aws_mqtt_client_on_connection_termination_fn *termination_handler = NULL;
833 void *termination_handler_user_data = NULL;
834 if (connection->on_termination != NULL) {
835 termination_handler = connection->on_termination;
836 termination_handler_user_data = connection->on_termination_ud;
837 }
838
839 aws_mqtt311_callback_set_manager_clean_up(&connection->callback_manager);
840
841 /* If the reconnect_task isn't freed, free it */
842 if (connection->reconnect_task) {
843 aws_mem_release(connection->reconnect_task->allocator, connection->reconnect_task);
844 }
845 aws_string_destroy(connection->host_name);
846
847 /* Clear the credentials */
848 if (connection->username) {
849 aws_string_destroy_secure(connection->username);
850 }
851 if (connection->password) {
852 aws_string_destroy_secure(connection->password);
853 }
854
855 /* Clean up the will */
856 aws_byte_buf_clean_up(&connection->will.topic);
857 aws_byte_buf_clean_up(&connection->will.payload);
858
859 /* Clear the client_id */
860 aws_byte_buf_clean_up(&connection->client_id);
861
862 /* Free all of the active subscriptions */
863 aws_mqtt_topic_tree_clean_up(&connection->thread_data.subscriptions);
864
865 aws_mqtt311_decoder_clean_up(&connection->thread_data.decoder);
866
867 aws_hash_table_clean_up(&connection->synced_data.outstanding_requests_table);
868 /* clean up the pending_requests if it's not empty */
869 while (!aws_linked_list_empty(&connection->synced_data.pending_requests_list)) {
870 struct aws_linked_list_node *node = aws_linked_list_pop_front(&connection->synced_data.pending_requests_list);
871 struct aws_mqtt_request *request = AWS_CONTAINER_OF(node, struct aws_mqtt_request, list_node);
872 /* Fire the callback and clean up the memory, as the connection get destroyed. */
873 if (request->on_complete) {
874 request->on_complete(
875 &connection->base, request->packet_id, AWS_ERROR_MQTT_CONNECTION_DESTROYED, request->on_complete_ud);
876 }
877 aws_memory_pool_release(&connection->synced_data.requests_pool, request);
878 }
879 aws_memory_pool_clean_up(&connection->synced_data.requests_pool);
880
881 aws_mutex_clean_up(&connection->synced_data.lock);
882 aws_rw_lock_clean_up(&connection->callback_lock);
883
884 aws_tls_connection_options_clean_up(&connection->tls_options);
885
886 /* Clean up the websocket proxy options */
887 if (connection->http_proxy_config) {
888 aws_http_proxy_config_destroy(connection->http_proxy_config);
889 connection->http_proxy_config = NULL;
890 }
891
892 /* Clean up metrics */
893 if (connection->metrics_storage) {
894 aws_mqtt_iot_metrics_storage_destroy(connection->metrics_storage);
895 connection->metrics_storage = NULL;
896 }
897
898 aws_mqtt_client_release(connection->client);
899
900 /* Frees all allocated memory */
901 aws_mem_release(connection->allocator, connection);
902
903 if (termination_handler != NULL) {
904 (*termination_handler)(termination_handler_user_data);
905 }
906 }
907
908 static void s_on_final_disconnect(struct aws_mqtt_client_connection *connection, void *userdata) {
909 (void)userdata;
910
911 s_mqtt_client_connection_destroy_final(connection);
912 }
913
914 static void s_mqtt_client_connection_start_destroy(struct aws_mqtt_client_connection_311_impl *connection) {
915 bool call_destroy_final = false;
916
917 AWS_LOGF_DEBUG(
918 AWS_LS_MQTT_CLIENT,
919 "id=%p: Last refcount on connection has been released, start destroying the connection.",
920 (void *)connection);
921 { /* BEGIN CRITICAL SECTION */
922 mqtt_connection_lock_synced_data(connection);
923 if (connection->synced_data.state != AWS_MQTT_CLIENT_STATE_DISCONNECTED) {
924 /*
925 * We don't call the on_disconnect callback until we've transitioned to the DISCONNECTED state. So it's
926 * safe to change it now while we hold the lock since we know we're not DISCONNECTED yet.
927 */
928 connection->on_disconnect = s_on_final_disconnect;
929
930 if (connection->synced_data.state != AWS_MQTT_CLIENT_STATE_DISCONNECTING) {
931 mqtt_disconnect_impl(connection, AWS_ERROR_SUCCESS);
932 AWS_LOGF_DEBUG(
933 AWS_LS_MQTT_CLIENT,
934 "id=%p: final refcount has been released, switch state to DISCONNECTING.",
935 (void *)connection);
936 mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_DISCONNECTING);
937 }
938 } else {
939 call_destroy_final = true;
940 }
941
942 mqtt_connection_unlock_synced_data(connection);
943 } /* END CRITICAL SECTION */
944
945 if (call_destroy_final) {
946 s_mqtt_client_connection_destroy_final(&connection->base);
947 }
948 }
949
950 /*******************************************************************************
951 * Connection Configuration
952 ******************************************************************************/
953
954 static int s_aws_mqtt_client_connection_311_set_will(
955 void *impl,
956 const struct aws_byte_cursor *topic,
957 enum aws_mqtt_qos qos,
958 bool retain,
959 const struct aws_byte_cursor *payload) {
960
961 struct aws_mqtt_client_connection_311_impl *connection = impl;
962
963 AWS_PRECONDITION(connection);
964 AWS_PRECONDITION(topic);
965
966 if (!aws_mqtt_is_valid_topic(topic)) {
967 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Will topic is invalid", (void *)connection);
968 return aws_raise_error(AWS_ERROR_MQTT_INVALID_TOPIC);
969 }
970
971 if (qos > AWS_MQTT_QOS_EXACTLY_ONCE) {
972 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Will qos is invalid", (void *)connection);
973 return aws_raise_error(AWS_ERROR_MQTT_INVALID_QOS);
974 }
975
976 int result = AWS_OP_ERR;
977 AWS_LOGF_TRACE(
978 AWS_LS_MQTT_CLIENT,
979 "id=%p: Setting last will with topic \"" PRInSTR "\"",
980 (void *)connection,
981 AWS_BYTE_CURSOR_PRI(*topic));
982
983 struct aws_byte_buf local_topic_buf;
984 struct aws_byte_buf local_payload_buf;
985 AWS_ZERO_STRUCT(local_topic_buf);
986 AWS_ZERO_STRUCT(local_payload_buf);
987 struct aws_byte_buf topic_buf = aws_byte_buf_from_array(topic->ptr, topic->len);
988 if (aws_byte_buf_init_copy(&local_topic_buf, connection->allocator, &topic_buf)) {
989 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to copy will topic", (void *)connection);
990 goto cleanup;
991 }
992
993 struct aws_byte_buf payload_buf = aws_byte_buf_from_array(payload->ptr, payload->len);
994 if (aws_byte_buf_init_copy(&local_payload_buf, connection->allocator, &payload_buf)) {
995 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to copy will body", (void *)connection);
996 goto cleanup;
997 }
998
999 { /* BEGIN CRITICAL SECTION */
1000 mqtt_connection_lock_synced_data(connection);
1001
1002 /* Check state and modify connection under lock to ensure thread safety */
1003 if (!s_is_valid_connection_state_for_configuration(connection)) {
1004 AWS_LOGF_ERROR(
1005 AWS_LS_MQTT_CLIENT,
1006 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
1007 "pending operation completes.",
1008 (void *)connection);
1009 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1010 } else {
1011 connection->will.qos = qos;
1012 connection->will.retain = retain;
1013
1014 if (connection->will.topic.len) {
1015 AWS_LOGF_TRACE(
1016 AWS_LS_MQTT_CLIENT, "id=%p: Will has been set before, resetting it.", (void *)connection);
1017 }
1018
1019 /* swap the local buffer with connection */
1020 struct aws_byte_buf temp = local_topic_buf;
1021 local_topic_buf = connection->will.topic;
1022 connection->will.topic = temp;
1023 temp = local_payload_buf;
1024 local_payload_buf = connection->will.payload;
1025 connection->will.payload = temp;
1026
1027 /* Succeed. */
1028 result = AWS_OP_SUCCESS;
1029 }
1030
1031 mqtt_connection_unlock_synced_data(connection);
1032 } /* END CRITICAL SECTION */
1033
1034 cleanup:
1035 aws_byte_buf_clean_up(&local_topic_buf);
1036 aws_byte_buf_clean_up(&local_payload_buf);
1037
1038 return result;
1039 }
1040
1041 static int s_aws_mqtt_client_connection_311_set_login(
1042 void *impl,
1043 const struct aws_byte_cursor *username,
1044 const struct aws_byte_cursor *password) {
1045
1046 struct aws_mqtt_client_connection_311_impl *connection = impl;
1047
1048 AWS_PRECONDITION(connection);
1049 AWS_PRECONDITION(username);
1050
1051 if (username != NULL && aws_mqtt_validate_utf8_text(*username) == AWS_OP_ERR) {
1052 AWS_LOGF_DEBUG(
1053 AWS_LS_MQTT_CLIENT, "id=%p: Invalid utf8 or forbidden codepoints in username", (void *)connection);
1054 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1055 }
1056
1057 int result = AWS_OP_ERR;
1058 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Setting username and password", (void *)connection);
1059
1060 struct aws_string *username_string = NULL;
1061 struct aws_string *password_string = NULL;
1062
1063 username_string = aws_string_new_from_array(connection->allocator, username->ptr, username->len);
1064 if (!username_string) {
1065 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to copy username", (void *)connection);
1066 goto cleanup;
1067 }
1068
1069 if (password) {
1070 password_string = aws_string_new_from_array(connection->allocator, password->ptr, password->len);
1071 if (!password_string) {
1072 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to copy password", (void *)connection);
1073 goto cleanup;
1074 }
1075 }
1076
1077 { /* BEGIN CRITICAL SECTION */
1078 mqtt_connection_lock_synced_data(connection);
1079 /* Check state and modify connection under lock to ensure thread safety */
1080 if (!s_is_valid_connection_state_for_configuration(connection)) {
1081 AWS_LOGF_ERROR(
1082 AWS_LS_MQTT_CLIENT,
1083 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
1084 "pending operation completes.",
1085 (void *)connection);
1086 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1087 } else {
1088
1089 if (connection->username) {
1090 AWS_LOGF_TRACE(
1091 AWS_LS_MQTT_CLIENT,
1092 "id=%p: Login information has been set before, resetting it.",
1093 (void *)connection);
1094 }
1095
1096 /* swap the local string with connection */
1097 struct aws_string *temp = username_string;
1098 username_string = connection->username;
1099 connection->username = temp;
1100 temp = password_string;
1101 password_string = connection->password;
1102 connection->password = temp;
1103
1104 /* Succeed. */
1105 result = AWS_OP_SUCCESS;
1106 }
1107
1108 mqtt_connection_unlock_synced_data(connection);
1109 } /* END CRITICAL SECTION */
1110
1111 cleanup:
1112 aws_string_destroy_secure(username_string);
1113 aws_string_destroy_secure(password_string);
1114
1115 return result;
1116 }
1117
1118 static int s_aws_mqtt_client_connection_311_set_reconnect_timeout(
1119 void *impl,
1120 uint64_t min_timeout,
1121 uint64_t max_timeout) {
1122
1123 struct aws_mqtt_client_connection_311_impl *connection = impl;
1124
1125 AWS_PRECONDITION(connection);
1126
1127 AWS_LOGF_TRACE(
1128 AWS_LS_MQTT_CLIENT,
1129 "id=%p: Setting reconnect timeouts min: %" PRIu64 " max: %" PRIu64,
1130 (void *)connection,
1131 min_timeout,
1132 max_timeout);
1133
1134 int result = AWS_OP_ERR;
1135 /* BEGIN CRITICAL SECTION */
1136 mqtt_connection_lock_synced_data(connection);
1137
1138 /* Check state and modify connection under lock to ensure thread safety */
1139 if (!s_is_valid_connection_state_for_configuration(connection)) {
1140 AWS_LOGF_ERROR(
1141 AWS_LS_MQTT_CLIENT,
1142 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
1143 "pending operation completes.",
1144 (void *)connection);
1145 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1146 goto done;
1147 }
1148
1149 connection->reconnect_timeouts.min_sec = min_timeout;
1150 connection->reconnect_timeouts.max_sec = max_timeout;
1151 connection->reconnect_timeouts.current_sec = min_timeout;
1152 result = AWS_OP_SUCCESS;
1153
1154 done:
1155 mqtt_connection_unlock_synced_data(connection);
1156 /* END CRITICAL SECTION */
1157
1158 return result;
1159 }
1160
1161 static int s_aws_mqtt_client_connection_311_set_connection_result_handlers(
1162 void *impl,
1163 aws_mqtt_client_on_connection_success_fn *on_connection_success,
1164 void *on_connection_success_ud,
1165 aws_mqtt_client_on_connection_failure_fn *on_connection_failure,
1166 void *on_connection_failure_ud) {
1167
1168 struct aws_mqtt_client_connection_311_impl *connection = impl;
1169
1170 AWS_PRECONDITION(connection);
1171 int result = AWS_OP_ERR;
1172
1173 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Setting connection success and failure handlers", (void *)connection);
1174
1175 /* BEGIN CRITICAL SECTION */
1176 mqtt_connection_lock_synced_data(connection);
1177
1178 /* Check state and modify connection under lock to ensure thread safety */
1179 if (!s_is_valid_connection_state_for_configuration(connection)) {
1180 AWS_LOGF_ERROR(
1181 AWS_LS_MQTT_CLIENT,
1182 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
1183 "pending operation completes.",
1184 (void *)connection);
1185 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1186 goto done;
1187 }
1188
1189 if (aws_rw_lock_try_wlock(&connection->callback_lock)) {
1190 AWS_LOGF_ERROR(
1191 AWS_LS_MQTT_CLIENT, "id=%p: Failed to set callback handlers, callbacks are in use.", (void *)connection);
1192 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1193 goto done;
1194 }
1195
1196 connection->on_connection_success = on_connection_success;
1197 connection->on_connection_success_ud = on_connection_success_ud;
1198 connection->on_connection_failure = on_connection_failure;
1199 connection->on_connection_failure_ud = on_connection_failure_ud;
1200 result = AWS_OP_SUCCESS;
1201
1202 aws_rw_lock_wunlock(&connection->callback_lock);
1203
1204 done:
1205 mqtt_connection_unlock_synced_data(connection);
1206 /* END CRITICAL SECTION */
1207
1208 return result;
1209 }
1210
1211 static int s_aws_mqtt_client_connection_311_set_connection_interruption_handlers(
1212 void *impl,
1213 aws_mqtt_client_on_connection_interrupted_fn *on_interrupted,
1214 void *on_interrupted_ud,
1215 aws_mqtt_client_on_connection_resumed_fn *on_resumed,
1216 void *on_resumed_ud) {
1217
1218 struct aws_mqtt_client_connection_311_impl *connection = impl;
1219
1220 AWS_PRECONDITION(connection);
1221
1222 AWS_LOGF_TRACE(
1223 AWS_LS_MQTT_CLIENT, "id=%p: Setting connection interrupted and resumed handlers", (void *)connection);
1224
1225 int result = AWS_OP_ERR;
1226
1227 /* BEGIN CRITICAL SECTION */
1228 mqtt_connection_lock_synced_data(connection);
1229
1230 /* Check state and modify connection under lock to ensure thread safety */
1231 if (!s_is_valid_connection_state_for_configuration(connection)) {
1232 AWS_LOGF_ERROR(
1233 AWS_LS_MQTT_CLIENT,
1234 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
1235 "pending operation completes.",
1236 (void *)connection);
1237 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1238 goto done;
1239 }
1240
1241 if (aws_rw_lock_try_wlock(&connection->callback_lock)) {
1242 AWS_LOGF_ERROR(
1243 AWS_LS_MQTT_CLIENT, "id=%p: Failed to set callback handlers, callbacks are in use.", (void *)connection);
1244 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1245 goto done;
1246 }
1247
1248 connection->on_interrupted = on_interrupted;
1249 connection->on_interrupted_ud = on_interrupted_ud;
1250 connection->on_resumed = on_resumed;
1251 connection->on_resumed_ud = on_resumed_ud;
1252 result = AWS_OP_SUCCESS;
1253
1254 aws_rw_lock_wunlock(&connection->callback_lock);
1255
1256 done:
1257 mqtt_connection_unlock_synced_data(connection);
1258 /* END CRITICAL SECTION */
1259
1260 return result;
1261 }
1262
1263 static int s_aws_mqtt_client_connection_311_set_connection_closed_handler(
1264 void *impl,
1265 aws_mqtt_client_on_connection_closed_fn *on_closed,
1266 void *on_closed_ud) {
1267
1268 struct aws_mqtt_client_connection_311_impl *connection = impl;
1269
1270 AWS_PRECONDITION(connection);
1271
1272 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Setting connection closed handler", (void *)connection);
1273
1274 int result = AWS_OP_ERR;
1275
1276 /* BEGIN CRITICAL SECTION */
1277 mqtt_connection_lock_synced_data(connection);
1278
1279 /* Check state and modify connection under lock to ensure thread safety */
1280 if (!s_is_valid_connection_state_for_configuration(connection)) {
1281 AWS_LOGF_ERROR(
1282 AWS_LS_MQTT_CLIENT,
1283 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
1284 "pending operation completes.",
1285 (void *)connection);
1286 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1287 goto done;
1288 }
1289
1290 if (aws_rw_lock_try_wlock(&connection->callback_lock)) {
1291 AWS_LOGF_ERROR(
1292 AWS_LS_MQTT_CLIENT, "id=%p: Failed to set callback handlers, callbacks are in use.", (void *)connection);
1293 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1294 goto done;
1295 }
1296
1297 connection->on_closed = on_closed;
1298 connection->on_closed_ud = on_closed_ud;
1299
1300 aws_rw_lock_wunlock(&connection->callback_lock);
1301 result = AWS_OP_SUCCESS;
1302
1303 done:
1304 /* END CRITICAL SECTION */
1305 mqtt_connection_unlock_synced_data(connection);
1306 return result;
1307 }
1308
1309 static int s_aws_mqtt_client_connection_311_set_on_any_publish_handler(
1310 void *impl,
1311 aws_mqtt_client_publish_received_fn *on_any_publish,
1312 void *on_any_publish_ud) {
1313
1314 struct aws_mqtt_client_connection_311_impl *connection = impl;
1315 int result = AWS_OP_ERR;
1316
1317 AWS_PRECONDITION(connection);
1318 /* BEGIN CRITICAL SECTION */
1319 mqtt_connection_lock_synced_data(connection);
1320
1321 if (connection->synced_data.state == AWS_MQTT_CLIENT_STATE_CONNECTED) {
1322 AWS_LOGF_ERROR(
1323 AWS_LS_MQTT_CLIENT,
1324 "id=%p: Connection is connected, publishes may arrive anytime. Unable to set publish handler until "
1325 "offline.",
1326 (void *)connection);
1327 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1328 goto done;
1329 }
1330
1331 if (aws_rw_lock_try_wlock(&connection->callback_lock)) {
1332 AWS_LOGF_ERROR(
1333 AWS_LS_MQTT_CLIENT, "id=%p: Failed to set callback handlers, callbacks are in use.", (void *)connection);
1334 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1335 goto done;
1336 }
1337
1338 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Setting on_any_publish handler", (void *)connection);
1339 connection->on_any_publish = on_any_publish;
1340 connection->on_any_publish_ud = on_any_publish_ud;
1341
1342 aws_rw_lock_wunlock(&connection->callback_lock);
1343 result = AWS_OP_SUCCESS;
1344
1345 done:
1346 mqtt_connection_unlock_synced_data(connection);
1347 /* END CRITICAL SECTION */
1348
1349 return result;
1350 }
1351
1352 static int s_aws_mqtt_client_connection_311_set_connection_termination_handler(
1353 void *impl,
1354 aws_mqtt_client_on_connection_termination_fn *on_termination,
1355 void *on_termination_ud) {
1356
1357 struct aws_mqtt_client_connection_311_impl *connection = impl;
1358
1359 AWS_PRECONDITION(connection);
1360
1361 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Setting connection termination handler", (void *)connection);
1362
1363 int result = AWS_OP_ERR;
1364 /* BEGIN CRITICAL SECTION */
1365 mqtt_connection_lock_synced_data(connection);
1366
1367 /* Check state and modify connection under lock to ensure thread safety */
1368 if (!s_is_valid_connection_state_for_configuration(connection)) {
1369 AWS_LOGF_ERROR(
1370 AWS_LS_MQTT_CLIENT,
1371 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
1372 "pending operation completes.",
1373 (void *)connection);
1374 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1375 goto done;
1376 }
1377
1378 if (aws_rw_lock_try_wlock(&connection->callback_lock)) {
1379 AWS_LOGF_ERROR(
1380 AWS_LS_MQTT_CLIENT, "id=%p: Failed to set callback handlers, callbacks are in use.", (void *)connection);
1381 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1382 goto done;
1383 }
1384
1385 connection->on_termination = on_termination;
1386 connection->on_termination_ud = on_termination_ud;
1387
1388 aws_rw_lock_wunlock(&connection->callback_lock);
1389 result = AWS_OP_SUCCESS;
1390
1391 done:
1392 mqtt_connection_unlock_synced_data(connection);
1393 /* END CRITICAL SECTION */
1394
1395 return result;
1396 }
1397
1398 /*******************************************************************************
1399 * Websockets
1400 ******************************************************************************/
1401
1402 static int s_aws_mqtt_client_connection_311_use_websockets(
1403 void *impl,
1404 aws_mqtt_transform_websocket_handshake_fn *transformer,
1405 void *transformer_ud,
1406 aws_mqtt_validate_websocket_handshake_fn *validator,
1407 void *validator_ud) {
1408
1409 struct aws_mqtt_client_connection_311_impl *connection = impl;
1410
1411 connection->websocket.handshake_transformer = transformer;
1412 connection->websocket.handshake_transformer_ud = transformer_ud;
1413 connection->websocket.handshake_validator = validator;
1414 connection->websocket.handshake_validator_ud = validator_ud;
1415 connection->websocket.enabled = true;
1416
1417 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Using websockets", (void *)connection);
1418
1419 return AWS_OP_SUCCESS;
1420 }
1421
1422 static int s_aws_mqtt_client_connection_311_set_http_proxy_options(
1423 void *impl,
1424 struct aws_http_proxy_options *proxy_options) {
1425
1426 struct aws_mqtt_client_connection_311_impl *connection = impl;
1427 int result = AWS_OP_ERR;
1428
1429 /* BEGIN CRITICAL SECTION */
1430 mqtt_connection_lock_synced_data(connection);
1431
1432 /* Check state and modify connection under lock to ensure thread safety */
1433 if (!s_is_valid_connection_state_for_configuration(connection)) {
1434 AWS_LOGF_ERROR(
1435 AWS_LS_MQTT_CLIENT,
1436 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
1437 "pending operation completes.",
1438 (void *)connection);
1439 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1440 } else {
1441 /* If there is existing proxy options, nuke em */
1442 if (connection->http_proxy_config) {
1443 aws_http_proxy_config_destroy(connection->http_proxy_config);
1444 connection->http_proxy_config = NULL;
1445 }
1446
1447 connection->http_proxy_config =
1448 aws_http_proxy_config_new_tunneling_from_proxy_options(connection->allocator, proxy_options);
1449
1450 result = connection->http_proxy_config != NULL ? AWS_OP_SUCCESS : AWS_OP_ERR;
1451 }
1452
1453 mqtt_connection_unlock_synced_data(connection);
1454 /* END CRITICAL SECTION */
1455
1456 return result;
1457 }
1458
1459 static int s_aws_mqtt_client_connection_311_set_host_resolution_options(
1460 void *impl,
1461 const struct aws_host_resolution_config *host_resolution_config) {
1462
1463 struct aws_mqtt_client_connection_311_impl *connection = impl;
1464
1465 int result = AWS_OP_ERR;
1466 /* BEGIN CRITICAL SECTION */
1467 mqtt_connection_lock_synced_data(connection);
1468
1469 /* Check state and modify connection under lock to ensure thread safety */
1470 if (!s_is_valid_connection_state_for_configuration(connection)) {
1471 AWS_LOGF_ERROR(
1472 AWS_LS_MQTT_CLIENT,
1473 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
1474 "pending operation completes.",
1475 (void *)connection);
1476 result = aws_raise_error(AWS_ERROR_INVALID_STATE);
1477 } else {
1478
1479 connection->host_resolution_config = *host_resolution_config;
1480 result = AWS_OP_SUCCESS;
1481 }
1482
1483 mqtt_connection_unlock_synced_data(connection);
1484 /* END CRITICAL SECTION */
1485 return result;
1486 }
1487
1488 static void s_on_websocket_shutdown(struct aws_websocket *websocket, int error_code, void *user_data) {
1489 struct aws_mqtt_client_connection_311_impl *connection = user_data;
1490
1491 struct aws_channel *channel = connection->slot ? connection->slot->channel : NULL;
1492
1493 s_mqtt_client_shutdown(connection->client->bootstrap, error_code, channel, connection);
1494
1495 if (websocket) {
1496 aws_websocket_release(websocket);
1497 }
1498 }
1499
1500 static void s_on_websocket_setup(const struct aws_websocket_on_connection_setup_data *setup, void *user_data) {
1501
1502 /* Setup callback contract is: if error_code is non-zero then websocket is NULL. */
1503 AWS_FATAL_ASSERT((setup->error_code != 0) == (setup->websocket == NULL));
1504
1505 struct aws_mqtt_client_connection_311_impl *connection = user_data;
1506 struct aws_channel *channel = NULL;
1507
1508 if (connection->websocket.handshake_request) {
1509 aws_http_message_release(connection->websocket.handshake_request);
1510 connection->websocket.handshake_request = NULL;
1511 }
1512
1513 if (setup->websocket) {
1514 channel = aws_websocket_get_channel(setup->websocket);
1515 AWS_FATAL_ASSERT(channel);
1516 AWS_FATAL_ASSERT(aws_channel_get_event_loop(channel) == connection->loop);
1517
1518 /* Websocket must be "converted" before the MQTT handler can be installed next to it. */
1519 if (aws_websocket_convert_to_midchannel_handler(setup->websocket)) {
1520 AWS_LOGF_ERROR(
1521 AWS_LS_MQTT_CLIENT,
1522 "id=%p: Failed converting websocket, error %d (%s)",
1523 (void *)connection,
1524 aws_last_error(),
1525 aws_error_name(aws_last_error()));
1526
1527 aws_channel_shutdown(channel, aws_last_error());
1528 return;
1529 }
1530
1531 /* If validation callback is set, let the user accept/reject the handshake */
1532 if (connection->websocket.handshake_validator) {
1533 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Validating websocket handshake response.", (void *)connection);
1534
1535 if (connection->websocket.handshake_validator(
1536 &connection->base,
1537 setup->handshake_response_header_array,
1538 setup->num_handshake_response_headers,
1539 connection->websocket.handshake_validator_ud)) {
1540
1541 AWS_LOGF_ERROR(
1542 AWS_LS_MQTT_CLIENT,
1543 "id=%p: Failure reported by websocket handshake validator callback, error %d (%s)",
1544 (void *)connection,
1545 aws_last_error(),
1546 aws_error_name(aws_last_error()));
1547
1548 aws_channel_shutdown(channel, aws_last_error());
1549 return;
1550 }
1551
1552 AWS_LOGF_TRACE(
1553 AWS_LS_MQTT_CLIENT, "id=%p: Done validating websocket handshake response.", (void *)connection);
1554 }
1555 }
1556
1557 /* Call into the channel-setup callback, the rest of the logic is the same. */
1558 s_mqtt_client_init(connection->client->bootstrap, setup->error_code, channel, connection);
1559 }
1560
1561 static aws_mqtt_transform_websocket_handshake_complete_fn s_websocket_handshake_transform_complete; /* fwd declare */
1562
1563 static int s_websocket_connect(struct aws_mqtt_client_connection_311_impl *connection) {
1564 AWS_ASSERT(connection->websocket.enabled);
1565
1566 /* Build websocket handshake request */
1567 connection->websocket.handshake_request = aws_http_message_new_websocket_handshake_request(
1568 connection->allocator, *g_websocket_handshake_default_path, aws_byte_cursor_from_string(connection->host_name));
1569
1570 if (!connection->websocket.handshake_request) {
1571 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to generate websocket handshake request", (void *)connection);
1572 goto error;
1573 }
1574
1575 if (aws_http_message_add_header(
1576 connection->websocket.handshake_request, *g_websocket_handshake_default_protocol_header)) {
1577 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to generate websocket handshake request", (void *)connection);
1578 goto error;
1579 }
1580
1581 /* If user registered a transform callback, call it and wait for transform_complete() to be called.
1582 * If no callback registered, call the transform_complete() function ourselves. */
1583 if (connection->websocket.handshake_transformer) {
1584 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Transforming websocket handshake request.", (void *)connection);
1585
1586 connection->websocket.handshake_transformer(
1587 connection->websocket.handshake_request,
1588 connection->websocket.handshake_transformer_ud,
1589 s_websocket_handshake_transform_complete,
1590 connection);
1591
1592 } else {
1593 s_websocket_handshake_transform_complete(
1594 connection->websocket.handshake_request, AWS_ERROR_SUCCESS, connection);
1595 }
1596
1597 return AWS_OP_SUCCESS;
1598
1599 error:
1600 aws_http_message_release(connection->websocket.handshake_request);
1601 connection->websocket.handshake_request = NULL;
1602 return AWS_OP_ERR;
1603 }
1604
1605 struct mqtt_on_websocket_setup_task_arg {
1606 struct aws_allocator *allocator;
1607 struct aws_task task;
1608 struct aws_mqtt_client_connection_311_impl *connection;
1609 int error_code;
1610 };
1611
1612 static void s_on_websocket_setup_task_fn(struct aws_task *task, void *userdata, enum aws_task_status status) {
1613 (void)task;
1614 (void)status;
1615
1616 struct mqtt_on_websocket_setup_task_arg *on_websocket_setup_task_arg = userdata;
1617 struct aws_mqtt_client_connection_311_impl *connection = on_websocket_setup_task_arg->connection;
1618 int error_code = on_websocket_setup_task_arg->error_code;
1619
1620 aws_mem_release(on_websocket_setup_task_arg->allocator, on_websocket_setup_task_arg);
1621
1622 struct aws_websocket_on_connection_setup_data websocket_setup = {.error_code = error_code};
1623 s_on_websocket_setup(&websocket_setup, connection);
1624 }
1625
1626 static void s_websocket_handshake_transform_complete(
1627 struct aws_http_message *handshake_request,
1628 int error_code,
1629 void *complete_ctx) {
1630
1631 struct aws_mqtt_client_connection_311_impl *connection = complete_ctx;
1632
1633 if (error_code) {
1634 AWS_LOGF_ERROR(
1635 AWS_LS_MQTT_CLIENT,
1636 "id=%p: Failure reported by websocket handshake transform callback.",
1637 (void *)connection);
1638
1639 goto error;
1640 }
1641
1642 if (connection->websocket.handshake_transformer) {
1643 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Done transforming websocket handshake request.", (void *)connection);
1644 }
1645
1646 /* Call websocket connect() */
1647 struct aws_websocket_client_connection_options websocket_options = {
1648 .allocator = connection->allocator,
1649 .bootstrap = connection->client->bootstrap,
1650 .socket_options = &connection->socket_options,
1651 .tls_options = connection->tls_options.ctx ? &connection->tls_options : NULL,
1652 .host = aws_byte_cursor_from_string(connection->host_name),
1653 .port = connection->port,
1654 .handshake_request = handshake_request,
1655 .initial_window_size = 0, /* Prevent websocket data from arriving before the MQTT handler is installed */
1656 .user_data = connection,
1657 .on_connection_setup = s_on_websocket_setup,
1658 .on_connection_shutdown = s_on_websocket_shutdown,
1659 .requested_event_loop = connection->loop,
1660 .host_resolution_config = &connection->host_resolution_config,
1661 };
1662
1663 struct aws_http_proxy_options proxy_options;
1664 AWS_ZERO_STRUCT(proxy_options);
1665 if (connection->http_proxy_config != NULL) {
1666 aws_http_proxy_options_init_from_config(&proxy_options, connection->http_proxy_config);
1667 websocket_options.proxy_options = &proxy_options;
1668 }
1669
1670 if (aws_websocket_client_connect(&websocket_options)) {
1671 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to initiate websocket connection.", (void *)connection);
1672 error_code = aws_last_error();
1673 goto error;
1674 }
1675
1676 /* Success */
1677 return;
1678
1679 error:;
1680 /* Proceed to next step, telling it that we failed.
1681 * s_on_websocket_setup will shutdown MQTT connection, and this MUST happen on the MQTT connection's event loop. */
1682 struct mqtt_on_websocket_setup_task_arg *on_websocket_setup_task_arg =
1683 aws_mem_calloc(connection->allocator, 1, sizeof(struct mqtt_on_websocket_setup_task_arg));
1684 on_websocket_setup_task_arg->allocator = connection->allocator;
1685 /* NOTE: No need in acquiring MQTT connection ref counter, as it is already acquired at the start of connection
1686 * process. s_on_websocket_setup will release it. */
1687 on_websocket_setup_task_arg->connection = connection;
1688 on_websocket_setup_task_arg->error_code = error_code;
1689 aws_task_init(
1690 &on_websocket_setup_task_arg->task,
1691 s_on_websocket_setup_task_fn,
1692 (void *)on_websocket_setup_task_arg,
1693 "on_websocket_setup_task");
1694 aws_event_loop_schedule_task_now(connection->loop, &on_websocket_setup_task_arg->task);
1695 }
1696
1697 /*******************************************************************************
1698 * Connect
1699 ******************************************************************************/
1700
1701 static int s_aws_mqtt_client_connection_311_connect(
1702 void *impl,
1703 const struct aws_mqtt_connection_options *connection_options) {
1704
1705 struct aws_mqtt_client_connection_311_impl *connection = impl;
1706
1707 if (connection_options == NULL) {
1708 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1709 }
1710
1711 if (aws_mqtt_validate_utf8_text(connection_options->client_id) == AWS_OP_ERR) {
1712 AWS_LOGF_DEBUG(
1713 AWS_LS_MQTT_CLIENT, "id=%p: Invalid utf8 or forbidden codepoints in client id", (void *)connection);
1714 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
1715 }
1716
1717 /* TODO: Do we need to support resuming the connection if user connect to the same connection & endpoint and the
1718 * clean_session is false?
1719 * If not, the broker will resume the connection in this case, and we pretend we are making a new connection, which
1720 * may cause some confusing behavior. This is basically what we have now. NOTE: The topic_tree is living with the
1721 * connection right now, which is really confusing.
1722 * If yes, an edge case will be: User disconnected from the connection with clean_session
1723 * being false, then connect to another endpoint with the same connection object, we probably need to clear all
1724 * those states from last connection and create a new "connection". Problem is what if user finish the second
1725 * connection and reconnect to the first endpoint. There is no way for us to resume the connection in this case. */
1726
1727 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Opening connection", (void *)connection);
1728 { /* BEGIN CRITICAL SECTION */
1729 mqtt_connection_lock_synced_data(connection);
1730
1731 if (connection->synced_data.state != AWS_MQTT_CLIENT_STATE_DISCONNECTED) {
1732 mqtt_connection_unlock_synced_data(connection);
1733 return aws_raise_error(AWS_ERROR_MQTT_ALREADY_CONNECTED);
1734 }
1735 mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_CONNECTING);
1736 AWS_LOGF_DEBUG(
1737 AWS_LS_MQTT_CLIENT, "id=%p: Begin connecting process, switch state to CONNECTING.", (void *)connection);
1738 mqtt_connection_unlock_synced_data(connection);
1739 } /* END CRITICAL SECTION */
1740
1741 if (connection->host_name) {
1742 aws_string_destroy(connection->host_name);
1743 }
1744
1745 connection->host_name = aws_string_new_from_array(
1746 connection->allocator, connection_options->host_name.ptr, connection_options->host_name.len);
1747 connection->port = connection_options->port;
1748 connection->socket_options = *connection_options->socket_options;
1749 connection->clean_session = connection_options->clean_session;
1750 connection->keep_alive_time_secs = connection_options->keep_alive_time_secs;
1751 connection->connection_count = 0;
1752
1753 if (!connection->keep_alive_time_secs) {
1754 connection->keep_alive_time_secs = s_default_keep_alive_sec;
1755 }
1756 connection->keep_alive_time_ns =
1757 aws_timestamp_convert(connection->keep_alive_time_secs, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
1758
1759 if (!connection_options->protocol_operation_timeout_ms) {
1760 connection->operation_timeout_ns = UINT64_MAX;
1761 } else {
1762 connection->operation_timeout_ns = aws_timestamp_convert(
1763 (uint64_t)connection_options->protocol_operation_timeout_ms,
1764 AWS_TIMESTAMP_MILLIS,
1765 AWS_TIMESTAMP_NANOS,
1766 NULL);
1767 }
1768
1769 if (!connection_options->ping_timeout_ms) {
1770 connection->ping_timeout_ns = s_default_ping_timeout_ns;
1771 } else {
1772 connection->ping_timeout_ns = aws_timestamp_convert(
1773 (uint64_t)connection_options->ping_timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL);
1774 }
1775
1776 /* Keep alive time should always be greater than the timeouts. */
1777 if (AWS_UNLIKELY(connection->keep_alive_time_ns <= connection->ping_timeout_ns)) {
1778 AWS_LOGF_FATAL(
1779 AWS_LS_MQTT_CLIENT,
1780 "id=%p: Illegal configuration, Connection keep alive %" PRIu64
1781 "ns must be greater than the request timeouts %" PRIu64 "ns.",
1782 (void *)connection,
1783 connection->keep_alive_time_ns,
1784 connection->ping_timeout_ns);
1785 AWS_FATAL_ASSERT(connection->keep_alive_time_ns > connection->ping_timeout_ns);
1786 }
1787
1788 AWS_LOGF_INFO(
1789 AWS_LS_MQTT_CLIENT,
1790 "id=%p: using ping timeout of %" PRIu64 " ns",
1791 (void *)connection,
1792 connection->ping_timeout_ns);
1793
1794 /* Cheat and set the tls_options host_name to our copy if they're the same */
1795 if (connection_options->tls_options) {
1796 connection->use_tls = true;
1797 if (aws_tls_connection_options_copy(&connection->tls_options, connection_options->tls_options)) {
1798
1799 AWS_LOGF_ERROR(
1800 AWS_LS_MQTT_CLIENT, "id=%p: Failed to copy TLS Connection Options into connection", (void *)connection);
1801 return AWS_OP_ERR;
1802 }
1803
1804 if (!connection_options->tls_options->server_name) {
1805 struct aws_byte_cursor host_name_cur = aws_byte_cursor_from_string(connection->host_name);
1806 if (aws_tls_connection_options_set_server_name(
1807 &connection->tls_options, connection->allocator, &host_name_cur)) {
1808
1809 AWS_LOGF_ERROR(
1810 AWS_LS_MQTT_CLIENT, "id=%p: Failed to set TLS Connection Options server name", (void *)connection);
1811 goto error;
1812 }
1813 }
1814
1815 } else {
1816 AWS_ZERO_STRUCT(connection->tls_options);
1817 }
1818
1819 /* Clean up old client_id */
1820 if (connection->client_id.buffer) {
1821 aws_byte_buf_clean_up(&connection->client_id);
1822 }
1823
1824 /* Only set connection->client_id if a new one was provided */
1825 struct aws_byte_buf client_id_buf =
1826 aws_byte_buf_from_array(connection_options->client_id.ptr, connection_options->client_id.len);
1827 if (aws_byte_buf_init_copy(&connection->client_id, connection->allocator, &client_id_buf)) {
1828 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Failed to copy client_id into connection", (void *)connection);
1829 goto error;
1830 }
1831
1832 struct aws_linked_list cancelling_requests;
1833 aws_linked_list_init(&cancelling_requests);
1834 { /* BEGIN CRITICAL SECTION */
1835 mqtt_connection_lock_synced_data(connection);
1836 if (connection->clean_session) {
1837 AWS_LOGF_TRACE(
1838 AWS_LS_MQTT_CLIENT,
1839 "id=%p: a clean session connection requested, all the previous requests will fail",
1840 (void *)connection);
1841 aws_linked_list_swap_contents(&connection->synced_data.pending_requests_list, &cancelling_requests);
1842 }
1843 mqtt_connection_unlock_synced_data(connection);
1844 } /* END CRITICAL SECTION */
1845
1846 if (!aws_linked_list_empty(&cancelling_requests)) {
1847
1848 struct aws_linked_list_node *current = aws_linked_list_front(&cancelling_requests);
1849 const struct aws_linked_list_node *end = aws_linked_list_end(&cancelling_requests);
1850 /* invoke all the complete callback for requests from previous session */
1851 while (current != end) {
1852 struct aws_mqtt_request *request = AWS_CONTAINER_OF(current, struct aws_mqtt_request, list_node);
1853 AWS_LOGF_TRACE(
1854 AWS_LS_MQTT_CLIENT,
1855 "id=%p: Establishing a new clean session connection, discard the previous request %" PRIu16,
1856 (void *)connection,
1857 request->packet_id);
1858 if (request->on_complete) {
1859 request->on_complete(
1860 &connection->base,
1861 request->packet_id,
1862 AWS_ERROR_MQTT_CANCELLED_FOR_CLEAN_SESSION,
1863 request->on_complete_ud);
1864 }
1865 current = current->next;
1866 }
1867 /* free the resource */
1868 { /* BEGIN CRITICAL SECTION */
1869 mqtt_connection_lock_synced_data(connection);
1870 while (!aws_linked_list_empty(&cancelling_requests)) {
1871 struct aws_linked_list_node *node = aws_linked_list_pop_front(&cancelling_requests);
1872 struct aws_mqtt_request *request = AWS_CONTAINER_OF(node, struct aws_mqtt_request, list_node);
1873 aws_hash_table_remove(
1874 &connection->synced_data.outstanding_requests_table, &request->packet_id, NULL, NULL);
1875 aws_memory_pool_release(&connection->synced_data.requests_pool, request);
1876 }
1877 mqtt_connection_unlock_synced_data(connection);
1878 } /* END CRITICAL SECTION */
1879 }
1880
1881 /* Begin the connecting process, acquire the connection to keep it alive until we disconnected */
1882 aws_mqtt_client_connection_acquire(&connection->base);
1883
1884 if (s_mqtt_client_connect(connection, connection_options->on_connection_complete, connection_options->user_data)) {
1885 /*
1886 * An error calling s_mqtt_client_connect should (must) be mutually exclusive with s_mqtt_client_shutdown().
1887 * So it should be safe and correct to call release now to undo the pinning we did a few lines above.
1888 */
1889 aws_mqtt_client_connection_release(&connection->base);
1890
1891 /* client_id has been updated with something but it will get cleaned up when the connection gets cleaned up
1892 * so we don't need to worry about it here*/
1893 if (connection->clean_session) {
1894 AWS_LOGF_WARN(
1895 AWS_LS_MQTT_CLIENT, "id=%p: The previous session has been cleaned up and losted!", (void *)connection);
1896 }
1897 goto error;
1898 }
1899
1900 return AWS_OP_SUCCESS;
1901
1902 error:
1903 aws_tls_connection_options_clean_up(&connection->tls_options);
1904 AWS_ZERO_STRUCT(connection->tls_options);
1905 { /* BEGIN CRITICAL SECTION */
1906 mqtt_connection_lock_synced_data(connection);
1907 mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_DISCONNECTED);
1908 mqtt_connection_unlock_synced_data(connection);
1909 } /* END CRITICAL SECTION */
1910 return AWS_OP_ERR;
1911 }
1912
1913 static int s_mqtt_client_connect(
1914 struct aws_mqtt_client_connection_311_impl *connection,
1915 aws_mqtt_client_on_connection_complete_fn *on_connection_complete,
1916 void *userdata) {
1917 connection->on_connection_complete = on_connection_complete;
1918 connection->on_connection_complete_ud = userdata;
1919
1920 int result = 0;
1921 if (connection->websocket.enabled) {
1922 result = s_websocket_connect(connection);
1923 } else {
1924 struct aws_socket_channel_bootstrap_options channel_options;
1925 AWS_ZERO_STRUCT(channel_options);
1926 channel_options.bootstrap = connection->client->bootstrap;
1927 channel_options.host_name = aws_string_c_str(connection->host_name);
1928 channel_options.port = connection->port;
1929 channel_options.socket_options = &connection->socket_options;
1930 channel_options.tls_options = connection->use_tls ? &connection->tls_options : NULL;
1931 channel_options.setup_callback = &s_mqtt_client_init;
1932 channel_options.shutdown_callback = &s_mqtt_client_shutdown;
1933 channel_options.user_data = connection;
1934 channel_options.requested_event_loop = connection->loop;
1935 channel_options.host_resolution_override_config = &connection->host_resolution_config;
1936
1937 if (connection->http_proxy_config == NULL) {
1938 result = aws_client_bootstrap_new_socket_channel(&channel_options);
1939 } else {
1940 struct aws_http_proxy_options proxy_options;
1941 AWS_ZERO_STRUCT(proxy_options);
1942
1943 aws_http_proxy_options_init_from_config(&proxy_options, connection->http_proxy_config);
1944 result = aws_http_proxy_new_socket_channel(&channel_options, &proxy_options);
1945 }
1946 }
1947
1948 if (result) {
1949 /* Connection attempt failed */
1950 AWS_LOGF_ERROR(
1951 AWS_LS_MQTT_CLIENT,
1952 "id=%p: Failed to begin connection routine, error %d (%s).",
1953 (void *)connection,
1954 aws_last_error(),
1955 aws_error_name(aws_last_error()));
1956 return AWS_OP_ERR;
1957 }
1958
1959 return AWS_OP_SUCCESS;
1960 }
1961
1962 /*******************************************************************************
1963 * Reconnect DEPRECATED
1964 ******************************************************************************/
1965
1966 static int s_aws_mqtt_client_connection_311_reconnect(
1967 void *impl,
1968 aws_mqtt_client_on_connection_complete_fn *on_connection_complete,
1969 void *userdata) {
1970 (void)impl;
1971 (void)on_connection_complete;
1972 (void)userdata;
1973
1974 /* DEPRECATED, connection will reconnect automatically now. */
1975 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "aws_mqtt_client_connection_reconnect has been DEPRECATED.");
1976 return aws_raise_error(AWS_ERROR_UNSUPPORTED_OPERATION);
1977 }
1978
1979 /*******************************************************************************
1980 * Disconnect
1981 ******************************************************************************/
1982
1983 static int s_aws_mqtt_client_connection_311_disconnect(
1984 void *impl,
1985 aws_mqtt_client_on_disconnect_fn *on_disconnect,
1986 void *userdata) {
1987
1988 struct aws_mqtt_client_connection_311_impl *connection = impl;
1989
1990 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: user called disconnect.", (void *)connection);
1991
1992 { /* BEGIN CRITICAL SECTION */
1993 mqtt_connection_lock_synced_data(connection);
1994
1995 if (connection->synced_data.state != AWS_MQTT_CLIENT_STATE_CONNECTED &&
1996 connection->synced_data.state != AWS_MQTT_CLIENT_STATE_RECONNECTING) {
1997 mqtt_connection_unlock_synced_data(connection);
1998 AWS_LOGF_ERROR(
1999 AWS_LS_MQTT_CLIENT, "id=%p: Connection is not open, and may not be closed", (void *)connection);
2000 aws_raise_error(AWS_ERROR_MQTT_NOT_CONNECTED);
2001 return AWS_OP_ERR;
2002 }
2003 mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_DISCONNECTING);
2004 AWS_LOGF_DEBUG(
2005 AWS_LS_MQTT_CLIENT,
2006 "id=%p: User requests disconnecting, switch state to DISCONNECTING.",
2007 (void *)connection);
2008 connection->on_disconnect = on_disconnect;
2009 connection->on_disconnect_ud = userdata;
2010 mqtt_connection_unlock_synced_data(connection);
2011 } /* END CRITICAL SECTION */
2012
2013 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Closing connection", (void *)connection);
2014
2015 mqtt_disconnect_impl(connection, AWS_OP_SUCCESS);
2016
2017 return AWS_OP_SUCCESS;
2018 }
2019
2020 /*******************************************************************************
2021 * Subscribe
2022 ******************************************************************************/
2023
2024 static void s_on_publish_client_wrapper(
2025 const struct aws_byte_cursor *topic,
2026 const struct aws_byte_cursor *payload,
2027 bool dup,
2028 enum aws_mqtt_qos qos,
2029 bool retain,
2030 void *userdata) {
2031
2032 struct subscribe_task_topic *task_topic = userdata;
2033
2034 /* Call out to the user callback */
2035 if (task_topic->request.on_publish) {
2036 task_topic->request.on_publish(
2037 &task_topic->connection->base, topic, payload, dup, qos, retain, task_topic->request.on_publish_ud);
2038 }
2039 }
2040
2041 static void s_task_topic_release(void *userdata) {
2042 struct subscribe_task_topic *task_topic = userdata;
2043 if (task_topic != NULL) {
2044 aws_ref_count_release(&task_topic->ref_count);
2045 }
2046 }
2047
2048 static void s_task_topic_clean_up(void *userdata) {
2049
2050 struct subscribe_task_topic *task_topic = userdata;
2051
2052 if (task_topic->request.on_cleanup) {
2053 task_topic->request.on_cleanup(task_topic->request.on_publish_ud);
2054 }
2055 aws_string_destroy(task_topic->filter);
2056 aws_mem_release(task_topic->connection->allocator, task_topic);
2057 }
2058
2059 static enum aws_mqtt_client_request_state s_subscribe_send(uint16_t packet_id, bool is_first_attempt, void *userdata) {
2060
2061 (void)is_first_attempt;
2062
2063 struct subscribe_task_arg *task_arg = userdata;
2064 bool initing_packet = task_arg->subscribe.fixed_header.packet_type == 0;
2065 struct aws_io_message *message = NULL;
2066
2067 AWS_LOGF_TRACE(
2068 AWS_LS_MQTT_CLIENT,
2069 "id=%p: Attempting send of subscribe %" PRIu16 " (%s)",
2070 (void *)task_arg->connection,
2071 packet_id,
2072 is_first_attempt ? "first attempt" : "resend");
2073
2074 if (initing_packet) {
2075 /* Init the subscribe packet */
2076 if (aws_mqtt_packet_subscribe_init(&task_arg->subscribe, task_arg->connection->allocator, packet_id)) {
2077 return AWS_MQTT_CLIENT_REQUEST_ERROR;
2078 }
2079 }
2080
2081 const size_t num_topics = aws_array_list_length(&task_arg->topics);
2082 if (num_topics <= 0) {
2083 aws_raise_error(AWS_ERROR_MQTT_INVALID_TOPIC);
2084 return AWS_MQTT_CLIENT_REQUEST_ERROR;
2085 }
2086
2087 AWS_VARIABLE_LENGTH_ARRAY(uint8_t, transaction_buf, num_topics * aws_mqtt_topic_tree_action_size);
2088 struct aws_array_list transaction;
2089 aws_array_list_init_static(&transaction, transaction_buf, num_topics, aws_mqtt_topic_tree_action_size);
2090
2091 for (size_t i = 0; i < num_topics; ++i) {
2092
2093 struct subscribe_task_topic *topic = NULL;
2094 aws_array_list_get_at(&task_arg->topics, &topic, i);
2095 AWS_ASSUME(topic); /* We know we're within bounds */
2096
2097 if (initing_packet) {
2098 if (aws_mqtt_packet_subscribe_add_topic(&task_arg->subscribe, topic->request.topic, topic->request.qos)) {
2099 goto handle_error;
2100 }
2101 }
2102
2103 if (!task_arg->tree_updated) {
2104
2105 struct aws_byte_cursor filter_cursor = aws_byte_cursor_from_string(topic->filter);
2106 if (s_is_topic_shared_topic(&filter_cursor)) {
2107 struct aws_string *normal_topic = s_get_normal_topic_from_shared_topic(topic->filter);
2108 if (normal_topic == NULL) {
2109 AWS_LOGF_ERROR(
2110 AWS_LS_MQTT_CLIENT,
2111 "id=%p: Topic is shared subscription topic but topic could not be parsed from "
2112 "shared subscription topic.",
2113 (void *)task_arg->connection);
2114 goto handle_error;
2115 }
2116 if (aws_mqtt_topic_tree_transaction_insert(
2117 &task_arg->connection->thread_data.subscriptions,
2118 &transaction,
2119 normal_topic,
2120 topic->request.qos,
2121 s_on_publish_client_wrapper,
2122 s_task_topic_release,
2123 topic)) {
2124 aws_string_destroy(normal_topic);
2125 goto handle_error;
2126 }
2127 aws_string_destroy(normal_topic);
2128 } else {
2129 if (aws_mqtt_topic_tree_transaction_insert(
2130 &task_arg->connection->thread_data.subscriptions,
2131 &transaction,
2132 topic->filter,
2133 topic->request.qos,
2134 s_on_publish_client_wrapper,
2135 s_task_topic_release,
2136 topic)) {
2137 goto handle_error;
2138 }
2139 }
2140 /* If insert succeed, acquire the refcount */
2141 aws_ref_count_acquire(&topic->ref_count);
2142 }
2143 }
2144
2145 message = mqtt_get_message_for_packet(task_arg->connection, &task_arg->subscribe.fixed_header);
2146 if (!message) {
2147
2148 goto handle_error;
2149 }
2150
2151 if (aws_mqtt_packet_subscribe_encode(&message->message_data, &task_arg->subscribe)) {
2152
2153 goto handle_error;
2154 }
2155
2156 /* This is not necessarily a fatal error; if the subscribe fails, it'll just retry. Still need to clean up though.
2157 */
2158 if (aws_channel_slot_send_message(task_arg->connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
2159 aws_mem_release(message->allocator, message);
2160 }
2161
2162 /* TODO: timing should start from the message written into the socket, which is aws_io_message->on_completion
2163 * invoked, but there are bugs in the websocket handler (and maybe also the h1 handler?) where we don't properly
2164 * fire the on_completion callbacks. */
2165 struct request_timeout_task_arg *timeout_task_arg =
2166 s_schedule_timeout_task(task_arg->connection, packet_id, task_arg->timeout_duration_in_ns);
2167 if (timeout_task_arg) {
2168 /*
2169 * Set up mutual references between the operation task args and the timeout task args. Whoever runs first
2170 * "wins", does its logic, and then breaks the connection between the two.
2171 */
2172 task_arg->timeout_wrapper.timeout_task_arg = timeout_task_arg;
2173 timeout_task_arg->task_arg_wrapper = &task_arg->timeout_wrapper;
2174 }
2175
2176 if (!task_arg->tree_updated) {
2177 aws_mqtt_topic_tree_transaction_commit(&task_arg->connection->thread_data.subscriptions, &transaction);
2178 task_arg->tree_updated = true;
2179 }
2180
2181 aws_array_list_clean_up(&transaction);
2182 return AWS_MQTT_CLIENT_REQUEST_ONGOING;
2183
2184 handle_error:
2185
2186 if (message) {
2187 aws_mem_release(message->allocator, message);
2188 }
2189 if (!task_arg->tree_updated) {
2190 aws_mqtt_topic_tree_transaction_roll_back(&task_arg->connection->thread_data.subscriptions, &transaction);
2191 }
2192
2193 aws_array_list_clean_up(&transaction);
2194 return AWS_MQTT_CLIENT_REQUEST_ERROR;
2195 }
2196
2197 static void s_subscribe_complete(
2198 struct aws_mqtt_client_connection *connection_base,
2199 uint16_t packet_id,
2200 int error_code,
2201 void *userdata) {
2202
2203 struct aws_mqtt_client_connection_311_impl *connection = connection_base->impl;
2204 struct subscribe_task_arg *task_arg = userdata;
2205
2206 struct subscribe_task_topic *topic = NULL;
2207 aws_array_list_get_at(&task_arg->topics, &topic, 0);
2208 AWS_ASSUME(topic);
2209
2210 AWS_LOGF_DEBUG(
2211 AWS_LS_MQTT_CLIENT,
2212 "id=%p: Subscribe %" PRIu16 " completed with error_code %d",
2213 (void *)connection,
2214 packet_id,
2215 error_code);
2216
2217 size_t list_len = aws_array_list_length(&task_arg->topics);
2218 if (task_arg->on_suback.multi) {
2219 /* create a list of aws_mqtt_topic_subscription pointers from topics for the callback */
2220 AWS_VARIABLE_LENGTH_ARRAY(uint8_t, cb_list_buf, list_len * sizeof(void *));
2221 struct aws_array_list cb_list;
2222 aws_array_list_init_static(&cb_list, cb_list_buf, list_len, sizeof(void *));
2223 int err = 0;
2224 for (size_t i = 0; i < list_len; i++) {
2225 err |= aws_array_list_get_at(&task_arg->topics, &topic, i);
2226 struct aws_mqtt_topic_subscription *subscription = &topic->request;
2227 err |= aws_array_list_push_back(&cb_list, &subscription);
2228 }
2229 AWS_ASSUME(!err);
2230 task_arg->on_suback.multi(&connection->base, packet_id, &cb_list, error_code, task_arg->on_suback_ud);
2231 aws_array_list_clean_up(&cb_list);
2232 } else if (task_arg->on_suback.single) {
2233 task_arg->on_suback.single(
2234 &connection->base,
2235 packet_id,
2236 &topic->request.topic,
2237 topic->request.qos,
2238 error_code,
2239 task_arg->on_suback_ud);
2240 }
2241
2242 /*
2243 * If we have a forward pointer to a timeout task, then that means the timeout task has not run yet. So we should
2244 * follow it and zero out the back pointer to us, because we're going away now. The timeout task will run later
2245 * and be harmless (even vs. future operations with the same packet id) because it only cancels if it has a back
2246 * pointer.
2247 */
2248 if (task_arg->timeout_wrapper.timeout_task_arg) {
2249 task_arg->timeout_wrapper.timeout_task_arg->task_arg_wrapper = NULL;
2250 }
2251
2252 for (size_t i = 0; i < list_len; i++) {
2253 aws_array_list_get_at(&task_arg->topics, &topic, i);
2254 s_task_topic_release(topic);
2255 }
2256 aws_array_list_clean_up(&task_arg->topics);
2257 aws_mqtt_packet_subscribe_clean_up(&task_arg->subscribe);
2258 aws_mem_release(task_arg->connection->allocator, task_arg);
2259 }
2260
2261 static uint16_t s_aws_mqtt_client_connection_311_subscribe_multiple(
2262 void *impl,
2263 const struct aws_array_list *topic_filters,
2264 aws_mqtt_suback_multi_fn *on_suback,
2265 void *on_suback_ud) {
2266
2267 struct aws_mqtt_client_connection_311_impl *connection = impl;
2268
2269 AWS_PRECONDITION(connection);
2270
2271 if (topic_filters == NULL || aws_array_list_length(topic_filters) == 0) {
2272 aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
2273 return 0;
2274 }
2275
2276 struct subscribe_task_arg *task_arg = aws_mem_calloc(connection->allocator, 1, sizeof(struct subscribe_task_arg));
2277 if (!task_arg) {
2278 return 0;
2279 }
2280
2281 task_arg->connection = connection;
2282 task_arg->on_suback.multi = on_suback;
2283 task_arg->on_suback_ud = on_suback_ud;
2284 task_arg->timeout_duration_in_ns = connection->operation_timeout_ns;
2285
2286 const size_t num_topics = aws_array_list_length(topic_filters);
2287
2288 if (aws_array_list_init_dynamic(&task_arg->topics, connection->allocator, num_topics, sizeof(void *))) {
2289 goto handle_error;
2290 }
2291
2292 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Starting multi-topic subscribe", (void *)connection);
2293
2294 /* Calculate the size of the subscribe packet
2295 * The fixed header is 2 bytes and the packet ID is 2 bytes.
2296 * Note: The size of the topic filter(s) are calculated in the loop below */
2297 uint64_t subscribe_packet_size = 4;
2298
2299 for (size_t i = 0; i < num_topics; ++i) {
2300
2301 struct aws_mqtt_topic_subscription *request = NULL;
2302 aws_array_list_get_at_ptr(topic_filters, (void **)&request, i);
2303
2304 if (!aws_mqtt_is_valid_topic_filter(&request->topic)) {
2305 aws_raise_error(AWS_ERROR_MQTT_INVALID_TOPIC);
2306 goto handle_error;
2307 }
2308
2309 struct subscribe_task_topic *task_topic =
2310 aws_mem_calloc(connection->allocator, 1, sizeof(struct subscribe_task_topic));
2311 if (!task_topic) {
2312 goto handle_error;
2313 }
2314 aws_ref_count_init(&task_topic->ref_count, task_topic, (aws_simple_completion_callback *)s_task_topic_clean_up);
2315
2316 task_topic->connection = connection;
2317 task_topic->request = *request;
2318
2319 task_topic->filter = aws_string_new_from_array(
2320 connection->allocator, task_topic->request.topic.ptr, task_topic->request.topic.len);
2321 if (!task_topic->filter) {
2322 aws_mem_release(connection->allocator, task_topic);
2323 goto handle_error;
2324 }
2325
2326 /* Update request topic cursor to refer to owned string */
2327 task_topic->request.topic = aws_byte_cursor_from_string(task_topic->filter);
2328
2329 AWS_LOGF_DEBUG(
2330 AWS_LS_MQTT_CLIENT,
2331 "id=%p: Adding topic \"" PRInSTR "\"",
2332 (void *)connection,
2333 AWS_BYTE_CURSOR_PRI(task_topic->request.topic));
2334
2335 /* Push into the list */
2336 aws_array_list_push_back(&task_arg->topics, &task_topic);
2337
2338 /* Subscribe topic filter is: always 3 bytes (1 for QoS, 2 for Length MSB/LSB) + the size of the topic filter */
2339 subscribe_packet_size += 3 + task_topic->request.topic.len;
2340 }
2341
2342 uint16_t packet_id = mqtt_create_request(
2343 task_arg->connection,
2344 &s_subscribe_send,
2345 task_arg,
2346 &s_subscribe_complete,
2347 task_arg,
2348 false, /* noRetry */
2349 subscribe_packet_size);
2350
2351 if (packet_id == 0) {
2352 AWS_LOGF_ERROR(
2353 AWS_LS_MQTT_CLIENT,
2354 "id=%p: Failed to kick off multi-topic subscribe, with error %s",
2355 (void *)connection,
2356 aws_error_debug_str(aws_last_error()));
2357 goto handle_error;
2358 }
2359
2360 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Sending multi-topic subscribe %" PRIu16, (void *)connection, packet_id);
2361 return packet_id;
2362
2363 handle_error:
2364
2365 if (task_arg) {
2366
2367 if (task_arg->topics.data) {
2368
2369 const size_t num_added_topics = aws_array_list_length(&task_arg->topics);
2370 for (size_t i = 0; i < num_added_topics; ++i) {
2371
2372 struct subscribe_task_topic *task_topic = NULL;
2373 aws_array_list_get_at(&task_arg->topics, (void **)&task_topic, i);
2374 AWS_ASSUME(task_topic);
2375
2376 aws_string_destroy(task_topic->filter);
2377 aws_mem_release(connection->allocator, task_topic);
2378 }
2379
2380 aws_array_list_clean_up(&task_arg->topics);
2381 }
2382
2383 aws_mem_release(connection->allocator, task_arg);
2384 }
2385 return 0;
2386 }
2387
2388 /*******************************************************************************
2389 * Subscribe Single
2390 ******************************************************************************/
2391
2392 static void s_subscribe_single_complete(
2393 struct aws_mqtt_client_connection *connection_base,
2394 uint16_t packet_id,
2395 int error_code,
2396 void *userdata) {
2397
2398 struct aws_mqtt_client_connection_311_impl *connection = connection_base->impl;
2399 struct subscribe_task_arg *task_arg = userdata;
2400
2401 AWS_LOGF_DEBUG(
2402 AWS_LS_MQTT_CLIENT,
2403 "id=%p: Subscribe %" PRIu16 " completed with error code %d",
2404 (void *)connection,
2405 packet_id,
2406 error_code);
2407
2408 AWS_ASSERT(aws_array_list_length(&task_arg->topics) == 1);
2409 struct subscribe_task_topic *topic = NULL;
2410 aws_array_list_get_at(&task_arg->topics, &topic, 0);
2411 AWS_ASSUME(topic); /* There needs to be exactly 1 topic in this list */
2412 if (task_arg->on_suback.single) {
2413 AWS_ASSUME(aws_string_is_valid(topic->filter));
2414 aws_mqtt_suback_fn *suback = task_arg->on_suback.single;
2415 suback(
2416 &connection->base,
2417 packet_id,
2418 &topic->request.topic,
2419 topic->request.qos,
2420 error_code,
2421 task_arg->on_suback_ud);
2422 }
2423
2424 /*
2425 * If we have a forward pointer to a timeout task, then that means the timeout task has not run yet. So we should
2426 * follow it and zero out the back pointer to us, because we're going away now. The timeout task will run later
2427 * and be harmless (even vs. future operations with the same packet id) because it only cancels if it has a back
2428 * pointer.
2429 */
2430 if (task_arg->timeout_wrapper.timeout_task_arg) {
2431 task_arg->timeout_wrapper.timeout_task_arg->task_arg_wrapper = NULL;
2432 }
2433
2434 s_task_topic_release(topic);
2435 aws_array_list_clean_up(&task_arg->topics);
2436 aws_mqtt_packet_subscribe_clean_up(&task_arg->subscribe);
2437 aws_mem_release(task_arg->connection->allocator, task_arg);
2438 }
2439
2440 uint16_t aws_mqtt_client_connection_311_subscribe(
2441 struct aws_mqtt_client_connection_311_impl *connection,
2442 const struct aws_byte_cursor *topic_filter,
2443 enum aws_mqtt_qos qos,
2444 aws_mqtt_client_publish_received_fn *on_publish,
2445 void *on_publish_ud,
2446 aws_mqtt_userdata_cleanup_fn *on_ud_cleanup,
2447 aws_mqtt_suback_fn *on_suback,
2448 void *on_suback_ud,
2449 uint64_t timeout_ns) {
2450
2451 AWS_PRECONDITION(connection);
2452
2453 if (!aws_mqtt_is_valid_topic_filter(topic_filter)) {
2454 aws_raise_error(AWS_ERROR_MQTT_INVALID_TOPIC);
2455 return 0;
2456 }
2457
2458 /* Because we know we're only going to have 1 topic, we can cheat and allocate the array_list in the same block as
2459 * the task argument. */
2460 void *task_topic_storage = NULL;
2461 struct subscribe_task_topic *task_topic = NULL;
2462 struct subscribe_task_arg *task_arg = aws_mem_acquire_many(
2463 connection->allocator,
2464 2,
2465 &task_arg,
2466 sizeof(struct subscribe_task_arg),
2467 &task_topic_storage,
2468 sizeof(struct subscribe_task_topic *));
2469
2470 if (!task_arg) {
2471 goto handle_error;
2472 }
2473 AWS_ZERO_STRUCT(*task_arg);
2474
2475 task_arg->connection = connection;
2476 task_arg->on_suback.single = on_suback;
2477 task_arg->on_suback_ud = on_suback_ud;
2478 task_arg->timeout_duration_in_ns = timeout_ns;
2479
2480 /* It stores the pointer */
2481 aws_array_list_init_static(&task_arg->topics, task_topic_storage, 1, sizeof(void *));
2482
2483 /* Allocate the topic and push into the list */
2484 task_topic = aws_mem_calloc(connection->allocator, 1, sizeof(struct subscribe_task_topic));
2485 if (!task_topic) {
2486 goto handle_error;
2487 }
2488 aws_ref_count_init(&task_topic->ref_count, task_topic, (aws_simple_completion_callback *)s_task_topic_clean_up);
2489 aws_array_list_push_back(&task_arg->topics, &task_topic);
2490
2491 task_topic->filter = aws_string_new_from_array(connection->allocator, topic_filter->ptr, topic_filter->len);
2492 if (!task_topic->filter) {
2493 goto handle_error;
2494 }
2495
2496 task_topic->connection = connection;
2497 task_topic->request.topic = aws_byte_cursor_from_string(task_topic->filter);
2498 task_topic->request.qos = qos;
2499 task_topic->request.on_publish = on_publish;
2500 task_topic->request.on_cleanup = on_ud_cleanup;
2501 task_topic->request.on_publish_ud = on_publish_ud;
2502
2503 /* Calculate the size of the (single) subscribe packet
2504 * The fixed header is 2 bytes,
2505 * the topic filter is always at least 3 bytes (1 for QoS, 2 for Length MSB/LSB)
2506 * - plus the size of the topic filter
2507 * and finally the packet ID is 2 bytes */
2508 uint64_t subscribe_packet_size = 7 + topic_filter->len;
2509
2510 uint16_t packet_id = mqtt_create_request(
2511 task_arg->connection,
2512 &s_subscribe_send,
2513 task_arg,
2514 &s_subscribe_single_complete,
2515 task_arg,
2516 false, /* noRetry */
2517 subscribe_packet_size);
2518
2519 if (packet_id == 0) {
2520 AWS_LOGF_ERROR(
2521 AWS_LS_MQTT_CLIENT,
2522 "id=%p: Failed to start subscribe on topic " PRInSTR " with error %s",
2523 (void *)connection,
2524 AWS_BYTE_CURSOR_PRI(task_topic->request.topic),
2525 aws_error_debug_str(aws_last_error()));
2526 goto handle_error;
2527 }
2528
2529 AWS_LOGF_DEBUG(
2530 AWS_LS_MQTT_CLIENT,
2531 "id=%p: Starting subscribe %" PRIu16 " on topic " PRInSTR,
2532 (void *)connection,
2533 packet_id,
2534 AWS_BYTE_CURSOR_PRI(task_topic->request.topic));
2535
2536 return packet_id;
2537
2538 handle_error:
2539
2540 if (task_topic) {
2541 if (task_topic->filter) {
2542 aws_string_destroy(task_topic->filter);
2543 }
2544 aws_mem_release(connection->allocator, task_topic);
2545 }
2546
2547 if (task_arg) {
2548 aws_mem_release(connection->allocator, task_arg);
2549 }
2550
2551 return 0;
2552 }
2553
2554 static uint16_t s_aws_mqtt_client_connection_311_subscribe(
2555 void *impl,
2556 const struct aws_byte_cursor *topic_filter,
2557 enum aws_mqtt_qos qos,
2558 aws_mqtt_client_publish_received_fn *on_publish,
2559 void *on_publish_ud,
2560 aws_mqtt_userdata_cleanup_fn *on_ud_cleanup,
2561 aws_mqtt_suback_fn *on_suback,
2562 void *on_suback_ud) {
2563
2564 struct aws_mqtt_client_connection_311_impl *connection = impl;
2565 return aws_mqtt_client_connection_311_subscribe(
2566 connection,
2567 topic_filter,
2568 qos,
2569 on_publish,
2570 on_publish_ud,
2571 on_ud_cleanup,
2572 on_suback,
2573 on_suback_ud,
2574 connection->operation_timeout_ns);
2575 }
2576
2577 /*******************************************************************************
2578 * Resubscribe
2579 ******************************************************************************/
2580
2581 static bool s_reconnect_resub_iterator(const struct aws_byte_cursor *topic, enum aws_mqtt_qos qos, void *user_data) {
2582 struct subscribe_task_arg *task_arg = user_data;
2583
2584 struct subscribe_task_topic *task_topic =
2585 aws_mem_calloc(task_arg->connection->allocator, 1, sizeof(struct subscribe_task_topic));
2586 struct aws_mqtt_topic_subscription sub;
2587 AWS_ZERO_STRUCT(sub);
2588 sub.topic = *topic;
2589 sub.qos = qos;
2590 task_topic->request = sub;
2591 task_topic->connection = task_arg->connection;
2592
2593 aws_array_list_push_back(&task_arg->topics, &task_topic);
2594 aws_ref_count_init(&task_topic->ref_count, task_topic, (aws_simple_completion_callback *)s_task_topic_clean_up);
2595 return true;
2596 }
2597
2598 static bool s_reconnect_resub_operation_statistics_iterator(
2599 const struct aws_byte_cursor *topic,
2600 enum aws_mqtt_qos qos,
2601 void *user_data) {
2602 (void)qos;
2603 uint64_t *packet_size = user_data;
2604 /* Always 3 bytes (1 for QoS, 2 for length MSB and LSB respectively) */
2605 *packet_size += 3;
2606 /* The size of the topic filter */
2607 *packet_size += topic->len;
2608 return true;
2609 }
2610
2611 static enum aws_mqtt_client_request_state s_resubscribe_send(
2612 uint16_t packet_id,
2613 bool is_first_attempt,
2614 void *userdata) {
2615
2616 struct subscribe_task_arg *task_arg = userdata;
2617 bool initing_packet = task_arg->subscribe.fixed_header.packet_type == 0;
2618 struct aws_io_message *message = NULL;
2619
2620 const size_t sub_count = aws_mqtt_topic_tree_get_sub_count(&task_arg->connection->thread_data.subscriptions);
2621 /* Init the topics list even if there are no topics because the s_resubscribe_complete callback will always run. */
2622 if (aws_array_list_init_dynamic(&task_arg->topics, task_arg->connection->allocator, sub_count, sizeof(void *))) {
2623 goto handle_error;
2624 }
2625 if (sub_count == 0) {
2626 AWS_LOGF_TRACE(
2627 AWS_LS_MQTT_CLIENT,
2628 "id=%p: Not subscribed to any topics. Resubscribe is unnecessary, no packet will be sent.",
2629 (void *)task_arg->connection);
2630 return AWS_MQTT_CLIENT_REQUEST_COMPLETE;
2631 }
2632 aws_mqtt_topic_tree_iterate(&task_arg->connection->thread_data.subscriptions, s_reconnect_resub_iterator, task_arg);
2633
2634 AWS_LOGF_TRACE(
2635 AWS_LS_MQTT_CLIENT,
2636 "id=%p: Attempting send of resubscribe %" PRIu16 " (%s)",
2637 (void *)task_arg->connection,
2638 packet_id,
2639 is_first_attempt ? "first attempt" : "resend");
2640
2641 if (initing_packet) {
2642 /* Init the subscribe packet */
2643 if (aws_mqtt_packet_subscribe_init(&task_arg->subscribe, task_arg->connection->allocator, packet_id)) {
2644 return AWS_MQTT_CLIENT_REQUEST_ERROR;
2645 }
2646
2647 const size_t num_topics = aws_array_list_length(&task_arg->topics);
2648 if (num_topics <= 0) {
2649 aws_raise_error(AWS_ERROR_MQTT_INVALID_TOPIC);
2650 return AWS_MQTT_CLIENT_REQUEST_ERROR;
2651 }
2652
2653 for (size_t i = 0; i < num_topics; ++i) {
2654
2655 struct subscribe_task_topic *topic = NULL;
2656 aws_array_list_get_at(&task_arg->topics, &topic, i);
2657 AWS_ASSUME(topic); /* We know we're within bounds */
2658
2659 if (aws_mqtt_packet_subscribe_add_topic(&task_arg->subscribe, topic->request.topic, topic->request.qos)) {
2660 goto handle_error;
2661 }
2662 }
2663 }
2664
2665 message = mqtt_get_message_for_packet(task_arg->connection, &task_arg->subscribe.fixed_header);
2666 if (!message) {
2667
2668 goto handle_error;
2669 }
2670
2671 if (aws_mqtt_packet_subscribe_encode(&message->message_data, &task_arg->subscribe)) {
2672
2673 goto handle_error;
2674 }
2675
2676 /* This is not necessarily a fatal error; if the send fails, it'll just retry. Still need to clean up though. */
2677 if (aws_channel_slot_send_message(task_arg->connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
2678 aws_mem_release(message->allocator, message);
2679 }
2680
2681 /* TODO: timing should start from the message written into the socket, which is aws_io_message->on_completion
2682 * invoked, but there are bugs in the websocket handler (and maybe also the h1 handler?) where we don't properly
2683 * fire the on_completion callbacks. */
2684 struct request_timeout_task_arg *timeout_task_arg =
2685 s_schedule_timeout_task(task_arg->connection, packet_id, task_arg->timeout_duration_in_ns);
2686 if (timeout_task_arg) {
2687 /*
2688 * Set up mutual references between the operation task args and the timeout task args. Whoever runs first
2689 * "wins", does its logic, and then breaks the connection between the two.
2690 */
2691 task_arg->timeout_wrapper.timeout_task_arg = timeout_task_arg;
2692 timeout_task_arg->task_arg_wrapper = &task_arg->timeout_wrapper;
2693 }
2694
2695 return AWS_MQTT_CLIENT_REQUEST_ONGOING;
2696
2697 handle_error:
2698
2699 if (message) {
2700 aws_mem_release(message->allocator, message);
2701 }
2702
2703 return AWS_MQTT_CLIENT_REQUEST_ERROR;
2704 }
2705
2706 static void s_resubscribe_complete(
2707 struct aws_mqtt_client_connection *connection_base,
2708 uint16_t packet_id,
2709 int error_code,
2710 void *userdata) {
2711
2712 struct aws_mqtt_client_connection_311_impl *connection = connection_base->impl;
2713
2714 struct subscribe_task_arg *task_arg = userdata;
2715
2716 const size_t list_len = aws_array_list_length(&task_arg->topics);
2717 if (list_len <= 0) {
2718 goto clean_up;
2719 }
2720
2721 struct subscribe_task_topic *topic = NULL;
2722 aws_array_list_get_at(&task_arg->topics, &topic, 0);
2723 AWS_ASSUME(topic);
2724
2725 AWS_LOGF_DEBUG(
2726 AWS_LS_MQTT_CLIENT,
2727 "id=%p: Subscribe %" PRIu16 " completed with error_code %d",
2728 (void *)connection,
2729 packet_id,
2730 error_code);
2731
2732 if (task_arg->on_suback.multi) {
2733 /* create a list of aws_mqtt_topic_subscription pointers from topics for the callback */
2734 AWS_VARIABLE_LENGTH_ARRAY(uint8_t, cb_list_buf, list_len * sizeof(void *));
2735 struct aws_array_list cb_list;
2736 aws_array_list_init_static(&cb_list, cb_list_buf, list_len, sizeof(void *));
2737 int err = 0;
2738 for (size_t i = 0; i < list_len; i++) {
2739 err |= aws_array_list_get_at(&task_arg->topics, &topic, i);
2740 struct aws_mqtt_topic_subscription *subscription = &topic->request;
2741 err |= aws_array_list_push_back(&cb_list, &subscription);
2742 }
2743 AWS_ASSUME(!err);
2744 task_arg->on_suback.multi(&connection->base, packet_id, &cb_list, error_code, task_arg->on_suback_ud);
2745 aws_array_list_clean_up(&cb_list);
2746 } else if (task_arg->on_suback.single) {
2747 task_arg->on_suback.single(
2748 &connection->base,
2749 packet_id,
2750 &topic->request.topic,
2751 topic->request.qos,
2752 error_code,
2753 task_arg->on_suback_ud);
2754 }
2755
2756 clean_up:
2757
2758 /*
2759 * If we have a forward pointer to a timeout task, then that means the timeout task has not run yet. So we should
2760 * follow it and zero out the back pointer to us, because we're going away now. The timeout task will run later
2761 * and be harmless (even vs. future operations with the same packet id) because it only cancels if it has a back
2762 * pointer.
2763 */
2764 if (task_arg->timeout_wrapper.timeout_task_arg) {
2765 task_arg->timeout_wrapper.timeout_task_arg->task_arg_wrapper = NULL;
2766 }
2767
2768 /* We need to cleanup the subscribe_task_topics, since they are not inserted into the topic tree by resubscribe. We
2769 * take the ownership to clean it up */
2770 for (size_t i = 0; i < list_len; i++) {
2771 aws_array_list_get_at(&task_arg->topics, &topic, i);
2772 s_task_topic_release(topic);
2773 }
2774 aws_array_list_clean_up(&task_arg->topics);
2775 aws_mqtt_packet_subscribe_clean_up(&task_arg->subscribe);
2776 aws_mem_release(task_arg->connection->allocator, task_arg);
2777 }
2778
2779 static uint16_t s_aws_mqtt_311_resubscribe_existing_topics(
2780 void *impl,
2781 aws_mqtt_suback_multi_fn *on_suback,
2782 void *on_suback_ud) {
2783
2784 struct aws_mqtt_client_connection_311_impl *connection = impl;
2785
2786 struct subscribe_task_arg *task_arg = aws_mem_calloc(connection->allocator, 1, sizeof(struct subscribe_task_arg));
2787 if (!task_arg) {
2788 AWS_LOGF_ERROR(
2789 AWS_LS_MQTT_CLIENT, "id=%p: failed to allocate storage for resubscribe arguments", (void *)connection);
2790 return 0;
2791 }
2792
2793 AWS_ZERO_STRUCT(*task_arg);
2794 task_arg->connection = connection;
2795 task_arg->on_suback.multi = on_suback;
2796 task_arg->on_suback_ud = on_suback_ud;
2797 task_arg->timeout_duration_in_ns = connection->operation_timeout_ns;
2798
2799 /* Calculate the size of the packet.
2800 * The fixed header is 2 bytes and the packet ID is 2 bytes
2801 * plus the size of each topic in the topic tree */
2802 uint64_t resubscribe_packet_size = 4;
2803 /* Get the length of each subscription we are going to resubscribe with */
2804 aws_mqtt_topic_tree_iterate(
2805 &connection->thread_data.subscriptions,
2806 s_reconnect_resub_operation_statistics_iterator,
2807 &resubscribe_packet_size);
2808
2809 uint16_t packet_id = mqtt_create_request(
2810 task_arg->connection,
2811 &s_resubscribe_send,
2812 task_arg,
2813 &s_resubscribe_complete,
2814 task_arg,
2815 false, /* noRetry */
2816 resubscribe_packet_size);
2817
2818 if (packet_id == 0) {
2819 AWS_LOGF_ERROR(
2820 AWS_LS_MQTT_CLIENT,
2821 "id=%p: Failed to send multi-topic resubscribe with error %s",
2822 (void *)connection,
2823 aws_error_name(aws_last_error()));
2824 goto handle_error;
2825 }
2826
2827 AWS_LOGF_DEBUG(
2828 AWS_LS_MQTT_CLIENT, "id=%p: Sending multi-topic resubscribe %" PRIu16, (void *)connection, packet_id);
2829
2830 return packet_id;
2831
2832 handle_error:
2833
2834 aws_mem_release(connection->allocator, task_arg);
2835
2836 return 0;
2837 }
2838
2839 /*******************************************************************************
2840 * Unsubscribe
2841 ******************************************************************************/
2842
2843 struct unsubscribe_task_arg {
2844 struct aws_mqtt_client_connection_311_impl *connection;
2845 struct aws_string *filter_string;
2846 struct aws_byte_cursor filter;
2847
2848 /* Packet to populate */
2849 struct aws_mqtt_packet_unsubscribe unsubscribe;
2850
2851 /* true if transaction was committed to the topic tree, false requires a retry */
2852 bool tree_updated;
2853
2854 aws_mqtt_op_complete_fn *on_unsuback;
2855 void *on_unsuback_ud;
2856
2857 struct request_timeout_wrapper timeout_wrapper;
2858 uint64_t timeout_duration_in_ns;
2859 };
2860
2861 static enum aws_mqtt_client_request_state s_unsubscribe_send(
2862 uint16_t packet_id,
2863 bool is_first_attempt,
2864 void *userdata) {
2865
2866 (void)is_first_attempt;
2867
2868 struct unsubscribe_task_arg *task_arg = userdata;
2869 struct aws_io_message *message = NULL;
2870
2871 AWS_LOGF_TRACE(
2872 AWS_LS_MQTT_CLIENT,
2873 "id=%p: Attempting send of unsubscribe %" PRIu16 " %s",
2874 (void *)task_arg->connection,
2875 packet_id,
2876 is_first_attempt ? "first attempt" : "resend");
2877
2878 static const size_t num_topics = 1;
2879
2880 AWS_VARIABLE_LENGTH_ARRAY(uint8_t, transaction_buf, num_topics * aws_mqtt_topic_tree_action_size);
2881 struct aws_array_list transaction;
2882 aws_array_list_init_static(&transaction, transaction_buf, num_topics, aws_mqtt_topic_tree_action_size);
2883
2884 if (!task_arg->tree_updated) {
2885
2886 struct subscribe_task_topic *topic;
2887
2888 if (s_is_topic_shared_topic(&task_arg->filter)) {
2889 struct aws_string *shared_topic =
2890 aws_string_new_from_cursor(task_arg->connection->allocator, &task_arg->filter);
2891 struct aws_string *normal_topic = s_get_normal_topic_from_shared_topic(shared_topic);
2892 if (normal_topic == NULL) {
2893 AWS_LOGF_ERROR(
2894 AWS_LS_MQTT_CLIENT,
2895 "id=%p: Topic is shared subscription topic but topic could not be parsed from "
2896 "shared subscription topic.",
2897 (void *)task_arg->connection);
2898 aws_string_destroy(shared_topic);
2899 goto handle_error;
2900 }
2901 struct aws_byte_cursor normal_topic_cursor = aws_byte_cursor_from_string(normal_topic);
2902 if (aws_mqtt_topic_tree_transaction_remove(
2903 &task_arg->connection->thread_data.subscriptions,
2904 &transaction,
2905 &normal_topic_cursor,
2906 (void **)&topic)) {
2907 aws_string_destroy(shared_topic);
2908 aws_string_destroy(normal_topic);
2909 goto handle_error;
2910 }
2911 aws_string_destroy(shared_topic);
2912 aws_string_destroy(normal_topic);
2913 } else {
2914 if (aws_mqtt_topic_tree_transaction_remove(
2915 &task_arg->connection->thread_data.subscriptions,
2916 &transaction,
2917 &task_arg->filter,
2918 (void **)&topic)) {
2919 goto handle_error;
2920 }
2921 }
2922 }
2923
2924 if (task_arg->unsubscribe.fixed_header.packet_type == 0) {
2925 /* If unsubscribe packet is uninitialized, init it */
2926 if (aws_mqtt_packet_unsubscribe_init(&task_arg->unsubscribe, task_arg->connection->allocator, packet_id)) {
2927 goto handle_error;
2928 }
2929 if (aws_mqtt_packet_unsubscribe_add_topic(&task_arg->unsubscribe, task_arg->filter)) {
2930 goto handle_error;
2931 }
2932 }
2933
2934 message = mqtt_get_message_for_packet(task_arg->connection, &task_arg->unsubscribe.fixed_header);
2935 if (!message) {
2936 goto handle_error;
2937 }
2938
2939 if (aws_mqtt_packet_unsubscribe_encode(&message->message_data, &task_arg->unsubscribe)) {
2940 goto handle_error;
2941 }
2942
2943 if (aws_channel_slot_send_message(task_arg->connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
2944 goto handle_error;
2945 }
2946
2947 /* TODO: timing should start from the message written into the socket, which is aws_io_message->on_completion
2948 * invoked, but there are bugs in the websocket handler (and maybe also the h1 handler?) where we don't properly
2949 * fire the on_completion callbacks. */
2950 struct request_timeout_task_arg *timeout_task_arg =
2951 s_schedule_timeout_task(task_arg->connection, packet_id, task_arg->timeout_duration_in_ns);
2952 if (timeout_task_arg) {
2953 /*
2954 * Set up mutual references between the operation task args and the timeout task args. Whoever runs first
2955 * "wins", does its logic, and then breaks the connection between the two.
2956 */
2957 task_arg->timeout_wrapper.timeout_task_arg = timeout_task_arg;
2958 timeout_task_arg->task_arg_wrapper = &task_arg->timeout_wrapper;
2959 }
2960
2961 if (!task_arg->tree_updated) {
2962 aws_mqtt_topic_tree_transaction_commit(&task_arg->connection->thread_data.subscriptions, &transaction);
2963 task_arg->tree_updated = true;
2964 }
2965
2966 aws_array_list_clean_up(&transaction);
2967
2968 return AWS_MQTT_CLIENT_REQUEST_ONGOING;
2969
2970 handle_error:
2971
2972 if (message) {
2973 aws_mem_release(message->allocator, message);
2974 }
2975 if (!task_arg->tree_updated) {
2976 aws_mqtt_topic_tree_transaction_roll_back(&task_arg->connection->thread_data.subscriptions, &transaction);
2977 }
2978
2979 aws_array_list_clean_up(&transaction);
2980 return AWS_MQTT_CLIENT_REQUEST_ERROR;
2981 }
2982
2983 static void s_unsubscribe_complete(
2984 struct aws_mqtt_client_connection *connection_base,
2985 uint16_t packet_id,
2986 int error_code,
2987 void *userdata) {
2988
2989 struct aws_mqtt_client_connection_311_impl *connection = connection_base->impl;
2990
2991 struct unsubscribe_task_arg *task_arg = userdata;
2992
2993 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Unsubscribe %" PRIu16 " complete", (void *)connection, packet_id);
2994
2995 /*
2996 * If we have a forward pointer to a timeout task, then that means the timeout task has not run yet. So we should
2997 * follow it and zero out the back pointer to us, because we're going away now. The timeout task will run later
2998 * and be harmless (even vs. future operations with the same packet id) because it only cancels if it has a back
2999 * pointer.
3000 */
3001 if (task_arg->timeout_wrapper.timeout_task_arg) {
3002 task_arg->timeout_wrapper.timeout_task_arg->task_arg_wrapper = NULL;
3003 }
3004
3005 if (task_arg->on_unsuback) {
3006 task_arg->on_unsuback(&connection->base, packet_id, error_code, task_arg->on_unsuback_ud);
3007 }
3008
3009 aws_string_destroy(task_arg->filter_string);
3010 aws_mqtt_packet_unsubscribe_clean_up(&task_arg->unsubscribe);
3011 aws_mem_release(task_arg->connection->allocator, task_arg);
3012 }
3013
3014 uint16_t aws_mqtt_client_connection_311_unsubscribe(
3015 struct aws_mqtt_client_connection_311_impl *connection,
3016 const struct aws_byte_cursor *topic_filter,
3017 aws_mqtt_op_complete_fn *on_unsuback,
3018 void *on_unsuback_ud,
3019 uint64_t timeout_ns) {
3020
3021 AWS_PRECONDITION(connection);
3022
3023 if (!aws_mqtt_is_valid_topic_filter(topic_filter)) {
3024 aws_raise_error(AWS_ERROR_MQTT_INVALID_TOPIC);
3025 return 0;
3026 }
3027
3028 struct unsubscribe_task_arg *task_arg =
3029 aws_mem_calloc(connection->allocator, 1, sizeof(struct unsubscribe_task_arg));
3030 if (!task_arg) {
3031 return 0;
3032 }
3033
3034 task_arg->connection = connection;
3035 task_arg->filter_string = aws_string_new_from_array(connection->allocator, topic_filter->ptr, topic_filter->len);
3036 task_arg->filter = aws_byte_cursor_from_string(task_arg->filter_string);
3037 task_arg->on_unsuback = on_unsuback;
3038 task_arg->on_unsuback_ud = on_unsuback_ud;
3039 task_arg->timeout_duration_in_ns = timeout_ns;
3040
3041 /* Calculate the size of the unsubscribe packet.
3042 * The fixed header is always 2 bytes, the packet ID is always 2 bytes
3043 * plus the size of the topic filter */
3044 uint64_t unsubscribe_packet_size = 4 + task_arg->filter.len;
3045
3046 uint16_t packet_id = mqtt_create_request(
3047 connection,
3048 &s_unsubscribe_send,
3049 task_arg,
3050 s_unsubscribe_complete,
3051 task_arg,
3052 false, /* noRetry */
3053 unsubscribe_packet_size);
3054 if (packet_id == 0) {
3055 AWS_LOGF_DEBUG(
3056 AWS_LS_MQTT_CLIENT,
3057 "id=%p: Failed to start unsubscribe, with error %s",
3058 (void *)connection,
3059 aws_error_debug_str(aws_last_error()));
3060 goto handle_error;
3061 }
3062
3063 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Starting unsubscribe %" PRIu16, (void *)connection, packet_id);
3064
3065 return packet_id;
3066
3067 handle_error:
3068
3069 aws_string_destroy(task_arg->filter_string);
3070 aws_mem_release(connection->allocator, task_arg);
3071
3072 return 0;
3073 }
3074
3075 static uint16_t s_aws_mqtt_client_connection_311_unsubscribe(
3076 void *impl,
3077 const struct aws_byte_cursor *topic_filter,
3078 aws_mqtt_op_complete_fn *on_unsuback,
3079 void *on_unsuback_ud) {
3080
3081 struct aws_mqtt_client_connection_311_impl *connection = impl;
3082
3083 return aws_mqtt_client_connection_311_unsubscribe(
3084 connection, topic_filter, on_unsuback, on_unsuback_ud, connection->operation_timeout_ns);
3085 }
3086
3087 /*******************************************************************************
3088 * Publish
3089 ******************************************************************************/
3090
3091 struct publish_task_arg {
3092 struct aws_mqtt_client_connection_311_impl *connection;
3093 struct aws_string *topic_string;
3094 struct aws_byte_cursor topic;
3095 enum aws_mqtt_qos qos;
3096 bool retain;
3097 struct aws_byte_cursor payload;
3098 struct aws_byte_buf payload_buf;
3099
3100 /* Packet to populate */
3101 struct aws_mqtt_packet_publish publish;
3102
3103 aws_mqtt_op_complete_fn *on_complete;
3104 void *userdata;
3105
3106 uint64_t timeout_duration_in_ns;
3107 struct request_timeout_wrapper timeout_wrapper;
3108 };
3109
3110 /* should only be called by tests */
3111 static int s_get_stuff_from_outstanding_requests_table(
3112 struct aws_mqtt_client_connection_311_impl *connection,
3113 uint16_t packet_id,
3114 struct aws_allocator *allocator,
3115 struct aws_byte_buf *result_buf,
3116 struct aws_string **result_string) {
3117
3118 int err = AWS_OP_SUCCESS;
3119
3120 aws_mutex_lock(&connection->synced_data.lock);
3121 struct aws_hash_element *elem = NULL;
3122 aws_hash_table_find(&connection->synced_data.outstanding_requests_table, &packet_id, &elem);
3123 if (elem) {
3124 struct aws_mqtt_request *request = elem->value;
3125 struct publish_task_arg *pub = (struct publish_task_arg *)request->send_request_ud;
3126 if (result_buf != NULL) {
3127 if (aws_byte_buf_init_copy(result_buf, allocator, &pub->payload_buf)) {
3128 err = AWS_OP_ERR;
3129 }
3130 } else if (result_string != NULL) {
3131 *result_string = aws_string_new_from_string(allocator, pub->topic_string);
3132 if (*result_string == NULL) {
3133 err = AWS_OP_ERR;
3134 }
3135 }
3136 } else {
3137 /* So lovely that this error is defined, but hashtable never actually raises it */
3138 err = aws_raise_error(AWS_ERROR_HASHTBL_ITEM_NOT_FOUND);
3139 }
3140 aws_mutex_unlock(&connection->synced_data.lock);
3141
3142 return err;
3143 }
3144
3145 /* should only be called by tests */
3146 int aws_mqtt_client_get_payload_for_outstanding_publish_packet(
3147 struct aws_mqtt_client_connection *connection_base,
3148 uint16_t packet_id,
3149 struct aws_allocator *allocator,
3150 struct aws_byte_buf *result) {
3151
3152 AWS_ZERO_STRUCT(*result);
3153 return s_get_stuff_from_outstanding_requests_table(connection_base->impl, packet_id, allocator, result, NULL);
3154 }
3155
3156 /* should only be called by tests */
3157 int aws_mqtt_client_get_topic_for_outstanding_publish_packet(
3158 struct aws_mqtt_client_connection *connection_base,
3159 uint16_t packet_id,
3160 struct aws_allocator *allocator,
3161 struct aws_string **result) {
3162
3163 *result = NULL;
3164 return s_get_stuff_from_outstanding_requests_table(connection_base->impl, packet_id, allocator, NULL, result);
3165 }
3166
3167 static enum aws_mqtt_client_request_state s_publish_send(uint16_t packet_id, bool is_first_attempt, void *userdata) {
3168 struct publish_task_arg *task_arg = userdata;
3169 struct aws_mqtt_client_connection_311_impl *connection = task_arg->connection;
3170
3171 AWS_LOGF_TRACE(
3172 AWS_LS_MQTT_CLIENT,
3173 "id=%p: Attempting send of publish %" PRIu16 " %s",
3174 (void *)task_arg->connection,
3175 packet_id,
3176 is_first_attempt ? "first attempt" : "resend");
3177
3178 bool is_qos_0 = task_arg->qos == AWS_MQTT_QOS_AT_MOST_ONCE;
3179 if (is_qos_0) {
3180 packet_id = 0;
3181 }
3182
3183 if (is_first_attempt) {
3184 if (aws_mqtt_packet_publish_init(
3185 &task_arg->publish,
3186 task_arg->retain,
3187 task_arg->qos,
3188 !is_first_attempt,
3189 task_arg->topic,
3190 packet_id,
3191 task_arg->payload)) {
3192
3193 return AWS_MQTT_CLIENT_REQUEST_ERROR;
3194 }
3195 } else {
3196 aws_mqtt_packet_publish_set_dup(&task_arg->publish);
3197 }
3198
3199 struct aws_io_message *message = mqtt_get_message_for_packet(task_arg->connection, &task_arg->publish.fixed_header);
3200 if (!message) {
3201 return AWS_MQTT_CLIENT_REQUEST_ERROR;
3202 }
3203
3204 /* Encode the headers, and everything but the payload */
3205 if (aws_mqtt_packet_publish_encode_headers(&message->message_data, &task_arg->publish)) {
3206 return AWS_MQTT_CLIENT_REQUEST_ERROR;
3207 }
3208
3209 struct aws_byte_cursor payload_cur = task_arg->payload;
3210 {
3211 write_payload_chunk:
3212 (void)NULL;
3213
3214 const size_t left_in_message = message->message_data.capacity - message->message_data.len;
3215 const size_t to_write = payload_cur.len < left_in_message ? payload_cur.len : left_in_message;
3216
3217 if (to_write) {
3218 /* Write this chunk */
3219 struct aws_byte_cursor to_write_cur = aws_byte_cursor_advance(&payload_cur, to_write);
3220 AWS_ASSERT(to_write_cur.ptr); /* to_write is guaranteed to be inside the bounds of payload_cur */
3221 if (!aws_byte_buf_write_from_whole_cursor(&message->message_data, to_write_cur)) {
3222
3223 aws_mem_release(message->allocator, message);
3224 return AWS_MQTT_CLIENT_REQUEST_ERROR;
3225 }
3226 }
3227
3228 if (aws_channel_slot_send_message(task_arg->connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
3229 aws_mem_release(message->allocator, message);
3230 /* If it's QoS 0, telling user that the message haven't been sent, else, the message will be resent once the
3231 * connection is back */
3232 return is_qos_0 ? AWS_MQTT_CLIENT_REQUEST_ERROR : AWS_MQTT_CLIENT_REQUEST_ONGOING;
3233 }
3234
3235 /* If there's still payload left, get a new message and start again. */
3236 if (payload_cur.len) {
3237 message = mqtt_get_message_for_packet(task_arg->connection, &task_arg->publish.fixed_header);
3238 goto write_payload_chunk;
3239 }
3240 }
3241
3242 /* TODO: timing should start from the message written into the socket, which is aws_io_message->on_completion
3243 * invoked, but there are bugs in the websocket handler (and maybe also the h1 handler?) where we don't properly
3244 * fire fire the on_completion callbacks. */
3245 struct request_timeout_task_arg *timeout_task_arg =
3246 s_schedule_timeout_task(connection, packet_id, task_arg->timeout_duration_in_ns);
3247 if (timeout_task_arg != NULL) {
3248 /*
3249 * Set up mutual references between the operation task args and the timeout task args. Whoever runs first
3250 * "wins", does its logic, and then breaks the connection between the two.
3251 */
3252 task_arg->timeout_wrapper.timeout_task_arg = timeout_task_arg;
3253 timeout_task_arg->task_arg_wrapper = &task_arg->timeout_wrapper;
3254 }
3255
3256 /* If QoS == 0, there will be no ack, so consider the request done now. */
3257 return is_qos_0 ? AWS_MQTT_CLIENT_REQUEST_COMPLETE : AWS_MQTT_CLIENT_REQUEST_ONGOING;
3258 }
3259
3260 static void s_publish_complete(
3261 struct aws_mqtt_client_connection *connection_base,
3262 uint16_t packet_id,
3263 int error_code,
3264 void *userdata) {
3265
3266 struct aws_mqtt_client_connection_311_impl *connection = connection_base->impl;
3267
3268 struct publish_task_arg *task_arg = userdata;
3269
3270 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Publish %" PRIu16 " complete", (void *)connection, packet_id);
3271
3272 if (task_arg->on_complete) {
3273 task_arg->on_complete(&connection->base, packet_id, error_code, task_arg->userdata);
3274 }
3275
3276 /*
3277 * If we have a forward pointer to a timeout task, then that means the timeout task has not run yet. So we should
3278 * follow it and zero out the back pointer to us, because we're going away now. The timeout task will run later
3279 * and be harmless (even vs. future operations with the same packet id) because it only cancels if it has a back
3280 * pointer.
3281 */
3282 if (task_arg->timeout_wrapper.timeout_task_arg != NULL) {
3283 task_arg->timeout_wrapper.timeout_task_arg->task_arg_wrapper = NULL;
3284 }
3285
3286 aws_byte_buf_clean_up(&task_arg->payload_buf);
3287 aws_string_destroy(task_arg->topic_string);
3288 aws_mem_release(connection->allocator, task_arg);
3289 }
3290
3291 uint16_t aws_mqtt_client_connection_311_publish(
3292 struct aws_mqtt_client_connection_311_impl *connection,
3293 const struct aws_byte_cursor *topic,
3294 enum aws_mqtt_qos qos,
3295 bool retain,
3296 const struct aws_byte_cursor *payload,
3297 aws_mqtt_op_complete_fn *on_complete,
3298 void *userdata,
3299 uint64_t timeout_ns) {
3300
3301 AWS_PRECONDITION(connection);
3302
3303 if (!aws_mqtt_is_valid_topic(topic)) {
3304 aws_raise_error(AWS_ERROR_MQTT_INVALID_TOPIC);
3305 return 0;
3306 }
3307
3308 if (qos > AWS_MQTT_QOS_EXACTLY_ONCE) {
3309 aws_raise_error(AWS_ERROR_MQTT_INVALID_QOS);
3310 return 0;
3311 }
3312
3313 struct publish_task_arg *arg = aws_mem_calloc(connection->allocator, 1, sizeof(struct publish_task_arg));
3314 if (!arg) {
3315 return 0;
3316 }
3317
3318 arg->connection = connection;
3319 arg->topic_string = aws_string_new_from_array(connection->allocator, topic->ptr, topic->len);
3320 arg->topic = aws_byte_cursor_from_string(arg->topic_string);
3321 arg->qos = qos;
3322 arg->retain = retain;
3323 arg->timeout_duration_in_ns = timeout_ns;
3324
3325 struct aws_byte_cursor payload_cursor;
3326 AWS_ZERO_STRUCT(payload_cursor);
3327 if (payload != NULL) {
3328 payload_cursor = *payload;
3329 }
3330
3331 if (aws_byte_buf_init_copy_from_cursor(&arg->payload_buf, connection->allocator, payload_cursor)) {
3332 goto handle_error;
3333 }
3334 arg->payload = aws_byte_cursor_from_buf(&arg->payload_buf);
3335 arg->on_complete = on_complete;
3336 arg->userdata = userdata;
3337
3338 /* Calculate the size of the publish packet.
3339 * The fixed header size is 2 bytes, the packet ID is 2 bytes,
3340 * plus the size of both the topic name and payload */
3341 uint64_t publish_packet_size = 4 + arg->topic.len + arg->payload.len;
3342
3343 bool retry = qos == AWS_MQTT_QOS_AT_MOST_ONCE;
3344 uint16_t packet_id =
3345 mqtt_create_request(connection, &s_publish_send, arg, &s_publish_complete, arg, retry, publish_packet_size);
3346
3347 if (packet_id == 0) {
3348 /* bummer, we failed to make a new request */
3349 AWS_LOGF_ERROR(
3350 AWS_LS_MQTT_CLIENT,
3351 "id=%p: Failed starting publish to topic " PRInSTR ",error %d (%s)",
3352 (void *)connection,
3353 AWS_BYTE_CURSOR_PRI(*topic),
3354 aws_last_error(),
3355 aws_error_name(aws_last_error()));
3356 goto handle_error;
3357 }
3358
3359 AWS_LOGF_DEBUG(
3360 AWS_LS_MQTT_CLIENT,
3361 "id=%p: Starting publish %" PRIu16 " to topic " PRInSTR,
3362 (void *)connection,
3363 packet_id,
3364 AWS_BYTE_CURSOR_PRI(*topic));
3365 return packet_id;
3366
3367 handle_error:
3368
3369 /* we know arg is valid, topic_string may or may not be valid */
3370 if (arg->topic_string) {
3371 aws_string_destroy(arg->topic_string);
3372 }
3373
3374 aws_byte_buf_clean_up(&arg->payload_buf);
3375
3376 aws_mem_release(connection->allocator, arg);
3377
3378 return 0;
3379 }
3380
3381 static uint16_t s_aws_mqtt_client_connection_311_publish(
3382 void *impl,
3383 const struct aws_byte_cursor *topic,
3384 enum aws_mqtt_qos qos,
3385 bool retain,
3386 const struct aws_byte_cursor *payload,
3387 aws_mqtt_op_complete_fn *on_complete,
3388 void *userdata) {
3389
3390 struct aws_mqtt_client_connection_311_impl *connection = impl;
3391
3392 return aws_mqtt_client_connection_311_publish(
3393 connection, topic, qos, retain, payload, on_complete, userdata, connection->operation_timeout_ns);
3394 }
3395
3396 /*******************************************************************************
3397 * Ping
3398 ******************************************************************************/
3399
3400 static void s_pingresp_received_timeout(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
3401 struct aws_mqtt_client_connection_311_impl *connection = arg;
3402
3403 if (status == AWS_TASK_STATUS_RUN_READY) {
3404 /* Check that a pingresp has been received since pingreq was sent */
3405 if (connection->thread_data.waiting_on_ping_response) {
3406 connection->thread_data.waiting_on_ping_response = false;
3407 /* It's been too long since the last ping, close the connection */
3408 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: ping timeout detected", (void *)connection);
3409 aws_channel_shutdown(connection->slot->channel, AWS_ERROR_MQTT_TIMEOUT);
3410 }
3411 }
3412
3413 aws_mem_release(connection->allocator, channel_task);
3414 }
3415
3416 static enum aws_mqtt_client_request_state s_pingreq_send(uint16_t packet_id, bool is_first_attempt, void *userdata) {
3417 (void)packet_id;
3418 (void)is_first_attempt;
3419 AWS_PRECONDITION(is_first_attempt);
3420
3421 struct aws_mqtt_client_connection_311_impl *connection = userdata;
3422
3423 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: pingreq send", (void *)connection);
3424 struct aws_mqtt_packet_connection pingreq;
3425 aws_mqtt_packet_pingreq_init(&pingreq);
3426
3427 struct aws_io_message *message = mqtt_get_message_for_packet(connection, &pingreq.fixed_header);
3428 if (!message) {
3429 return AWS_MQTT_CLIENT_REQUEST_ERROR;
3430 }
3431
3432 if (aws_mqtt_packet_connection_encode(&message->message_data, &pingreq)) {
3433 aws_mem_release(message->allocator, message);
3434 return AWS_MQTT_CLIENT_REQUEST_ERROR;
3435 }
3436
3437 if (aws_channel_slot_send_message(connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
3438 aws_mem_release(message->allocator, message);
3439 return AWS_MQTT_CLIENT_REQUEST_ERROR;
3440 }
3441
3442 /* Mark down that now is when the last pingreq was sent */
3443 connection->thread_data.waiting_on_ping_response = true;
3444
3445 struct aws_channel_task *ping_timeout_task =
3446 aws_mem_calloc(connection->allocator, 1, sizeof(struct aws_channel_task));
3447 if (!ping_timeout_task) {
3448 /* allocation failed, no log, just return error. */
3449 goto error;
3450 }
3451 aws_channel_task_init(ping_timeout_task, s_pingresp_received_timeout, connection, "mqtt_pingresp_timeout");
3452 uint64_t now = 0;
3453 if (aws_channel_current_clock_time(connection->slot->channel, &now)) {
3454 goto error;
3455 }
3456 now += connection->ping_timeout_ns;
3457 aws_channel_schedule_task_future(connection->slot->channel, ping_timeout_task, now);
3458 return AWS_MQTT_CLIENT_REQUEST_COMPLETE;
3459
3460 error:
3461 return AWS_MQTT_CLIENT_REQUEST_ERROR;
3462 }
3463
3464 int aws_mqtt_client_connection_ping(struct aws_mqtt_client_connection_311_impl *connection) {
3465
3466 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Starting ping", (void *)connection);
3467
3468 uint16_t packet_id =
3469 mqtt_create_request(connection, &s_pingreq_send, connection, NULL, NULL, true, /* noRetry */ 0);
3470
3471 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Starting ping with packet id %" PRIu16, (void *)connection, packet_id);
3472
3473 return (packet_id > 0) ? AWS_OP_SUCCESS : AWS_OP_ERR;
3474 }
3475
3476 /*******************************************************************************
3477 * Operation Statistics
3478 ******************************************************************************/
3479
3480 void aws_mqtt_connection_statistics_change_operation_statistic_state(
3481 struct aws_mqtt_client_connection_311_impl *connection,
3482 struct aws_mqtt_request *request,
3483 enum aws_mqtt_operation_statistic_state_flags new_state_flags) {
3484
3485 // Error checking
3486 if (!connection) {
3487 AWS_LOGF_ERROR(
3488 AWS_LS_MQTT_CLIENT, "Invalid MQTT311 connection used when trying to change operation statistic state");
3489 return;
3490 }
3491 if (!request) {
3492 AWS_LOGF_ERROR(
3493 AWS_LS_MQTT_CLIENT, "Invalid MQTT311 request used when trying to change operation statistic state");
3494 return;
3495 }
3496
3497 uint64_t packet_size = request->packet_size;
3498 /**
3499 * If the packet size is zero, then just skip it as we only want to track packets we have intentially
3500 * calculated the size of and therefore it will be non-zero (zero packets will be ACKs, Pings, etc)
3501 */
3502 if (packet_size <= 0) {
3503 return;
3504 }
3505
3506 enum aws_mqtt_operation_statistic_state_flags old_state_flags = request->statistic_state_flags;
3507 if (new_state_flags == old_state_flags) {
3508 return;
3509 }
3510
3511 struct aws_mqtt_connection_operation_statistics_impl *stats = &connection->operation_statistics_impl;
3512 if ((old_state_flags & AWS_MQTT_OSS_INCOMPLETE) != (new_state_flags & AWS_MQTT_OSS_INCOMPLETE)) {
3513 if ((new_state_flags & AWS_MQTT_OSS_INCOMPLETE) != 0) {
3514 aws_atomic_fetch_add(&stats->incomplete_operation_count_atomic, 1);
3515 aws_atomic_fetch_add(&stats->incomplete_operation_size_atomic, (size_t)packet_size);
3516 } else {
3517 aws_atomic_fetch_sub(&stats->incomplete_operation_count_atomic, 1);
3518 aws_atomic_fetch_sub(&stats->incomplete_operation_size_atomic, (size_t)packet_size);
3519 }
3520 }
3521
3522 if ((old_state_flags & AWS_MQTT_OSS_UNACKED) != (new_state_flags & AWS_MQTT_OSS_UNACKED)) {
3523 if ((new_state_flags & AWS_MQTT_OSS_UNACKED) != 0) {
3524 aws_atomic_fetch_add(&stats->unacked_operation_count_atomic, 1);
3525 aws_atomic_fetch_add(&stats->unacked_operation_size_atomic, (size_t)packet_size);
3526 } else {
3527 aws_atomic_fetch_sub(&stats->unacked_operation_count_atomic, 1);
3528 aws_atomic_fetch_sub(&stats->unacked_operation_size_atomic, (size_t)packet_size);
3529 }
3530 }
3531 request->statistic_state_flags = new_state_flags;
3532
3533 // If the callback is defined, then call it
3534 if (connection && connection->on_any_operation_statistics && connection->on_any_operation_statistics_ud) {
3535 (*connection->on_any_operation_statistics)(connection, connection->on_any_operation_statistics_ud);
3536 }
3537 }
3538
3539 static int s_aws_mqtt_client_connection_311_get_stats(
3540 void *impl,
3541 struct aws_mqtt_connection_operation_statistics *stats) {
3542
3543 struct aws_mqtt_client_connection_311_impl *connection = impl;
3544
3545 // Error checking
3546 if (!connection) {
3547 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "Invalid MQTT311 connection used when trying to get operation statistics");
3548 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
3549 }
3550 if (!stats) {
3551 AWS_LOGF_ERROR(
3552 AWS_LS_MQTT_CLIENT,
3553 "id=%p: Invalid MQTT311 connection statistics struct used when trying to get operation statistics",
3554 (void *)connection);
3555 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
3556 }
3557
3558 stats->incomplete_operation_count =
3559 (uint64_t)aws_atomic_load_int(&connection->operation_statistics_impl.incomplete_operation_count_atomic);
3560 stats->incomplete_operation_size =
3561 (uint64_t)aws_atomic_load_int(&connection->operation_statistics_impl.incomplete_operation_size_atomic);
3562 stats->unacked_operation_count =
3563 (uint64_t)aws_atomic_load_int(&connection->operation_statistics_impl.unacked_operation_count_atomic);
3564 stats->unacked_operation_size =
3565 (uint64_t)aws_atomic_load_int(&connection->operation_statistics_impl.unacked_operation_size_atomic);
3566
3567 return AWS_OP_SUCCESS;
3568 }
3569
3570 int aws_mqtt_client_connection_set_on_operation_statistics_handler(
3571 struct aws_mqtt_client_connection_311_impl *connection,
3572 aws_mqtt_on_operation_statistics_fn *on_operation_statistics,
3573 void *on_operation_statistics_ud) {
3574
3575 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Setting on_operation_statistics handler", (void *)connection);
3576
3577 connection->on_any_operation_statistics = on_operation_statistics;
3578 connection->on_any_operation_statistics_ud = on_operation_statistics_ud;
3579
3580 return AWS_OP_SUCCESS;
3581 }
3582
3583 static int s_aws_mqtt_client_connection_311_set_metrics(void *impl, const struct aws_mqtt_iot_metrics *metrics) {
3584
3585 struct aws_mqtt_client_connection_311_impl *connection = impl;
3586 AWS_PRECONDITION(connection);
3587
3588 struct aws_mqtt_iot_metrics_storage *metrics_storage = NULL;
3589 if (metrics) {
3590 if (aws_mqtt_validate_iot_metrics(metrics) == AWS_OP_ERR) {
3591 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Invalid metrics.", (void *)connection);
3592 return AWS_OP_ERR;
3593 }
3594
3595 metrics_storage = aws_mqtt_iot_metrics_storage_new(connection->allocator, metrics);
3596 if (!metrics_storage) {
3597 int error = aws_last_error();
3598 AWS_LOGF_ERROR(
3599 AWS_LS_MQTT_CLIENT,
3600 "id=%p: Failed to create IoT SDK metrics storage, error %d (%s)",
3601 (void *)connection,
3602 error,
3603 aws_error_name(error));
3604 return aws_raise_error(error);
3605 }
3606 }
3607
3608 int result = AWS_OP_ERR;
3609
3610 /* BEGIN CRITICAL SECTION */
3611 mqtt_connection_lock_synced_data(connection);
3612
3613 if (connection->synced_data.state != AWS_MQTT_CLIENT_STATE_DISCONNECTED &&
3614 connection->synced_data.state != AWS_MQTT_CLIENT_STATE_CONNECTED) {
3615 AWS_LOGF_ERROR(
3616 AWS_LS_MQTT_CLIENT,
3617 "id=%p: Connection is currently pending connect/disconnect. Unable to make configuration changes until "
3618 "pending operation completes.",
3619 (void *)connection);
3620 aws_raise_error(AWS_ERROR_INVALID_STATE);
3621 goto done;
3622 }
3623
3624 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Setting IoT SDK metrics", (void *)connection);
3625 aws_mqtt_iot_metrics_storage_destroy(connection->metrics_storage);
3626 connection->metrics_storage = metrics_storage;
3627
3628 metrics_storage = NULL;
3629 result = AWS_OP_SUCCESS;
3630
3631 done:
3632 mqtt_connection_unlock_synced_data(connection);
3633 /* END CRITICAL SECTION */
3634
3635 if (metrics_storage) {
3636 aws_mqtt_iot_metrics_storage_destroy(metrics_storage);
3637 }
3638
3639 return result;
3640 }
3641
3642 static struct aws_mqtt_client_connection *s_aws_mqtt_client_connection_311_acquire(void *impl) {
3643 struct aws_mqtt_client_connection_311_impl *connection = impl;
3644
3645 aws_ref_count_acquire(&connection->ref_count);
3646
3647 return &connection->base;
3648 }
3649
3650 static void s_aws_mqtt_client_connection_311_release(void *impl) {
3651 struct aws_mqtt_client_connection_311_impl *connection = impl;
3652
3653 aws_ref_count_release(&connection->ref_count);
3654 }
3655
3656 static enum aws_mqtt311_impl_type s_aws_mqtt_client_connection_311_get_impl(const void *impl) {
3657 (void)impl;
3658
3659 return AWS_MQTT311_IT_311_CONNECTION;
3660 }
3661
3662 static struct aws_event_loop *s_aws_mqtt_client_connection_311_get_event_loop(const void *impl) {
3663 const struct aws_mqtt_client_connection_311_impl *connection = impl;
3664
3665 return connection->loop;
3666 }
3667
3668 static struct aws_mqtt_client_connection_vtable s_aws_mqtt_client_connection_311_vtable = {
3669 .acquire_fn = s_aws_mqtt_client_connection_311_acquire,
3670 .release_fn = s_aws_mqtt_client_connection_311_release,
3671 .set_will_fn = s_aws_mqtt_client_connection_311_set_will,
3672 .set_login_fn = s_aws_mqtt_client_connection_311_set_login,
3673 .use_websockets_fn = s_aws_mqtt_client_connection_311_use_websockets,
3674 .set_http_proxy_options_fn = s_aws_mqtt_client_connection_311_set_http_proxy_options,
3675 .set_host_resolution_options_fn = s_aws_mqtt_client_connection_311_set_host_resolution_options,
3676 .set_reconnect_timeout_fn = s_aws_mqtt_client_connection_311_set_reconnect_timeout,
3677 .set_connection_result_handlers = s_aws_mqtt_client_connection_311_set_connection_result_handlers,
3678 .set_connection_interruption_handlers_fn = s_aws_mqtt_client_connection_311_set_connection_interruption_handlers,
3679 .set_connection_closed_handler_fn = s_aws_mqtt_client_connection_311_set_connection_closed_handler,
3680 .set_on_any_publish_handler_fn = s_aws_mqtt_client_connection_311_set_on_any_publish_handler,
3681 .set_connection_termination_handler_fn = s_aws_mqtt_client_connection_311_set_connection_termination_handler,
3682 .connect_fn = s_aws_mqtt_client_connection_311_connect,
3683 .reconnect_fn = s_aws_mqtt_client_connection_311_reconnect,
3684 .disconnect_fn = s_aws_mqtt_client_connection_311_disconnect,
3685 .subscribe_multiple_fn = s_aws_mqtt_client_connection_311_subscribe_multiple,
3686 .subscribe_fn = s_aws_mqtt_client_connection_311_subscribe,
3687 .resubscribe_existing_topics_fn = s_aws_mqtt_311_resubscribe_existing_topics,
3688 .unsubscribe_fn = s_aws_mqtt_client_connection_311_unsubscribe,
3689 .publish_fn = s_aws_mqtt_client_connection_311_publish,
3690 .get_stats_fn = s_aws_mqtt_client_connection_311_get_stats,
3691 .set_metrics_fn = s_aws_mqtt_client_connection_311_set_metrics,
3692 .get_impl_type = s_aws_mqtt_client_connection_311_get_impl,
3693 .get_event_loop = s_aws_mqtt_client_connection_311_get_event_loop,
3694 };
3695
3696 static struct aws_mqtt_client_connection_vtable *s_aws_mqtt_client_connection_311_vtable_ptr =
3697 &s_aws_mqtt_client_connection_311_vtable;
3698
3699 struct aws_mqtt_client_connection *aws_mqtt_client_connection_new(struct aws_mqtt_client *client) {
3700 AWS_PRECONDITION(client);
3701
3702 struct aws_mqtt_client_connection_311_impl *connection =
3703 aws_mem_calloc(client->allocator, 1, sizeof(struct aws_mqtt_client_connection_311_impl));
3704 if (!connection) {
3705 return NULL;
3706 }
3707
3708 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: Creating new mqtt 311 connection", (void *)connection);
3709
3710 /* Initialize the client */
3711 connection->allocator = client->allocator;
3712 connection->base.vtable = s_aws_mqtt_client_connection_311_vtable_ptr;
3713 connection->base.impl = connection;
3714 aws_ref_count_init(
3715 &connection->ref_count, connection, (aws_simple_completion_callback *)s_mqtt_client_connection_start_destroy);
3716 connection->client = aws_mqtt_client_acquire(client);
3717
3718 AWS_ZERO_STRUCT(connection->synced_data);
3719 connection->synced_data.state = AWS_MQTT_CLIENT_STATE_DISCONNECTED;
3720 connection->reconnect_timeouts.min_sec = 1;
3721 connection->reconnect_timeouts.current_sec = 1;
3722 connection->reconnect_timeouts.max_sec = 128;
3723 aws_linked_list_init(&connection->synced_data.pending_requests_list);
3724 aws_linked_list_init(&connection->thread_data.ongoing_requests_list);
3725 s_init_statistics(&connection->operation_statistics_impl);
3726
3727 if (aws_mutex_init(&connection->synced_data.lock)) {
3728 AWS_LOGF_ERROR(
3729 AWS_LS_MQTT_CLIENT,
3730 "id=%p: Failed to initialize mutex, error %d (%s)",
3731 (void *)connection,
3732 aws_last_error(),
3733 aws_error_name(aws_last_error()));
3734 goto failed_init_mutex;
3735 }
3736
3737 if (aws_rw_lock_init(&connection->callback_lock)) {
3738 AWS_LOGF_ERROR(
3739 AWS_LS_MQTT_CLIENT,
3740 "id=%p: Failed to initialize callback lock, error %d (%s)",
3741 (void *)connection,
3742 aws_last_error(),
3743 aws_error_name(aws_last_error()));
3744 goto failed_init_callback_lock;
3745 }
3746
3747 struct aws_mqtt311_decoder_options config = {
3748 .packet_handlers = aws_mqtt311_get_default_packet_handlers(),
3749 .handler_user_data = connection,
3750 };
3751 aws_mqtt311_decoder_init(&connection->thread_data.decoder, client->allocator, &config);
3752
3753 if (aws_mqtt_topic_tree_init(&connection->thread_data.subscriptions, connection->allocator)) {
3754
3755 AWS_LOGF_ERROR(
3756 AWS_LS_MQTT_CLIENT,
3757 "id=%p: Failed to initialize subscriptions topic_tree, error %d (%s)",
3758 (void *)connection,
3759 aws_last_error(),
3760 aws_error_name(aws_last_error()));
3761 goto failed_init_subscriptions;
3762 }
3763
3764 if (aws_memory_pool_init(
3765 &connection->synced_data.requests_pool, connection->allocator, 32, sizeof(struct aws_mqtt_request))) {
3766
3767 AWS_LOGF_ERROR(
3768 AWS_LS_MQTT_CLIENT,
3769 "id=%p: Failed to initialize request pool, error %d (%s)",
3770 (void *)connection,
3771 aws_last_error(),
3772 aws_error_name(aws_last_error()));
3773 goto failed_init_requests_pool;
3774 }
3775
3776 if (aws_hash_table_init(
3777 &connection->synced_data.outstanding_requests_table,
3778 connection->allocator,
3779 DEFAULT_MQTT311_OPERATION_TABLE_SIZE,
3780 aws_mqtt_hash_uint16_t,
3781 aws_mqtt_compare_uint16_t_eq,
3782 NULL,
3783 NULL)) {
3784
3785 AWS_LOGF_ERROR(
3786 AWS_LS_MQTT_CLIENT,
3787 "id=%p: Failed to initialize outstanding requests table, error %d (%s)",
3788 (void *)connection,
3789 aws_last_error(),
3790 aws_error_name(aws_last_error()));
3791 goto failed_init_outstanding_requests_table;
3792 }
3793
3794 connection->loop = aws_event_loop_group_get_next_loop(client->bootstrap->event_loop_group);
3795
3796 connection->host_resolution_config = aws_host_resolver_init_default_resolution_config();
3797 connection->host_resolution_config.resolve_frequency_ns =
3798 aws_timestamp_convert(connection->reconnect_timeouts.max_sec, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
3799
3800 /* Initialize the handler */
3801 connection->handler.alloc = connection->allocator;
3802 connection->handler.vtable = aws_mqtt_get_client_channel_vtable();
3803 connection->handler.impl = connection;
3804
3805 aws_mqtt311_callback_set_manager_init(&connection->callback_manager, connection->allocator, &connection->base);
3806
3807 return &connection->base;
3808
3809 failed_init_outstanding_requests_table:
3810 aws_memory_pool_clean_up(&connection->synced_data.requests_pool);
3811
3812 failed_init_requests_pool:
3813 aws_mqtt_topic_tree_clean_up(&connection->thread_data.subscriptions);
3814
3815 failed_init_subscriptions:
3816 aws_rw_lock_clean_up(&connection->callback_lock);
3817
3818 failed_init_callback_lock:
3819 aws_mutex_clean_up(&connection->synced_data.lock);
3820
3821 failed_init_mutex:
3822 aws_mem_release(client->allocator, connection);
3823
3824 return NULL;
3825 }
3826
3827 int aws_mqtt_client_connection_set_metrics(
3828 struct aws_mqtt_client_connection *connection,
3829 const struct aws_mqtt_iot_metrics *metrics) {
3830
3831 AWS_PRECONDITION(connection);
3832 return connection->vtable->set_metrics_fn(connection->impl, metrics);
3833 }