Debian Codegraph @

crt/aws-c-mqtt/source/client_channel_handler.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/private/client_impl.h>
7
8 #include <aws/mqtt/private/packets.h>
9 #include <aws/mqtt/private/topic_tree.h>
10
11 #include <aws/io/logging.h>
12
13 #include <aws/common/clock.h>
14 #include <aws/common/math.h>
15 #include <aws/common/task_scheduler.h>
16
17 #include <inttypes.h>
18
19 #ifdef _MSC_VER
20 # pragma warning(disable : 4204)
21 #endif
22
23 /*******************************************************************************
24 * Static Helper functions
25 ******************************************************************************/
26
27 /* Caches the socket write time for ping scheduling purposes */
28 static void s_update_next_ping_time(struct aws_mqtt_client_connection_311_impl *connection) {
29 if (connection->slot != NULL && connection->slot->channel != NULL) {
30 aws_channel_current_clock_time(connection->slot->channel, &connection->next_ping_time);
31 aws_add_u64_checked(connection->next_ping_time, connection->keep_alive_time_ns, &connection->next_ping_time);
32 }
33 }
34
35 /* Caches the request send time. The `request_send_timestamp` will be used to push off ping request on request complete.
36 */
37 static void s_update_request_send_time(struct aws_mqtt_request *request) {
38 if (request->connection != NULL && request->connection->slot != NULL &&
39 request->connection->slot->channel != NULL) {
40 aws_channel_current_clock_time(request->connection->slot->channel, &request->request_send_timestamp);
41 }
42 }
43
44 /* push off next ping time on ack received to last_request_send_timestamp_ns + keep_alive_time_ns
45 * The function must be called in critical section. */
46 static void s_pushoff_next_ping_time(
47 struct aws_mqtt_client_connection_311_impl *connection,
48 uint64_t last_request_send_timestamp_ns) {
49 ASSERT_SYNCED_DATA_LOCK_HELD(connection);
50 aws_add_u64_checked(
51 last_request_send_timestamp_ns, connection->keep_alive_time_ns, &last_request_send_timestamp_ns);
52 if (last_request_send_timestamp_ns > connection->next_ping_time) {
53 connection->next_ping_time = last_request_send_timestamp_ns;
54 }
55 }
56
57 /*******************************************************************************
58 * Packet State Machine
59 ******************************************************************************/
60
61 static int s_packet_handler_default(struct aws_byte_cursor message_cursor, void *user_data) {
62 (void)message_cursor;
63
64 struct aws_mqtt_client_connection_311_impl *connection = user_data;
65 AWS_LOGF_ERROR(AWS_LS_MQTT_CLIENT, "id=%p: Unhandled packet type received", (void *)connection);
66 return aws_raise_error(AWS_ERROR_MQTT_INVALID_PACKET_TYPE);
67 }
68
69 static void s_on_time_to_ping(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status);
70 static void s_schedule_ping(struct aws_mqtt_client_connection_311_impl *connection) {
71 aws_channel_task_init(&connection->ping_task, s_on_time_to_ping, connection, "mqtt_ping");
72
73 uint64_t now = 0;
74 aws_channel_current_clock_time(connection->slot->channel, &now);
75
76 AWS_LOGF_TRACE(
77 AWS_LS_MQTT_CLIENT, "id=%p: Scheduling PING task. current timestamp is %" PRIu64, (void *)connection, now);
78
79 AWS_LOGF_TRACE(
80 AWS_LS_MQTT_CLIENT,
81 "id=%p: The next PING task will be run at timestamp %" PRIu64,
82 (void *)connection,
83 connection->next_ping_time);
84
85 aws_channel_schedule_task_future(connection->slot->channel, &connection->ping_task, connection->next_ping_time);
86 }
87
88 static void s_on_time_to_ping(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
89 (void)channel_task;
90
91 if (status == AWS_TASK_STATUS_RUN_READY) {
92 struct aws_mqtt_client_connection_311_impl *connection = arg;
93
94 uint64_t now = 0;
95 aws_channel_current_clock_time(connection->slot->channel, &now);
96 if (now >= connection->next_ping_time) {
97 s_update_next_ping_time(connection);
98 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Sending PING", (void *)connection);
99 aws_mqtt_client_connection_ping(connection);
100 } else {
101
102 AWS_LOGF_TRACE(
103 AWS_LS_MQTT_CLIENT,
104 "id=%p: Skipped sending PING because scheduled ping time %" PRIu64
105 " has not elapsed yet. Current time is %" PRIu64
106 ". Rescheduling ping to run at the scheduled ping time...",
107 (void *)connection,
108 connection->next_ping_time,
109 now);
110 }
111 s_schedule_ping(connection);
112 }
113 }
114
115 static int s_validate_received_packet_type(
116 struct aws_mqtt_client_connection_311_impl *connection,
117 enum aws_mqtt_packet_type packet_type) {
118 { /* BEGIN CRITICAL SECTION */
119 mqtt_connection_lock_synced_data(connection);
120 /* [MQTT-3.2.0-1] The first packet sent from the Server to the Client MUST be a CONNACK Packet */
121 if (connection->synced_data.state == AWS_MQTT_CLIENT_STATE_CONNECTING &&
122 packet_type != AWS_MQTT_PACKET_CONNACK) {
123 mqtt_connection_unlock_synced_data(connection);
124 AWS_LOGF_ERROR(
125 AWS_LS_MQTT_CLIENT,
126 "id=%p: First message received from the server was not a CONNACK. Terminating connection.",
127 (void *)connection);
128 return aws_raise_error(AWS_ERROR_MQTT_PROTOCOL_ERROR);
129 }
130 mqtt_connection_unlock_synced_data(connection);
131 } /* END CRITICAL SECTION */
132
133 if (AWS_UNLIKELY(packet_type > AWS_MQTT_PACKET_DISCONNECT || packet_type < AWS_MQTT_PACKET_CONNECT)) {
134 AWS_LOGF_ERROR(
135 AWS_LS_MQTT_CLIENT,
136 "id=%p: Invalid packet type received %d. Terminating connection.",
137 (void *)connection,
138 packet_type);
139 return aws_raise_error(AWS_ERROR_MQTT_INVALID_PACKET_TYPE);
140 }
141
142 /* Handle the packet */
143 return AWS_OP_SUCCESS;
144 }
145
146 static int s_packet_handler_connack(struct aws_byte_cursor message_cursor, void *user_data) {
147
148 struct aws_mqtt_client_connection_311_impl *connection = user_data;
149 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: CONNACK received", (void *)connection);
150 if (s_validate_received_packet_type(connection, AWS_MQTT_PACKET_CONNACK)) {
151 return AWS_OP_ERR;
152 }
153
154 struct aws_mqtt_packet_connack connack;
155 if (aws_mqtt_packet_connack_decode(&message_cursor, &connack)) {
156 AWS_LOGF_ERROR(
157 AWS_LS_MQTT_CLIENT, "id=%p: error %d parsing CONNACK packet", (void *)connection, aws_last_error());
158
159 return AWS_OP_ERR;
160 }
161 bool was_reconnecting;
162 struct aws_linked_list requests;
163 aws_linked_list_init(&requests);
164 { /* BEGIN CRITICAL SECTION */
165 mqtt_connection_lock_synced_data(connection);
166 /* User requested disconnect, don't do anything */
167 if (connection->synced_data.state >= AWS_MQTT_CLIENT_STATE_DISCONNECTING) {
168 mqtt_connection_unlock_synced_data(connection);
169 AWS_LOGF_TRACE(
170 AWS_LS_MQTT_CLIENT, "id=%p: User has requested disconnect, dropping connection", (void *)connection);
171 return AWS_OP_SUCCESS;
172 }
173
174 was_reconnecting = connection->synced_data.state == AWS_MQTT_CLIENT_STATE_RECONNECTING;
175 if (connack.connect_return_code == AWS_MQTT_CONNECT_ACCEPTED) {
176 AWS_LOGF_DEBUG(
177 AWS_LS_MQTT_CLIENT,
178 "id=%p: connection was accepted, switch state from %d to CONNECTED.",
179 (void *)connection,
180 (int)connection->synced_data.state);
181 /* Don't change the state if it's not ACCEPTED by broker */
182 mqtt_connection_set_state(connection, AWS_MQTT_CLIENT_STATE_CONNECTED);
183 aws_linked_list_swap_contents(&connection->synced_data.pending_requests_list, &requests);
184 }
185 mqtt_connection_unlock_synced_data(connection);
186 } /* END CRITICAL SECTION */
187 connection->connection_count++;
188
189 uint64_t now = 0;
190 aws_high_res_clock_get_ticks(&now);
191
192 if (connack.connect_return_code == AWS_MQTT_CONNECT_ACCEPTED) {
193
194 /*
195 * This was a successful MQTT connection establishment, record the time so that channel shutdown
196 * can make a good decision about reconnect backoff reset.
197 */
198 connection->reconnect_timeouts.channel_successful_connack_timestamp_ns = now;
199
200 /* If successfully connected, schedule all pending tasks */
201 AWS_LOGF_TRACE(
202 AWS_LS_MQTT_CLIENT, "id=%p: connection was accepted processing offline requests.", (void *)connection);
203
204 if (!aws_linked_list_empty(&requests)) {
205
206 struct aws_linked_list_node *current = aws_linked_list_front(&requests);
207 const struct aws_linked_list_node *end = aws_linked_list_end(&requests);
208
209 do {
210 struct aws_mqtt_request *request = AWS_CONTAINER_OF(current, struct aws_mqtt_request, list_node);
211 AWS_LOGF_TRACE(
212 AWS_LS_MQTT_CLIENT,
213 "id=%p: processing offline request %" PRIu16,
214 (void *)connection,
215 request->packet_id);
216 aws_channel_schedule_task_now(connection->slot->channel, &request->outgoing_task);
217 current = current->next;
218 } while (current != end);
219 }
220 } else {
221 AWS_LOGF_ERROR(
222 AWS_LS_MQTT_CLIENT,
223 "id=%p: invalid connect return code %d, disconnecting",
224 (void *)connection,
225 connack.connect_return_code);
226 /* If error code returned, disconnect, on_completed will be invoked from shutdown process */
227 aws_channel_shutdown(connection->slot->channel, AWS_ERROR_MQTT_PROTOCOL_ERROR);
228
229 return AWS_OP_SUCCESS;
230 }
231
232 /* It is possible for a connection to complete, and a hangup to occur before the
233 * CONNECT/CONNACK cycle completes. In that case, we must deliver on_connection_complete
234 * on the first successful CONNACK or user code will never think it's connected */
235 if (was_reconnecting && connection->connection_count > 1) {
236
237 AWS_LOGF_TRACE(
238 AWS_LS_MQTT_CLIENT,
239 "id=%p: connection is a resumed connection, invoking on_resumed callback",
240 (void *)connection);
241
242 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_resumed, connack.connect_return_code, connack.session_present);
243 } else {
244
245 aws_create_reconnect_task(connection);
246
247 AWS_LOGF_TRACE(
248 AWS_LS_MQTT_CLIENT,
249 "id=%p: connection is a new connection, invoking on_connection_complete callback",
250 (void *)connection);
251 MQTT_CLIENT_CALL_CALLBACK_ARGS(
252 connection, on_connection_complete, AWS_OP_SUCCESS, connack.connect_return_code, connack.session_present);
253 }
254
255 /*
256 * The on_connection_success would get triggered on the successful CONNACK. It invoked with both the first connect
257 * attempt and reconnection attempt as Mqtt5 does not have on_resume callback for reconnection.
258 */
259 AWS_LOGF_TRACE(
260 AWS_LS_MQTT_CLIENT,
261 "id=%p: received a successful CONNACK, invoking on_connection_success callback",
262 (void *)connection);
263 MQTT_CLIENT_CALL_CALLBACK_ARGS(
264 connection, on_connection_success, connack.connect_return_code, connack.session_present);
265
266 aws_mqtt311_callback_set_manager_on_connection_success(
267 &connection->callback_manager, connack.connect_return_code, connack.session_present);
268
269 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: connection callback completed", (void *)connection);
270
271 s_update_next_ping_time(connection);
272 s_schedule_ping(connection);
273 return AWS_OP_SUCCESS;
274 }
275
276 static int s_packet_handler_publish(struct aws_byte_cursor message_cursor, void *user_data) {
277 struct aws_mqtt_client_connection_311_impl *connection = user_data;
278 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: PUBLISH received", (void *)connection);
279 if (s_validate_received_packet_type(connection, AWS_MQTT_PACKET_PUBLISH)) {
280 return AWS_OP_ERR;
281 }
282
283 /* TODO: need to handle the QoS 2 message to avoid processing the message a second time */
284 struct aws_mqtt_packet_publish publish;
285 if (aws_mqtt_packet_publish_decode(&message_cursor, &publish)) {
286 return AWS_OP_ERR;
287 }
288
289 aws_mqtt_topic_tree_publish(&connection->thread_data.subscriptions, &publish);
290
291 bool dup = aws_mqtt_packet_publish_get_dup(&publish);
292 enum aws_mqtt_qos qos = aws_mqtt_packet_publish_get_qos(&publish);
293 bool retain = aws_mqtt_packet_publish_get_retain(&publish);
294
295 MQTT_CLIENT_CALL_CALLBACK_ARGS(connection, on_any_publish, &publish.topic_name, &publish.payload, dup, qos, retain);
296
297 aws_mqtt311_callback_set_manager_on_publish_received(
298 &connection->callback_manager, &publish.topic_name, &publish.payload, dup, qos, retain);
299
300 AWS_LOGF_TRACE(
301 AWS_LS_MQTT_CLIENT,
302 "id=%p: publish received with msg id=%" PRIu16 " dup=%d qos=%d retain=%d payload-size=%zu topic=" PRInSTR,
303 (void *)connection,
304 publish.packet_identifier,
305 dup,
306 qos,
307 retain,
308 publish.payload.len,
309 AWS_BYTE_CURSOR_PRI(publish.topic_name));
310 struct aws_mqtt_packet_ack puback;
311 AWS_ZERO_STRUCT(puback);
312
313 /* Switch on QoS flags (bits 1 & 2) */
314 switch (qos) {
315 case AWS_MQTT_QOS_AT_MOST_ONCE:
316 AWS_LOGF_TRACE(
317 AWS_LS_MQTT_CLIENT, "id=%p: received publish QOS is 0, not sending puback", (void *)connection);
318 /* No more communication necessary */
319 break;
320 case AWS_MQTT_QOS_AT_LEAST_ONCE:
321 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: received publish QOS is 1, sending puback", (void *)connection);
322 aws_mqtt_packet_puback_init(&puback, publish.packet_identifier);
323 break;
324 case AWS_MQTT_QOS_EXACTLY_ONCE:
325 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: received publish QOS is 2, sending pubrec", (void *)connection);
326 aws_mqtt_packet_pubrec_init(&puback, publish.packet_identifier);
327 break;
328 default:
329 /* Impossible to hit this branch. QoS value is checked when decoding */
330 AWS_FATAL_ASSERT(0);
331 break;
332 }
333
334 if (puback.packet_identifier) {
335 struct aws_io_message *message = mqtt_get_message_for_packet(connection, &puback.fixed_header);
336 if (!message) {
337 return AWS_OP_ERR;
338 }
339
340 if (aws_mqtt_packet_ack_encode(&message->message_data, &puback)) {
341 aws_mem_release(message->allocator, message);
342 return AWS_OP_ERR;
343 }
344
345 if (aws_channel_slot_send_message(connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
346 aws_mem_release(message->allocator, message);
347 return AWS_OP_ERR;
348 }
349 }
350
351 return AWS_OP_SUCCESS;
352 }
353
354 static int s_packet_handler_puback(struct aws_byte_cursor message_cursor, void *user_data) {
355
356 struct aws_mqtt_client_connection_311_impl *connection = user_data;
357 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: received a PUBACK", (void *)connection);
358 if (s_validate_received_packet_type(connection, AWS_MQTT_PACKET_PUBACK)) {
359 return AWS_OP_ERR;
360 }
361
362 struct aws_mqtt_packet_ack ack;
363 if (aws_mqtt_packet_ack_decode(&message_cursor, &ack)) {
364 return AWS_OP_ERR;
365 }
366
367 AWS_LOGF_TRACE(
368 AWS_LS_MQTT_CLIENT, "id=%p: received ack for message id %" PRIu16, (void *)connection, ack.packet_identifier);
369
370 mqtt_request_complete(connection, AWS_ERROR_SUCCESS, ack.packet_identifier);
371
372 return AWS_OP_SUCCESS;
373 }
374
375 static int s_packet_handler_suback(struct aws_byte_cursor message_cursor, void *user_data) {
376
377 struct aws_mqtt_client_connection_311_impl *connection = user_data;
378 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: received a SUBACK", (void *)connection);
379 if (s_validate_received_packet_type(connection, AWS_MQTT_PACKET_SUBACK)) {
380 return AWS_OP_ERR;
381 }
382
383 struct aws_mqtt_packet_suback suback;
384 if (aws_mqtt_packet_suback_init(&suback, connection->allocator, 0 /* fake packet_id */)) {
385 return AWS_OP_ERR;
386 }
387
388 if (aws_mqtt_packet_suback_decode(&message_cursor, &suback)) {
389 goto error;
390 }
391
392 AWS_LOGF_TRACE(
393 AWS_LS_MQTT_CLIENT,
394 "id=%p: received suback for message id %" PRIu16,
395 (void *)connection,
396 suback.packet_identifier);
397
398 struct aws_mqtt_request *request = NULL;
399
400 { /* BEGIN CRITICAL SECTION */
401 mqtt_connection_lock_synced_data(connection);
402 struct aws_hash_element *elem = NULL;
403 aws_hash_table_find(&connection->synced_data.outstanding_requests_table, &suback.packet_identifier, &elem);
404 if (elem != NULL) {
405 request = elem->value;
406 }
407 mqtt_connection_unlock_synced_data(connection);
408 } /* END CRITICAL SECTION */
409
410 if (request == NULL) {
411 /* no corresponding request found */
412 goto done;
413 }
414
415 struct subscribe_task_arg *task_arg = request->on_complete_ud;
416 size_t request_topics_len = aws_array_list_length(&task_arg->topics);
417 size_t suback_return_code_len = aws_array_list_length(&suback.return_codes);
418 if (request_topics_len != suback_return_code_len) {
419 goto error;
420 }
421 size_t num_filters = aws_array_list_length(&suback.return_codes);
422 for (size_t i = 0; i < num_filters; ++i) {
423
424 uint8_t return_code = 0;
425 struct subscribe_task_topic *topic = NULL;
426 aws_array_list_get_at(&suback.return_codes, (void *)&return_code, i);
427 aws_array_list_get_at(&task_arg->topics, &topic, i);
428 topic->request.qos = return_code;
429 }
430
431 done:
432 mqtt_request_complete(connection, AWS_ERROR_SUCCESS, suback.packet_identifier);
433 aws_mqtt_packet_suback_clean_up(&suback);
434 return AWS_OP_SUCCESS;
435 error:
436 aws_mqtt_packet_suback_clean_up(&suback);
437 return AWS_OP_ERR;
438 }
439
440 static int s_packet_handler_unsuback(struct aws_byte_cursor message_cursor, void *user_data) {
441
442 struct aws_mqtt_client_connection_311_impl *connection = user_data;
443 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: received a UNSUBACK", (void *)connection);
444 if (s_validate_received_packet_type(connection, AWS_MQTT_PACKET_UNSUBACK)) {
445 return AWS_OP_ERR;
446 }
447
448 struct aws_mqtt_packet_ack ack;
449 if (aws_mqtt_packet_ack_decode(&message_cursor, &ack)) {
450 return AWS_OP_ERR;
451 }
452
453 AWS_LOGF_DEBUG(
454 AWS_LS_MQTT_CLIENT, "id=%p: received ack for message id %" PRIu16, (void *)connection, ack.packet_identifier);
455
456 mqtt_request_complete(connection, AWS_ERROR_SUCCESS, ack.packet_identifier);
457 return AWS_OP_SUCCESS;
458 }
459
460 static int s_packet_handler_pubrec(struct aws_byte_cursor message_cursor, void *user_data) {
461
462 struct aws_mqtt_client_connection_311_impl *connection = user_data;
463 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: received a PUBREC", (void *)connection);
464 if (s_validate_received_packet_type(connection, AWS_MQTT_PACKET_PUBREC)) {
465 return AWS_OP_ERR;
466 }
467
468 struct aws_mqtt_packet_ack ack;
469 if (aws_mqtt_packet_ack_decode(&message_cursor, &ack)) {
470 return AWS_OP_ERR;
471 }
472
473 /* TODO: When sending PUBLISH with QoS 2, we should be storing the data until this packet is received, at which
474 * point we may discard it. */
475
476 /* Send PUBREL */
477 aws_mqtt_packet_pubrel_init(&ack, ack.packet_identifier);
478 struct aws_io_message *message = mqtt_get_message_for_packet(connection, &ack.fixed_header);
479 if (!message) {
480 return AWS_OP_ERR;
481 }
482
483 if (aws_mqtt_packet_ack_encode(&message->message_data, &ack)) {
484 goto on_error;
485 }
486
487 if (aws_channel_slot_send_message(connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
488 goto on_error;
489 }
490
491 return AWS_OP_SUCCESS;
492
493 on_error:
494
495 if (message) {
496 aws_mem_release(message->allocator, message);
497 }
498
499 return AWS_OP_ERR;
500 }
501
502 static int s_packet_handler_pubrel(struct aws_byte_cursor message_cursor, void *user_data) {
503
504 struct aws_mqtt_client_connection_311_impl *connection = user_data;
505 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: received a PUBREL", (void *)connection);
506 if (s_validate_received_packet_type(connection, AWS_MQTT_PACKET_PUBREL)) {
507 return AWS_OP_ERR;
508 }
509
510 struct aws_mqtt_packet_ack ack;
511 if (aws_mqtt_packet_ack_decode(&message_cursor, &ack)) {
512 return AWS_OP_ERR;
513 }
514
515 /* Send PUBCOMP */
516 aws_mqtt_packet_pubcomp_init(&ack, ack.packet_identifier);
517 struct aws_io_message *message = mqtt_get_message_for_packet(connection, &ack.fixed_header);
518 if (!message) {
519 return AWS_OP_ERR;
520 }
521
522 if (aws_mqtt_packet_ack_encode(&message->message_data, &ack)) {
523 goto on_error;
524 }
525
526 if (aws_channel_slot_send_message(connection->slot, message, AWS_CHANNEL_DIR_WRITE)) {
527 goto on_error;
528 }
529
530 return AWS_OP_SUCCESS;
531
532 on_error:
533
534 if (message) {
535 aws_mem_release(message->allocator, message);
536 }
537
538 return AWS_OP_ERR;
539 }
540
541 static int s_packet_handler_pubcomp(struct aws_byte_cursor message_cursor, void *user_data) {
542
543 struct aws_mqtt_client_connection_311_impl *connection = user_data;
544 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: received a PUBCOMP", (void *)connection);
545 if (s_validate_received_packet_type(connection, AWS_MQTT_PACKET_PUBCOMP)) {
546 return AWS_OP_ERR;
547 }
548
549 struct aws_mqtt_packet_ack ack;
550 if (aws_mqtt_packet_ack_decode(&message_cursor, &ack)) {
551 return AWS_OP_ERR;
552 }
553
554 AWS_LOGF_DEBUG(
555 AWS_LS_MQTT_CLIENT, "id=%p: received ack for message id %" PRIu16, (void *)connection, ack.packet_identifier);
556
557 mqtt_request_complete(connection, AWS_ERROR_SUCCESS, ack.packet_identifier);
558 return AWS_OP_SUCCESS;
559 }
560
561 static int s_packet_handler_pingresp(struct aws_byte_cursor message_cursor, void *user_data) {
562
563 (void)message_cursor;
564
565 struct aws_mqtt_client_connection_311_impl *connection = user_data;
566 AWS_LOGF_DEBUG(AWS_LS_MQTT_CLIENT, "id=%p: PINGRESP received", (void *)connection);
567
568 connection->thread_data.waiting_on_ping_response = false;
569
570 return AWS_OP_SUCCESS;
571 }
572
573 /* Bake up a big ol' function table just like Gramma used to make */
574 static struct aws_mqtt_client_connection_packet_handlers s_default_packet_handlers = {
575 .handlers_by_packet_type = {
576 [AWS_MQTT_PACKET_CONNECT] = &s_packet_handler_default,
577 [AWS_MQTT_PACKET_CONNACK] = &s_packet_handler_connack,
578 [AWS_MQTT_PACKET_PUBLISH] = &s_packet_handler_publish,
579 [AWS_MQTT_PACKET_PUBACK] = &s_packet_handler_puback,
580 [AWS_MQTT_PACKET_PUBREC] = &s_packet_handler_pubrec,
581 [AWS_MQTT_PACKET_PUBREL] = &s_packet_handler_pubrel,
582 [AWS_MQTT_PACKET_PUBCOMP] = &s_packet_handler_pubcomp,
583 [AWS_MQTT_PACKET_SUBSCRIBE] = &s_packet_handler_default,
584 [AWS_MQTT_PACKET_SUBACK] = &s_packet_handler_suback,
585 [AWS_MQTT_PACKET_UNSUBSCRIBE] = &s_packet_handler_default,
586 [AWS_MQTT_PACKET_UNSUBACK] = &s_packet_handler_unsuback,
587 [AWS_MQTT_PACKET_PINGREQ] = &s_packet_handler_default,
588 [AWS_MQTT_PACKET_PINGRESP] = &s_packet_handler_pingresp,
589 [AWS_MQTT_PACKET_DISCONNECT] = &s_packet_handler_default,
590 }};
591
592 const struct aws_mqtt_client_connection_packet_handlers *aws_mqtt311_get_default_packet_handlers(void) {
593 return &s_default_packet_handlers;
594 }
595
596 /*******************************************************************************
597 * Channel Handler
598 ******************************************************************************/
599
600 /**
601 * Handles incoming messages from the server.
602 */
603 static int s_process_read_message(
604 struct aws_channel_handler *handler,
605 struct aws_channel_slot *slot,
606 struct aws_io_message *message) {
607
608 struct aws_mqtt_client_connection_311_impl *connection = handler->impl;
609
610 if (message->message_type != AWS_IO_MESSAGE_APPLICATION_DATA || message->message_data.len < 1) {
611 return aws_raise_error(AWS_ERROR_INVALID_STATE);
612 }
613
614 AWS_LOGF_TRACE(
615 AWS_LS_MQTT_CLIENT,
616 "id=%p: precessing read message of size %zu",
617 (void *)connection,
618 message->message_data.len);
619
620 /* This cursor will be updated as we read through the message. */
621 struct aws_byte_cursor message_cursor = aws_byte_cursor_from_buf(&message->message_data);
622
623 int result = aws_mqtt311_decoder_on_bytes_received(&connection->thread_data.decoder, message_cursor);
624
625 if (result == AWS_OP_SUCCESS) {
626 /* Do cleanup */
627 size_t message_data_length = message->message_data.len;
628 aws_mem_release(message->allocator, message);
629 aws_channel_slot_increment_read_window(slot, message_data_length);
630 } else {
631 aws_channel_shutdown(connection->slot->channel, aws_last_error());
632 }
633
634 return result;
635 }
636
637 static int s_shutdown(
638 struct aws_channel_handler *handler,
639 struct aws_channel_slot *slot,
640 enum aws_channel_direction dir,
641 int error_code,
642 bool free_scarce_resources_immediately) {
643
644 struct aws_mqtt_client_connection_311_impl *connection = handler->impl;
645
646 if (dir == AWS_CHANNEL_DIR_WRITE) {
647 /* On closing write direction, send out disconnect packet before closing connection. */
648
649 if (!free_scarce_resources_immediately) {
650
651 if (error_code == AWS_OP_SUCCESS) {
652 AWS_LOGF_INFO(
653 AWS_LS_MQTT_CLIENT,
654 "id=%p: sending disconnect message as part of graceful shutdown.",
655 (void *)connection);
656 /* On clean shutdown, send the disconnect message */
657 struct aws_mqtt_packet_connection disconnect;
658 aws_mqtt_packet_disconnect_init(&disconnect);
659
660 struct aws_io_message *message = mqtt_get_message_for_packet(connection, &disconnect.fixed_header);
661 if (!message) {
662 goto done;
663 }
664
665 if (aws_mqtt_packet_connection_encode(&message->message_data, &disconnect)) {
666 AWS_LOGF_DEBUG(
667 AWS_LS_MQTT_CLIENT,
668 "id=%p: failed to encode courteous disconnect io message",
669 (void *)connection);
670 aws_mem_release(message->allocator, message);
671 goto done;
672 }
673
674 if (aws_channel_slot_send_message(slot, message, AWS_CHANNEL_DIR_WRITE)) {
675 AWS_LOGF_DEBUG(
676 AWS_LS_MQTT_CLIENT,
677 "id=%p: failed to send courteous disconnect io message",
678 (void *)connection);
679 aws_mem_release(message->allocator, message);
680 goto done;
681 }
682 }
683 }
684 }
685
686 done:
687 return aws_channel_slot_on_handler_shutdown_complete(slot, dir, error_code, free_scarce_resources_immediately);
688 }
689
690 static size_t s_initial_window_size(struct aws_channel_handler *handler) {
691
692 (void)handler;
693
694 return SIZE_MAX;
695 }
696
697 static void s_destroy(struct aws_channel_handler *handler) {
698
699 struct aws_mqtt_client_connection_311_impl *connection = handler->impl;
700 (void)connection;
701 }
702
703 static size_t s_message_overhead(struct aws_channel_handler *handler) {
704 (void)handler;
705 return 0;
706 }
707
708 struct aws_channel_handler_vtable *aws_mqtt_get_client_channel_vtable(void) {
709
710 static struct aws_channel_handler_vtable s_vtable = {
711 .process_read_message = &s_process_read_message,
712 .process_write_message = NULL,
713 .increment_read_window = NULL,
714 .shutdown = &s_shutdown,
715 .initial_window_size = &s_initial_window_size,
716 .message_overhead = &s_message_overhead,
717 .destroy = &s_destroy,
718 };
719
720 return &s_vtable;
721 }
722
723 /*******************************************************************************
724 * Helpers
725 ******************************************************************************/
726
727 struct aws_io_message *mqtt_get_message_for_packet(
728 struct aws_mqtt_client_connection_311_impl *connection,
729 struct aws_mqtt_fixed_header *header) {
730
731 const size_t required_length = 3 + header->remaining_length;
732
733 struct aws_io_message *message = aws_channel_acquire_message_from_pool(
734 connection->slot->channel, AWS_IO_MESSAGE_APPLICATION_DATA, required_length);
735
736 AWS_LOGF_TRACE(
737 AWS_LS_MQTT_CLIENT,
738 "id=%p: Acquiring memory from pool of required_length %zu",
739 (void *)connection,
740 required_length);
741
742 return message;
743 }
744
745 /*******************************************************************************
746 * Requests
747 ******************************************************************************/
748
749 /* Send the request */
750 static void s_request_outgoing_task(struct aws_channel_task *task, void *arg, enum aws_task_status status) {
751
752 struct aws_mqtt_request *request = arg;
753 struct aws_mqtt_client_connection_311_impl *connection = request->connection;
754
755 if (status == AWS_TASK_STATUS_CANCELED) {
756 /* Connection lost before the request ever get send, check the request needs to be retried or not */
757 if (request->retryable) {
758 AWS_LOGF_DEBUG(
759 AWS_LS_MQTT_CLIENT,
760 "static: task id %p, was canceled due to the channel shutting down. Request for packet id "
761 "%" PRIu16 ". will be retried",
762 (void *)task,
763 request->packet_id);
764
765 /* put it into the offline queue. */
766 { /* BEGIN CRITICAL SECTION */
767 mqtt_connection_lock_synced_data(connection);
768
769 /* Set the status as incomplete */
770 aws_mqtt_connection_statistics_change_operation_statistic_state(
771 connection, request, AWS_MQTT_OSS_INCOMPLETE);
772
773 aws_linked_list_push_back(&connection->synced_data.pending_requests_list, &request->list_node);
774
775 mqtt_connection_unlock_synced_data(connection);
776 } /* END CRITICAL SECTION */
777 } else {
778 AWS_LOGF_DEBUG(
779 AWS_LS_MQTT_CLIENT,
780 "static: task id %p, was canceled due to the channel shutting down. Request for packet id "
781 "%" PRIu16 ". will NOT be retried, will be cancelled",
782 (void *)task,
783 request->packet_id);
784
785 /* Fire the callback and clean up the memory, as the connection get destroyed. */
786 if (request->on_complete) {
787 request->on_complete(
788 &connection->base, request->packet_id, AWS_ERROR_MQTT_NOT_CONNECTED, request->on_complete_ud);
789 }
790
791 { /* BEGIN CRITICAL SECTION */
792 mqtt_connection_lock_synced_data(connection);
793
794 /* Cancel the request in the operation statistics */
795 aws_mqtt_connection_statistics_change_operation_statistic_state(connection, request, AWS_MQTT_OSS_NONE);
796
797 aws_hash_table_remove(
798 &connection->synced_data.outstanding_requests_table, &request->packet_id, NULL, NULL);
799 aws_memory_pool_release(&connection->synced_data.requests_pool, request);
800 mqtt_connection_unlock_synced_data(connection);
801 } /* END CRITICAL SECTION */
802 }
803 return;
804 }
805
806 /* Send the request */
807 enum aws_mqtt_client_request_state state =
808 request->send_request(request->packet_id, !request->initiated, request->send_request_ud);
809 /* Update the request send time.*/
810 s_update_request_send_time(request);
811 request->initiated = true;
812 int error_code = AWS_ERROR_SUCCESS;
813 switch (state) {
814 case AWS_MQTT_CLIENT_REQUEST_ERROR:
815 error_code = aws_last_error();
816 AWS_LOGF_ERROR(
817 AWS_LS_MQTT_CLIENT,
818 "id=%p: sending request %" PRIu16 " failed with error %d.",
819 (void *)request->connection,
820 request->packet_id,
821 error_code);
822 /* fall-thru */
823
824 case AWS_MQTT_CLIENT_REQUEST_COMPLETE:
825 AWS_LOGF_TRACE(
826 AWS_LS_MQTT_CLIENT,
827 "id=%p: sending request %" PRIu16 " complete, invoking on_complete callback.",
828 (void *)request->connection,
829 request->packet_id);
830
831 /* If the send_request function reports the request is complete,
832 * remove from the hash table and call the callback. */
833 if (request->on_complete) {
834 request->on_complete(&connection->base, request->packet_id, error_code, request->on_complete_ud);
835 }
836
837 { /* BEGIN CRITICAL SECTION */
838 mqtt_connection_lock_synced_data(connection);
839
840 /* Set the request as complete in the operation statistics */
841 aws_mqtt_connection_statistics_change_operation_statistic_state(
842 request->connection, request, AWS_MQTT_OSS_NONE);
843
844 aws_hash_table_remove(
845 &connection->synced_data.outstanding_requests_table, &request->packet_id, NULL, NULL);
846 aws_memory_pool_release(&connection->synced_data.requests_pool, request);
847 mqtt_connection_unlock_synced_data(connection);
848 } /* END CRITICAL SECTION */
849 break;
850
851 case AWS_MQTT_CLIENT_REQUEST_ONGOING:
852 AWS_LOGF_TRACE(
853 AWS_LS_MQTT_CLIENT,
854 "id=%p: request %" PRIu16 " sent, but waiting on an acknowledgement from peer.",
855 (void *)request->connection,
856 request->packet_id);
857
858 { /* BEGIN CRITICAL SECTION */
859 mqtt_connection_lock_synced_data(connection);
860
861 /* Set the request as incomplete and un-acked in the operation statistics */
862 aws_mqtt_connection_statistics_change_operation_statistic_state(
863 request->connection, request, AWS_MQTT_OSS_INCOMPLETE | AWS_MQTT_OSS_UNACKED);
864
865 mqtt_connection_unlock_synced_data(connection);
866 } /* END CRITICAL SECTION */
867
868 /* Put the request into the ongoing list */
869 aws_linked_list_push_back(&connection->thread_data.ongoing_requests_list, &request->list_node);
870 break;
871 }
872 }
873
874 uint16_t mqtt_create_request(
875 struct aws_mqtt_client_connection_311_impl *connection,
876 aws_mqtt_send_request_fn *send_request,
877 void *send_request_ud,
878 aws_mqtt_op_complete_fn *on_complete,
879 void *on_complete_ud,
880 bool noRetry,
881 uint64_t packet_size) {
882
883 AWS_ASSERT(connection);
884 AWS_ASSERT(send_request);
885 struct aws_mqtt_request *next_request = NULL;
886 bool should_schedule_task = false;
887 struct aws_channel *channel = NULL;
888 { /* BEGIN CRITICAL SECTION */
889 mqtt_connection_lock_synced_data(connection);
890 if (connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING) {
891 mqtt_connection_unlock_synced_data(connection);
892 /* User requested disconnecting, ensure no new requests are made until the channel finished shutting
893 * down. */
894 AWS_LOGF_ERROR(
895 AWS_LS_MQTT_CLIENT,
896 "id=%p: Disconnect requested, stop creating any new request until disconnect process finishes.",
897 (void *)connection);
898 aws_raise_error(AWS_ERROR_MQTT_CONNECTION_DISCONNECTING);
899 return 0;
900 }
901
902 if (noRetry && connection->synced_data.state != AWS_MQTT_CLIENT_STATE_CONNECTED) {
903 mqtt_connection_unlock_synced_data(connection);
904 /* Not offline queueing QoS 0 publish or PINGREQ. Fail the call. */
905 AWS_LOGF_DEBUG(
906 AWS_LS_MQTT_CLIENT,
907 "id=%p: Not currently connected. No offline queueing for QoS 0 publish or pingreq.",
908 (void *)connection);
909 aws_raise_error(AWS_ERROR_MQTT_NOT_CONNECTED);
910 return 0;
911 }
912 /**
913 * Find a free packet ID.
914 * QoS 0 PUBLISH packets don't actually need an ID on the wire,
915 * but we assign them internally anyway just so everything has a unique ID.
916 *
917 * Yes, this is an O(N) search.
918 * We remember the last ID we assigned, so it's O(1) in the common case.
919 * But it's theoretically possible to reach O(N) where N is just above 64000
920 * if the user is letting a ton of un-ack'd messages queue up
921 */
922 uint16_t search_start = connection->synced_data.packet_id;
923 struct aws_hash_element *elem = NULL;
924 while (true) {
925 /* Increment ID, watch out for overflow, ID cannot be 0 */
926 if (connection->synced_data.packet_id == UINT16_MAX) {
927 connection->synced_data.packet_id = 1;
928 } else {
929 connection->synced_data.packet_id++;
930 }
931
932 /* Is there already an outstanding request using this ID? */
933 aws_hash_table_find(
934 &connection->synced_data.outstanding_requests_table, &connection->synced_data.packet_id, &elem);
935
936 if (elem == NULL) {
937 /* Found a free ID! Break out of loop */
938 break;
939 } else if (connection->synced_data.packet_id == search_start) {
940 /* Every ID is taken */
941 mqtt_connection_unlock_synced_data(connection);
942 AWS_LOGF_ERROR(
943 AWS_LS_MQTT_CLIENT,
944 "id=%p: Queue is full. No more packet IDs are available at this time.",
945 (void *)connection);
946 aws_raise_error(AWS_ERROR_MQTT_QUEUE_FULL);
947 return 0;
948 }
949 }
950
951 next_request = aws_memory_pool_acquire(&connection->synced_data.requests_pool);
952 if (!next_request) {
953 mqtt_connection_unlock_synced_data(connection);
954 return 0;
955 }
956 memset(next_request, 0, sizeof(struct aws_mqtt_request));
957
958 next_request->packet_id = connection->synced_data.packet_id;
959
960 if (aws_hash_table_put(
961 &connection->synced_data.outstanding_requests_table, &next_request->packet_id, next_request, NULL)) {
962 /* failed to put the next request into the table */
963 aws_memory_pool_release(&connection->synced_data.requests_pool, next_request);
964 mqtt_connection_unlock_synced_data(connection);
965 return 0;
966 }
967 /* Store the request by packet_id */
968 next_request->allocator = connection->allocator;
969 next_request->connection = connection;
970 next_request->initiated = false;
971 next_request->retryable = !noRetry;
972 next_request->send_request = send_request;
973 next_request->send_request_ud = send_request_ud;
974 next_request->on_complete = on_complete;
975 next_request->on_complete_ud = on_complete_ud;
976 next_request->packet_size = packet_size;
977 aws_channel_task_init(
978 &next_request->outgoing_task, s_request_outgoing_task, next_request, "mqtt_outgoing_request_task");
979 if (connection->synced_data.state != AWS_MQTT_CLIENT_STATE_CONNECTED) {
980 aws_linked_list_push_back(&connection->synced_data.pending_requests_list, &next_request->list_node);
981 } else {
982 AWS_ASSERT(connection->slot);
983 AWS_ASSERT(connection->slot->channel);
984 should_schedule_task = true;
985 channel = connection->slot->channel;
986 /* keep the channel alive until the task is scheduled */
987 aws_channel_acquire_hold(channel);
988 }
989
990 if (next_request && next_request->packet_size > 0) {
991 /* Set the status as incomplete */
992 aws_mqtt_connection_statistics_change_operation_statistic_state(
993 next_request->connection, next_request, AWS_MQTT_OSS_INCOMPLETE);
994 }
995
996 mqtt_connection_unlock_synced_data(connection);
997 } /* END CRITICAL SECTION */
998
999 if (should_schedule_task) {
1000 AWS_LOGF_TRACE(
1001 AWS_LS_MQTT_CLIENT,
1002 "id=%p: Currently not in the event-loop thread, scheduling a task to send message id %" PRIu16 ".",
1003 (void *)connection,
1004 next_request->packet_id);
1005 aws_channel_schedule_task_now(channel, &next_request->outgoing_task);
1006 /* release the refcount we hold with the protection of lock */
1007 aws_channel_release_hold(channel);
1008 }
1009
1010 return next_request->packet_id;
1011 }
1012
1013 void mqtt_request_complete(struct aws_mqtt_client_connection_311_impl *connection, int error_code, uint16_t packet_id) {
1014
1015 AWS_LOGF_TRACE(
1016 AWS_LS_MQTT_CLIENT,
1017 "id=%p: message id %" PRIu16 " completed with error code %d, removing from outstanding requests list.",
1018 (void *)connection,
1019 packet_id,
1020 error_code);
1021
1022 bool found_request = false;
1023 aws_mqtt_op_complete_fn *on_complete = NULL;
1024 void *on_complete_ud = NULL;
1025
1026 { /* BEGIN CRITICAL SECTION */
1027 mqtt_connection_lock_synced_data(connection);
1028 struct aws_hash_element *elem = NULL;
1029 aws_hash_table_find(&connection->synced_data.outstanding_requests_table, &packet_id, &elem);
1030 if (elem != NULL) {
1031 found_request = true;
1032
1033 struct aws_mqtt_request *request = elem->value;
1034 on_complete = request->on_complete;
1035 on_complete_ud = request->on_complete_ud;
1036
1037 /* Set the status as complete */
1038 aws_mqtt_connection_statistics_change_operation_statistic_state(
1039 request->connection, request, AWS_MQTT_OSS_NONE);
1040
1041 if (error_code == AWS_OP_SUCCESS) {
1042 s_pushoff_next_ping_time(connection, request->request_send_timestamp);
1043 }
1044 /* clean up request resources */
1045 aws_hash_table_remove_element(&connection->synced_data.outstanding_requests_table, elem);
1046 /* remove the request from the list, which is thread_data.ongoing_requests_list */
1047 aws_linked_list_remove(&request->list_node);
1048 aws_memory_pool_release(&connection->synced_data.requests_pool, request);
1049 }
1050 mqtt_connection_unlock_synced_data(connection);
1051 } /* END CRITICAL SECTION */
1052
1053 if (!found_request) {
1054 AWS_LOGF_DEBUG(
1055 AWS_LS_MQTT_CLIENT,
1056 "id=%p: received completion for message id %" PRIu16
1057 " but no outstanding request exists. Assuming this is an ack of a resend when the first request has "
1058 "already completed.",
1059 (void *)connection,
1060 packet_id);
1061 return;
1062 }
1063
1064 /* Invoke the complete callback. */
1065 if (on_complete) {
1066 on_complete(&connection->base, packet_id, error_code, on_complete_ud);
1067 }
1068 }
1069
1070 struct mqtt_shutdown_task {
1071 int error_code;
1072 struct aws_channel_task task;
1073 };
1074
1075 static void s_mqtt_disconnect_task(struct aws_channel_task *channel_task, void *arg, enum aws_task_status status) {
1076
1077 (void)status;
1078
1079 struct mqtt_shutdown_task *task = AWS_CONTAINER_OF(channel_task, struct mqtt_shutdown_task, task);
1080 struct aws_mqtt_client_connection_311_impl *connection = arg;
1081
1082 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Doing disconnect", (void *)connection);
1083 { /* BEGIN CRITICAL SECTION */
1084 mqtt_connection_lock_synced_data(connection);
1085 /* If there is an outstanding reconnect task, cancel it */
1086 if (connection->synced_data.state == AWS_MQTT_CLIENT_STATE_DISCONNECTING && connection->reconnect_task) {
1087 aws_atomic_store_ptr(&connection->reconnect_task->connection_ptr, NULL);
1088 /* If the reconnect_task isn't scheduled, free it */
1089 if (connection->reconnect_task && !connection->reconnect_task->task.timestamp) {
1090 aws_mem_release(connection->reconnect_task->allocator, connection->reconnect_task);
1091 }
1092 connection->reconnect_task = NULL;
1093 }
1094 mqtt_connection_unlock_synced_data(connection);
1095 } /* END CRITICAL SECTION */
1096
1097 if (connection->slot && connection->slot->channel) {
1098 aws_channel_shutdown(connection->slot->channel, task->error_code);
1099 }
1100
1101 aws_mem_release(connection->allocator, task);
1102 }
1103
1104 void mqtt_disconnect_impl(struct aws_mqtt_client_connection_311_impl *connection, int error_code) {
1105 if (connection->slot) {
1106 struct mqtt_shutdown_task *shutdown_task =
1107 aws_mem_calloc(connection->allocator, 1, sizeof(struct mqtt_shutdown_task));
1108 shutdown_task->error_code = error_code;
1109 aws_channel_task_init(&shutdown_task->task, s_mqtt_disconnect_task, connection, "mqtt_disconnect");
1110 aws_channel_schedule_task_now(connection->slot->channel, &shutdown_task->task);
1111 } else {
1112 AWS_LOGF_TRACE(AWS_LS_MQTT_CLIENT, "id=%p: Client currently has no slot to disconnect", (void *)connection);
1113 }
1114 }