Debian Codegraph @

crt/aws-c-mqtt/source/v5/mqtt5_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
6 #include <aws/mqtt/v5/mqtt5_client.h>
7
8 #include <aws/common/clock.h>
9 #include <aws/common/string.h>
10 #include <aws/http/proxy.h>
11 #include <aws/http/request_response.h>
12 #include <aws/http/websocket.h>
13 #include <aws/io/channel_bootstrap.h>
14 #include <aws/io/event_loop.h>
15 #include <aws/mqtt/private/client_impl_shared.h>
16 #include <aws/mqtt/private/shared.h>
17 #include <aws/mqtt/private/v5/mqtt5_client_impl.h>
18 #include <aws/mqtt/private/v5/mqtt5_options_storage.h>
19 #include <aws/mqtt/private/v5/mqtt5_utils.h>
20
21 #include <inttypes.h>
22
23 #ifdef _MSC_VER
24 # pragma warning(push)
25 # pragma warning(disable : 4232) /* function pointer to dll symbol */
26 #endif
27
28 #define AWS_MQTT5_IO_MESSAGE_DEFAULT_LENGTH 4096
29 #define AWS_MQTT5_DEFAULT_CONNACK_PACKET_TIMEOUT_MS 10000
30 #define DEFAULT_MQTT5_OPERATION_TABLE_SIZE 200
31
32 const char *aws_mqtt5_client_state_to_c_string(enum aws_mqtt5_client_state state) {
33 switch (state) {
34 case AWS_MCS_STOPPED:
35 return "STOPPED";
36
37 case AWS_MCS_CONNECTING:
38 return "CONNECTING";
39
40 case AWS_MCS_MQTT_CONNECT:
41 return "MQTT_CONNECT";
42
43 case AWS_MCS_CONNECTED:
44 return "CONNECTED";
45
46 case AWS_MCS_CLEAN_DISCONNECT:
47 return "CLEAN_DISCONNECT";
48
49 case AWS_MCS_CHANNEL_SHUTDOWN:
50 return "CHANNEL_SHUTDOWN";
51
52 case AWS_MCS_PENDING_RECONNECT:
53 return "PENDING_RECONNECT";
54
55 case AWS_MCS_TERMINATED:
56 return "TERMINATED";
57
58 default:
59 return "UNKNOWN";
60 }
61 }
62
63 static bool s_aws_mqtt5_operation_is_retainable(struct aws_mqtt5_operation *operation) {
64 switch (operation->packet_type) {
65 case AWS_MQTT5_PT_PUBLISH:
66 case AWS_MQTT5_PT_SUBSCRIBE:
67 case AWS_MQTT5_PT_UNSUBSCRIBE:
68 return true;
69
70 default:
71 return false;
72 }
73 }
74
75 static void s_init_statistics(struct aws_mqtt5_client_operation_statistics_impl *stats) {
76 aws_atomic_store_int(&stats->incomplete_operation_count_atomic, 0);
77 aws_atomic_store_int(&stats->incomplete_operation_size_atomic, 0);
78 aws_atomic_store_int(&stats->unacked_operation_count_atomic, 0);
79 aws_atomic_store_int(&stats->unacked_operation_size_atomic, 0);
80 }
81
82 static bool s_aws_mqtt5_operation_satisfies_offline_queue_retention_policy(
83 struct aws_mqtt5_operation *operation,
84 enum aws_mqtt5_client_operation_queue_behavior_type queue_behavior) {
85 switch (aws_mqtt5_client_operation_queue_behavior_type_to_non_default(queue_behavior)) {
86 case AWS_MQTT5_COQBT_FAIL_ALL_ON_DISCONNECT:
87 return false;
88
89 case AWS_MQTT5_COQBT_FAIL_QOS0_PUBLISH_ON_DISCONNECT:
90 if (!s_aws_mqtt5_operation_is_retainable(operation)) {
91 return false;
92 }
93
94 if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
95 const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
96 if (publish_view->qos == AWS_MQTT5_QOS_AT_MOST_ONCE) {
97 return false;
98 }
99 }
100
101 return true;
102
103 case AWS_MQTT5_COQBT_FAIL_NON_QOS1_PUBLISH_ON_DISCONNECT:
104 if (!s_aws_mqtt5_operation_is_retainable(operation)) {
105 return false;
106 }
107
108 if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
109 const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
110 if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
111 return true;
112 }
113 }
114
115 return false;
116
117 default:
118 return false;
119 }
120 }
121
122 typedef bool(mqtt5_operation_filter)(struct aws_mqtt5_operation *operation, void *filter_context);
123
124 static void s_filter_operation_list(
125 struct aws_linked_list *source_operations,
126 mqtt5_operation_filter *filter_fn,
127 struct aws_linked_list *filtered_operations,
128 void *filter_context) {
129 struct aws_linked_list_node *node = aws_linked_list_begin(source_operations);
130 while (node != aws_linked_list_end(source_operations)) {
131 struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
132 node = aws_linked_list_next(node);
133
134 if (filter_fn(operation, filter_context)) {
135 aws_linked_list_remove(&operation->node);
136 aws_linked_list_push_back(filtered_operations, &operation->node);
137 }
138 }
139 }
140
141 typedef void(mqtt5_operation_applicator)(struct aws_mqtt5_operation *operation, void *applicator_context);
142
143 static void s_apply_to_operation_list(
144 struct aws_linked_list *operations,
145 mqtt5_operation_applicator *applicator_fn,
146 void *applicator_context) {
147 struct aws_linked_list_node *node = aws_linked_list_begin(operations);
148 while (node != aws_linked_list_end(operations)) {
149 struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
150 node = aws_linked_list_next(node);
151
152 applicator_fn(operation, applicator_context);
153 }
154 }
155
156 static int s_aws_mqtt5_client_change_desired_state(
157 struct aws_mqtt5_client *client,
158 enum aws_mqtt5_client_state desired_state,
159 struct aws_mqtt5_operation_disconnect *disconnect_operation);
160
161 static uint64_t s_aws_mqtt5_client_compute_operational_state_service_time(
162 const struct aws_mqtt5_client_operational_state *client_operational_state,
163 uint64_t now);
164
165 static int s_submit_operation(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation);
166
167 static void s_complete_operation(
168 struct aws_mqtt5_client *client,
169 struct aws_mqtt5_operation *operation,
170 int error_code,
171 enum aws_mqtt5_packet_type packet_type,
172 const void *view) {
173 if (client != NULL) {
174 aws_mqtt5_client_statistics_change_operation_statistic_state(client, operation, AWS_MQTT5_OSS_NONE);
175 if (aws_priority_queue_node_is_in_queue(&operation->priority_queue_node)) {
176 struct aws_mqtt5_operation *queued_operation = NULL;
177 aws_priority_queue_remove(
178 &client->operational_state.operations_by_ack_timeout,
179 &queued_operation,
180 &operation->priority_queue_node);
181 }
182 }
183
184 aws_mqtt5_operation_complete(operation, error_code, packet_type, view);
185 aws_mqtt5_operation_release(operation);
186 }
187
188 static void s_complete_operation_list(
189 struct aws_mqtt5_client *client,
190 struct aws_linked_list *operation_list,
191 int error_code) {
192
193 struct aws_linked_list_node *node = aws_linked_list_begin(operation_list);
194 while (node != aws_linked_list_end(operation_list)) {
195 struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
196
197 node = aws_linked_list_next(node);
198
199 s_complete_operation(client, operation, error_code, AWS_MQTT5_PT_NONE, NULL);
200 }
201
202 /* we've released everything, so reset the list to empty */
203 aws_linked_list_init(operation_list);
204 }
205
206 static void s_check_timeouts(struct aws_mqtt5_client *client, uint64_t now) {
207 struct aws_priority_queue *timeout_queue = &client->operational_state.operations_by_ack_timeout;
208
209 bool done = aws_priority_queue_size(timeout_queue) == 0;
210 while (!done) {
211 struct aws_mqtt5_operation **next_operation_by_timeout_ptr = NULL;
212 aws_priority_queue_top(timeout_queue, (void **)&next_operation_by_timeout_ptr);
213 AWS_FATAL_ASSERT(next_operation_by_timeout_ptr != NULL);
214 struct aws_mqtt5_operation *next_operation_by_timeout = *next_operation_by_timeout_ptr;
215 AWS_FATAL_ASSERT(next_operation_by_timeout != NULL);
216
217 // If the top of the heap hasn't timed out than nothing has
218 if (next_operation_by_timeout->ack_timeout_timepoint_ns > now) {
219 break;
220 }
221
222 /* Ack timeout for this operation has been reached */
223 aws_priority_queue_pop(timeout_queue, &next_operation_by_timeout);
224
225 aws_mqtt5_packet_id_t packet_id = aws_mqtt5_operation_get_packet_id(next_operation_by_timeout);
226 AWS_LOGF_INFO(
227 AWS_LS_MQTT5_CLIENT,
228 "id=%p: %s packet with id:%d has timed out",
229 (void *)client,
230 aws_mqtt5_packet_type_to_c_string(next_operation_by_timeout->packet_type),
231 (int)packet_id);
232
233 struct aws_hash_element *elem = NULL;
234 aws_hash_table_find(&client->operational_state.unacked_operations_table, &packet_id, &elem);
235
236 if (elem == NULL || elem->value == NULL) {
237 AWS_LOGF_ERROR(
238 AWS_LS_MQTT5_CLIENT, "id=%p: timeout for unknown operation with id %d", (void *)client, (int)packet_id);
239 return;
240 }
241
242 aws_linked_list_remove(&next_operation_by_timeout->node);
243 aws_hash_table_remove(&client->operational_state.unacked_operations_table, &packet_id, NULL, NULL);
244
245 s_complete_operation(client, next_operation_by_timeout, AWS_ERROR_MQTT_TIMEOUT, AWS_MQTT5_PT_NONE, NULL);
246
247 done = aws_priority_queue_size(timeout_queue) == 0;
248 }
249 }
250
251 static void s_mqtt5_client_final_destroy(struct aws_mqtt5_client *client) {
252 if (client == NULL) {
253 return;
254 }
255
256 aws_mqtt5_client_termination_completion_fn *client_termination_handler = NULL;
257 void *client_termination_handler_user_data = NULL;
258 if (client->config != NULL) {
259 client_termination_handler = client->config->client_termination_handler;
260 client_termination_handler_user_data = client->config->client_termination_handler_user_data;
261 }
262
263 aws_mqtt5_callback_set_manager_clean_up(&client->callback_manager);
264
265 aws_mqtt5_client_operational_state_clean_up(&client->operational_state);
266
267 aws_mqtt5_client_options_storage_destroy((struct aws_mqtt5_client_options_storage *)client->config);
268
269 aws_mqtt5_negotiated_settings_clean_up(&client->negotiated_settings);
270
271 aws_http_message_release(client->handshake);
272
273 aws_mqtt5_encoder_clean_up(&client->encoder);
274 aws_mqtt5_decoder_clean_up(&client->decoder);
275
276 aws_mqtt5_inbound_topic_alias_resolver_clean_up(&client->inbound_topic_alias_resolver);
277 aws_mqtt5_outbound_topic_alias_resolver_destroy(client->outbound_topic_alias_resolver);
278
279 aws_mem_release(client->allocator, client);
280
281 if (client_termination_handler != NULL) {
282 (*client_termination_handler)(client_termination_handler_user_data);
283 }
284 }
285
286 static void s_on_mqtt5_client_zero_ref_count(void *user_data) {
287 struct aws_mqtt5_client *client = user_data;
288
289 s_aws_mqtt5_client_change_desired_state(client, AWS_MCS_TERMINATED, NULL);
290 }
291
292 static void s_aws_mqtt5_client_emit_stopped_lifecycle_event(struct aws_mqtt5_client *client) {
293 AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: emitting stopped lifecycle event", (void *)client);
294
295 struct aws_mqtt5_client_lifecycle_event event;
296 AWS_ZERO_STRUCT(event);
297
298 event.event_type = AWS_MQTT5_CLET_STOPPED;
299 event.client = client;
300
301 aws_mqtt5_callback_set_manager_on_lifecycle_event(&client->callback_manager, &event);
302 }
303
304 static void s_aws_mqtt5_client_emit_connecting_lifecycle_event(struct aws_mqtt5_client *client) {
305 AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: emitting connecting lifecycle event", (void *)client);
306
307 client->lifecycle_state = AWS_MQTT5_LS_CONNECTING;
308
309 struct aws_mqtt5_client_lifecycle_event event;
310 AWS_ZERO_STRUCT(event);
311
312 event.event_type = AWS_MQTT5_CLET_ATTEMPTING_CONNECT;
313 event.client = client;
314
315 aws_mqtt5_callback_set_manager_on_lifecycle_event(&client->callback_manager, &event);
316 }
317
318 static void s_aws_mqtt5_client_emit_connection_success_lifecycle_event(
319 struct aws_mqtt5_client *client,
320 const struct aws_mqtt5_packet_connack_view *connack_view) {
321
322 AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: emitting connection success lifecycle event", (void *)client);
323
324 client->lifecycle_state = AWS_MQTT5_LS_CONNECTED;
325
326 struct aws_mqtt5_client_lifecycle_event event;
327 AWS_ZERO_STRUCT(event);
328
329 event.event_type = AWS_MQTT5_CLET_CONNECTION_SUCCESS;
330 event.client = client;
331 event.settings = &client->negotiated_settings;
332 event.connack_data = connack_view;
333
334 aws_mqtt5_callback_set_manager_on_lifecycle_event(&client->callback_manager, &event);
335 }
336
337 /*
338 * Emits either a CONNECTION_FAILED or DISCONNECT event based on the current life cycle state. Once a "final"
339 * event is emitted by the client, it must attempt to reconnect before another one will be emitted, since the
340 * lifecycle state check will early out until then. It is expected that this function may get called unnecessarily
341 * often during various channel shutdown or disconnection/failure flows. This will not affect overall correctness.
342 */
343 static void s_aws_mqtt5_client_emit_final_lifecycle_event(
344 struct aws_mqtt5_client *client,
345 int error_code,
346 const struct aws_mqtt5_packet_connack_view *connack_view,
347 const struct aws_mqtt5_packet_disconnect_view *disconnect_view) {
348
349 if (client->lifecycle_state == AWS_MQTT5_LS_NONE) {
350 /* we already emitted a final event earlier */
351 return;
352 }
353
354 struct aws_mqtt5_client_lifecycle_event event;
355 AWS_ZERO_STRUCT(event);
356
357 if (client->lifecycle_state == AWS_MQTT5_LS_CONNECTING) {
358 AWS_FATAL_ASSERT(disconnect_view == NULL);
359 event.event_type = AWS_MQTT5_CLET_CONNECTION_FAILURE;
360
361 AWS_LOGF_INFO(
362 AWS_LS_MQTT5_CLIENT,
363 "id=%p: emitting connection failure lifecycle event with error code %d(%s)",
364 (void *)client,
365 error_code,
366 aws_error_debug_str(error_code));
367 } else {
368 AWS_FATAL_ASSERT(client->lifecycle_state == AWS_MQTT5_LS_CONNECTED);
369 AWS_FATAL_ASSERT(connack_view == NULL);
370 event.event_type = AWS_MQTT5_CLET_DISCONNECTION;
371
372 AWS_LOGF_INFO(
373 AWS_LS_MQTT5_CLIENT,
374 "id=%p: emitting disconnection lifecycle event with error code %d(%s)",
375 (void *)client,
376 error_code,
377 aws_error_debug_str(error_code));
378 }
379
380 event.error_code = error_code;
381 event.connack_data = connack_view;
382 event.disconnect_data = disconnect_view;
383
384 client->lifecycle_state = AWS_MQTT5_LS_NONE;
385
386 aws_mqtt5_callback_set_manager_on_lifecycle_event(&client->callback_manager, &event);
387 }
388
389 /*
390 * next_service_time == 0 means to not service the client, i.e. a state that only cares about external events
391 *
392 * This includes connecting and channel shutdown. Terminated is also included, but it's a state that only exists
393 * instantaneously before final destruction.
394 */
395 static uint64_t s_compute_next_service_time_client_stopped(struct aws_mqtt5_client *client, uint64_t now) {
396 /* have we been told to connect or terminate? */
397 if (client->desired_state != AWS_MCS_STOPPED) {
398 return now;
399 }
400
401 return 0;
402 }
403
404 static uint64_t s_compute_next_service_time_client_connecting(struct aws_mqtt5_client *client, uint64_t now) {
405 (void)client;
406 (void)now;
407
408 return 0;
409 }
410
411 static uint64_t s_compute_next_service_time_client_mqtt_connect(struct aws_mqtt5_client *client, uint64_t now) {
412 /* This state is interruptable by a stop/terminate */
413 if (client->desired_state != AWS_MCS_CONNECTED) {
414 return now;
415 }
416
417 uint64_t operation_processing_time =
418 s_aws_mqtt5_client_compute_operational_state_service_time(&client->operational_state, now);
419 if (operation_processing_time == 0) {
420 return client->next_mqtt_connect_packet_timeout_time;
421 }
422
423 return aws_min_u64(client->next_mqtt_connect_packet_timeout_time, operation_processing_time);
424 }
425
426 /*
427 * Returns the minimum of two numbers, ignoring zero. Zero is returned only if both are zero. Useful when we're
428 * computing (next service) timepoints and zero means "no timepoint"
429 */
430 static uint64_t s_min_non_zero_u64(uint64_t a, uint64_t b) {
431 if (a == 0) {
432 return b;
433 }
434
435 if (b == 0) {
436 return a;
437 }
438
439 return aws_min_u64(a, b);
440 }
441
442 /*
443 * If there are unacked operations, returns the earliest point in time that one could timeout.
444 */
445 static uint64_t s_get_unacked_operation_timeout_for_next_service_time(struct aws_mqtt5_client *client) {
446 if (aws_priority_queue_size(&client->operational_state.operations_by_ack_timeout) > 0) {
447 struct aws_mqtt5_operation **operation = NULL;
448 aws_priority_queue_top(&client->operational_state.operations_by_ack_timeout, (void **)&operation);
449 return (*operation)->ack_timeout_timepoint_ns;
450 }
451
452 return 0;
453 }
454
455 static uint64_t s_compute_next_service_time_client_connected(struct aws_mqtt5_client *client, uint64_t now) {
456
457 /* ping and ping timeout */
458 uint64_t next_service_time = client->next_ping_time;
459 if (client->next_ping_timeout_time != 0) {
460 next_service_time = aws_min_u64(next_service_time, client->next_ping_timeout_time);
461 }
462
463 next_service_time =
464 s_min_non_zero_u64(next_service_time, s_get_unacked_operation_timeout_for_next_service_time(client));
465
466 if (client->desired_state != AWS_MCS_CONNECTED) {
467 next_service_time = now;
468 }
469
470 uint64_t operation_processing_time =
471 s_aws_mqtt5_client_compute_operational_state_service_time(&client->operational_state, now);
472
473 next_service_time = s_min_non_zero_u64(operation_processing_time, next_service_time);
474
475 /* reset reconnect delay interval */
476 next_service_time = s_min_non_zero_u64(client->next_reconnect_delay_reset_time_ns, next_service_time);
477
478 return next_service_time;
479 }
480
481 static uint64_t s_compute_next_service_time_client_clean_disconnect(struct aws_mqtt5_client *client, uint64_t now) {
482 uint64_t ack_timeout_time = s_get_unacked_operation_timeout_for_next_service_time(client);
483
484 uint64_t operation_processing_time =
485 s_aws_mqtt5_client_compute_operational_state_service_time(&client->operational_state, now);
486
487 return s_min_non_zero_u64(ack_timeout_time, operation_processing_time);
488 }
489
490 static uint64_t s_compute_next_service_time_client_channel_shutdown(struct aws_mqtt5_client *client, uint64_t now) {
491 (void)client;
492 (void)now;
493
494 return 0;
495 }
496
497 static uint64_t s_compute_next_service_time_client_pending_reconnect(struct aws_mqtt5_client *client, uint64_t now) {
498 if (client->desired_state != AWS_MCS_CONNECTED) {
499 return now;
500 }
501
502 return client->next_reconnect_time_ns;
503 }
504
505 static uint64_t s_compute_next_service_time_client_terminated(struct aws_mqtt5_client *client, uint64_t now) {
506 (void)client;
507 (void)now;
508
509 return 0;
510 }
511
512 static uint64_t s_compute_next_service_time_by_current_state(struct aws_mqtt5_client *client, uint64_t now) {
513 switch (client->current_state) {
514 case AWS_MCS_STOPPED:
515 return s_compute_next_service_time_client_stopped(client, now);
516 case AWS_MCS_CONNECTING:
517 return s_compute_next_service_time_client_connecting(client, now);
518 case AWS_MCS_MQTT_CONNECT:
519 return s_compute_next_service_time_client_mqtt_connect(client, now);
520 case AWS_MCS_CONNECTED:
521 return s_compute_next_service_time_client_connected(client, now);
522 case AWS_MCS_CLEAN_DISCONNECT:
523 return s_compute_next_service_time_client_clean_disconnect(client, now);
524 case AWS_MCS_CHANNEL_SHUTDOWN:
525 return s_compute_next_service_time_client_channel_shutdown(client, now);
526 case AWS_MCS_PENDING_RECONNECT:
527 return s_compute_next_service_time_client_pending_reconnect(client, now);
528 case AWS_MCS_TERMINATED:
529 return s_compute_next_service_time_client_terminated(client, now);
530 }
531
532 return 0;
533 }
534
535 static void s_reevaluate_service_task(struct aws_mqtt5_client *client) {
536 /*
537 * This causes the client to only reevaluate service schedule time at the end of the service call or in
538 * a callback from an external event.
539 */
540 if (client->in_service) {
541 return;
542 }
543
544 uint64_t now = (*client->vtable->get_current_time_fn)();
545 uint64_t next_service_time = s_compute_next_service_time_by_current_state(client, now);
546
547 /*
548 * This catches both the case when there's an existing service schedule and we either want to not
549 * perform it (next_service_time == 0) or need to run service at a different time than the current scheduled time.
550 */
551 if (next_service_time != client->next_service_task_run_time && client->next_service_task_run_time > 0) {
552 aws_event_loop_cancel_task(client->loop, &client->service_task);
553 client->next_service_task_run_time = 0;
554
555 AWS_LOGF_TRACE(AWS_LS_MQTT5_CLIENT, "id=%p: cancelling previously scheduled service task", (void *)client);
556 }
557
558 if (next_service_time > 0 &&
559 (next_service_time < client->next_service_task_run_time || client->next_service_task_run_time == 0)) {
560 aws_event_loop_schedule_task_future(client->loop, &client->service_task, next_service_time);
561
562 AWS_LOGF_TRACE(
563 AWS_LS_MQTT5_CLIENT, "id=%p: scheduled service task for time %" PRIu64, (void *)client, next_service_time);
564 }
565
566 client->next_service_task_run_time = next_service_time;
567 }
568
569 static void s_enqueue_operation_back(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation) {
570 AWS_LOGF_DEBUG(
571 AWS_LS_MQTT5_CLIENT,
572 "id=%p: enqueuing %s operation to back",
573 (void *)client,
574 aws_mqtt5_packet_type_to_c_string(operation->packet_type));
575
576 aws_linked_list_push_back(&client->operational_state.queued_operations, &operation->node);
577
578 s_reevaluate_service_task(client);
579 }
580
581 static void s_enqueue_operation_front(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation) {
582 AWS_LOGF_DEBUG(
583 AWS_LS_MQTT5_CLIENT,
584 "id=%p: enqueuing %s operation to front",
585 (void *)client,
586 aws_mqtt5_packet_type_to_c_string(operation->packet_type));
587
588 aws_linked_list_push_front(&client->operational_state.queued_operations, &operation->node);
589
590 s_reevaluate_service_task(client);
591 }
592
593 /* This is used to move the aws_mqtt5_manual_pub_ack_entry stored in the active table to cancelled table. We don't
594 * simply clear out the active table because we need to keep the entries in memory until we are fully done with them. */
595 static int s_manual_pub_ack_transfer(void *context, struct aws_hash_element *element) {
596 struct aws_hash_table *manual_pub_ack_cancelled_control_id_table = context;
597
598 struct aws_mqtt5_manual_pub_ack_entry *manual_pub_ack_entry = element->value;
599 // Add the control id to the destination table
600 if (aws_hash_table_put(manual_pub_ack_cancelled_control_id_table, element->key, element->value, NULL)) {
601 return AWS_COMMON_HASH_TABLE_ITER_ERROR;
602 }
603 // incref the ref_count because when this entry is removed from the original set it will decref.
604 aws_ref_count_acquire(&manual_pub_ack_entry->ref_count);
605
606 // We simply continue here and will clear (and thus decref) after we finish iterating.
607 return AWS_COMMON_HASH_TABLE_ITER_CONTINUE;
608 }
609
610 /* This is called when the manual publish acknowledgement entry is removed from a hashset to properly decref on removal
611 */
612 static void s_aws_mqtt5_manual_pub_ack_entry_decref(void *value) {
613 struct aws_mqtt5_manual_pub_ack_entry *manual_pub_ack_entry = value;
614 if (manual_pub_ack_entry != NULL) {
615 aws_ref_count_release(&manual_pub_ack_entry->ref_count);
616 }
617 }
618
619 /* When a disconnect or stop occurs all publish acknowledgements become invalid. We clear packet ids which may be reused
620 * by the server and transfer manual publish acknowledgement entries from the active table to the cancelled table
621 * to provide better communication if the user attempts to invoke a publish acknowledgement they think they have control
622 * over. */
623 static void s_aws_mqtt5_reset_manual_pub_ack_tables(
624 struct aws_mqtt5_client_operational_state *client_operational_state) {
625 size_t count = aws_hash_table_get_entry_count(&client_operational_state->manual_pub_ack_control_id_table);
626 if (count > 0) {
627 AWS_LOGF_DEBUG(
628 AWS_LS_MQTT5_CLIENT,
629 "id=%p: Clearing %zu PUBACKs under user control. Previously controlled PUBACKs are no longer valid and "
630 "have been cancelled.",
631 (void *)client_operational_state->client,
632 count);
633 aws_hash_table_clear(&client_operational_state->manual_pub_ack_packet_id_table);
634 aws_hash_table_foreach(
635 &client_operational_state->manual_pub_ack_control_id_table,
636 s_manual_pub_ack_transfer,
637 &client_operational_state->manual_pub_ack_cancelled_control_id_table);
638 aws_hash_table_clear(&client_operational_state->manual_pub_ack_control_id_table);
639 }
640 }
641
642 static void s_aws_mqtt5_client_operational_state_reset(
643 struct aws_mqtt5_client_operational_state *client_operational_state,
644 int completion_error_code,
645 bool is_final) {
646
647 struct aws_mqtt5_client *client = client_operational_state->client;
648
649 s_complete_operation_list(client, &client_operational_state->queued_operations, completion_error_code);
650 s_complete_operation_list(client, &client_operational_state->write_completion_operations, completion_error_code);
651 s_complete_operation_list(client, &client_operational_state->unacked_operations, completion_error_code);
652
653 if (is_final) {
654 aws_priority_queue_clean_up(&client_operational_state->operations_by_ack_timeout);
655 aws_hash_table_clean_up(&client_operational_state->unacked_operations_table);
656 aws_hash_table_clean_up(&client_operational_state->manual_pub_ack_control_id_table);
657 aws_hash_table_clean_up(&client_operational_state->manual_pub_ack_packet_id_table);
658 aws_hash_table_clean_up(&client_operational_state->manual_pub_ack_cancelled_control_id_table);
659 } else {
660 aws_priority_queue_clear(&client->operational_state.operations_by_ack_timeout);
661 aws_hash_table_clear(&client_operational_state->unacked_operations_table);
662 s_aws_mqtt5_reset_manual_pub_ack_tables(client_operational_state);
663 }
664 }
665
666 static void s_change_current_state(struct aws_mqtt5_client *client, enum aws_mqtt5_client_state next_state);
667
668 static void s_change_current_state_to_stopped(struct aws_mqtt5_client *client) {
669 client->current_state = AWS_MCS_STOPPED;
670
671 s_aws_mqtt5_client_operational_state_reset(&client->operational_state, AWS_ERROR_MQTT5_USER_REQUESTED_STOP, false);
672
673 /* Stop works as a complete session wipe, and so the next time we connect, we want it to be clean unless
674 * client session behavior type is set to AWS_MQTT5_CSBT_REJOIN_ALWAYS. */
675 client->has_connected_successfully = false;
676
677 s_aws_mqtt5_client_emit_stopped_lifecycle_event(client);
678 }
679
680 static void s_aws_mqtt5_client_shutdown_channel(struct aws_mqtt5_client *client, int error_code) {
681 if (error_code == AWS_ERROR_SUCCESS) {
682 error_code = AWS_ERROR_UNKNOWN;
683 }
684
685 s_aws_mqtt5_client_emit_final_lifecycle_event(client, error_code, NULL, NULL);
686
687 if (client->current_state != AWS_MCS_MQTT_CONNECT && client->current_state != AWS_MCS_CONNECTED &&
688 client->current_state != AWS_MCS_CLEAN_DISCONNECT) {
689 AWS_LOGF_ERROR(
690 AWS_LS_MQTT5_CLIENT,
691 "id=%p: client channel shutdown invoked from unexpected state %d(%s)",
692 (void *)client,
693 (int)client->current_state,
694 aws_mqtt5_client_state_to_c_string(client->current_state));
695 return;
696 }
697
698 if (client->slot == NULL || client->slot->channel == NULL) {
699 AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: client channel shutdown invoked without a channel", (void *)client);
700 return;
701 }
702
703 s_change_current_state(client, AWS_MCS_CHANNEL_SHUTDOWN);
704 (*client->vtable->channel_shutdown_fn)(client->slot->channel, error_code);
705 }
706
707 static void s_aws_mqtt5_client_shutdown_channel_with_disconnect(
708 struct aws_mqtt5_client *client,
709 int error_code,
710 struct aws_mqtt5_operation_disconnect *disconnect_op) {
711 if (client->current_state != AWS_MCS_CONNECTED && client->current_state != AWS_MCS_MQTT_CONNECT) {
712 s_aws_mqtt5_client_shutdown_channel(client, error_code);
713 return;
714 }
715
716 aws_linked_list_push_front(&client->operational_state.queued_operations, &disconnect_op->base.node);
717 aws_mqtt5_operation_disconnect_acquire(disconnect_op);
718 client->clean_disconnect_error_code = error_code;
719
720 s_change_current_state(client, AWS_MCS_CLEAN_DISCONNECT);
721 }
722
723 static void s_on_disconnect_operation_complete(int error_code, void *user_data) {
724 struct aws_mqtt5_client *client = user_data;
725
726 s_aws_mqtt5_client_shutdown_channel(
727 client, (error_code != AWS_ERROR_SUCCESS) ? error_code : client->clean_disconnect_error_code);
728 }
729
730 static void s_aws_mqtt5_client_shutdown_channel_clean(
731 struct aws_mqtt5_client *client,
732 int error_code,
733 enum aws_mqtt5_disconnect_reason_code reason_code) {
734 struct aws_mqtt5_packet_disconnect_view disconnect_options = {
735 .reason_code = reason_code,
736 };
737
738 struct aws_mqtt5_disconnect_completion_options internal_completion_options = {
739 .completion_callback = s_on_disconnect_operation_complete,
740 .completion_user_data = client,
741 };
742
743 struct aws_mqtt5_operation_disconnect *disconnect_op =
744 aws_mqtt5_operation_disconnect_new(client->allocator, &disconnect_options, NULL, &internal_completion_options);
745 if (disconnect_op == NULL) {
746 s_aws_mqtt5_client_shutdown_channel(client, error_code);
747 return;
748 }
749
750 s_aws_mqtt5_client_shutdown_channel_with_disconnect(client, error_code, disconnect_op);
751 aws_mqtt5_operation_disconnect_release(disconnect_op);
752 }
753
754 static void s_mqtt5_client_shutdown_final(int error_code, struct aws_mqtt5_client *client) {
755
756 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
757
758 s_aws_mqtt5_client_emit_final_lifecycle_event(client, error_code, NULL, NULL);
759
760 AWS_LOGF_INFO(
761 AWS_LS_MQTT5_CLIENT,
762 "id=%p: channel tore down with error code %d(%s)",
763 (void *)client,
764 error_code,
765 aws_error_debug_str(error_code));
766
767 if (client->slot) {
768 aws_channel_slot_remove(client->slot);
769 AWS_LOGF_TRACE(AWS_LS_MQTT5_CLIENT, "id=%p: slot removed successfully", (void *)client);
770 client->slot = NULL;
771 }
772
773 aws_mqtt5_client_on_disconnection_update_operational_state(client);
774
775 if (client->desired_state == AWS_MCS_CONNECTED) {
776 s_change_current_state(client, AWS_MCS_PENDING_RECONNECT);
777 } else {
778 s_change_current_state(client, AWS_MCS_STOPPED);
779 }
780 }
781
782 static void s_mqtt5_client_shutdown(
783 struct aws_client_bootstrap *bootstrap,
784 int error_code,
785 struct aws_channel *channel,
786 void *user_data) {
787
788 (void)bootstrap;
789 (void)channel;
790
791 struct aws_mqtt5_client *client = user_data;
792
793 if (error_code == AWS_ERROR_SUCCESS) {
794 error_code = AWS_ERROR_MQTT_UNEXPECTED_HANGUP;
795 }
796
797 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
798 s_mqtt5_client_shutdown_final(error_code, client);
799 }
800
801 static void s_mqtt5_client_setup(
802 struct aws_client_bootstrap *bootstrap,
803 int error_code,
804 struct aws_channel *channel,
805 void *user_data) {
806
807 (void)bootstrap;
808
809 /* Setup callback contract is: if error_code is non-zero then channel is NULL. */
810 AWS_FATAL_ASSERT((error_code != 0) == (channel == NULL));
811 struct aws_mqtt5_client *client = user_data;
812
813 if (error_code != AWS_OP_SUCCESS) {
814 /* client shutdown already handles this case, so just call that. */
815 s_mqtt5_client_shutdown(bootstrap, error_code, channel, user_data);
816 return;
817 }
818
819 AWS_FATAL_ASSERT(client->current_state == AWS_MCS_CONNECTING);
820 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
821
822 if (client->desired_state != AWS_MCS_CONNECTED) {
823 aws_raise_error(AWS_ERROR_MQTT5_USER_REQUESTED_STOP);
824 goto error;
825 }
826
827 client->slot = aws_channel_slot_new(channel); /* allocs or crashes */
828
829 if (aws_channel_slot_insert_end(channel, client->slot)) {
830 AWS_LOGF_ERROR(
831 AWS_LS_MQTT5_CLIENT,
832 "id=%p: Failed to insert slot into channel %p, error %d (%s).",
833 (void *)client,
834 (void *)channel,
835 aws_last_error(),
836 aws_error_name(aws_last_error()));
837 goto error;
838 }
839
840 if (aws_channel_slot_set_handler(client->slot, &client->handler)) {
841 AWS_LOGF_ERROR(
842 AWS_LS_MQTT5_CLIENT,
843 "id=%p: Failed to set MQTT handler into slot on channel %p, error %d (%s).",
844 (void *)client,
845 (void *)channel,
846 aws_last_error(),
847 aws_error_name(aws_last_error()));
848
849 goto error;
850 }
851
852 s_change_current_state(client, AWS_MCS_MQTT_CONNECT);
853
854 return;
855
856 error:
857
858 s_change_current_state(client, AWS_MCS_CHANNEL_SHUTDOWN);
859 (*client->vtable->channel_shutdown_fn)(channel, aws_last_error());
860 }
861
862 static void s_on_websocket_shutdown(struct aws_websocket *websocket, int error_code, void *user_data) {
863 struct aws_mqtt5_client *client = user_data;
864
865 struct aws_channel *channel = client->slot ? client->slot->channel : NULL;
866
867 s_mqtt5_client_shutdown(client->config->bootstrap, error_code, channel, client);
868
869 if (websocket) {
870 aws_websocket_release(websocket);
871 }
872 }
873
874 static void s_on_websocket_setup(const struct aws_websocket_on_connection_setup_data *setup, void *user_data) {
875
876 struct aws_mqtt5_client *client = user_data;
877 client->handshake = aws_http_message_release(client->handshake);
878
879 /* Setup callback contract is: if error_code is non-zero then websocket is NULL. */
880 AWS_FATAL_ASSERT((setup->error_code != 0) == (setup->websocket == NULL));
881
882 struct aws_channel *channel = NULL;
883
884 if (setup->websocket) {
885 channel = aws_websocket_get_channel(setup->websocket);
886 AWS_ASSERT(channel);
887
888 /* Websocket must be "converted" before the MQTT handler can be installed next to it. */
889 if (aws_websocket_convert_to_midchannel_handler(setup->websocket)) {
890 AWS_LOGF_ERROR(
891 AWS_LS_MQTT5_CLIENT,
892 "id=%p: Failed converting websocket, error %d (%s)",
893 (void *)client,
894 aws_last_error(),
895 aws_error_name(aws_last_error()));
896
897 (*client->vtable->channel_shutdown_fn)(channel, aws_last_error());
898 return;
899 }
900 }
901
902 /* Call into the channel-setup callback, the rest of the logic is the same. */
903 s_mqtt5_client_setup(client->config->bootstrap, setup->error_code, channel, client);
904 }
905
906 struct aws_mqtt5_websocket_transform_complete_task {
907 struct aws_task task;
908 struct aws_allocator *allocator;
909 struct aws_mqtt5_client *client;
910 int error_code;
911 struct aws_http_message *handshake;
912 };
913
914 void s_websocket_transform_complete_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
915 (void)task;
916
917 struct aws_mqtt5_websocket_transform_complete_task *websocket_transform_complete_task = arg;
918 if (status != AWS_TASK_STATUS_RUN_READY) {
919 goto done;
920 }
921
922 struct aws_mqtt5_client *client = websocket_transform_complete_task->client;
923
924 aws_http_message_release(client->handshake);
925 client->handshake = aws_http_message_acquire(websocket_transform_complete_task->handshake);
926
927 int error_code = websocket_transform_complete_task->error_code;
928 if (error_code == 0 && client->desired_state == AWS_MCS_CONNECTED) {
929
930 struct aws_websocket_client_connection_options websocket_options = {
931 .allocator = client->allocator,
932 .bootstrap = client->config->bootstrap,
933 .socket_options = &client->config->socket_options,
934 .tls_options = client->config->tls_options_ptr,
935 .host = aws_byte_cursor_from_string(client->config->host_name),
936 .port = client->config->port,
937 .handshake_request = websocket_transform_complete_task->handshake,
938 .initial_window_size = 0, /* Prevent websocket data from arriving before the MQTT handler is installed */
939 .user_data = client,
940 .on_connection_setup = s_on_websocket_setup,
941 .on_connection_shutdown = s_on_websocket_shutdown,
942 .requested_event_loop = client->loop,
943 .host_resolution_config = &client->config->host_resolution_override};
944
945 if (client->config->http_proxy_config != NULL) {
946 websocket_options.proxy_options = &client->config->http_proxy_options;
947 }
948
949 if (client->vtable->websocket_connect_fn(&websocket_options)) {
950 AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: Failed to initiate websocket connection.", (void *)client);
951 error_code = aws_last_error();
952 goto error;
953 }
954
955 goto done;
956
957 } else {
958 if (error_code == AWS_ERROR_SUCCESS) {
959 AWS_ASSERT(client->desired_state != AWS_MCS_CONNECTED);
960 error_code = AWS_ERROR_MQTT5_USER_REQUESTED_STOP;
961 }
962 }
963
964 error:;
965 struct aws_websocket_on_connection_setup_data websocket_setup = {.error_code = error_code};
966 s_on_websocket_setup(&websocket_setup, client);
967
968 done:
969
970 aws_http_message_release(websocket_transform_complete_task->handshake);
971 aws_mqtt5_client_release(websocket_transform_complete_task->client);
972
973 aws_mem_release(websocket_transform_complete_task->allocator, websocket_transform_complete_task);
974 }
975
976 static void s_websocket_handshake_transform_complete(
977 struct aws_http_message *handshake_request,
978 int error_code,
979 void *complete_ctx) {
980
981 struct aws_mqtt5_client *client = complete_ctx;
982
983 struct aws_mqtt5_websocket_transform_complete_task *task =
984 aws_mem_calloc(client->allocator, 1, sizeof(struct aws_mqtt5_websocket_transform_complete_task));
985
986 aws_task_init(
987 &task->task, s_websocket_transform_complete_task_fn, (void *)task, "WebsocketHandshakeTransformComplete");
988
989 task->allocator = client->allocator;
990 task->client = aws_mqtt5_client_acquire(client);
991 task->error_code = error_code;
992 task->handshake = handshake_request;
993
994 aws_event_loop_schedule_task_now(client->loop, &task->task);
995 }
996
997 static int s_websocket_connect(struct aws_mqtt5_client *client) {
998 AWS_ASSERT(client);
999 AWS_ASSERT(client->config->websocket_handshake_transform);
1000
1001 /* Build websocket handshake request */
1002 struct aws_http_message *handshake = aws_http_message_new_websocket_handshake_request(
1003 client->allocator, *g_websocket_handshake_default_path, aws_byte_cursor_from_string(client->config->host_name));
1004
1005 if (handshake == NULL) {
1006 AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: Failed to generate websocket handshake request", (void *)client);
1007 return AWS_OP_ERR;
1008 }
1009
1010 if (aws_http_message_add_header(handshake, *g_websocket_handshake_default_protocol_header)) {
1011 AWS_LOGF_ERROR(
1012 AWS_LS_MQTT5_CLIENT, "id=%p: Failed to add default header to websocket handshake request", (void *)client);
1013 goto on_error;
1014 }
1015
1016 AWS_LOGF_TRACE(AWS_LS_MQTT5_CLIENT, "id=%p: Transforming websocket handshake request.", (void *)client);
1017
1018 /*
1019 * There is no need to inc the client's ref count here since this state (AWS_MCS_CONNECTING) is uninterruptible by
1020 * the async destruction process. Only a completion of the chain of connection establishment callbacks can cause
1021 * this state to be left by the client.
1022 */
1023 client->config->websocket_handshake_transform(
1024 handshake,
1025 client->config->websocket_handshake_transform_user_data,
1026 s_websocket_handshake_transform_complete,
1027 client);
1028
1029 return AWS_OP_SUCCESS;
1030
1031 on_error:
1032
1033 aws_http_message_release(handshake);
1034
1035 return AWS_OP_ERR;
1036 }
1037
1038 static void s_change_current_state_to_connecting(struct aws_mqtt5_client *client) {
1039 AWS_ASSERT(client->current_state == AWS_MCS_STOPPED || client->current_state == AWS_MCS_PENDING_RECONNECT);
1040
1041 client->current_state = AWS_MCS_CONNECTING;
1042 client->clean_disconnect_error_code = AWS_ERROR_SUCCESS;
1043 client->should_reset_connection = false;
1044
1045 s_aws_mqtt5_client_emit_connecting_lifecycle_event(client);
1046
1047 int result = 0;
1048 if (client->config->websocket_handshake_transform != NULL) {
1049 result = s_websocket_connect(client);
1050 } else {
1051 struct aws_socket_channel_bootstrap_options channel_options;
1052 AWS_ZERO_STRUCT(channel_options);
1053 channel_options.bootstrap = client->config->bootstrap;
1054 channel_options.host_name = aws_string_c_str(client->config->host_name);
1055 channel_options.port = client->config->port;
1056 channel_options.socket_options = &client->config->socket_options;
1057 channel_options.tls_options = client->config->tls_options_ptr;
1058 channel_options.setup_callback = &s_mqtt5_client_setup;
1059 channel_options.shutdown_callback = &s_mqtt5_client_shutdown;
1060 channel_options.user_data = client;
1061 channel_options.requested_event_loop = client->loop;
1062 channel_options.host_resolution_override_config = &client->config->host_resolution_override;
1063
1064 if (client->config->http_proxy_config == NULL) {
1065 result = (*client->vtable->client_bootstrap_new_socket_channel_fn)(&channel_options);
1066 } else {
1067 result = (*client->vtable->http_proxy_new_socket_channel_fn)(
1068 &channel_options, &client->config->http_proxy_options);
1069 }
1070 }
1071
1072 if (result) {
1073 int error_code = aws_last_error();
1074 AWS_LOGF_INFO(
1075 AWS_LS_MQTT5_CLIENT,
1076 "id=%p: failed to kick off connection with error %d(%s)",
1077 (void *)client,
1078 error_code,
1079 aws_error_debug_str(error_code));
1080
1081 s_aws_mqtt5_client_emit_final_lifecycle_event(client, aws_last_error(), NULL, NULL);
1082
1083 s_change_current_state(client, AWS_MCS_PENDING_RECONNECT);
1084 }
1085 }
1086
1087 static int s_aws_mqtt5_client_set_current_operation(
1088 struct aws_mqtt5_client *client,
1089 struct aws_mqtt5_operation *operation) {
1090
1091 if (aws_mqtt5_operation_bind_packet_id(operation, &client->operational_state)) {
1092 int error_code = aws_last_error();
1093 AWS_LOGF_ERROR(
1094 AWS_LS_MQTT5_CLIENT,
1095 "id=%p: failed to bind mqtt packet id for current operation, with error %d(%s)",
1096 (void *)client,
1097 error_code,
1098 aws_error_debug_str(error_code));
1099
1100 return AWS_OP_ERR;
1101 }
1102
1103 if (aws_mqtt5_encoder_append_packet_encoding(&client->encoder, operation->packet_type, operation->packet_view)) {
1104 int error_code = aws_last_error();
1105 AWS_LOGF_ERROR(
1106 AWS_LS_MQTT5_CLIENT,
1107 "id=%p: failed to append packet encoding sequence for current operation with error %d(%s)",
1108 (void *)client,
1109 error_code,
1110 aws_error_debug_str(error_code));
1111
1112 return AWS_OP_ERR;
1113 }
1114
1115 client->operational_state.current_operation = operation;
1116
1117 return AWS_OP_SUCCESS;
1118 }
1119
1120 static void s_reset_ping(struct aws_mqtt5_client *client) {
1121 uint64_t now = (*client->vtable->get_current_time_fn)();
1122 uint16_t keep_alive_seconds = client->negotiated_settings.server_keep_alive;
1123
1124 uint64_t keep_alive_interval_nanos =
1125 aws_timestamp_convert(keep_alive_seconds, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
1126 if (keep_alive_interval_nanos == 0) {
1127 client->next_ping_time = UINT64_MAX;
1128 } else {
1129 client->next_ping_time = aws_add_u64_saturating(now, keep_alive_interval_nanos);
1130 }
1131
1132 AWS_LOGF_DEBUG(
1133 AWS_LS_MQTT5_CLIENT, "id=%p: next PINGREQ scheduled for time %" PRIu64, (void *)client, client->next_ping_time);
1134 }
1135
1136 static void s_aws_mqtt5_on_socket_write_completion_mqtt_connect(struct aws_mqtt5_client *client, int error_code) {
1137 if (error_code != AWS_ERROR_SUCCESS) {
1138 s_aws_mqtt5_client_shutdown_channel(client, error_code);
1139 return;
1140 }
1141
1142 s_reevaluate_service_task(client);
1143 }
1144
1145 static void s_aws_mqtt5_on_socket_write_completion_connected(struct aws_mqtt5_client *client, int error_code) {
1146 if (error_code != AWS_ERROR_SUCCESS) {
1147 s_aws_mqtt5_client_shutdown_channel(client, error_code);
1148 return;
1149 }
1150
1151 s_reevaluate_service_task(client);
1152 }
1153
1154 static void s_aws_mqtt5_on_socket_write_completion(
1155 struct aws_channel *channel,
1156 struct aws_io_message *message,
1157 int error_code,
1158 void *user_data) {
1159
1160 (void)channel;
1161 (void)message;
1162
1163 struct aws_mqtt5_client *client = user_data;
1164 client->operational_state.pending_write_completion = false;
1165
1166 if (error_code != AWS_ERROR_SUCCESS) {
1167 AWS_LOGF_INFO(
1168 AWS_LS_MQTT5_CLIENT,
1169 "id=%p: socket write completion invoked with error %d(%s)",
1170 (void *)client,
1171 error_code,
1172 aws_error_debug_str(error_code));
1173 }
1174
1175 switch (client->current_state) {
1176 case AWS_MCS_MQTT_CONNECT:
1177 s_aws_mqtt5_on_socket_write_completion_mqtt_connect(client, error_code);
1178 break;
1179
1180 case AWS_MCS_CONNECTED:
1181 s_aws_mqtt5_on_socket_write_completion_connected(client, error_code);
1182 break;
1183
1184 case AWS_MCS_CLEAN_DISCONNECT:
1185 /* the CONNECTED callback works just fine for CLEAN_DISCONNECT */
1186 s_aws_mqtt5_on_socket_write_completion_connected(client, error_code);
1187 break;
1188
1189 default:
1190 break;
1191 }
1192
1193 s_complete_operation_list(client, &client->operational_state.write_completion_operations, error_code);
1194 }
1195
1196 static bool s_should_resume_session(const struct aws_mqtt5_client *client) {
1197 enum aws_mqtt5_client_session_behavior_type session_behavior =
1198 aws_mqtt5_client_session_behavior_type_to_non_default(client->config->session_behavior);
1199
1200 return (session_behavior == AWS_MQTT5_CSBT_REJOIN_POST_SUCCESS && client->has_connected_successfully) ||
1201 (session_behavior == AWS_MQTT5_CSBT_REJOIN_ALWAYS);
1202 }
1203
1204 static void s_change_current_state_to_mqtt_connect(struct aws_mqtt5_client *client) {
1205 AWS_FATAL_ASSERT(client->current_state == AWS_MCS_CONNECTING);
1206 AWS_FATAL_ASSERT(client->operational_state.current_operation == NULL);
1207
1208 client->current_state = AWS_MCS_MQTT_CONNECT;
1209 if (client->should_reset_connection) {
1210 s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT_CONNECTION_RESET_FOR_ADAPTER_CONNECT);
1211 return;
1212 }
1213
1214 client->operational_state.pending_write_completion = false;
1215
1216 aws_mqtt5_encoder_reset(&client->encoder);
1217 aws_mqtt5_decoder_reset(&client->decoder);
1218
1219 bool resume_session = s_should_resume_session(client);
1220 struct aws_mqtt5_packet_connect_view connect_view = client->config->connect->storage_view;
1221 connect_view.clean_start = !resume_session;
1222
1223 if (aws_mqtt5_inbound_topic_alias_behavior_type_to_non_default(
1224 client->config->topic_aliasing_options.inbound_topic_alias_behavior) == AWS_MQTT5_CITABT_ENABLED) {
1225 connect_view.topic_alias_maximum = &client->config->topic_aliasing_options.inbound_alias_cache_size;
1226 }
1227
1228 aws_mqtt5_negotiated_settings_reset(&client->negotiated_settings, &connect_view);
1229 connect_view.client_id = aws_byte_cursor_from_buf(&client->negotiated_settings.client_id_storage);
1230
1231 struct aws_mqtt5_operation_connect *connect_op =
1232 aws_mqtt5_operation_connect_new(client->allocator, &connect_view, client->config);
1233 if (connect_op == NULL) {
1234 int error_code = aws_last_error();
1235 AWS_LOGF_ERROR(
1236 AWS_LS_MQTT5_CLIENT,
1237 "id=%p: failed to create CONNECT operation with error %d(%s)",
1238 (void *)client,
1239 error_code,
1240 aws_error_debug_str(error_code));
1241
1242 s_aws_mqtt5_client_shutdown_channel(client, error_code);
1243 return;
1244 }
1245
1246 s_enqueue_operation_front(client, &connect_op->base);
1247
1248 uint32_t timeout_ms = client->config->connack_timeout_ms;
1249 if (timeout_ms == 0) {
1250 timeout_ms = AWS_MQTT5_DEFAULT_CONNACK_PACKET_TIMEOUT_MS;
1251 }
1252
1253 uint64_t now = (*client->vtable->get_current_time_fn)();
1254 client->next_mqtt_connect_packet_timeout_time =
1255 now + aws_timestamp_convert(timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL);
1256
1257 AWS_LOGF_DEBUG(
1258 AWS_LS_MQTT5_CLIENT,
1259 "id=%p: setting CONNECT timeout to %" PRIu64,
1260 (void *)client,
1261 client->next_mqtt_connect_packet_timeout_time);
1262 }
1263
1264 static void s_reset_reconnection_delay_time(struct aws_mqtt5_client *client) {
1265 uint64_t now = (*client->vtable->get_current_time_fn)();
1266 uint64_t reset_reconnection_delay_time_nanos = aws_timestamp_convert(
1267 client->config->min_connected_time_to_reset_reconnect_delay_ms,
1268 AWS_TIMESTAMP_MILLIS,
1269 AWS_TIMESTAMP_NANOS,
1270 NULL);
1271 client->next_reconnect_delay_reset_time_ns = aws_add_u64_saturating(now, reset_reconnection_delay_time_nanos);
1272
1273 AWS_LOGF_DEBUG(
1274 AWS_LS_MQTT5_CLIENT,
1275 "id=%p: reconnection delay reset time set to %" PRIu64,
1276 (void *)client,
1277 client->next_reconnect_delay_reset_time_ns);
1278 }
1279
1280 static void s_change_current_state_to_connected(struct aws_mqtt5_client *client) {
1281 AWS_FATAL_ASSERT(client->current_state == AWS_MCS_MQTT_CONNECT);
1282
1283 client->current_state = AWS_MCS_CONNECTED;
1284
1285 aws_mqtt5_client_on_connection_update_operational_state(client);
1286
1287 client->has_connected_successfully = true;
1288 client->next_ping_timeout_time = 0;
1289 s_reset_ping(client);
1290 s_reset_reconnection_delay_time(client);
1291 }
1292
1293 static void s_change_current_state_to_clean_disconnect(struct aws_mqtt5_client *client) {
1294 (void)client;
1295 AWS_FATAL_ASSERT(client->current_state == AWS_MCS_MQTT_CONNECT || client->current_state == AWS_MCS_CONNECTED);
1296
1297 client->current_state = AWS_MCS_CLEAN_DISCONNECT;
1298 }
1299
1300 static void s_change_current_state_to_channel_shutdown(struct aws_mqtt5_client *client) {
1301 enum aws_mqtt5_client_state current_state = client->current_state;
1302 AWS_FATAL_ASSERT(
1303 current_state == AWS_MCS_MQTT_CONNECT || current_state == AWS_MCS_CONNECTING ||
1304 current_state == AWS_MCS_CONNECTED || current_state == AWS_MCS_CLEAN_DISCONNECT);
1305
1306 client->current_state = AWS_MCS_CHANNEL_SHUTDOWN;
1307
1308 /*
1309 * Critical requirement: The caller must invoke the channel shutdown function themselves (with the desired error
1310 * code) *after* changing state.
1311 *
1312 * The caller is the only one with the error context and we want to be safe and avoid the possibility of a
1313 * synchronous channel shutdown (mocks) leading to a situation where we get the shutdown callback before we've
1314 * transitioned into the CHANNEL_SHUTDOWN state.
1315 *
1316 * We could relax this if a synchronous channel shutdown is literally impossible even with mocked channels.
1317 */
1318 }
1319
1320 /* TODO: refactor and reunify with internals of retry strategy to expose these as usable functions in aws-c-io */
1321
1322 static uint64_t s_aws_mqtt5_compute_reconnect_backoff_no_jitter(struct aws_mqtt5_client *client) {
1323 uint64_t retry_count = aws_min_u64(client->reconnect_count, 63);
1324 return aws_mul_u64_saturating((uint64_t)1 << retry_count, client->config->min_reconnect_delay_ms);
1325 }
1326
1327 static uint64_t s_aws_mqtt5_compute_reconnect_backoff_full_jitter(struct aws_mqtt5_client *client) {
1328 uint64_t non_jittered = s_aws_mqtt5_compute_reconnect_backoff_no_jitter(client);
1329 return aws_mqtt5_client_random_in_range(0, non_jittered);
1330 }
1331
1332 static uint64_t s_compute_deccorelated_jitter(struct aws_mqtt5_client *client) {
1333 uint64_t last_backoff_val = client->current_reconnect_delay_ms;
1334
1335 if (!last_backoff_val) {
1336 return s_aws_mqtt5_compute_reconnect_backoff_full_jitter(client);
1337 }
1338
1339 return aws_mqtt5_client_random_in_range(
1340 client->config->min_reconnect_delay_ms, aws_mul_u64_saturating(last_backoff_val, 3));
1341 }
1342
1343 static void s_update_reconnect_delay_for_pending_reconnect(struct aws_mqtt5_client *client) {
1344 uint64_t delay_ms = 0;
1345
1346 switch (client->config->retry_jitter_mode) {
1347 case AWS_EXPONENTIAL_BACKOFF_JITTER_DECORRELATED:
1348 delay_ms = s_compute_deccorelated_jitter(client);
1349 break;
1350
1351 case AWS_EXPONENTIAL_BACKOFF_JITTER_NONE:
1352 delay_ms = s_aws_mqtt5_compute_reconnect_backoff_no_jitter(client);
1353 break;
1354
1355 case AWS_EXPONENTIAL_BACKOFF_JITTER_FULL:
1356 case AWS_EXPONENTIAL_BACKOFF_JITTER_DEFAULT:
1357 default:
1358 delay_ms = s_aws_mqtt5_compute_reconnect_backoff_full_jitter(client);
1359 break;
1360 }
1361
1362 delay_ms = aws_min_u64(delay_ms, client->config->max_reconnect_delay_ms);
1363 uint64_t now = (*client->vtable->get_current_time_fn)();
1364
1365 client->next_reconnect_time_ns =
1366 aws_add_u64_saturating(now, aws_timestamp_convert(delay_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL));
1367
1368 AWS_LOGF_DEBUG(
1369 AWS_LS_MQTT5_CLIENT, "id=%p: next connection attempt in %" PRIu64 " milliseconds", (void *)client, delay_ms);
1370
1371 client->reconnect_count++;
1372 }
1373
1374 static void s_change_current_state_to_pending_reconnect(struct aws_mqtt5_client *client) {
1375 client->current_state = AWS_MCS_PENDING_RECONNECT;
1376
1377 s_update_reconnect_delay_for_pending_reconnect(client);
1378 }
1379
1380 static void s_change_current_state_to_terminated(struct aws_mqtt5_client *client) {
1381 client->current_state = AWS_MCS_TERMINATED;
1382
1383 s_mqtt5_client_final_destroy(client);
1384 }
1385
1386 static void s_change_current_state(struct aws_mqtt5_client *client, enum aws_mqtt5_client_state next_state) {
1387 AWS_ASSERT(next_state != client->current_state);
1388 if (next_state == client->current_state) {
1389 return;
1390 }
1391
1392 AWS_LOGF_DEBUG(
1393 AWS_LS_MQTT5_CLIENT,
1394 "id=%p: switching current state from %s to %s",
1395 (void *)client,
1396 aws_mqtt5_client_state_to_c_string(client->current_state),
1397 aws_mqtt5_client_state_to_c_string(next_state));
1398
1399 if (client->vtable->on_client_state_change_callback_fn != NULL) {
1400 (*client->vtable->on_client_state_change_callback_fn)(
1401 client, client->current_state, next_state, client->vtable->vtable_user_data);
1402 }
1403
1404 switch (next_state) {
1405 case AWS_MCS_STOPPED:
1406 s_change_current_state_to_stopped(client);
1407 break;
1408 case AWS_MCS_CONNECTING:
1409 s_change_current_state_to_connecting(client);
1410 break;
1411 case AWS_MCS_MQTT_CONNECT:
1412 s_change_current_state_to_mqtt_connect(client);
1413 break;
1414 case AWS_MCS_CONNECTED:
1415 s_change_current_state_to_connected(client);
1416 break;
1417 case AWS_MCS_CLEAN_DISCONNECT:
1418 s_change_current_state_to_clean_disconnect(client);
1419 break;
1420 case AWS_MCS_CHANNEL_SHUTDOWN:
1421 s_change_current_state_to_channel_shutdown(client);
1422 break;
1423 case AWS_MCS_PENDING_RECONNECT:
1424 s_change_current_state_to_pending_reconnect(client);
1425 break;
1426 case AWS_MCS_TERMINATED:
1427 s_change_current_state_to_terminated(client);
1428 return;
1429 }
1430
1431 s_reevaluate_service_task(client);
1432 }
1433
1434 static bool s_service_state_stopped(struct aws_mqtt5_client *client) {
1435 enum aws_mqtt5_client_state desired_state = client->desired_state;
1436 if (desired_state == AWS_MCS_CONNECTED) {
1437 s_change_current_state(client, AWS_MCS_CONNECTING);
1438 } else if (desired_state == AWS_MCS_TERMINATED) {
1439 s_change_current_state(client, AWS_MCS_TERMINATED);
1440 return true;
1441 }
1442
1443 return false;
1444 }
1445
1446 static void s_service_state_connecting(struct aws_mqtt5_client *client) {
1447 (void)client;
1448 }
1449
1450 static void s_service_state_mqtt_connect(struct aws_mqtt5_client *client, uint64_t now) {
1451 enum aws_mqtt5_client_state desired_state = client->desired_state;
1452 if (desired_state != AWS_MCS_CONNECTED) {
1453 s_aws_mqtt5_client_emit_final_lifecycle_event(client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP, NULL, NULL);
1454 s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP);
1455 return;
1456 }
1457
1458 if (now >= client->next_mqtt_connect_packet_timeout_time) {
1459 s_aws_mqtt5_client_emit_final_lifecycle_event(client, AWS_ERROR_MQTT5_CONNACK_TIMEOUT, NULL, NULL);
1460
1461 AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: shutting down channel due to CONNACK timeout", (void *)client);
1462 s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_CONNACK_TIMEOUT);
1463 return;
1464 }
1465
1466 if (aws_mqtt5_client_service_operational_state(&client->operational_state)) {
1467 int error_code = aws_last_error();
1468 AWS_LOGF_ERROR(
1469 AWS_LS_MQTT5_CLIENT,
1470 "id=%p: failed to service outgoing CONNECT packet to channel with error %d(%s)",
1471 (void *)client,
1472 error_code,
1473 aws_error_debug_str(error_code));
1474
1475 s_aws_mqtt5_client_shutdown_channel(client, error_code);
1476 return;
1477 }
1478 }
1479
1480 static int s_aws_mqtt5_client_queue_ping(struct aws_mqtt5_client *client) {
1481 s_reset_ping(client);
1482
1483 AWS_LOGF_DEBUG(AWS_LS_MQTT5_CLIENT, "id=%p: queuing PINGREQ", (void *)client);
1484
1485 struct aws_mqtt5_operation_pingreq *pingreq_op = aws_mqtt5_operation_pingreq_new(client->allocator);
1486 s_enqueue_operation_front(client, &pingreq_op->base);
1487
1488 return AWS_OP_SUCCESS;
1489 }
1490
1491 static void s_service_state_connected(struct aws_mqtt5_client *client, uint64_t now) {
1492 enum aws_mqtt5_client_state desired_state = client->desired_state;
1493 if (desired_state != AWS_MCS_CONNECTED) {
1494 s_aws_mqtt5_client_emit_final_lifecycle_event(client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP, NULL, NULL);
1495
1496 AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: channel shutdown due to user Stop request", (void *)client);
1497 s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP);
1498 return;
1499 }
1500
1501 if (now >= client->next_ping_timeout_time && client->next_ping_timeout_time != 0) {
1502 s_aws_mqtt5_client_emit_final_lifecycle_event(client, AWS_ERROR_MQTT5_PING_RESPONSE_TIMEOUT, NULL, NULL);
1503
1504 AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: channel shutdown due to PINGRESP timeout", (void *)client);
1505
1506 s_aws_mqtt5_client_shutdown_channel_clean(
1507 client, AWS_ERROR_MQTT5_PING_RESPONSE_TIMEOUT, AWS_MQTT5_DRC_KEEP_ALIVE_TIMEOUT);
1508 return;
1509 }
1510
1511 if (now >= client->next_ping_time) {
1512 if (s_aws_mqtt5_client_queue_ping(client)) {
1513 int error_code = aws_last_error();
1514 AWS_LOGF_ERROR(
1515 AWS_LS_MQTT5_CLIENT,
1516 "id=%p: failed to queue PINGREQ with error %d(%s)",
1517 (void *)client,
1518 error_code,
1519 aws_error_debug_str(error_code));
1520
1521 s_aws_mqtt5_client_shutdown_channel(client, error_code);
1522 return;
1523 }
1524 }
1525
1526 if (now >= client->next_reconnect_delay_reset_time_ns && client->next_reconnect_delay_reset_time_ns != 0) {
1527 AWS_LOGF_DEBUG(
1528 AWS_LS_MQTT5_CLIENT,
1529 "id=%p: connected sufficiently long that reconnect backoff delay has been reset back to "
1530 "minimum value",
1531 (void *)client);
1532
1533 client->reconnect_count = 0;
1534 client->current_reconnect_delay_ms = 0;
1535 client->next_reconnect_delay_reset_time_ns = 0;
1536 }
1537
1538 s_check_timeouts(client, now);
1539
1540 if (aws_mqtt5_client_service_operational_state(&client->operational_state)) {
1541 int error_code = aws_last_error();
1542 AWS_LOGF_ERROR(
1543 AWS_LS_MQTT5_CLIENT,
1544 "id=%p: failed to service CONNECTED operation queue with error %d(%s)",
1545 (void *)client,
1546 error_code,
1547 aws_error_debug_str(error_code));
1548
1549 s_aws_mqtt5_client_shutdown_channel(client, error_code);
1550 return;
1551 }
1552 }
1553
1554 static void s_service_state_clean_disconnect(struct aws_mqtt5_client *client, uint64_t now) {
1555 if (aws_mqtt5_client_service_operational_state(&client->operational_state)) {
1556 int error_code = aws_last_error();
1557 AWS_LOGF_ERROR(
1558 AWS_LS_MQTT5_CLIENT,
1559 "id=%p: failed to service CLEAN_DISCONNECT operation queue with error %d(%s)",
1560 (void *)client,
1561 error_code,
1562 aws_error_debug_str(error_code));
1563
1564 s_aws_mqtt5_client_shutdown_channel(client, error_code);
1565 return;
1566 }
1567
1568 s_check_timeouts(client, now);
1569 }
1570
1571 static void s_service_state_channel_shutdown(struct aws_mqtt5_client *client) {
1572 (void)client;
1573 }
1574
1575 static void s_service_state_pending_reconnect(struct aws_mqtt5_client *client, uint64_t now) {
1576 if (client->desired_state != AWS_MCS_CONNECTED) {
1577 s_change_current_state(client, AWS_MCS_STOPPED);
1578 return;
1579 }
1580
1581 if (now >= client->next_reconnect_time_ns) {
1582 s_change_current_state(client, AWS_MCS_CONNECTING);
1583 return;
1584 }
1585 }
1586
1587 static void s_mqtt5_service_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
1588 (void)task;
1589 if (status != AWS_TASK_STATUS_RUN_READY) {
1590 return;
1591 }
1592
1593 struct aws_mqtt5_client *client = arg;
1594 client->next_service_task_run_time = 0;
1595 client->in_service = true;
1596
1597 uint64_t now = (*client->vtable->get_current_time_fn)();
1598 bool terminated = false;
1599 switch (client->current_state) {
1600 case AWS_MCS_STOPPED:
1601 terminated = s_service_state_stopped(client);
1602 break;
1603 case AWS_MCS_CONNECTING:
1604 s_service_state_connecting(client);
1605 break;
1606 case AWS_MCS_MQTT_CONNECT:
1607 s_service_state_mqtt_connect(client, now);
1608 break;
1609 case AWS_MCS_CONNECTED:
1610 s_service_state_connected(client, now);
1611 break;
1612 case AWS_MCS_CLEAN_DISCONNECT:
1613 s_service_state_clean_disconnect(client, now);
1614 break;
1615 case AWS_MCS_CHANNEL_SHUTDOWN:
1616 s_service_state_channel_shutdown(client);
1617 break;
1618 case AWS_MCS_PENDING_RECONNECT:
1619 s_service_state_pending_reconnect(client, now);
1620 break;
1621 default:
1622 break;
1623 }
1624
1625 /*
1626 * We can only enter the terminated state from stopped. If we do so, the client memory is now freed and we
1627 * will crash if we access anything anymore.
1628 */
1629 if (terminated) {
1630 return;
1631 }
1632
1633 /* we're not scheduled anymore, reschedule as needed */
1634 client->in_service = false;
1635 s_reevaluate_service_task(client);
1636 }
1637
1638 static bool s_should_client_disconnect_cleanly(struct aws_mqtt5_client *client) {
1639 enum aws_mqtt5_client_state current_state = client->current_state;
1640
1641 return current_state == AWS_MCS_CONNECTED;
1642 }
1643
1644 static int s_process_read_message(
1645 struct aws_channel_handler *handler,
1646 struct aws_channel_slot *slot,
1647 struct aws_io_message *message) {
1648
1649 struct aws_mqtt5_client *client = handler->impl;
1650
1651 if (message->message_type != AWS_IO_MESSAGE_APPLICATION_DATA) {
1652 AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: unexpected io message data", (void *)client);
1653 return aws_raise_error(AWS_ERROR_INVALID_STATE);
1654 }
1655
1656 AWS_LOGF_TRACE(
1657 AWS_LS_MQTT5_CLIENT, "id=%p: processing read message of size %zu", (void *)client, message->message_data.len);
1658
1659 struct aws_byte_cursor message_cursor = aws_byte_cursor_from_buf(&message->message_data);
1660
1661 int result = aws_mqtt5_decoder_on_data_received(&client->decoder, message_cursor);
1662 if (result != AWS_OP_SUCCESS) {
1663 int error_code = aws_last_error();
1664 AWS_LOGF_ERROR(
1665 AWS_LS_MQTT5_CLIENT,
1666 "id=%p: decode failure with error %d(%s)",
1667 (void *)client,
1668 error_code,
1669 aws_error_debug_str(error_code));
1670
1671 if (error_code == AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR && s_should_client_disconnect_cleanly(client)) {
1672 s_aws_mqtt5_client_shutdown_channel_clean(client, error_code, AWS_MQTT5_DRC_PROTOCOL_ERROR);
1673 } else {
1674 s_aws_mqtt5_client_shutdown_channel(client, error_code);
1675 }
1676
1677 goto done;
1678 }
1679
1680 aws_channel_slot_increment_read_window(slot, message->message_data.len);
1681
1682 done:
1683
1684 aws_mem_release(message->allocator, message);
1685
1686 return AWS_OP_SUCCESS;
1687 }
1688
1689 static int s_shutdown(
1690 struct aws_channel_handler *handler,
1691 struct aws_channel_slot *slot,
1692 enum aws_channel_direction dir,
1693 int error_code,
1694 bool free_scarce_resources_immediately) {
1695
1696 (void)handler;
1697
1698 return aws_channel_slot_on_handler_shutdown_complete(slot, dir, error_code, free_scarce_resources_immediately);
1699 }
1700
1701 static size_t s_initial_window_size(struct aws_channel_handler *handler) {
1702 (void)handler;
1703
1704 return SIZE_MAX;
1705 }
1706
1707 static void s_destroy(struct aws_channel_handler *handler) {
1708 (void)handler;
1709 }
1710
1711 static size_t s_message_overhead(struct aws_channel_handler *handler) {
1712 (void)handler;
1713
1714 return 0;
1715 }
1716
1717 static struct aws_channel_handler_vtable s_mqtt5_channel_handler_vtable = {
1718 .process_read_message = &s_process_read_message,
1719 .process_write_message = NULL,
1720 .increment_read_window = NULL,
1721 .shutdown = &s_shutdown,
1722 .initial_window_size = &s_initial_window_size,
1723 .message_overhead = &s_message_overhead,
1724 .destroy = &s_destroy,
1725 };
1726
1727 static bool s_aws_is_successful_reason_code(int value) {
1728 return value < 128;
1729 }
1730
1731 static void s_aws_mqtt5_client_on_connack(
1732 struct aws_mqtt5_client *client,
1733 struct aws_mqtt5_packet_connack_view *connack_view) {
1734 AWS_FATAL_ASSERT(client->current_state == AWS_MCS_MQTT_CONNECT);
1735
1736 bool is_successful = s_aws_is_successful_reason_code((int)connack_view->reason_code);
1737 if (!is_successful) {
1738 s_aws_mqtt5_client_emit_final_lifecycle_event(
1739 client, AWS_ERROR_MQTT5_CONNACK_CONNECTION_REFUSED, connack_view, NULL);
1740
1741 enum aws_mqtt5_connect_reason_code reason_code = connack_view->reason_code;
1742
1743 AWS_LOGF_INFO(
1744 AWS_LS_MQTT5_CLIENT,
1745 "id=%p: connection refused (via failed CONNACK) by remote host with reason code %d(%s)",
1746 (void *)client,
1747 (int)reason_code,
1748 aws_mqtt5_connect_reason_code_to_c_string(reason_code));
1749
1750 s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_CONNACK_CONNECTION_REFUSED);
1751 return;
1752 }
1753
1754 aws_mqtt5_negotiated_settings_apply_connack(&client->negotiated_settings, connack_view);
1755
1756 /* Check if a session is being rejoined and perform associated rejoin connect logic here */
1757 if (client->negotiated_settings.rejoined_session) {
1758 /* Disconnect if the server is attempting to connect the client to an unexpected session */
1759 if (!s_should_resume_session(client)) {
1760 s_aws_mqtt5_client_emit_final_lifecycle_event(
1761 client, AWS_ERROR_MQTT_CANCELLED_FOR_CLEAN_SESSION, connack_view, NULL);
1762 s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT_CANCELLED_FOR_CLEAN_SESSION);
1763 return;
1764 } else if (!client->has_connected_successfully) {
1765 /*
1766 * We were configured with REJOIN_ALWAYS and this is the first connection. This is technically not safe
1767 * and so let's log a warning for future diagnostics should it cause the user problems.
1768 */
1769 AWS_LOGF_WARN(
1770 AWS_LS_MQTT5_CLIENT,
1771 "id=%p: initial connection rejoined existing session. This may cause packet id collisions.",
1772 (void *)client);
1773 }
1774 }
1775
1776 s_change_current_state(client, AWS_MCS_CONNECTED);
1777 s_aws_mqtt5_client_emit_connection_success_lifecycle_event(client, connack_view);
1778 }
1779
1780 static void s_aws_mqtt5_client_log_received_packet(
1781 struct aws_mqtt5_client *client,
1782 enum aws_mqtt5_packet_type type,
1783 void *packet_view) {
1784 AWS_LOGF_DEBUG(
1785 AWS_LS_MQTT5_CLIENT, "id=%p: Received %s packet", (void *)client, aws_mqtt5_packet_type_to_c_string(type));
1786
1787 switch (type) {
1788 case AWS_MQTT5_PT_CONNACK:
1789 aws_mqtt5_packet_connack_view_log(packet_view, AWS_LL_DEBUG);
1790 break;
1791
1792 case AWS_MQTT5_PT_PUBLISH:
1793 aws_mqtt5_packet_publish_view_log(packet_view, AWS_LL_DEBUG);
1794 break;
1795
1796 case AWS_MQTT5_PT_PUBACK:
1797 aws_mqtt5_packet_puback_view_log(packet_view, AWS_LL_DEBUG);
1798 break;
1799
1800 case AWS_MQTT5_PT_SUBACK:
1801 aws_mqtt5_packet_suback_view_log(packet_view, AWS_LL_DEBUG);
1802 break;
1803
1804 case AWS_MQTT5_PT_UNSUBACK:
1805 aws_mqtt5_packet_unsuback_view_log(packet_view, AWS_LL_DEBUG);
1806 break;
1807
1808 case AWS_MQTT5_PT_PINGRESP:
1809 break; /* nothing to log */
1810
1811 case AWS_MQTT5_PT_DISCONNECT:
1812 aws_mqtt5_packet_disconnect_view_log(packet_view, AWS_LL_DEBUG);
1813 break;
1814
1815 default:
1816 break;
1817 }
1818 }
1819
1820 static void s_aws_mqtt5_client_mqtt_connect_on_packet_received(
1821 struct aws_mqtt5_client *client,
1822 enum aws_mqtt5_packet_type type,
1823 void *packet_view) {
1824 if (type == AWS_MQTT5_PT_CONNACK) {
1825 s_aws_mqtt5_client_on_connack(client, (struct aws_mqtt5_packet_connack_view *)packet_view);
1826 } else {
1827 AWS_LOGF_ERROR(
1828 AWS_LS_MQTT5_CLIENT, "id=%p: Invalid packet type received while in MQTT_CONNECT state", (void *)client);
1829
1830 s_aws_mqtt5_client_shutdown_channel_clean(
1831 client, AWS_ERROR_MQTT5_DECODE_PROTOCOL_ERROR, AWS_MQTT5_DRC_PROTOCOL_ERROR);
1832 }
1833 }
1834
1835 typedef bool(aws_linked_list_node_predicate_fn)(struct aws_linked_list_node *);
1836
1837 /*
1838 * This predicate finds the first (if any) operation in the queue that is not a PUBACK or a PINGREQ.
1839 */
1840 static bool s_is_ping_or_puback(struct aws_linked_list_node *operation_node) {
1841 struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(operation_node, struct aws_mqtt5_operation, node);
1842
1843 return operation->packet_type == AWS_MQTT5_PT_PUBACK || operation->packet_type == AWS_MQTT5_PT_PINGREQ;
1844 }
1845
1846 /*
1847 * Helper function to insert a node (operation) into a list (operation queue) in the correct spot. Currently, this
1848 * is only used to enqueue PUBACKs after existing PUBACKs and PINGREQs. This ensure that PUBACKs go out in the order
1849 * the corresponding PUBLISH was received, regardless of whether or not there was an intervening service call.
1850 */
1851 static void s_insert_node_before_predicate_failure(
1852 struct aws_linked_list *list,
1853 struct aws_linked_list_node *node,
1854 aws_linked_list_node_predicate_fn predicate) {
1855 struct aws_linked_list_node *current_node = NULL;
1856 for (current_node = aws_linked_list_begin(list); current_node != aws_linked_list_end(list);
1857 current_node = aws_linked_list_next(current_node)) {
1858 if (!predicate(current_node)) {
1859 break;
1860 }
1861 }
1862
1863 AWS_FATAL_ASSERT(current_node != NULL);
1864
1865 aws_linked_list_insert_before(current_node, node);
1866 }
1867
1868 static int s_aws_mqtt5_client_queue_puback(
1869 struct aws_mqtt5_client *client,
1870 uint16_t packet_id,
1871 const struct aws_mqtt5_manual_publish_acknowledgement_completion_options *completion_options) {
1872 AWS_PRECONDITION(client != NULL);
1873
1874 const struct aws_mqtt5_packet_puback_view puback_view = {
1875 .packet_id = packet_id,
1876 .reason_code = AWS_MQTT5_PARC_SUCCESS,
1877 };
1878
1879 struct aws_mqtt5_operation_puback *puback_op =
1880 aws_mqtt5_operation_puback_new(client->allocator, &puback_view, completion_options);
1881
1882 if (puback_op == NULL) {
1883 return AWS_OP_ERR;
1884 }
1885
1886 AWS_LOGF_DEBUG(
1887 AWS_LS_MQTT5_CLIENT,
1888 "id=%p: enqueuing PUBACK operation to first position in queue that is not a PUBACK or PINGREQ",
1889 (void *)client);
1890
1891 /*
1892 * Put the PUBACK ahead of all user-submitted operations (PUBLISH, SUBSCRIBE, UNSUBSCRIBE, DISCONNECT), but behind
1893 * all pre-existing "internal" operations (PINGREQ, PUBACK).
1894 *
1895 * Qos 2 support will need to extend the predicate to include Qos 2 publish packets.
1896 */
1897 s_insert_node_before_predicate_failure(
1898 &client->operational_state.queued_operations, &puback_op->base.node, s_is_ping_or_puback);
1899
1900 s_reevaluate_service_task(client);
1901
1902 return AWS_OP_SUCCESS;
1903 }
1904
1905 static void s_aws_mqtt5_client_connected_on_packet_received(
1906 struct aws_mqtt5_client *client,
1907 enum aws_mqtt5_packet_type type,
1908 void *packet_view) {
1909
1910 switch (type) {
1911 case AWS_MQTT5_PT_PINGRESP:
1912 AWS_LOGF_DEBUG(AWS_LS_MQTT5_CLIENT, "id=%p: resetting PINGREQ timer", (void *)client);
1913 client->next_ping_timeout_time = 0;
1914 break;
1915
1916 case AWS_MQTT5_PT_DISCONNECT:
1917 s_aws_mqtt5_client_emit_final_lifecycle_event(
1918 client, AWS_ERROR_MQTT5_DISCONNECT_RECEIVED, NULL, packet_view);
1919
1920 AWS_LOGF_INFO(AWS_LS_MQTT5_CLIENT, "id=%p: shutting down channel due to DISCONNECT", (void *)client);
1921
1922 s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT5_DISCONNECT_RECEIVED);
1923 break;
1924
1925 case AWS_MQTT5_PT_SUBACK: {
1926 uint16_t packet_id = ((const struct aws_mqtt5_packet_suback_view *)packet_view)->packet_id;
1927 aws_mqtt5_client_operational_state_handle_ack(
1928 &client->operational_state, packet_id, AWS_MQTT5_PT_SUBACK, packet_view, AWS_ERROR_SUCCESS);
1929 break;
1930 }
1931
1932 case AWS_MQTT5_PT_UNSUBACK: {
1933 uint16_t packet_id = ((const struct aws_mqtt5_packet_unsuback_view *)packet_view)->packet_id;
1934 aws_mqtt5_client_operational_state_handle_ack(
1935 &client->operational_state, packet_id, AWS_MQTT5_PT_UNSUBACK, packet_view, AWS_ERROR_SUCCESS);
1936 break;
1937 }
1938
1939 case AWS_MQTT5_PT_PUBLISH: {
1940 const struct aws_mqtt5_packet_publish_view *publish_view = packet_view;
1941
1942 aws_mqtt5_callback_set_manager_on_publish_received(&client->callback_manager, publish_view);
1943
1944 if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
1945 // Check if this PUBLSIH packet is manually controlled
1946 struct aws_hash_element *elem = NULL;
1947 aws_hash_table_find(
1948 &client->operational_state.manual_pub_ack_packet_id_table, &publish_view->packet_id, &elem);
1949
1950 /* This PUBLISH isn't a manually controlled PUBACK. We schedule the PUBACK to be sent immediately. */
1951 if (elem == NULL) {
1952 if (s_aws_mqtt5_client_queue_puback(client, publish_view->packet_id, NULL)) {
1953 int error_code = aws_last_error();
1954 AWS_LOGF_ERROR(
1955 AWS_LS_MQTT5_CLIENT,
1956 "id=%p: decode failure with error %d(%s)",
1957 (void *)client,
1958 error_code,
1959 aws_error_debug_str(error_code));
1960
1961 s_aws_mqtt5_client_shutdown_channel(client, error_code);
1962 }
1963 }
1964 }
1965 break;
1966 }
1967
1968 case AWS_MQTT5_PT_PUBACK: {
1969 uint16_t packet_id = ((const struct aws_mqtt5_packet_puback_view *)packet_view)->packet_id;
1970 aws_mqtt5_client_operational_state_handle_ack(
1971 &client->operational_state, packet_id, AWS_MQTT5_PT_PUBACK, packet_view, AWS_ERROR_SUCCESS);
1972 break;
1973 }
1974
1975 default:
1976 break;
1977 }
1978 }
1979
1980 static int s_aws_mqtt5_client_on_packet_received(
1981 enum aws_mqtt5_packet_type type,
1982 void *packet_view,
1983 void *decoder_callback_user_data) {
1984
1985 struct aws_mqtt5_client *client = decoder_callback_user_data;
1986
1987 s_aws_mqtt5_client_log_received_packet(client, type, packet_view);
1988
1989 switch (client->current_state) {
1990 case AWS_MCS_MQTT_CONNECT:
1991 s_aws_mqtt5_client_mqtt_connect_on_packet_received(client, type, packet_view);
1992 break;
1993
1994 case AWS_MCS_CONNECTED:
1995 case AWS_MCS_CLEAN_DISCONNECT:
1996 s_aws_mqtt5_client_connected_on_packet_received(client, type, packet_view);
1997 break;
1998
1999 default:
2000 break;
2001 }
2002
2003 s_reevaluate_service_task(client);
2004
2005 return AWS_OP_SUCCESS;
2006 }
2007
2008 static uint64_t s_aws_high_res_clock_get_ticks_proxy(void) {
2009 uint64_t current_time = 0;
2010 AWS_FATAL_ASSERT(aws_high_res_clock_get_ticks(&current_time) == AWS_OP_SUCCESS);
2011
2012 return current_time;
2013 }
2014
2015 struct aws_io_message *s_aws_channel_acquire_message_from_pool_default(
2016 struct aws_channel *channel,
2017 enum aws_io_message_type message_type,
2018 size_t size_hint,
2019 void *user_data) {
2020 (void)user_data;
2021
2022 return aws_channel_acquire_message_from_pool(channel, message_type, size_hint);
2023 }
2024
2025 static int s_aws_channel_slot_send_message_default(
2026 struct aws_channel_slot *slot,
2027 struct aws_io_message *message,
2028 enum aws_channel_direction dir,
2029 void *user_data) {
2030 (void)user_data;
2031
2032 return aws_channel_slot_send_message(slot, message, dir);
2033 }
2034
2035 static struct aws_mqtt5_client_vtable s_default_client_vtable = {
2036 .get_current_time_fn = s_aws_high_res_clock_get_ticks_proxy,
2037 .channel_shutdown_fn = aws_channel_shutdown,
2038 .websocket_connect_fn = aws_websocket_client_connect,
2039 .client_bootstrap_new_socket_channel_fn = aws_client_bootstrap_new_socket_channel,
2040 .http_proxy_new_socket_channel_fn = aws_http_proxy_new_socket_channel,
2041 .on_client_state_change_callback_fn = NULL,
2042 .aws_channel_acquire_message_from_pool_fn = s_aws_channel_acquire_message_from_pool_default,
2043 .aws_channel_slot_send_message_fn = s_aws_channel_slot_send_message_default,
2044
2045 .vtable_user_data = NULL,
2046 };
2047
2048 void aws_mqtt5_client_set_vtable(struct aws_mqtt5_client *client, const struct aws_mqtt5_client_vtable *vtable) {
2049 client->vtable = vtable;
2050 }
2051
2052 const struct aws_mqtt5_client_vtable *aws_mqtt5_client_get_default_vtable(void) {
2053 return &s_default_client_vtable;
2054 }
2055
2056 struct aws_mqtt5_client *aws_mqtt5_client_new(
2057 struct aws_allocator *allocator,
2058 const struct aws_mqtt5_client_options *options) {
2059 AWS_FATAL_ASSERT(allocator != NULL);
2060 AWS_FATAL_ASSERT(options != NULL);
2061
2062 struct aws_mqtt5_client *client = aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt5_client));
2063 if (client == NULL) {
2064 return NULL;
2065 }
2066
2067 aws_task_init(&client->service_task, s_mqtt5_service_task_fn, client, "Mqtt5Service");
2068
2069 client->allocator = allocator;
2070 client->vtable = &s_default_client_vtable;
2071
2072 aws_ref_count_init(&client->ref_count, client, s_on_mqtt5_client_zero_ref_count);
2073
2074 aws_mqtt5_callback_set_manager_init(&client->callback_manager, client);
2075
2076 if (aws_mqtt5_client_operational_state_init(&client->operational_state, allocator, client)) {
2077 goto on_error;
2078 }
2079
2080 client->config = aws_mqtt5_client_options_storage_new(allocator, options);
2081 if (client->config == NULL) {
2082 goto on_error;
2083 }
2084
2085 aws_mqtt5_client_flow_control_state_init(client);
2086
2087 /* all client activity will take place on this event loop, serializing things like reconnect, ping, etc... */
2088 client->loop = aws_event_loop_group_get_next_loop(client->config->bootstrap->event_loop_group);
2089 if (client->loop == NULL) {
2090 goto on_error;
2091 }
2092
2093 client->desired_state = AWS_MCS_STOPPED;
2094 client->current_state = AWS_MCS_STOPPED;
2095 client->lifecycle_state = AWS_MQTT5_LS_NONE;
2096
2097 struct aws_mqtt5_decoder_options decoder_options = {
2098 .callback_user_data = client,
2099 .on_packet_received = s_aws_mqtt5_client_on_packet_received,
2100 };
2101
2102 if (aws_mqtt5_decoder_init(&client->decoder, allocator, &decoder_options)) {
2103 goto on_error;
2104 }
2105
2106 struct aws_mqtt5_encoder_options encoder_options = {
2107 .client = client,
2108 };
2109
2110 if (aws_mqtt5_encoder_init(&client->encoder, allocator, &encoder_options)) {
2111 goto on_error;
2112 }
2113
2114 if (aws_mqtt5_inbound_topic_alias_resolver_init(&client->inbound_topic_alias_resolver, allocator)) {
2115 goto on_error;
2116 }
2117
2118 client->outbound_topic_alias_resolver = aws_mqtt5_outbound_topic_alias_resolver_new(
2119 allocator, client->config->topic_aliasing_options.outbound_topic_alias_behavior);
2120 if (client->outbound_topic_alias_resolver == NULL) {
2121 goto on_error;
2122 }
2123
2124 if (aws_mqtt5_negotiated_settings_init(
2125 allocator, &client->negotiated_settings, &client->config->connect->storage_view.client_id)) {
2126 goto on_error;
2127 }
2128
2129 client->current_reconnect_delay_ms = 0;
2130
2131 client->handler.alloc = client->allocator;
2132 client->handler.vtable = &s_mqtt5_channel_handler_vtable;
2133 client->handler.impl = client;
2134
2135 aws_mqtt5_client_options_storage_log(client->config, AWS_LL_DEBUG);
2136
2137 s_init_statistics(&client->operation_statistics_impl);
2138
2139 return client;
2140
2141 on_error:
2142
2143 /* release isn't usable here since we may not even have an event loop */
2144 s_mqtt5_client_final_destroy(client);
2145
2146 return NULL;
2147 }
2148
2149 struct aws_mqtt5_client *aws_mqtt5_client_acquire(struct aws_mqtt5_client *client) {
2150 if (client != NULL) {
2151 aws_ref_count_acquire(&client->ref_count);
2152 }
2153
2154 return client;
2155 }
2156
2157 struct aws_mqtt5_client *aws_mqtt5_client_release(struct aws_mqtt5_client *client) {
2158 if (client != NULL) {
2159 aws_ref_count_release(&client->ref_count);
2160 }
2161
2162 return NULL;
2163 }
2164
2165 struct aws_mqtt_change_desired_state_task {
2166 struct aws_task task;
2167 struct aws_allocator *allocator;
2168 struct aws_mqtt5_client *client;
2169 enum aws_mqtt5_client_state desired_state;
2170 struct aws_mqtt5_operation_disconnect *disconnect_operation;
2171 };
2172
2173 void aws_mqtt5_client_change_desired_state(
2174 struct aws_mqtt5_client *client,
2175 enum aws_mqtt5_client_state desired_state,
2176 struct aws_mqtt5_operation_disconnect *disconnect_op) {
2177 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
2178
2179 if (client->desired_state != desired_state) {
2180 AWS_LOGF_INFO(
2181 AWS_LS_MQTT5_CLIENT,
2182 "id=%p: changing desired client state from %s to %s",
2183 (void *)client,
2184 aws_mqtt5_client_state_to_c_string(client->desired_state),
2185 aws_mqtt5_client_state_to_c_string(desired_state));
2186
2187 client->desired_state = desired_state;
2188
2189 if (desired_state == AWS_MCS_STOPPED && disconnect_op != NULL) {
2190 s_aws_mqtt5_client_shutdown_channel_with_disconnect(
2191 client, AWS_ERROR_MQTT5_USER_REQUESTED_STOP, disconnect_op);
2192 }
2193
2194 s_reevaluate_service_task(client);
2195 }
2196 }
2197
2198 static void s_change_state_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
2199 (void)task;
2200
2201 struct aws_mqtt_change_desired_state_task *change_state_task = arg;
2202 struct aws_mqtt5_client *client = change_state_task->client;
2203 enum aws_mqtt5_client_state desired_state = change_state_task->desired_state;
2204 if (status != AWS_TASK_STATUS_RUN_READY) {
2205 goto done;
2206 }
2207
2208 aws_mqtt5_client_change_desired_state(client, desired_state, change_state_task->disconnect_operation);
2209
2210 done:
2211
2212 aws_mqtt5_operation_disconnect_release(change_state_task->disconnect_operation);
2213 if (desired_state != AWS_MCS_TERMINATED) {
2214 aws_mqtt5_client_release(client);
2215 }
2216
2217 aws_mem_release(change_state_task->allocator, change_state_task);
2218 }
2219
2220 static struct aws_mqtt_change_desired_state_task *s_aws_mqtt_change_desired_state_task_new(
2221 struct aws_allocator *allocator,
2222 struct aws_mqtt5_client *client,
2223 enum aws_mqtt5_client_state desired_state,
2224 struct aws_mqtt5_operation_disconnect *disconnect_operation) {
2225
2226 struct aws_mqtt_change_desired_state_task *change_state_task =
2227 aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt_change_desired_state_task));
2228 if (change_state_task == NULL) {
2229 return NULL;
2230 }
2231
2232 aws_task_init(&change_state_task->task, s_change_state_task_fn, (void *)change_state_task, "ChangeStateTask");
2233 change_state_task->allocator = client->allocator;
2234 change_state_task->client = (desired_state == AWS_MCS_TERMINATED) ? client : aws_mqtt5_client_acquire(client);
2235 change_state_task->desired_state = desired_state;
2236 change_state_task->disconnect_operation = aws_mqtt5_operation_disconnect_acquire(disconnect_operation);
2237
2238 return change_state_task;
2239 }
2240
2241 static bool s_is_valid_desired_state(enum aws_mqtt5_client_state desired_state) {
2242 switch (desired_state) {
2243 case AWS_MCS_STOPPED:
2244 case AWS_MCS_CONNECTED:
2245 case AWS_MCS_TERMINATED:
2246 return true;
2247
2248 default:
2249 return false;
2250 }
2251 }
2252
2253 static int s_aws_mqtt5_client_change_desired_state(
2254 struct aws_mqtt5_client *client,
2255 enum aws_mqtt5_client_state desired_state,
2256 struct aws_mqtt5_operation_disconnect *disconnect_operation) {
2257 AWS_FATAL_ASSERT(client != NULL);
2258 AWS_FATAL_ASSERT(client->loop != NULL);
2259 AWS_FATAL_ASSERT(disconnect_operation == NULL || desired_state == AWS_MCS_STOPPED);
2260
2261 if (!s_is_valid_desired_state(desired_state)) {
2262 AWS_LOGF_ERROR(
2263 AWS_LS_MQTT5_CLIENT,
2264 "id=%p: invalid desired state argument %d(%s)",
2265 (void *)client,
2266 (int)desired_state,
2267 aws_mqtt5_client_state_to_c_string(desired_state));
2268
2269 return aws_raise_error(AWS_ERROR_INVALID_ARGUMENT);
2270 }
2271
2272 struct aws_mqtt_change_desired_state_task *task =
2273 s_aws_mqtt_change_desired_state_task_new(client->allocator, client, desired_state, disconnect_operation);
2274 if (task == NULL) {
2275 AWS_LOGF_ERROR(AWS_LS_MQTT5_CLIENT, "id=%p: failed to create change desired state task", (void *)client);
2276 return AWS_OP_ERR;
2277 }
2278
2279 aws_event_loop_schedule_task_now(client->loop, &task->task);
2280
2281 return AWS_OP_SUCCESS;
2282 }
2283
2284 int aws_mqtt5_client_start(struct aws_mqtt5_client *client) {
2285 return s_aws_mqtt5_client_change_desired_state(client, AWS_MCS_CONNECTED, NULL);
2286 }
2287
2288 int aws_mqtt5_client_stop(
2289 struct aws_mqtt5_client *client,
2290 const struct aws_mqtt5_packet_disconnect_view *options,
2291 const struct aws_mqtt5_disconnect_completion_options *completion_options) {
2292 AWS_FATAL_ASSERT(client != NULL);
2293 struct aws_mqtt5_operation_disconnect *disconnect_op = NULL;
2294 if (options != NULL) {
2295 struct aws_mqtt5_disconnect_completion_options internal_completion_options = {
2296 .completion_callback = s_on_disconnect_operation_complete,
2297 .completion_user_data = client,
2298 };
2299
2300 disconnect_op = aws_mqtt5_operation_disconnect_new(
2301 client->allocator, options, completion_options, &internal_completion_options);
2302 if (disconnect_op == NULL) {
2303 AWS_LOGF_ERROR(
2304 AWS_LS_MQTT5_CLIENT, "id=%p: failed to create requested DISCONNECT operation", (void *)client);
2305 return AWS_OP_ERR;
2306 }
2307
2308 AWS_LOGF_DEBUG(
2309 AWS_LS_MQTT5_CLIENT,
2310 "id=%p: Stopping client via DISCONNECT operation (%p)",
2311 (void *)client,
2312 (void *)disconnect_op);
2313 aws_mqtt5_packet_disconnect_view_log(disconnect_op->base.packet_view, AWS_LL_DEBUG);
2314 } else {
2315 AWS_LOGF_DEBUG(AWS_LS_MQTT5_CLIENT, "id=%p: Stopping client immediately", (void *)client);
2316 }
2317
2318 int result = s_aws_mqtt5_client_change_desired_state(client, AWS_MCS_STOPPED, disconnect_op);
2319
2320 aws_mqtt5_operation_disconnect_release(disconnect_op);
2321
2322 return result;
2323 }
2324
2325 struct aws_mqtt5_submit_operation_task {
2326 struct aws_task task;
2327 struct aws_allocator *allocator;
2328 struct aws_mqtt5_client *client;
2329 struct aws_mqtt5_operation *operation;
2330 };
2331
2332 void aws_mqtt5_client_submit_operation_internal(
2333 struct aws_mqtt5_client *client,
2334 struct aws_mqtt5_operation *operation,
2335 bool is_terminated) {
2336
2337 /*
2338 * Take a ref to the operation that represents the client taking ownership
2339 * If we subsequently reject it (task cancel or offline queue policy), then the operation completion
2340 * will undo this ref acquisition.
2341 */
2342 aws_mqtt5_operation_acquire(operation);
2343
2344 if (is_terminated) {
2345 s_complete_operation(NULL, operation, AWS_ERROR_MQTT5_CLIENT_TERMINATED, AWS_MQTT5_PT_NONE, NULL);
2346 return;
2347 }
2348
2349 /*
2350 * If we're offline and this operation doesn't meet the requirements of the offline queue retention policy,
2351 * fail it immediately.
2352 */
2353 if (client->current_state != AWS_MCS_CONNECTED) {
2354 if (!s_aws_mqtt5_operation_satisfies_offline_queue_retention_policy(
2355 operation, client->config->offline_queue_behavior)) {
2356 s_complete_operation(
2357 NULL, operation, AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY, AWS_MQTT5_PT_NONE, NULL);
2358 return;
2359 }
2360 }
2361
2362 /* newly-submitted operations must have a 0 packet id */
2363 aws_mqtt5_operation_set_packet_id(operation, 0);
2364
2365 s_enqueue_operation_back(client, operation);
2366 aws_mqtt5_client_statistics_change_operation_statistic_state(client, operation, AWS_MQTT5_OSS_INCOMPLETE);
2367 }
2368
2369 static void s_mqtt5_submit_operation_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
2370 (void)task;
2371
2372 struct aws_mqtt5_submit_operation_task *submit_operation_task = arg;
2373 struct aws_mqtt5_client *client = submit_operation_task->client;
2374 struct aws_mqtt5_operation *operation = submit_operation_task->operation;
2375
2376 aws_mqtt5_client_submit_operation_internal(client, operation, status != AWS_TASK_STATUS_RUN_READY);
2377
2378 aws_mqtt5_operation_release(submit_operation_task->operation);
2379 aws_mqtt5_client_release(submit_operation_task->client);
2380
2381 aws_mem_release(submit_operation_task->allocator, submit_operation_task);
2382 }
2383
2384 static int s_submit_operation(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation) {
2385 struct aws_mqtt5_submit_operation_task *submit_task =
2386 aws_mem_calloc(client->allocator, 1, sizeof(struct aws_mqtt5_submit_operation_task));
2387 if (submit_task == NULL) {
2388 return AWS_OP_ERR;
2389 }
2390
2391 aws_task_init(&submit_task->task, s_mqtt5_submit_operation_task_fn, submit_task, "Mqtt5SubmitOperation");
2392 submit_task->allocator = client->allocator;
2393 submit_task->client = aws_mqtt5_client_acquire(client);
2394 submit_task->operation = operation;
2395
2396 aws_event_loop_schedule_task_now(client->loop, &submit_task->task);
2397
2398 return AWS_OP_SUCCESS;
2399 }
2400
2401 int aws_mqtt5_client_publish(
2402 struct aws_mqtt5_client *client,
2403 const struct aws_mqtt5_packet_publish_view *publish_options,
2404 const struct aws_mqtt5_publish_completion_options *completion_options) {
2405
2406 AWS_PRECONDITION(client != NULL);
2407 AWS_PRECONDITION(publish_options != NULL);
2408
2409 struct aws_mqtt5_operation_publish *publish_op =
2410 aws_mqtt5_operation_publish_new(client->allocator, client, publish_options, completion_options);
2411
2412 if (publish_op == NULL) {
2413 return AWS_OP_ERR;
2414 }
2415
2416 AWS_LOGF_DEBUG(AWS_LS_MQTT5_CLIENT, "id=%p: Submitting PUBLISH operation (%p)", (void *)client, (void *)publish_op);
2417 aws_mqtt5_packet_publish_view_log(publish_op->base.packet_view, AWS_LL_DEBUG);
2418
2419 if (s_submit_operation(client, &publish_op->base)) {
2420 goto error;
2421 }
2422
2423 return AWS_OP_SUCCESS;
2424
2425 error:
2426
2427 aws_mqtt5_operation_release(&publish_op->base);
2428
2429 return AWS_OP_ERR;
2430 }
2431
2432 int aws_mqtt5_client_subscribe(
2433 struct aws_mqtt5_client *client,
2434 const struct aws_mqtt5_packet_subscribe_view *subscribe_options,
2435 const struct aws_mqtt5_subscribe_completion_options *completion_options) {
2436
2437 AWS_PRECONDITION(client != NULL);
2438 AWS_PRECONDITION(subscribe_options != NULL);
2439
2440 struct aws_mqtt5_operation_subscribe *subscribe_op =
2441 aws_mqtt5_operation_subscribe_new(client->allocator, client, subscribe_options, completion_options);
2442
2443 if (subscribe_op == NULL) {
2444 return AWS_OP_ERR;
2445 }
2446
2447 AWS_LOGF_DEBUG(
2448 AWS_LS_MQTT5_CLIENT, "id=%p: Submitting SUBSCRIBE operation (%p)", (void *)client, (void *)subscribe_op);
2449 aws_mqtt5_packet_subscribe_view_log(subscribe_op->base.packet_view, AWS_LL_DEBUG);
2450
2451 if (s_submit_operation(client, &subscribe_op->base)) {
2452 goto error;
2453 }
2454
2455 return AWS_OP_SUCCESS;
2456
2457 error:
2458
2459 aws_mqtt5_operation_release(&subscribe_op->base);
2460
2461 return AWS_OP_ERR;
2462 }
2463
2464 int aws_mqtt5_client_unsubscribe(
2465 struct aws_mqtt5_client *client,
2466 const struct aws_mqtt5_packet_unsubscribe_view *unsubscribe_options,
2467 const struct aws_mqtt5_unsubscribe_completion_options *completion_options) {
2468
2469 AWS_PRECONDITION(client != NULL);
2470 AWS_PRECONDITION(unsubscribe_options != NULL);
2471
2472 struct aws_mqtt5_operation_unsubscribe *unsubscribe_op =
2473 aws_mqtt5_operation_unsubscribe_new(client->allocator, client, unsubscribe_options, completion_options);
2474
2475 if (unsubscribe_op == NULL) {
2476 return AWS_OP_ERR;
2477 }
2478
2479 AWS_LOGF_DEBUG(
2480 AWS_LS_MQTT5_CLIENT, "id=%p: Submitting UNSUBSCRIBE operation (%p)", (void *)client, (void *)unsubscribe_op);
2481 aws_mqtt5_packet_unsubscribe_view_log(unsubscribe_op->base.packet_view, AWS_LL_DEBUG);
2482
2483 if (s_submit_operation(client, &unsubscribe_op->base)) {
2484 goto error;
2485 }
2486
2487 return AWS_OP_SUCCESS;
2488
2489 error:
2490
2491 aws_mqtt5_operation_release(&unsubscribe_op->base);
2492
2493 return AWS_OP_ERR;
2494 }
2495
2496 struct aws_mqtt5_manual_pub_ack_task {
2497 struct aws_task task;
2498 struct aws_allocator *allocator;
2499 struct aws_mqtt5_client *client;
2500 uint64_t pub_ack_control_id;
2501 struct aws_mqtt5_manual_publish_acknowledgement_completion_options completion_options;
2502 };
2503
2504 static void s_mqtt5_manual_pub_ack_task_fn(struct aws_task *task, void *arg, enum aws_task_status status) {
2505 (void)task;
2506
2507 struct aws_mqtt5_manual_pub_ack_task *manual_pub_ack_task = arg;
2508 struct aws_mqtt5_client *client = manual_pub_ack_task->client;
2509 uint64_t pub_ack_control_id = manual_pub_ack_task->pub_ack_control_id;
2510
2511 if (status != AWS_TASK_STATUS_RUN_READY) {
2512 goto cleanup;
2513 }
2514
2515 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
2516
2517 enum aws_mqtt5_manual_publish_acknowledgement_result puback_result = AWS_MQTT5_MPAR_SUCCESS;
2518
2519 struct aws_hash_element *elem = NULL;
2520 aws_hash_table_find(&client->operational_state.manual_pub_ack_control_id_table, &pub_ack_control_id, &elem);
2521
2522 // We can schedule the PUBACK as an mqtt operation if it exists in the control id table.
2523 if (elem != NULL) {
2524 struct aws_mqtt5_manual_pub_ack_entry *manual_pub_ack_entry =
2525 (struct aws_mqtt5_manual_pub_ack_entry *)(elem->value);
2526
2527 AWS_LOGF_DEBUG(
2528 AWS_LS_MQTT5_CLIENT,
2529 "id=%p: Scheuduling puback for control id: %llu for packet id: %d \n",
2530 (void *)client,
2531 (unsigned long long)manual_pub_ack_entry->pub_ack_control_id,
2532 manual_pub_ack_entry->packet_id);
2533
2534 uint16_t packet_id = manual_pub_ack_entry->packet_id;
2535
2536 aws_hash_table_remove(&client->operational_state.manual_pub_ack_packet_id_table, &packet_id, NULL, NULL);
2537 // This removal from the control id table will also deallocate the manual publish acknowledgement entry.
2538 aws_hash_table_remove(
2539 &client->operational_state.manual_pub_ack_control_id_table, &pub_ack_control_id, NULL, NULL);
2540
2541 if (s_aws_mqtt5_client_queue_puback(client, packet_id, &manual_pub_ack_task->completion_options)) {
2542 // this failure doesn't trigger the completion so we do it here before cleanup.
2543 puback_result = AWS_MQTT5_MPAR_CRT_FAILURE;
2544 goto completion;
2545 }
2546
2547 // Completion will be handled by the puback mqtt operation so we go to cleanup.
2548 goto cleanup;
2549 }
2550
2551 // If the control id isn't in the active table, check if it's been cancelled.
2552 aws_hash_table_find(
2553 &client->operational_state.manual_pub_ack_cancelled_control_id_table, &pub_ack_control_id, &elem);
2554 if (elem != NULL) {
2555 AWS_LOGF_DEBUG(
2556 AWS_LS_MQTT5_CLIENT,
2557 "id=%p: pub_ack_control_id: %llu has been cancelled due to a disconnection.",
2558 (void *)client,
2559 (unsigned long long)pub_ack_control_id);
2560
2561 // A cancelled control id has been used so it can be cleared from the table and deallocated. We only report
2562 // a cancellation once. Past that we will simply treat it as invalid.
2563 aws_hash_table_remove(
2564 &client->operational_state.manual_pub_ack_cancelled_control_id_table, &pub_ack_control_id, NULL, NULL);
2565 puback_result = AWS_MQTT5_MPAR_PUBACK_CANCELLED;
2566 goto completion;
2567 }
2568
2569 AWS_LOGF_DEBUG(
2570 AWS_LS_MQTT5_CLIENT,
2571 "id=%p: pub_ack_control_id: %llu is not tracked in any way.",
2572 (void *)client,
2573 (unsigned long long)pub_ack_control_id);
2574 puback_result = AWS_MQTT5_MPAR_PUBACK_INVALID;
2575
2576 completion:
2577 // We call the completion callback here in cases where there is no PUBACK operation scheduled on the client.
2578 if (manual_pub_ack_task->completion_options.completion_callback != NULL) {
2579 manual_pub_ack_task->completion_options.completion_callback(
2580 puback_result, manual_pub_ack_task->completion_options.completion_user_data);
2581 }
2582
2583 cleanup:
2584 aws_mqtt5_client_release(manual_pub_ack_task->client);
2585 aws_mem_release(manual_pub_ack_task->allocator, manual_pub_ack_task);
2586 }
2587
2588 // Schedules task to process a manual publish acknowledgement for provided pub_ack_control_id
2589 int aws_mqtt5_client_invoke_publish_acknowledgement(
2590 struct aws_mqtt5_client *client,
2591 uint64_t pub_ack_control_id,
2592 const struct aws_mqtt5_manual_publish_acknowledgement_completion_options *completion_options) {
2593 AWS_PRECONDITION(client != NULL);
2594
2595 struct aws_mqtt5_manual_pub_ack_task *manual_pub_ack_task =
2596 aws_mem_calloc(client->allocator, 1, sizeof(struct aws_mqtt5_manual_pub_ack_task));
2597
2598 aws_task_init(
2599 &manual_pub_ack_task->task, s_mqtt5_manual_pub_ack_task_fn, manual_pub_ack_task, "Mqtt5ManualPubackTask");
2600 manual_pub_ack_task->allocator = client->allocator;
2601 manual_pub_ack_task->client = aws_mqtt5_client_acquire(client);
2602 manual_pub_ack_task->pub_ack_control_id = pub_ack_control_id;
2603 if (completion_options != NULL) {
2604 manual_pub_ack_task->completion_options = *completion_options;
2605 }
2606
2607 aws_event_loop_schedule_task_now(client->loop, &manual_pub_ack_task->task);
2608
2609 return AWS_OP_SUCCESS;
2610 }
2611
2612 static void s_aws_mqtt5_manual_pub_ack_entry_destroy(void *object) {
2613 if (object == NULL) {
2614 return;
2615 }
2616 struct aws_mqtt5_manual_pub_ack_entry *manual_pub_ack_entry = object;
2617 aws_mem_release(manual_pub_ack_entry->allocator, manual_pub_ack_entry);
2618 }
2619
2620 static struct aws_mqtt5_manual_pub_ack_entry *s_aws_mqtt_manual_pub_ack_entry_new(
2621 struct aws_allocator *allocator,
2622 uint16_t packet_id,
2623 uint64_t pub_ack_control_id) {
2624
2625 struct aws_mqtt5_manual_pub_ack_entry *manual_pub_ack_entry =
2626 aws_mem_calloc(allocator, 1, sizeof(struct aws_mqtt5_manual_pub_ack_entry));
2627
2628 manual_pub_ack_entry->allocator = allocator;
2629 aws_ref_count_init(
2630 &manual_pub_ack_entry->ref_count, manual_pub_ack_entry, s_aws_mqtt5_manual_pub_ack_entry_destroy);
2631 manual_pub_ack_entry->packet_id = packet_id;
2632 manual_pub_ack_entry->pub_ack_control_id = pub_ack_control_id;
2633
2634 return manual_pub_ack_entry;
2635 }
2636
2637 uint64_t aws_mqtt5_client_acquire_publish_acknowledgement(
2638 struct aws_mqtt5_client *client,
2639 const struct aws_mqtt5_packet_publish_view *publish_view) {
2640 AWS_PRECONDITION(client != NULL);
2641 AWS_PRECONDITION(publish_view != NULL);
2642 /* This should only ever be called by the user within the publish received callback */
2643 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
2644
2645 if (publish_view->qos == AWS_MQTT5_QOS_AT_MOST_ONCE) {
2646 return 0;
2647 }
2648
2649 /* First check if the packet_id for the PUBLISH is already being controlled. This can potentialy be the case if a
2650 * PUBLISH that has its PUBACK acquired but hasn't been sent for long enough that the broker has sent the PUBLISH
2651 * packet again. */
2652 struct aws_hash_element *elem = NULL;
2653 aws_hash_table_find(&client->operational_state.manual_pub_ack_packet_id_table, &publish_view->packet_id, &elem);
2654 if (elem != NULL) {
2655 /* In this case we simply provide the same control_id that was already sent before. We do not want to create a
2656 * second control_id with the same packet_id. It is the user's responsibility to know that they have two PUBACKs
2657 * for the same PUBLISH. */
2658 struct aws_mqtt5_manual_pub_ack_entry *entry = elem->value;
2659 return entry->pub_ack_control_id;
2660 }
2661
2662 // The current_control_packet_id is incremented each time a new manual publish acknowledgement is scheduled.
2663 uint64_t current_control_packet_id = client->operational_state.next_mqtt5_pub_ack_control_id;
2664 struct aws_mqtt5_manual_pub_ack_entry *manual_pub_ack =
2665 s_aws_mqtt_manual_pub_ack_entry_new(client->allocator, publish_view->packet_id, current_control_packet_id);
2666
2667 /* Allows lookup of manual publish acknowledgement entries by packet id. */
2668 if (aws_hash_table_put(
2669 &client->operational_state.manual_pub_ack_packet_id_table,
2670 &manual_pub_ack->packet_id,
2671 manual_pub_ack,
2672 NULL)) {
2673 int error_code = aws_last_error();
2674 AWS_LOGF_ERROR(
2675 AWS_LS_MQTT5_CLIENT,
2676 "id=%p: Failed to insert manual publish acknowledgement entry into packet ID table: %d(%s)",
2677 (void *)client,
2678 error_code,
2679 aws_error_debug_str(error_code));
2680 goto cleanup;
2681 }
2682 /* We incref here because the packet_id table also has a ref to the manual_pub_ack */
2683 aws_ref_count_acquire(&manual_pub_ack->ref_count);
2684
2685 /* Allows lookup of manual publish acknowledgement entries by control id */
2686 if (aws_hash_table_put(
2687 &client->operational_state.manual_pub_ack_control_id_table,
2688 &manual_pub_ack->pub_ack_control_id,
2689 manual_pub_ack,
2690 NULL)) {
2691 int error_code = aws_last_error();
2692 AWS_LOGF_ERROR(
2693 AWS_LS_MQTT5_CLIENT,
2694 "id=%p: Failed to insert manual publish acknowledgement entry into control ID table: %d(%s)",
2695 (void *)client,
2696 error_code,
2697 aws_error_debug_str(error_code));
2698 // clean up the manual publish acknowledgement entry from the packet id table and deallocate.
2699 aws_hash_table_remove(
2700 &client->operational_state.manual_pub_ack_packet_id_table, &manual_pub_ack->packet_id, NULL, NULL);
2701 goto cleanup;
2702 }
2703
2704 /* Increment next_mqtt5_pub_ack_control_id for next use */
2705 client->operational_state.next_mqtt5_pub_ack_control_id = current_control_packet_id + 1;
2706
2707 size_t in_flight_unacked_publishes =
2708 aws_hash_table_get_entry_count(&client->operational_state.manual_pub_ack_control_id_table);
2709 if (in_flight_unacked_publishes >= 100) {
2710 AWS_LOGF_WARN(
2711 AWS_LS_MQTT5_CLIENT,
2712 "id=%p: 100 or more PUBACKs under user control: %zu. AWS IoT Core limits of 100 in-flight has been met or "
2713 "exceeded.",
2714 (void *)client,
2715 in_flight_unacked_publishes);
2716 } else {
2717 AWS_LOGF_DEBUG(
2718 AWS_LS_MQTT5_CLIENT,
2719 "id=%p: manual publish acknowledgement control taken for a PUBLISH packet. Current in-flight PUBACKs under "
2720 "user control: "
2721 "%zu",
2722 (void *)client,
2723 in_flight_unacked_publishes);
2724 }
2725
2726 return manual_pub_ack->pub_ack_control_id;
2727
2728 cleanup:
2729 aws_mem_release(manual_pub_ack->allocator, manual_pub_ack);
2730 return 0;
2731 }
2732
2733 static bool s_needs_packet_id(const struct aws_mqtt5_operation *operation) {
2734 switch (operation->packet_type) {
2735 case AWS_MQTT5_PT_SUBSCRIBE:
2736 case AWS_MQTT5_PT_UNSUBSCRIBE:
2737 return aws_mqtt5_operation_get_packet_id(operation) == 0;
2738
2739 case AWS_MQTT5_PT_PUBLISH: {
2740 const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
2741 if (publish_view->qos == AWS_MQTT5_QOS_AT_MOST_ONCE) {
2742 return false;
2743 }
2744
2745 return aws_mqtt5_operation_get_packet_id(operation) == 0;
2746 }
2747
2748 default:
2749 return false;
2750 }
2751 }
2752
2753 static uint16_t s_next_packet_id(uint16_t current_id) {
2754 if (++current_id == 0) {
2755 current_id = 1;
2756 }
2757
2758 return current_id;
2759 }
2760
2761 int aws_mqtt5_operation_bind_packet_id(
2762 struct aws_mqtt5_operation *operation,
2763 struct aws_mqtt5_client_operational_state *client_operational_state) {
2764 if (!s_needs_packet_id(operation)) {
2765 return AWS_OP_SUCCESS;
2766 }
2767
2768 uint16_t current_id = client_operational_state->next_mqtt_packet_id;
2769 struct aws_hash_element *elem = NULL;
2770 for (uint16_t i = 0; i < UINT16_MAX; ++i) {
2771 aws_hash_table_find(&client_operational_state->unacked_operations_table, &current_id, &elem);
2772
2773 if (elem == NULL) {
2774 aws_mqtt5_operation_set_packet_id(operation, current_id);
2775 client_operational_state->next_mqtt_packet_id = s_next_packet_id(current_id);
2776
2777 return AWS_OP_SUCCESS;
2778 }
2779
2780 current_id = s_next_packet_id(current_id);
2781 }
2782
2783 aws_raise_error(AWS_ERROR_INVALID_STATE);
2784 return AWS_OP_ERR;
2785 }
2786
2787 /*
2788 * Priority queue comparison function for ack timeout processing
2789 */
2790 static int s_compare_operation_timeouts(const void *a, const void *b) {
2791 const struct aws_mqtt5_operation **operation_a_ptr = (void *)a;
2792 const struct aws_mqtt5_operation *operation_a = *operation_a_ptr;
2793
2794 const struct aws_mqtt5_operation **operation_b_ptr = (void *)b;
2795 const struct aws_mqtt5_operation *operation_b = *operation_b_ptr;
2796
2797 if (operation_a->ack_timeout_timepoint_ns < operation_b->ack_timeout_timepoint_ns) {
2798 return -1;
2799 } else if (operation_a->ack_timeout_timepoint_ns > operation_b->ack_timeout_timepoint_ns) {
2800 return 1;
2801 } else {
2802 return 0;
2803 }
2804 }
2805
2806 int aws_mqtt5_client_operational_state_init(
2807 struct aws_mqtt5_client_operational_state *client_operational_state,
2808 struct aws_allocator *allocator,
2809 struct aws_mqtt5_client *client) {
2810
2811 aws_linked_list_init(&client_operational_state->queued_operations);
2812 aws_linked_list_init(&client_operational_state->write_completion_operations);
2813 aws_linked_list_init(&client_operational_state->unacked_operations);
2814
2815 if (aws_hash_table_init(
2816 &client_operational_state->unacked_operations_table,
2817 allocator,
2818 DEFAULT_MQTT5_OPERATION_TABLE_SIZE,
2819 aws_mqtt_hash_uint16_t,
2820 aws_mqtt_compare_uint16_t_eq,
2821 NULL,
2822 NULL)) {
2823 return AWS_OP_ERR;
2824 }
2825
2826 if (aws_hash_table_init(
2827 &client_operational_state->manual_pub_ack_packet_id_table,
2828 allocator,
2829 DEFAULT_MQTT5_OPERATION_TABLE_SIZE,
2830 aws_mqtt_hash_uint16_t,
2831 aws_mqtt_compare_uint16_t_eq,
2832 NULL,
2833 s_aws_mqtt5_manual_pub_ack_entry_decref)) {
2834 return AWS_OP_ERR;
2835 }
2836
2837 if (aws_hash_table_init(
2838 &client_operational_state->manual_pub_ack_control_id_table,
2839 allocator,
2840 DEFAULT_MQTT5_OPERATION_TABLE_SIZE,
2841 aws_mqtt_hash_uint64_t,
2842 aws_mqtt_compare_uint64_t_eq,
2843 NULL,
2844 s_aws_mqtt5_manual_pub_ack_entry_decref)) {
2845 return AWS_OP_ERR;
2846 }
2847
2848 if (aws_hash_table_init(
2849 &client_operational_state->manual_pub_ack_cancelled_control_id_table,
2850 allocator,
2851 DEFAULT_MQTT5_OPERATION_TABLE_SIZE,
2852 aws_mqtt_hash_uint64_t,
2853 aws_mqtt_compare_uint64_t_eq,
2854 NULL,
2855 s_aws_mqtt5_manual_pub_ack_entry_decref)) {
2856 return AWS_OP_ERR;
2857 }
2858
2859 if (aws_priority_queue_init_dynamic(
2860 &client_operational_state->operations_by_ack_timeout,
2861 allocator,
2862 100,
2863 sizeof(struct aws_mqtt5_operation *),
2864 s_compare_operation_timeouts)) {
2865 return AWS_OP_ERR;
2866 }
2867
2868 client_operational_state->next_mqtt_packet_id = 1;
2869 client_operational_state->next_mqtt5_pub_ack_control_id = 1;
2870 client_operational_state->current_operation = NULL;
2871 client_operational_state->client = client;
2872
2873 return AWS_OP_SUCCESS;
2874 }
2875
2876 void aws_mqtt5_client_operational_state_clean_up(struct aws_mqtt5_client_operational_state *client_operational_state) {
2877 AWS_ASSERT(client_operational_state->current_operation == NULL);
2878
2879 s_aws_mqtt5_client_operational_state_reset(client_operational_state, AWS_ERROR_MQTT5_CLIENT_TERMINATED, true);
2880 }
2881
2882 static bool s_filter_queued_operations_for_offline(struct aws_mqtt5_operation *operation, void *context) {
2883 struct aws_mqtt5_client *client = context;
2884 enum aws_mqtt5_client_operation_queue_behavior_type queue_behavior = client->config->offline_queue_behavior;
2885
2886 return !s_aws_mqtt5_operation_satisfies_offline_queue_retention_policy(operation, queue_behavior);
2887 }
2888
2889 static void s_process_unacked_operations_for_disconnect(struct aws_mqtt5_operation *operation, void *context) {
2890 (void)context;
2891
2892 if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
2893 struct aws_mqtt5_packet_publish_view *publish_view =
2894 (struct aws_mqtt5_packet_publish_view *)operation->packet_view;
2895 if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
2896 publish_view->duplicate = true;
2897 return;
2898 }
2899 }
2900
2901 aws_mqtt5_operation_set_packet_id(operation, 0);
2902 }
2903
2904 static bool s_filter_unacked_operations_for_offline(struct aws_mqtt5_operation *operation, void *context) {
2905 struct aws_mqtt5_client *client = context;
2906 enum aws_mqtt5_client_operation_queue_behavior_type queue_behavior = client->config->offline_queue_behavior;
2907
2908 if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
2909 const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
2910 if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
2911 return false;
2912 }
2913 }
2914
2915 return !s_aws_mqtt5_operation_satisfies_offline_queue_retention_policy(operation, queue_behavior);
2916 }
2917
2918 /*
2919 * Resets the client's operational state based on a disconnection (from above comment):
2920 *
2921 * If current_operation
2922 * move current_operation to head of queued_operations
2923 * Fail all operations in the pending write completion list
2924 * Fail, remove, and release operations in queued_operations where they fail the offline queue policy
2925 * Iterate unacked_operations:
2926 * If qos1+ publish
2927 * set dup flag
2928 * else
2929 * unset/release packet id
2930 * Fail, remove, and release unacked_operations if:
2931 * (1) They fail the offline queue policy AND
2932 * (2) the operation is not Qos 1+ publish
2933 *
2934 * Clears the unacked_operations table
2935 */
2936 void aws_mqtt5_client_on_disconnection_update_operational_state(struct aws_mqtt5_client *client) {
2937 struct aws_mqtt5_client_operational_state *client_operational_state = &client->operational_state;
2938
2939 /* move current operation to the head of the queue */
2940 if (client_operational_state->current_operation != NULL) {
2941 aws_linked_list_push_front(
2942 &client_operational_state->queued_operations, &client_operational_state->current_operation->node);
2943 client_operational_state->current_operation = NULL;
2944 }
2945
2946 /* fail everything in pending write completion */
2947 s_complete_operation_list(
2948 client,
2949 &client_operational_state->write_completion_operations,
2950 AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY);
2951
2952 struct aws_linked_list operations_to_fail;
2953 AWS_ZERO_STRUCT(operations_to_fail);
2954 aws_linked_list_init(&operations_to_fail);
2955
2956 /* fail everything in the pending queue that doesn't meet the offline queue behavior retention requirements */
2957 s_filter_operation_list(
2958 &client_operational_state->queued_operations,
2959 s_filter_queued_operations_for_offline,
2960 &operations_to_fail,
2961 client);
2962 s_complete_operation_list(
2963 client, &operations_to_fail, AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY);
2964
2965 /* Mark unacked qos1+ publishes as duplicate and release packet ids for non qos1+ publish */
2966 s_apply_to_operation_list(
2967 &client_operational_state->unacked_operations, s_process_unacked_operations_for_disconnect, NULL);
2968
2969 /*
2970 * fail everything in the pending queue that
2971 * (1) isn't a qos1+ publish AND
2972 * (2) doesn't meet the offline queue behavior retention requirements
2973 */
2974 s_filter_operation_list(
2975 &client_operational_state->unacked_operations,
2976 s_filter_unacked_operations_for_offline,
2977 &operations_to_fail,
2978 client);
2979 s_complete_operation_list(
2980 client, &operations_to_fail, AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY);
2981
2982 aws_hash_table_clear(&client->operational_state.unacked_operations_table);
2983 aws_priority_queue_clear(&client->operational_state.operations_by_ack_timeout);
2984
2985 s_aws_mqtt5_reset_manual_pub_ack_tables(client_operational_state);
2986
2987 /*
2988 * Prevents inbound resolution on the highly unlikely, illegal server behavior of sending a PUBLISH before
2989 * a CONNACK on next connection establishment.
2990 */
2991 aws_mqtt5_decoder_set_inbound_topic_alias_resolver(&client->decoder, NULL);
2992 }
2993
2994 static void s_set_operation_list_statistic_state(
2995 struct aws_mqtt5_client *client,
2996 struct aws_linked_list *operation_list,
2997 enum aws_mqtt5_operation_statistic_state_flags new_state_flags) {
2998 struct aws_linked_list_node *node = aws_linked_list_begin(operation_list);
2999 while (node != aws_linked_list_end(operation_list)) {
3000 struct aws_mqtt5_operation *operation = AWS_CONTAINER_OF(node, struct aws_mqtt5_operation, node);
3001 node = aws_linked_list_next(node);
3002
3003 aws_mqtt5_client_statistics_change_operation_statistic_state(client, operation, new_state_flags);
3004 }
3005 }
3006
3007 static bool s_filter_unacked_operations_for_session_rejoin(struct aws_mqtt5_operation *operation, void *context) {
3008 (void)context;
3009
3010 if (operation->packet_type == AWS_MQTT5_PT_PUBLISH) {
3011 const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
3012 if (publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE) {
3013 return false;
3014 }
3015 }
3016
3017 return true;
3018 }
3019
3020 /*
3021 * Updates the client's operational state based on a successfully established connection event:
3022 *
3023 * if rejoined_session:
3024 * Move-and-append all non-qos1+-publishes in unacked_operations to the front of queued_operations
3025 * Move-and-append remaining operations (qos1+ publishes) to the front of queued_operations
3026 * else:
3027 * Fail, remove, and release unacked_operations that fail the offline queue policy
3028 * Move and append unacked operations to front of queued_operations
3029 */
3030 void aws_mqtt5_client_on_connection_update_operational_state(struct aws_mqtt5_client *client) {
3031
3032 struct aws_mqtt5_client_operational_state *client_operational_state = &client->operational_state;
3033
3034 if (client->negotiated_settings.rejoined_session) {
3035 struct aws_linked_list requeued_operations;
3036 AWS_ZERO_STRUCT(requeued_operations);
3037 aws_linked_list_init(&requeued_operations);
3038
3039 /*
3040 * qos1+ publishes must go out first, so split the unacked operation list into two sets: qos1+ publishes and
3041 * everything else.
3042 */
3043 s_filter_operation_list(
3044 &client_operational_state->unacked_operations,
3045 s_filter_unacked_operations_for_session_rejoin,
3046 &requeued_operations,
3047 client);
3048
3049 /*
3050 * Put non-qos1+ publishes on the front of the pending queue
3051 */
3052 aws_linked_list_move_all_front(&client->operational_state.queued_operations, &requeued_operations);
3053
3054 /*
3055 * Put qos1+ publishes on the front of the pending queue
3056 */
3057 aws_linked_list_move_all_front(
3058 &client->operational_state.queued_operations, &client_operational_state->unacked_operations);
3059 } else {
3060 struct aws_linked_list failed_operations;
3061 AWS_ZERO_STRUCT(failed_operations);
3062 aws_linked_list_init(&failed_operations);
3063
3064 s_filter_operation_list(
3065 &client_operational_state->unacked_operations,
3066 s_filter_queued_operations_for_offline,
3067 &failed_operations,
3068 client);
3069
3070 /*
3071 * fail operations that we aren't going to requeue. In this particular case it's only qos1+ publishes
3072 * that we didn't fail because we didn't know if we were going to rejoin a sesison or not.
3073 */
3074 s_complete_operation_list(
3075 client, &failed_operations, AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY);
3076
3077 /* requeue operations that we are going to perform again */
3078 aws_linked_list_move_all_front(
3079 &client->operational_state.queued_operations, &client->operational_state.unacked_operations);
3080 }
3081
3082 /* set everything remaining to incomplete */
3083 s_set_operation_list_statistic_state(
3084 client, &client->operational_state.queued_operations, AWS_MQTT5_OSS_INCOMPLETE);
3085
3086 aws_mqtt5_client_flow_control_state_reset(client);
3087
3088 uint16_t inbound_alias_maximum = client->negotiated_settings.topic_alias_maximum_to_client;
3089
3090 if (aws_mqtt5_inbound_topic_alias_resolver_reset(&client->inbound_topic_alias_resolver, inbound_alias_maximum)) {
3091 AWS_LOGF_ERROR(
3092 AWS_LS_MQTT5_CLIENT,
3093 "id=%p: client unable to reset inbound alias resolver",
3094 (void *)client_operational_state->client);
3095 goto on_error;
3096 }
3097
3098 if (inbound_alias_maximum > 0) {
3099 aws_mqtt5_decoder_set_inbound_topic_alias_resolver(&client->decoder, &client->inbound_topic_alias_resolver);
3100 } else {
3101 aws_mqtt5_decoder_set_inbound_topic_alias_resolver(&client->decoder, NULL);
3102 }
3103
3104 uint16_t outbound_alias_maximum = client->negotiated_settings.topic_alias_maximum_to_server;
3105 if (aws_mqtt5_outbound_topic_alias_resolver_reset(client->outbound_topic_alias_resolver, outbound_alias_maximum)) {
3106 AWS_LOGF_ERROR(
3107 AWS_LS_MQTT5_CLIENT,
3108 "id=%p: client unable to reset outbound alias resolver",
3109 (void *)client_operational_state->client);
3110 goto on_error;
3111 }
3112
3113 aws_mqtt5_encoder_set_outbound_topic_alias_resolver(&client->encoder, client->outbound_topic_alias_resolver);
3114
3115 return;
3116
3117 on_error:
3118
3119 s_aws_mqtt5_client_shutdown_channel(client, aws_last_error());
3120 }
3121
3122 static bool s_aws_mqtt5_client_has_pending_operational_work(
3123 const struct aws_mqtt5_client_operational_state *client_operational_state,
3124 enum aws_mqtt5_client_state client_state) {
3125 if (aws_linked_list_empty(&client_operational_state->queued_operations)) {
3126 return false;
3127 }
3128
3129 struct aws_linked_list_node *next_operation_node =
3130 aws_linked_list_front(&client_operational_state->queued_operations);
3131 struct aws_mqtt5_operation *next_operation =
3132 AWS_CONTAINER_OF(next_operation_node, struct aws_mqtt5_operation, node);
3133
3134 switch (client_state) {
3135 case AWS_MCS_MQTT_CONNECT:
3136 /* Only allowed to send a CONNECT packet in this state */
3137 return next_operation->packet_type == AWS_MQTT5_PT_CONNECT;
3138
3139 case AWS_MCS_CLEAN_DISCONNECT:
3140 /* Except for finishing the current operation, only allowed to send a DISCONNECT packet in this state */
3141 return next_operation->packet_type == AWS_MQTT5_PT_DISCONNECT;
3142
3143 case AWS_MCS_CONNECTED:
3144 return true;
3145
3146 default:
3147 return false;
3148 }
3149 }
3150
3151 static uint64_t s_aws_mqtt5_client_compute_next_operation_flow_control_service_time(
3152 struct aws_mqtt5_client *client,
3153 struct aws_mqtt5_operation *operation,
3154 uint64_t now) {
3155 (void)operation;
3156
3157 switch (client->current_state) {
3158 case AWS_MCS_MQTT_CONNECT:
3159 case AWS_MCS_CLEAN_DISCONNECT:
3160 return now;
3161
3162 case AWS_MCS_CONNECTED:
3163 return aws_mqtt5_client_flow_control_state_get_next_operation_service_time(client, operation, now);
3164
3165 default:
3166 /* no outbound traffic is allowed outside of the above states */
3167 return 0;
3168 }
3169 }
3170
3171 /*
3172 * We don't presently know if IoT Core's throughput limit is on the plaintext or encrypted data stream. Assume
3173 * it's on the encrypted stream for now and make a reasonable guess at the additional cost TLS imposes on data size:
3174 *
3175 * This calculation is intended to be a reasonable default but will not be accurate in all cases
3176 *
3177 * Estimate the # of ethernet frames (max 1444 bytes) and add in potential TLS framing and padding values per.
3178 *
3179 * TODO: query IoT Core to determine if this calculation is needed after all
3180 * TODO: may eventually want to expose the ethernet frame size here as a configurable option for networks that have
3181 * a lower MTU
3182 *
3183 * References:
3184 * https://tools.ietf.org/id/draft-mattsson-uta-tls-overhead-01.xml#rfc.section.3
3185 *
3186 */
3187
3188 #define ETHERNET_FRAME_MAX_PAYLOAD_SIZE 1500
3189 #define TCP_SIZE_OVERESTIMATE 72
3190 #define TLS_FRAMING_AND_PADDING_OVERESTIMATE 64
3191 #define AVAILABLE_ETHERNET_FRAME_SIZE \
3192 (ETHERNET_FRAME_MAX_PAYLOAD_SIZE - (TCP_SIZE_OVERESTIMATE + TLS_FRAMING_AND_PADDING_OVERESTIMATE))
3193 #define ETHERNET_FRAMES_PER_IO_MESSAGE_ESTIMATE \
3194 ((AWS_MQTT5_IO_MESSAGE_DEFAULT_LENGTH + AVAILABLE_ETHERNET_FRAME_SIZE - 1) / AVAILABLE_ETHERNET_FRAME_SIZE)
3195 #define THROUGHPUT_TOKENS_PER_IO_MESSAGE_OVERESTIMATE \
3196 (AWS_MQTT5_IO_MESSAGE_DEFAULT_LENGTH + \
3197 ETHERNET_FRAMES_PER_IO_MESSAGE_ESTIMATE * TLS_FRAMING_AND_PADDING_OVERESTIMATE)
3198
3199 static uint64_t s_compute_throughput_throttle_wait(const struct aws_mqtt5_client *client, uint64_t now) {
3200
3201 /* flow control only applies during CONNECTED/CLEAN_DISCONNECT */
3202 if (!aws_mqtt5_client_are_negotiated_settings_valid(client)) {
3203 return now;
3204 }
3205
3206 uint64_t throughput_wait = 0;
3207 if (client->config->extended_validation_and_flow_control_options != AWS_MQTT5_EVAFCO_NONE) {
3208 throughput_wait = aws_rate_limiter_token_bucket_compute_wait_for_tokens(
3209 (struct aws_rate_limiter_token_bucket *)&client->flow_control_state.throughput_throttle,
3210 THROUGHPUT_TOKENS_PER_IO_MESSAGE_OVERESTIMATE);
3211 }
3212
3213 return aws_add_u64_saturating(now, throughput_wait);
3214 }
3215
3216 static uint64_t s_aws_mqtt5_client_compute_operational_state_service_time(
3217 const struct aws_mqtt5_client_operational_state *client_operational_state,
3218 uint64_t now) {
3219 /* If an io message is in transit down the channel, then wait for it to complete */
3220 if (client_operational_state->pending_write_completion) {
3221 return 0;
3222 }
3223
3224 /* Throughput flow control check */
3225 uint64_t next_throttled_time = s_compute_throughput_throttle_wait(client_operational_state->client, now);
3226 if (next_throttled_time > now) {
3227 return next_throttled_time;
3228 }
3229
3230 /* If we're in the middle of something, keep going */
3231 if (client_operational_state->current_operation != NULL) {
3232 return now;
3233 }
3234
3235 /* If nothing is queued, there's nothing to do */
3236 enum aws_mqtt5_client_state client_state = client_operational_state->client->current_state;
3237 if (!s_aws_mqtt5_client_has_pending_operational_work(client_operational_state, client_state)) {
3238 return 0;
3239 }
3240
3241 AWS_FATAL_ASSERT(!aws_linked_list_empty(&client_operational_state->queued_operations));
3242
3243 struct aws_linked_list_node *next_operation_node =
3244 aws_linked_list_front(&client_operational_state->queued_operations);
3245 struct aws_mqtt5_operation *next_operation =
3246 AWS_CONTAINER_OF(next_operation_node, struct aws_mqtt5_operation, node);
3247
3248 AWS_FATAL_ASSERT(next_operation != NULL);
3249
3250 /*
3251 * Check the head of the pending operation queue against flow control and client state restrictions
3252 */
3253 return s_aws_mqtt5_client_compute_next_operation_flow_control_service_time(
3254 client_operational_state->client, next_operation, now);
3255 }
3256
3257 static bool s_aws_mqtt5_client_should_service_operational_state(
3258 const struct aws_mqtt5_client_operational_state *client_operational_state,
3259 uint64_t now) {
3260
3261 return now == s_aws_mqtt5_client_compute_operational_state_service_time(client_operational_state, now);
3262 }
3263
3264 static bool s_operation_requires_ack(const struct aws_mqtt5_operation *operation) {
3265 switch (operation->packet_type) {
3266 case AWS_MQTT5_PT_SUBSCRIBE:
3267 case AWS_MQTT5_PT_UNSUBSCRIBE:
3268 return true;
3269
3270 case AWS_MQTT5_PT_PUBLISH: {
3271 const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
3272 return publish_view->qos != AWS_MQTT5_QOS_AT_MOST_ONCE;
3273 }
3274
3275 default:
3276 return false;
3277 }
3278 }
3279
3280 static void s_on_pingreq_send(struct aws_mqtt5_client *client) {
3281 uint64_t now = client->vtable->get_current_time_fn();
3282 uint64_t ping_timeout_nanos =
3283 aws_timestamp_convert(client->config->ping_timeout_ms, AWS_TIMESTAMP_MILLIS, AWS_TIMESTAMP_NANOS, NULL);
3284 uint64_t half_keep_alive_nanos =
3285 aws_timestamp_convert(
3286 client->negotiated_settings.server_keep_alive, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL) /
3287 2;
3288
3289 uint64_t connection_ping_timeout = ping_timeout_nanos;
3290 if (connection_ping_timeout == 0 || connection_ping_timeout > half_keep_alive_nanos) {
3291 connection_ping_timeout = half_keep_alive_nanos;
3292 }
3293
3294 AWS_LOGF_DEBUG(
3295 AWS_LS_MQTT5_CLIENT, "id=%p: dynamic ping timeout: %" PRIu64 " ns", (void *)client, connection_ping_timeout);
3296
3297 client->next_ping_timeout_time = aws_add_u64_saturating(now, connection_ping_timeout);
3298 }
3299
3300 static int s_apply_throughput_flow_control(struct aws_mqtt5_client *client) {
3301 /* flow control only applies during CONNECTED/CLEAN_DISCONNECT */
3302 if (!aws_mqtt5_client_are_negotiated_settings_valid(client)) {
3303 return AWS_OP_SUCCESS;
3304 }
3305
3306 if (client->config->extended_validation_and_flow_control_options == AWS_MQTT5_EVAFCO_NONE) {
3307 return AWS_OP_SUCCESS;
3308 }
3309
3310 return aws_rate_limiter_token_bucket_take_tokens(
3311 (struct aws_rate_limiter_token_bucket *)&client->flow_control_state.throughput_throttle,
3312 THROUGHPUT_TOKENS_PER_IO_MESSAGE_OVERESTIMATE);
3313 }
3314
3315 static int s_apply_publish_tps_flow_control(struct aws_mqtt5_client *client, struct aws_mqtt5_operation *operation) {
3316 if (client->config->extended_validation_and_flow_control_options == AWS_MQTT5_EVAFCO_NONE) {
3317 return AWS_OP_SUCCESS;
3318 }
3319
3320 if (operation->packet_type != AWS_MQTT5_PT_PUBLISH) {
3321 return AWS_OP_SUCCESS;
3322 }
3323
3324 return aws_rate_limiter_token_bucket_take_tokens(
3325 (struct aws_rate_limiter_token_bucket *)&client->flow_control_state.publish_throttle, 1);
3326 }
3327
3328 int aws_mqtt5_client_service_operational_state(struct aws_mqtt5_client_operational_state *client_operational_state) {
3329 struct aws_mqtt5_client *client = client_operational_state->client;
3330 struct aws_channel_slot *slot = client->slot;
3331 const struct aws_mqtt5_client_vtable *vtable = client->vtable;
3332 uint64_t now = (*vtable->get_current_time_fn)();
3333
3334 /* Should we write data? */
3335 bool should_service = s_aws_mqtt5_client_should_service_operational_state(client_operational_state, now);
3336 if (!should_service) {
3337 return AWS_OP_SUCCESS;
3338 }
3339
3340 if (s_apply_throughput_flow_control(client)) {
3341 return AWS_OP_SUCCESS;
3342 }
3343
3344 /* If we're going to write data, we need something to write to */
3345 struct aws_io_message *io_message = (*vtable->aws_channel_acquire_message_from_pool_fn)(
3346 slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, AWS_MQTT5_IO_MESSAGE_DEFAULT_LENGTH, vtable->vtable_user_data);
3347 if (io_message == NULL) {
3348 return AWS_OP_ERR;
3349 }
3350
3351 int operational_error_code = AWS_ERROR_SUCCESS;
3352
3353 do {
3354 /* if no current operation, pull one in and setup encode */
3355 if (client_operational_state->current_operation == NULL) {
3356
3357 /*
3358 * Loop through queued operations, discarding ones that fail validation, until we run out or find
3359 * a good one. Failing validation against negotiated settings is expected to be a rare event.
3360 */
3361 struct aws_mqtt5_operation *next_operation = NULL;
3362 while (!aws_linked_list_empty(&client_operational_state->queued_operations)) {
3363 struct aws_linked_list_node *next_operation_node =
3364 aws_linked_list_front(&client_operational_state->queued_operations);
3365 struct aws_mqtt5_operation *operation =
3366 AWS_CONTAINER_OF(next_operation_node, struct aws_mqtt5_operation, node);
3367
3368 /* If this is a publish and we're throttled, just quit out of the loop. */
3369 if (s_apply_publish_tps_flow_control(client, operation)) {
3370 break;
3371 }
3372
3373 /* Wait until flow control has passed before actually dequeuing the operation. */
3374 aws_linked_list_pop_front(&client_operational_state->queued_operations);
3375
3376 if (!aws_mqtt5_operation_validate_vs_connection_settings(operation, client)) {
3377 next_operation = operation;
3378 break;
3379 }
3380
3381 enum aws_mqtt5_packet_type packet_type = operation->packet_type;
3382 int validation_error_code = aws_last_error();
3383 s_complete_operation(client, operation, validation_error_code, AWS_MQTT5_PT_NONE, NULL);
3384
3385 /* A DISCONNECT packet failing dynamic validation should shut down the whole channel */
3386 if (packet_type == AWS_MQTT5_PT_DISCONNECT) {
3387 operational_error_code = AWS_ERROR_MQTT5_OPERATION_PROCESSING_FAILURE;
3388 break;
3389 }
3390 }
3391
3392 if (next_operation != NULL && s_aws_mqtt5_client_set_current_operation(client, next_operation)) {
3393 operational_error_code = AWS_ERROR_MQTT5_OPERATION_PROCESSING_FAILURE;
3394 break;
3395 }
3396 }
3397
3398 struct aws_mqtt5_operation *current_operation = client_operational_state->current_operation;
3399 if (current_operation == NULL) {
3400 break;
3401 }
3402
3403 /* write current operation to message, handle errors */
3404 enum aws_mqtt5_encoding_result encoding_result =
3405 aws_mqtt5_encoder_encode_to_buffer(&client->encoder, &io_message->message_data);
3406 if (encoding_result == AWS_MQTT5_ER_ERROR) {
3407 operational_error_code = AWS_ERROR_MQTT5_ENCODE_FAILURE;
3408 break;
3409 }
3410
3411 /* if encoding finished:
3412 * push to write completion or unacked
3413 * clear current
3414 * else (message full)
3415 * break
3416 */
3417 if (encoding_result == AWS_MQTT5_ER_FINISHED) {
3418 aws_mqtt5_client_flow_control_state_on_outbound_operation(client, current_operation);
3419
3420 if (s_operation_requires_ack(current_operation)) {
3421 /* track the operation in the unacked data structures by packet id */
3422 AWS_FATAL_ASSERT(aws_mqtt5_operation_get_packet_id(current_operation) != 0);
3423
3424 if (aws_hash_table_put(
3425 &client_operational_state->unacked_operations_table,
3426 aws_mqtt5_operation_get_packet_id_address(current_operation),
3427 current_operation,
3428 NULL)) {
3429 operational_error_code = aws_last_error();
3430 break;
3431 }
3432
3433 uint32_t ack_timeout_seconds = aws_mqtt5_operation_get_ack_timeout_override(current_operation);
3434 if (ack_timeout_seconds == 0) {
3435 ack_timeout_seconds = client->config->ack_timeout_seconds;
3436 }
3437
3438 if (ack_timeout_seconds > 0) {
3439 current_operation->ack_timeout_timepoint_ns =
3440 now + aws_timestamp_convert(ack_timeout_seconds, AWS_TIMESTAMP_SECS, AWS_TIMESTAMP_NANOS, NULL);
3441 } else {
3442 current_operation->ack_timeout_timepoint_ns = UINT64_MAX;
3443 }
3444
3445 if (aws_priority_queue_push_ref(
3446 &client_operational_state->operations_by_ack_timeout,
3447 (void *)&current_operation,
3448 &current_operation->priority_queue_node)) {
3449 operational_error_code = aws_last_error();
3450 break;
3451 }
3452
3453 aws_linked_list_push_back(&client_operational_state->unacked_operations, &current_operation->node);
3454 aws_mqtt5_client_statistics_change_operation_statistic_state(
3455 client, current_operation, AWS_MQTT5_OSS_INCOMPLETE | AWS_MQTT5_OSS_UNACKED);
3456 } else {
3457 /* no ack is necessary, just add to socket write completion list */
3458 aws_linked_list_push_back(
3459 &client_operational_state->write_completion_operations, &current_operation->node);
3460
3461 /*
3462 * We special-case setting the ping timeout here. Other possible places are not appropriate:
3463 *
3464 * (1) Socket write completion - this leads to a race condition where our domain socket tests can
3465 * sporadically fail because the PINGRESP is processed before the write completion callback is
3466 * invoked.
3467 *
3468 * (2) Enqueue the ping - if the current operation is a large payload over a poor connection, it
3469 * may be an arbitrarily long time before the current operation completes and the ping even has a
3470 * chance to go out, meaning we will trigger a ping time out before it's even sent.
3471 *
3472 * Given a reasonable io message size, this is the best place to set the timeout.
3473 */
3474 if (current_operation->packet_type == AWS_MQTT5_PT_PINGREQ) {
3475 s_on_pingreq_send(client);
3476 }
3477 }
3478
3479 client->operational_state.current_operation = NULL;
3480 } else {
3481 AWS_FATAL_ASSERT(encoding_result == AWS_MQTT5_ER_OUT_OF_ROOM);
3482 break;
3483 }
3484
3485 now = (*vtable->get_current_time_fn)();
3486 should_service = s_aws_mqtt5_client_should_service_operational_state(client_operational_state, now);
3487 } while (should_service);
3488
3489 if (operational_error_code != AWS_ERROR_SUCCESS) {
3490 aws_mem_release(io_message->allocator, io_message);
3491 return aws_raise_error(operational_error_code);
3492 }
3493
3494 /* It's possible for there to be no data if we serviced operations that failed validation */
3495 if (io_message->message_data.len == 0) {
3496 aws_mem_release(io_message->allocator, io_message);
3497 return AWS_OP_SUCCESS;
3498 }
3499
3500 /* send io_message down channel in write direction, handle errors */
3501 io_message->on_completion = s_aws_mqtt5_on_socket_write_completion;
3502 io_message->user_data = client_operational_state->client;
3503 client_operational_state->pending_write_completion = true;
3504
3505 if ((*vtable->aws_channel_slot_send_message_fn)(
3506 slot, io_message, AWS_CHANNEL_DIR_WRITE, vtable->vtable_user_data)) {
3507 client_operational_state->pending_write_completion = false;
3508 aws_mem_release(io_message->allocator, io_message);
3509 return AWS_OP_ERR;
3510 }
3511
3512 return AWS_OP_SUCCESS;
3513 }
3514
3515 void aws_mqtt5_client_operational_state_handle_ack(
3516 struct aws_mqtt5_client_operational_state *client_operational_state,
3517 aws_mqtt5_packet_id_t packet_id,
3518 enum aws_mqtt5_packet_type packet_type,
3519 const void *packet_view,
3520 int error_code) {
3521
3522 if (packet_type == AWS_MQTT5_PT_PUBACK) {
3523 aws_mqtt5_client_flow_control_state_on_puback(client_operational_state->client);
3524 }
3525
3526 struct aws_hash_element *elem = NULL;
3527 aws_hash_table_find(&client_operational_state->unacked_operations_table, &packet_id, &elem);
3528
3529 if (elem == NULL || elem->value == NULL) {
3530 AWS_LOGF_ERROR(
3531 AWS_LS_MQTT5_CLIENT,
3532 "id=%p: received an ACK for an unknown operation with id %d",
3533 (void *)client_operational_state->client,
3534 (int)packet_id);
3535 return;
3536 } else {
3537 AWS_LOGF_TRACE(
3538 AWS_LS_MQTT5_CLIENT,
3539 "id=%p: Processing ACK with id %d",
3540 (void *)client_operational_state->client,
3541 (int)packet_id);
3542 }
3543
3544 struct aws_mqtt5_operation *operation = elem->value;
3545
3546 aws_linked_list_remove(&operation->node);
3547 aws_hash_table_remove(&client_operational_state->unacked_operations_table, &packet_id, NULL, NULL);
3548
3549 s_complete_operation(client_operational_state->client, operation, error_code, packet_type, packet_view);
3550 }
3551
3552 bool aws_mqtt5_client_are_negotiated_settings_valid(const struct aws_mqtt5_client *client) {
3553 return client->current_state == AWS_MCS_CONNECTED || client->current_state == AWS_MCS_CLEAN_DISCONNECT;
3554 }
3555
3556 void aws_mqtt5_client_flow_control_state_init(struct aws_mqtt5_client *client) {
3557 struct aws_mqtt5_client_flow_control_state *flow_control = &client->flow_control_state;
3558
3559 struct aws_rate_limiter_token_bucket_options publish_throttle_config = {
3560 .tokens_per_second = AWS_IOT_CORE_PUBLISH_PER_SECOND_LIMIT,
3561 .maximum_token_count = AWS_IOT_CORE_PUBLISH_PER_SECOND_LIMIT,
3562 .initial_token_count = 0,
3563 };
3564 aws_rate_limiter_token_bucket_init(&flow_control->publish_throttle, &publish_throttle_config);
3565
3566 struct aws_rate_limiter_token_bucket_options throughput_throttle_config = {
3567 .tokens_per_second = AWS_IOT_CORE_THROUGHPUT_LIMIT,
3568 .maximum_token_count = AWS_IOT_CORE_THROUGHPUT_LIMIT,
3569 .initial_token_count = 0,
3570 };
3571 aws_rate_limiter_token_bucket_init(&flow_control->throughput_throttle, &throughput_throttle_config);
3572 }
3573
3574 void aws_mqtt5_client_flow_control_state_reset(struct aws_mqtt5_client *client) {
3575 struct aws_mqtt5_client_flow_control_state *flow_control = &client->flow_control_state;
3576
3577 AWS_FATAL_ASSERT(aws_mqtt5_client_are_negotiated_settings_valid(client));
3578
3579 flow_control->unacked_publish_token_count = client->negotiated_settings.receive_maximum_from_server;
3580
3581 aws_rate_limiter_token_bucket_reset(&client->flow_control_state.publish_throttle);
3582 aws_rate_limiter_token_bucket_reset(&client->flow_control_state.throughput_throttle);
3583 }
3584
3585 void aws_mqtt5_client_flow_control_state_on_puback(struct aws_mqtt5_client *client) {
3586 struct aws_mqtt5_client_flow_control_state *flow_control = &client->flow_control_state;
3587
3588 bool was_zero = flow_control->unacked_publish_token_count == 0;
3589 flow_control->unacked_publish_token_count = aws_min_u32(
3590 client->negotiated_settings.receive_maximum_from_server, flow_control->unacked_publish_token_count + 1);
3591
3592 if (was_zero) {
3593 s_reevaluate_service_task(client);
3594 }
3595 }
3596
3597 void aws_mqtt5_client_flow_control_state_on_outbound_operation(
3598 struct aws_mqtt5_client *client,
3599 struct aws_mqtt5_operation *operation) {
3600 if (operation->packet_type != AWS_MQTT5_PT_PUBLISH) {
3601 return;
3602 }
3603
3604 const struct aws_mqtt5_packet_publish_view *publish_view = operation->packet_view;
3605 if (publish_view->qos == AWS_MQTT5_QOS_AT_MOST_ONCE) {
3606 return;
3607 }
3608
3609 struct aws_mqtt5_client_flow_control_state *flow_control = &client->flow_control_state;
3610
3611 AWS_FATAL_ASSERT(flow_control->unacked_publish_token_count > 0);
3612 --flow_control->unacked_publish_token_count;
3613 }
3614
3615 uint64_t aws_mqtt5_client_flow_control_state_get_next_operation_service_time(
3616 struct aws_mqtt5_client *client,
3617 struct aws_mqtt5_operation *next_operation,
3618 uint64_t now) {
3619
3620 if (next_operation->packet_type != AWS_MQTT5_PT_PUBLISH) {
3621 return now;
3622 }
3623
3624 /* publish tps check */
3625 if (client->config->extended_validation_and_flow_control_options != AWS_MQTT5_EVAFCO_NONE) {
3626 uint64_t publish_wait =
3627 aws_rate_limiter_token_bucket_compute_wait_for_tokens(&client->flow_control_state.publish_throttle, 1);
3628 if (publish_wait > 0) {
3629 return now + publish_wait;
3630 }
3631 }
3632
3633 /* receive maximum check */
3634 const struct aws_mqtt5_packet_publish_view *publish_view = next_operation->packet_view;
3635 if (publish_view->qos == AWS_MQTT5_QOS_AT_MOST_ONCE) {
3636 return now;
3637 }
3638
3639 if (client->flow_control_state.unacked_publish_token_count > 0) {
3640 return now;
3641 }
3642
3643 return 0;
3644 }
3645
3646 void aws_mqtt5_client_statistics_change_operation_statistic_state(
3647 struct aws_mqtt5_client *client,
3648 struct aws_mqtt5_operation *operation,
3649 enum aws_mqtt5_operation_statistic_state_flags new_state_flags) {
3650 enum aws_mqtt5_packet_type packet_type = operation->packet_type;
3651 if (packet_type != AWS_MQTT5_PT_PUBLISH && packet_type != AWS_MQTT5_PT_SUBSCRIBE &&
3652 packet_type != AWS_MQTT5_PT_UNSUBSCRIBE) {
3653 return;
3654 }
3655
3656 if (operation->packet_size == 0) {
3657 if (aws_mqtt5_packet_view_get_encoded_size(packet_type, operation->packet_view, &operation->packet_size)) {
3658 return;
3659 }
3660 }
3661
3662 AWS_FATAL_ASSERT(operation->packet_size > 0);
3663 uint64_t packet_size = (uint64_t)operation->packet_size;
3664
3665 enum aws_mqtt5_operation_statistic_state_flags old_state_flags = operation->statistic_state_flags;
3666 if (new_state_flags == old_state_flags) {
3667 return;
3668 }
3669
3670 struct aws_mqtt5_client_operation_statistics_impl *stats = &client->operation_statistics_impl;
3671
3672 if ((old_state_flags & AWS_MQTT5_OSS_INCOMPLETE) != (new_state_flags & AWS_MQTT5_OSS_INCOMPLETE)) {
3673 if ((new_state_flags & AWS_MQTT5_OSS_INCOMPLETE) != 0) {
3674 aws_atomic_fetch_add(&stats->incomplete_operation_count_atomic, 1);
3675 aws_atomic_fetch_add(&stats->incomplete_operation_size_atomic, (size_t)packet_size);
3676 } else {
3677 aws_atomic_fetch_sub(&stats->incomplete_operation_count_atomic, 1);
3678 aws_atomic_fetch_sub(&stats->incomplete_operation_size_atomic, (size_t)packet_size);
3679 }
3680 }
3681
3682 if ((old_state_flags & AWS_MQTT5_OSS_UNACKED) != (new_state_flags & AWS_MQTT5_OSS_UNACKED)) {
3683 if ((new_state_flags & AWS_MQTT5_OSS_UNACKED) != 0) {
3684 aws_atomic_fetch_add(&stats->unacked_operation_count_atomic, 1);
3685 aws_atomic_fetch_add(&stats->unacked_operation_size_atomic, (size_t)packet_size);
3686 } else {
3687 aws_atomic_fetch_sub(&stats->unacked_operation_count_atomic, 1);
3688 aws_atomic_fetch_sub(&stats->unacked_operation_size_atomic, (size_t)packet_size);
3689 }
3690 }
3691
3692 operation->statistic_state_flags = new_state_flags;
3693
3694 if (client->vtable != NULL && client->vtable->on_client_statistics_changed_callback_fn != NULL) {
3695 (*client->vtable->on_client_statistics_changed_callback_fn)(
3696 client, operation, client->vtable->vtable_user_data);
3697 }
3698 }
3699
3700 void aws_mqtt5_client_get_stats(struct aws_mqtt5_client *client, struct aws_mqtt5_client_operation_statistics *stats) {
3701 stats->incomplete_operation_count =
3702 (uint64_t)aws_atomic_load_int(&client->operation_statistics_impl.incomplete_operation_count_atomic);
3703 stats->incomplete_operation_size =
3704 (uint64_t)aws_atomic_load_int(&client->operation_statistics_impl.incomplete_operation_size_atomic);
3705 stats->unacked_operation_count =
3706 (uint64_t)aws_atomic_load_int(&client->operation_statistics_impl.unacked_operation_count_atomic);
3707 stats->unacked_operation_size =
3708 (uint64_t)aws_atomic_load_int(&client->operation_statistics_impl.unacked_operation_size_atomic);
3709 }
3710
3711 bool aws_mqtt5_client_reset_connection(struct aws_mqtt5_client *client) {
3712 AWS_FATAL_ASSERT(aws_event_loop_thread_is_callers_thread(client->loop));
3713
3714 client->current_reconnect_delay_ms = client->config->min_reconnect_delay_ms;
3715
3716 switch (client->current_state) {
3717 case AWS_MCS_MQTT_CONNECT:
3718 case AWS_MCS_CONNECTED:
3719 s_aws_mqtt5_client_shutdown_channel(client, AWS_ERROR_MQTT_CONNECTION_RESET_FOR_ADAPTER_CONNECT);
3720 return true;
3721
3722 case AWS_MCS_CONNECTING:
3723 client->should_reset_connection = true;
3724 return true;
3725
3726 default:
3727 break;
3728 }
3729
3730 return false;
3731 }