Debian Codegraph @

crt/aws-c-mqtt/include/aws/mqtt/private/client_impl.h

raw symbols SCIP
1 #ifndef AWS_MQTT_PRIVATE_CLIENT_IMPL_H
2 #define AWS_MQTT_PRIVATE_CLIENT_IMPL_H
3
4 /**
5 * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved.
6 * SPDX-License-Identifier: Apache-2.0.
7 */
8
9 #include <aws/mqtt/client.h>
10
11 #include <aws/mqtt/private/client_impl_shared.h>
12 #include <aws/mqtt/private/fixed_header.h>
13 #include <aws/mqtt/private/mqtt311_decoder.h>
14 #include <aws/mqtt/private/mqtt311_listener.h>
15 #include <aws/mqtt/private/topic_tree.h>
16
17 #include <aws/common/hash_table.h>
18 #include <aws/common/mutex.h>
19 #include <aws/common/rw_lock.h>
20 #include <aws/common/task_scheduler.h>
21
22 #include <aws/io/channel.h>
23 #include <aws/io/channel_bootstrap.h>
24 #include <aws/io/message_pool.h>
25 #include <aws/io/socket.h>
26 #include <aws/io/tls_channel_handler.h>
27
28 struct aws_mqtt_client_connection_311_impl;
29
30 #define MQTT_CLIENT_CALL_CALLBACK(client_ptr, callback) \
31 do { \
32 aws_rw_lock_rlock(&(client_ptr)->callback_lock); \
33 if ((client_ptr)->callback) { \
34 (client_ptr)->callback((&client_ptr->base), (client_ptr)->callback##_ud); \
35 } \
36 aws_rw_lock_runlock(&(client_ptr)->callback_lock); \
37 } while (false)
38 #define MQTT_CLIENT_CALL_CALLBACK_ARGS(client_ptr, callback, ...) \
39 do { \
40 aws_rw_lock_rlock(&(client_ptr)->callback_lock); \
41 if ((client_ptr)->callback) { \
42 (client_ptr)->callback((&client_ptr->base), __VA_ARGS__, (client_ptr)->callback##_ud); \
43 } \
44 aws_rw_lock_runlock(&(client_ptr)->callback_lock); \
45 } while (false)
46
47 #if ASSERT_LOCK_HELD
48 # define ASSERT_SYNCED_DATA_LOCK_HELD(object) \
49 { \
50 int cached_error = aws_last_error(); \
51 AWS_ASSERT(aws_mutex_try_lock(&(object)->synced_data.lock) == AWS_OP_ERR); \
52 aws_raise_error(cached_error); \
53 }
54 #else
55 # define ASSERT_SYNCED_DATA_LOCK_HELD(object)
56 #endif
57
58 enum aws_mqtt_client_connection_state {
59 AWS_MQTT_CLIENT_STATE_CONNECTING,
60 AWS_MQTT_CLIENT_STATE_CONNECTED,
61 AWS_MQTT_CLIENT_STATE_RECONNECTING,
62 AWS_MQTT_CLIENT_STATE_DISCONNECTING,
63 AWS_MQTT_CLIENT_STATE_DISCONNECTED,
64 };
65
66 enum aws_mqtt_client_request_state {
67 AWS_MQTT_CLIENT_REQUEST_ONGOING,
68 AWS_MQTT_CLIENT_REQUEST_COMPLETE,
69 AWS_MQTT_CLIENT_REQUEST_ERROR,
70 };
71
72 /**
73 * Contains some simple statistics about the current state of the connection's queue of operations
74 */
75 struct aws_mqtt_connection_operation_statistics_impl {
76 /**
77 * total number of operations submitted to the connection that have not yet been completed. Unacked operations
78 * are a subset of this.
79 */
80 struct aws_atomic_var incomplete_operation_count_atomic;
81
82 /**
83 * total packet size of operations submitted to the connection that have not yet been completed. Unacked operations
84 * are a subset of this.
85 */
86 struct aws_atomic_var incomplete_operation_size_atomic;
87
88 /**
89 * total number of operations that have been sent to the server and are waiting for a corresponding ACK before
90 * they can be completed.
91 */
92 struct aws_atomic_var unacked_operation_count_atomic;
93
94 /**
95 * total packet size of operations that have been sent to the server and are waiting for a corresponding ACK before
96 * they can be completed.
97 */
98 struct aws_atomic_var unacked_operation_size_atomic;
99 };
100
101 /**
102 * Called after the timeout if a matching ack packet hasn't arrived, with is_first_attempt set as false.
103 * Or called when the request packet attempt to send firstly, with is_first_attempt set as true.
104 * Return AWS_MQTT_CLIENT_REQUEST_ONGOING to check on the task later.
105 * Return AWS_MQTT_CLIENT_REQUEST_COMPLETE to consider request complete.
106 * Return AWS_MQTT_CLIENT_REQUEST_ERROR cancel the task and report an error to the caller.
107 */
108 typedef enum aws_mqtt_client_request_state(
109 aws_mqtt_send_request_fn)(uint16_t packet_id, bool is_first_attempt, void *userdata);
110
111 /**
112 * Called when the operation statistics change.
113 */
114 typedef void(
115 aws_mqtt_on_operation_statistics_fn)(struct aws_mqtt_client_connection_311_impl *connection, void *userdata);
116
117 /* Flags that indicate the way in which way an operation is currently affecting the statistics of the connection */
118 enum aws_mqtt_operation_statistic_state_flags {
119 /* The operation is not affecting the connection's statistics at all */
120 AWS_MQTT_OSS_NONE = 0,
121
122 /* The operation is affecting the connection's "incomplete operation" statistics */
123 AWS_MQTT_OSS_INCOMPLETE = 1 << 0,
124
125 /* The operation is affecting the connection's "unacked operation" statistics */
126 AWS_MQTT_OSS_UNACKED = 1 << 1,
127 };
128
129 struct aws_mqtt_request {
130 struct aws_linked_list_node list_node;
131
132 struct aws_allocator *allocator;
133 struct aws_mqtt_client_connection_311_impl *connection;
134
135 struct aws_channel_task outgoing_task;
136
137 /*
138 * The request send time. Currently used to push off keepalive packet.
139 */
140 uint64_t request_send_timestamp;
141
142 /* How this operation is currently affecting the statistics of the connection */
143 enum aws_mqtt_operation_statistic_state_flags statistic_state_flags;
144 /* The encoded size of the packet - used for operation statistics tracking */
145 uint64_t packet_size;
146
147 uint16_t packet_id;
148 bool retryable;
149 bool initiated;
150 aws_mqtt_send_request_fn *send_request;
151 void *send_request_ud;
152 aws_mqtt_op_complete_fn *on_complete;
153 void *on_complete_ud;
154 };
155
156 struct aws_mqtt_reconnect_task {
157 struct aws_task task;
158 struct aws_atomic_var connection_ptr;
159 struct aws_allocator *allocator;
160 };
161
162 struct request_timeout_wrapper;
163
164 /* used for timeout task */
165 struct request_timeout_task_arg {
166 uint16_t packet_id;
167 struct aws_mqtt_client_connection_311_impl *connection;
168 struct request_timeout_wrapper *task_arg_wrapper;
169 };
170
171 /*
172 * We want the timeout task to be able to destroy the forward reference from the operation's task arg structure
173 * to the timeout task. But the operation task arg structures don't have any data structure in common. So to allow
174 * the timeout to refer back to a zero-able forward pointer, we wrap a pointer to the timeout task and embed it
175 * in every operation's task arg that needs to create a timeout.
176 */
177 struct request_timeout_wrapper {
178 struct request_timeout_task_arg *timeout_task_arg;
179 };
180
181 /* The lifetime of this struct is from subscribe -> suback */
182 struct subscribe_task_arg {
183
184 struct aws_mqtt_client_connection_311_impl *connection;
185
186 /* list of pointer of subscribe_task_topics */
187 struct aws_array_list topics;
188
189 /* Packet to populate */
190 struct aws_mqtt_packet_subscribe subscribe;
191
192 /* true if transaction was committed to the topic tree, false requires a retry */
193 bool tree_updated;
194
195 struct {
196 aws_mqtt_suback_multi_fn *multi;
197 aws_mqtt_suback_fn *single;
198 } on_suback;
199 void *on_suback_ud;
200
201 struct request_timeout_wrapper timeout_wrapper;
202 uint64_t timeout_duration_in_ns;
203 };
204
205 /* The lifetime of this struct is the same as the lifetime of the subscription */
206 struct subscribe_task_topic {
207 struct aws_mqtt_client_connection_311_impl *connection;
208
209 struct aws_mqtt_topic_subscription request;
210 struct aws_string *filter;
211
212 struct aws_ref_count ref_count;
213 };
214
215 struct aws_mqtt_client_connection_311_impl {
216 struct aws_allocator *allocator;
217
218 struct aws_mqtt_client_connection base;
219
220 struct aws_ref_count ref_count;
221
222 struct aws_mqtt_client *client;
223
224 /* Channel handler information */
225 struct aws_channel_handler handler;
226 struct aws_channel_slot *slot;
227
228 /* The host information, changed by user when state is AWS_MQTT_CLIENT_STATE_DISCONNECTED */
229 struct aws_string *host_name;
230 uint32_t port;
231 struct aws_tls_connection_options tls_options;
232 struct aws_socket_options socket_options;
233 struct aws_http_proxy_config *http_proxy_config;
234 struct aws_event_loop *loop;
235 struct aws_host_resolution_config host_resolution_config;
236
237 /* Connect parameters */
238 struct aws_byte_buf client_id;
239 bool clean_session;
240 uint16_t keep_alive_time_secs;
241 uint64_t keep_alive_time_ns;
242 uint64_t ping_timeout_ns;
243 uint64_t operation_timeout_ns;
244 struct aws_string *username;
245 struct aws_string *password;
246 struct {
247 struct aws_byte_buf topic;
248 enum aws_mqtt_qos qos;
249 bool retain;
250 struct aws_byte_buf payload;
251 } will;
252 struct {
253 uint64_t current_sec; /* seconds */
254 uint64_t min_sec; /* seconds */
255 uint64_t max_sec; /* seconds */
256
257 /*
258 * Invariant: this is always zero except when the current MQTT channel has received a successful connack
259 * and is not yet shutdown. During that interval, it is the timestamp the connack was received.
260 */
261 uint64_t channel_successful_connack_timestamp_ns;
262 } reconnect_timeouts;
263
264 /* User connection callbacks */
265 aws_mqtt_client_on_connection_complete_fn *on_connection_complete;
266 void *on_connection_complete_ud;
267 aws_mqtt_client_on_connection_success_fn *on_connection_success;
268 void *on_connection_success_ud;
269 aws_mqtt_client_on_connection_failure_fn *on_connection_failure;
270 void *on_connection_failure_ud;
271 aws_mqtt_client_on_connection_interrupted_fn *on_interrupted;
272 void *on_interrupted_ud;
273 aws_mqtt_client_on_connection_resumed_fn *on_resumed;
274 void *on_resumed_ud;
275 aws_mqtt_client_on_connection_closed_fn *on_closed;
276 void *on_closed_ud;
277 aws_mqtt_client_publish_received_fn *on_any_publish;
278 void *on_any_publish_ud;
279 aws_mqtt_client_on_disconnect_fn *on_disconnect;
280 void *on_disconnect_ud;
281 aws_mqtt_client_on_connection_termination_fn *on_termination;
282 void *on_termination_ud;
283 aws_mqtt_on_operation_statistics_fn *on_any_operation_statistics;
284 void *on_any_operation_statistics_ud;
285
286 /* Read-write lock to protect callbacks from being modified during callback execution */
287 struct aws_rw_lock callback_lock;
288
289 /* listener callbacks */
290 struct aws_mqtt311_callback_set_manager callback_manager;
291
292 /* Connection tasks. */
293 struct aws_mqtt_reconnect_task *reconnect_task;
294 struct aws_channel_task ping_task;
295
296 /**
297 * Number of times this connection has successfully CONNACK-ed, used
298 * to ensure on_connection_completed is sent on the first completed
299 * CONNECT/CONNACK cycle
300 */
301 size_t connection_count;
302 bool use_tls; /* Only used by main thread */
303
304 /* Only the event-loop thread may touch this data */
305 struct {
306 struct aws_mqtt311_decoder decoder;
307
308 bool waiting_on_ping_response;
309
310 /* Keeps track of all open subscriptions */
311 /* TODO: The subscriptions are liveing with the connection object. So if the connection disconnect from one
312 * endpoint and connect with another endpoint, the subscription tree will still be the same as before. */
313 struct aws_mqtt_topic_tree subscriptions;
314
315 /**
316 * List of all requests waiting for response.
317 */
318 struct aws_linked_list ongoing_requests_list;
319 } thread_data;
320
321 /* Any thread may touch this data, but the lock must be held (unless it's an atomic) */
322 struct {
323 /* Note: never fire user callback with lock hold. */
324 struct aws_mutex lock;
325
326 /* The state of the connection */
327 enum aws_mqtt_client_connection_state state;
328
329 /**
330 * Memory pool for all aws_mqtt_request.
331 */
332 struct aws_memory_pool requests_pool;
333
334 /**
335 * Store all requests that is not completed including the pending requests.
336 *
337 * hash table from uint16_t (packet_id) to aws_mqtt_outstanding_request
338 */
339 struct aws_hash_table outstanding_requests_table;
340
341 /**
342 * List of all requests that cannot be scheduled until the connection comes online.
343 */
344 struct aws_linked_list pending_requests_list;
345
346 /**
347 * Remember the last packet ID assigned.
348 * Helps us find the next free ID faster.
349 */
350 uint16_t packet_id;
351
352 } synced_data;
353
354 struct {
355 aws_mqtt_transform_websocket_handshake_fn *handshake_transformer;
356 void *handshake_transformer_ud;
357 aws_mqtt_validate_websocket_handshake_fn *handshake_validator;
358 void *handshake_validator_ud;
359 bool enabled;
360
361 struct aws_http_message *handshake_request;
362 } websocket;
363
364 /**
365 * The time that the next ping task should execute at. Note that this does not mean that
366 * this IS when the ping task will execute, but rather that this is when the next ping
367 * SHOULD execute. There may be an already scheduled PING task that will elapse sooner
368 * than this time that has to be rescheduled.
369 */
370 uint64_t next_ping_time;
371
372 /**
373 * Statistics tracking operational state
374 */
375 struct aws_mqtt_connection_operation_statistics_impl operation_statistics_impl;
376
377 /**
378 * IoT SDK metrics configuration
379 */
380 struct aws_mqtt_iot_metrics_storage *metrics_storage;
381 };
382
383 struct aws_channel_handler_vtable *aws_mqtt_get_client_channel_vtable(void);
384
385 /* Helper for getting a message object for a packet */
386 struct aws_io_message *mqtt_get_message_for_packet(
387 struct aws_mqtt_client_connection_311_impl *connection,
388 struct aws_mqtt_fixed_header *header);
389
390 void mqtt_connection_lock_synced_data(struct aws_mqtt_client_connection_311_impl *connection);
391 void mqtt_connection_unlock_synced_data(struct aws_mqtt_client_connection_311_impl *connection);
392
393 /* Note: needs to be called with lock held. */
394 void mqtt_connection_set_state(
395 struct aws_mqtt_client_connection_311_impl *connection,
396 enum aws_mqtt_client_connection_state state);
397
398 /**
399 * This function registers a new outstanding request and returns the message identifier to use (or 0 on error).
400 * send_request will be called from request_timeout_task if everything succeed. Not called with error.
401 * on_complete will be called once the request completed, either either in success or error.
402 * noRetry is true for the packets will never be retried or offline queued.
403 */
404 AWS_MQTT_API uint16_t mqtt_create_request(
405 struct aws_mqtt_client_connection_311_impl *connection,
406 aws_mqtt_send_request_fn *send_request,
407 void *send_request_ud,
408 aws_mqtt_op_complete_fn *on_complete,
409 void *on_complete_ud,
410 bool noRetry,
411 uint64_t packet_size);
412
413 /* Call when an ack packet comes back from the server. */
414 AWS_MQTT_API void mqtt_request_complete(
415 struct aws_mqtt_client_connection_311_impl *connection,
416 int error_code,
417 uint16_t packet_id);
418
419 /* Call to close the connection with an error code */
420 AWS_MQTT_API void mqtt_disconnect_impl(struct aws_mqtt_client_connection_311_impl *connection, int error_code);
421
422 /* Creates the task used to reestablish a broken connection */
423 AWS_MQTT_API void aws_create_reconnect_task(struct aws_mqtt_client_connection_311_impl *connection);
424
425 /**
426 * Sets the callback to call whenever the operation statistics change.
427 *
428 * \param[in] connection The connection object
429 * \param[in] on_operation_statistics The function to call when the operation statistics change (pass NULL to unset)
430 * \param[in] on_operation_statistics_ud Userdata for on_operation_statistics
431 */
432 AWS_MQTT_API int aws_mqtt_client_connection_set_on_operation_statistics_handler(
433 struct aws_mqtt_client_connection_311_impl *connection,
434 aws_mqtt_on_operation_statistics_fn *on_operation_statistics,
435 void *on_operation_statistics_ud);
436
437 /*
438 * Sends a PINGREQ packet to the server to keep the connection alive. This is not exported and should not ever
439 * be called directly. This function is driven by the timeout values passed to aws_mqtt_client_connect().
440 * If a PINGRESP is not received within a reasonable period of time, the connection will be closed.
441 *
442 * \params[in] connection The connection to ping on
443 *
444 * \returns AWS_OP_SUCCESS if the connection is open and the PINGREQ is sent or queued to send,
445 * otherwise AWS_OP_ERR and aws_last_error() is set.
446 */
447 int aws_mqtt_client_connection_ping(struct aws_mqtt_client_connection_311_impl *connection);
448
449 /**
450 * Changes the operation statistics for the passed-in aws_mqtt_request. Used for tracking
451 * whether operations have been completed or not.
452 *
453 * NOTE: This function will get lock the synced data! Do NOT call with the synced data already
454 * held or the function will deadlock trying to get the lock
455 *
456 * @param connection The connection whose operations are being tracked
457 * @param request The request to change the state of
458 * @param new_state_flags The new state to use
459 */
460 void aws_mqtt_connection_statistics_change_operation_statistic_state(
461 struct aws_mqtt_client_connection_311_impl *connection,
462 struct aws_mqtt_request *request,
463 enum aws_mqtt_operation_statistic_state_flags new_state_flags);
464
465 AWS_MQTT_API const struct aws_mqtt_client_connection_packet_handlers *aws_mqtt311_get_default_packet_handlers(void);
466
467 AWS_MQTT_API uint16_t aws_mqtt_client_connection_311_unsubscribe(
468 struct aws_mqtt_client_connection_311_impl *connection,
469 const struct aws_byte_cursor *topic_filter,
470 aws_mqtt_op_complete_fn *on_unsuback,
471 void *on_unsuback_ud,
472 uint64_t timeout_ns);
473
474 AWS_MQTT_API uint16_t aws_mqtt_client_connection_311_subscribe(
475 struct aws_mqtt_client_connection_311_impl *connection,
476 const struct aws_byte_cursor *topic_filter,
477 enum aws_mqtt_qos qos,
478 aws_mqtt_client_publish_received_fn *on_publish,
479 void *on_publish_ud,
480 aws_mqtt_userdata_cleanup_fn *on_ud_cleanup,
481 aws_mqtt_suback_fn *on_suback,
482 void *on_suback_ud,
483 uint64_t timeout_ns);
484
485 AWS_MQTT_API uint16_t aws_mqtt_client_connection_311_publish(
486 struct aws_mqtt_client_connection_311_impl *connection,
487 const struct aws_byte_cursor *topic,
488 enum aws_mqtt_qos qos,
489 bool retain,
490 const struct aws_byte_cursor *payload,
491 aws_mqtt_op_complete_fn *on_complete,
492 void *userdata,
493 uint64_t timeout_ns);
494
495 #endif /* AWS_MQTT_PRIVATE_CLIENT_IMPL_H */