Debian Codegraph @

crt/aws-c-mqtt/bin/elastishadow/main.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/common/command_line_parser.h>
7 #include <aws/common/condition_variable.h>
8 #include <aws/common/hash_table.h>
9 #include <aws/common/log_channel.h>
10 #include <aws/common/mutex.h>
11 #include <aws/common/string.h>
12 #include <aws/common/uuid.h>
13
14 #include <aws/io/channel_bootstrap.h>
15 #include <aws/io/event_loop.h>
16 #include <aws/io/socket.h>
17 #include <aws/io/tls_channel_handler.h>
18 #include <aws/io/uri.h>
19
20 #include <aws/mqtt/private/shared.h>
21 #include <aws/mqtt/request-response/request_response_client.h>
22 #include <aws/mqtt/v5/mqtt5_client.h>
23 #include <aws/mqtt/v5/mqtt5_types.h>
24
25 #include <inttypes.h>
26
27 #ifdef _MSC_VER
28 # pragma warning(disable : 4996) /* Disable warnings about fopen() being insecure */
29 # pragma warning(disable : 4204) /* Declared initializers */
30 # pragma warning(disable : 4221) /* Local var in declared initializer */
31 #endif
32
33 #ifdef WIN32
34 // Windows does not need specific imports
35 #else
36 # include <stdio.h>
37 #endif
38
39 struct app_ctx {
40 struct aws_allocator *allocator;
41 struct aws_mutex lock;
42 struct aws_condition_variable signal;
43 struct aws_uri uri;
44 uint32_t port;
45 const char *cert;
46 const char *key;
47
48 struct aws_tls_connection_options tls_connection_options;
49
50 const char *log_filename;
51 enum aws_log_level log_level;
52
53 struct aws_mqtt5_client *client;
54 struct aws_mqtt_request_response_client *rr_client;
55
56 /*
57 * &aws_shadow_streaming_operation.id -> aws_shadow_streaming_operation *
58 */
59 struct aws_hash_table streaming_operations;
60 uint64_t next_id;
61 };
62
63 struct aws_shadow_streaming_operation {
64 struct aws_allocator *allocator;
65
66 struct aws_byte_buf thing;
67 struct aws_byte_buf shadow;
68 struct aws_byte_buf topic_filter;
69
70 uint64_t id;
71 struct aws_mqtt_rr_client_operation *streaming_operation;
72 };
73
74 struct aws_shadow_streaming_operation *s_aws_shadow_streaming_operation_new(
75 struct aws_allocator *allocator,
76 struct app_ctx *app_ctx,
77 struct aws_byte_cursor thing,
78 struct aws_byte_cursor shadow,
79 struct aws_byte_cursor topic_filter) {
80 struct aws_shadow_streaming_operation *operation =
81 aws_mem_calloc(allocator, 1, sizeof(struct aws_shadow_streaming_operation));
82
83 operation->allocator = allocator;
84 operation->id = ++app_ctx->next_id;
85 operation->streaming_operation = NULL;
86
87 aws_byte_buf_init_copy_from_cursor(&operation->thing, allocator, thing);
88 aws_byte_buf_init_copy_from_cursor(&operation->shadow, allocator, shadow);
89 aws_byte_buf_init_copy_from_cursor(&operation->topic_filter, allocator, topic_filter);
90
91 return operation;
92 }
93
94 void s_aws_shadow_streaming_operation_destroy(struct aws_shadow_streaming_operation *operation) {
95 if (operation == NULL) {
96 return;
97 }
98
99 aws_byte_buf_clean_up(&operation->thing);
100 aws_byte_buf_clean_up(&operation->shadow);
101 aws_byte_buf_clean_up(&operation->topic_filter);
102
103 aws_mem_release(operation->allocator, operation);
104 }
105
106 static void s_release_streaming_operation(void *value) {
107 struct aws_shadow_streaming_operation *operation = value;
108
109 if (operation->streaming_operation != NULL) {
110 aws_mqtt_rr_client_operation_release(operation->streaming_operation);
111 } else {
112 s_aws_shadow_streaming_operation_destroy(operation);
113 }
114 }
115
116 static void s_usage(int exit_code) {
117
118 fprintf(stderr, "usage: elastishadow [options] endpoint\n");
119 fprintf(stderr, " endpoint: url to connect to\n");
120 fprintf(stderr, "\n Options:\n\n");
121 fprintf(stderr, " --cert FILE: path to a PEM encoded certificate to use with mTLS\n");
122 fprintf(stderr, " --key FILE: Path to a PEM encoded private key that matches cert.\n");
123 fprintf(stderr, " -l, --log FILE: dumps logs to FILE instead of stderr.\n");
124 fprintf(stderr, " -v, --verbose: ERROR|INFO|DEBUG|TRACE: log level to configure. Default is none.\n");
125 fprintf(stderr, " -h, --help\n");
126 fprintf(stderr, " Display this message and quit.\n");
127 exit(exit_code);
128 }
129
130 static struct aws_cli_option s_long_options[] = {
131 {"cert", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'c'},
132 {"key", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'e'},
133 {"log", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'l'},
134 {"verbose", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'v'},
135 {"help", AWS_CLI_OPTIONS_NO_ARGUMENT, NULL, 'h'},
136 /* Per getopt(3) the last element of the array has to be filled with all zeros */
137 {NULL, AWS_CLI_OPTIONS_NO_ARGUMENT, NULL, 0},
138 };
139
140 static void s_parse_options(int argc, char **argv, struct app_ctx *ctx) {
141 bool uri_found = false;
142
143 while (true) {
144 int option_index = 0;
145 int c = aws_cli_getopt_long(argc, argv, "c:e:l:v:h", s_long_options, &option_index);
146 if (c == -1) {
147 break;
148 }
149
150 switch (c) {
151 case 0:
152 /* getopt_long() returns 0 if an option.flag is non-null */
153 break;
154 case 'c':
155 ctx->cert = aws_cli_optarg;
156 break;
157 case 'e':
158 ctx->key = aws_cli_optarg;
159 break;
160 case 'l':
161 ctx->log_filename = aws_cli_optarg;
162 break;
163 case 'v':
164 if (!strcmp(aws_cli_optarg, "TRACE")) {
165 ctx->log_level = AWS_LL_TRACE;
166 } else if (!strcmp(aws_cli_optarg, "INFO")) {
167 ctx->log_level = AWS_LL_INFO;
168 } else if (!strcmp(aws_cli_optarg, "DEBUG")) {
169 ctx->log_level = AWS_LL_DEBUG;
170 } else if (!strcmp(aws_cli_optarg, "ERROR")) {
171 ctx->log_level = AWS_LL_ERROR;
172 } else {
173 fprintf(stderr, "unsupported log level %s.\n", aws_cli_optarg);
174 s_usage(1);
175 }
176 break;
177 case 'h':
178 s_usage(0);
179 break;
180 case 0x02: {
181 struct aws_byte_cursor uri_cursor = aws_byte_cursor_from_c_str(aws_cli_positional_arg);
182 if (aws_uri_init_parse(&ctx->uri, ctx->allocator, &uri_cursor)) {
183 fprintf(
184 stderr,
185 "Failed to parse uri %s with error %s\n",
186 (char *)uri_cursor.ptr,
187 aws_error_debug_str(aws_last_error()));
188 s_usage(1);
189 }
190 uri_found = true;
191 break;
192 }
193
194 default:
195 fprintf(stderr, "Unknown option\n");
196 s_usage(1);
197 }
198 }
199
200 if (!uri_found) {
201 fprintf(stderr, "A URI for the request must be supplied.\n");
202 s_usage(1);
203 }
204 }
205
206 static bool s_skip_whitespace(uint8_t value) {
207 return value == '\n' || value == '\r' || value == '\t' || value == ' ';
208 }
209
210 static void s_split_command_line(struct aws_byte_cursor cursor, struct aws_array_list *words) {
211 struct aws_byte_cursor split_cursor;
212 AWS_ZERO_STRUCT(split_cursor);
213
214 while (aws_byte_cursor_next_split(&cursor, ' ', &split_cursor)) {
215 struct aws_byte_cursor word_cursor = aws_byte_cursor_trim_pred(&split_cursor, &s_skip_whitespace);
216 if (word_cursor.len > 0) {
217 aws_array_list_push_back(words, &word_cursor);
218 }
219 }
220 }
221
222 static void s_write_correlation_token_string(struct aws_byte_cursor scratch_space) {
223 struct aws_byte_buf correlation_token_buf = aws_byte_buf_from_empty_array(scratch_space.ptr, scratch_space.len);
224
225 struct aws_uuid uuid;
226 aws_uuid_init(&uuid);
227 aws_uuid_to_str(&uuid, &correlation_token_buf);
228 }
229
230 static void s_on_get_shadow_complete(
231 const struct aws_mqtt_rr_incoming_publish_event *publish_event,
232 int error_code,
233 void *user_data) {
234
235 struct aws_string *correlation_token = user_data;
236
237 if (publish_event != NULL) {
238 printf(
239 "GetNamedShadow request '%s' response received on topic '" PRInSTR "' with body:\n " PRInSTR "\n\n",
240 correlation_token->bytes,
241 AWS_BYTE_CURSOR_PRI(publish_event->topic),
242 AWS_BYTE_CURSOR_PRI(publish_event->payload));
243 } else {
244 printf(
245 "GetNamedShadow request '%s' failed with error code %d(%s)\n\n",
246 correlation_token->bytes,
247 error_code,
248 aws_error_debug_str(error_code));
249 }
250
251 aws_string_destroy(correlation_token);
252 }
253
254 static void s_handle_get(struct app_ctx *context, struct aws_allocator *allocator, struct aws_array_list *arguments) {
255
256 size_t argument_count = aws_array_list_length(arguments) - 1;
257 if (argument_count != 2) {
258 printf("invalid get-named-shadow options:\n");
259 printf(" get-named-shadow <thing-name> <shadow-name>\n\n");
260 return;
261 }
262
263 struct aws_byte_cursor thing_name_cursor;
264 AWS_ZERO_STRUCT(thing_name_cursor);
265 aws_array_list_get_at(arguments, &thing_name_cursor, 1);
266
267 struct aws_byte_cursor shadow_name_cursor;
268 AWS_ZERO_STRUCT(shadow_name_cursor);
269 aws_array_list_get_at(arguments, &shadow_name_cursor, 2);
270
271 char subscription_topic_filter[128];
272 snprintf(
273 subscription_topic_filter,
274 AWS_ARRAY_SIZE(subscription_topic_filter),
275 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/get/+",
276 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
277 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
278 struct aws_byte_cursor subscription_topic_filter_cursor = aws_byte_cursor_from_c_str(subscription_topic_filter);
279
280 char accepted_path[128];
281 snprintf(
282 accepted_path,
283 AWS_ARRAY_SIZE(accepted_path),
284 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/get/accepted",
285 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
286 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
287
288 char rejected_path[128];
289 snprintf(
290 rejected_path,
291 AWS_ARRAY_SIZE(rejected_path),
292 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/get/rejected",
293 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
294 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
295
296 struct aws_byte_cursor correlation_token_path = aws_byte_cursor_from_c_str("clientToken");
297 struct aws_mqtt_request_operation_response_path response_paths[] = {
298 {
299 .topic = aws_byte_cursor_from_c_str(accepted_path),
300 .correlation_token_json_path = correlation_token_path,
301 },
302 {
303 .topic = aws_byte_cursor_from_c_str(rejected_path),
304 .correlation_token_json_path = correlation_token_path,
305 },
306 };
307
308 char publish_topic[128];
309 snprintf(
310 publish_topic,
311 AWS_ARRAY_SIZE(publish_topic),
312 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/get",
313 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
314 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
315
316 char correlation_token[128];
317 s_write_correlation_token_string(aws_byte_cursor_from_array(correlation_token, AWS_ARRAY_SIZE(correlation_token)));
318 struct aws_string *correlation_token_string = aws_string_new_from_c_str(allocator, correlation_token);
319
320 char request[256];
321 snprintf(request, AWS_ARRAY_SIZE(request), "{\"clientToken\":\"%s\"}", correlation_token);
322
323 struct aws_mqtt_request_operation_options get_options = {
324 .subscription_topic_filters = &subscription_topic_filter_cursor,
325 .subscription_topic_filter_count = 1,
326 .response_paths = response_paths,
327 .response_path_count = 2,
328 .publish_topic = aws_byte_cursor_from_c_str(publish_topic),
329 .serialized_request = aws_byte_cursor_from_c_str(request),
330 .correlation_token = aws_byte_cursor_from_c_str(correlation_token),
331 .completion_callback = s_on_get_shadow_complete,
332 .user_data = correlation_token_string,
333 };
334
335 printf(
336 "Submitting GetNamedShadow request for shadow '" PRInSTR "' of thing '" PRInSTR
337 "' using correlation token %s...\n",
338 AWS_BYTE_CURSOR_PRI(shadow_name_cursor),
339 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
340 correlation_token);
341
342 if (aws_mqtt_request_response_client_submit_request(context->rr_client, &get_options) == AWS_OP_ERR) {
343 int error_code = aws_last_error();
344 printf("GetNamedShadow synchronous failure: %d(%s)\n", error_code, aws_error_debug_str(error_code));
345 aws_string_destroy(correlation_token_string);
346 }
347
348 printf("\n");
349 }
350
351 static void s_on_update_shadow_complete(
352 const struct aws_mqtt_rr_incoming_publish_event *publish_event,
353 int error_code,
354 void *user_data) {
355
356 struct aws_string *correlation_token = user_data;
357
358 if (publish_event != NULL) {
359 printf(
360 "UpdateNamedShadow request '%s' response received on topic '" PRInSTR "' with body:\n " PRInSTR "\n\n",
361 correlation_token->bytes,
362 AWS_BYTE_CURSOR_PRI(publish_event->topic),
363 AWS_BYTE_CURSOR_PRI(publish_event->payload));
364 } else {
365 printf(
366 "UpdateNamedShadow request '%s' failed with error code %d(%s)\n\n",
367 correlation_token->bytes,
368 error_code,
369 aws_error_debug_str(error_code));
370 }
371
372 aws_string_destroy(correlation_token);
373 }
374
375 static void s_handle_update(
376 struct app_ctx *context,
377 struct aws_allocator *allocator,
378 struct aws_array_list *arguments,
379 struct aws_byte_cursor desired_state,
380 struct aws_byte_cursor correlation_token) {
381
382 struct aws_byte_cursor thing_name_cursor;
383 AWS_ZERO_STRUCT(thing_name_cursor);
384 aws_array_list_get_at(arguments, &thing_name_cursor, 1);
385
386 struct aws_byte_cursor shadow_name_cursor;
387 AWS_ZERO_STRUCT(shadow_name_cursor);
388 aws_array_list_get_at(arguments, &shadow_name_cursor, 2);
389
390 char subscription_topic_filter_accepted[128];
391 snprintf(
392 subscription_topic_filter_accepted,
393 AWS_ARRAY_SIZE(subscription_topic_filter_accepted),
394 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/update/accepted",
395 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
396 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
397 struct aws_byte_cursor subscription_topic_filter_accepted_cursor =
398 aws_byte_cursor_from_c_str(subscription_topic_filter_accepted);
399
400 char subscription_topic_filter_rejected[128];
401 snprintf(
402 subscription_topic_filter_rejected,
403 AWS_ARRAY_SIZE(subscription_topic_filter_rejected),
404 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/update/rejected",
405 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
406 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
407 struct aws_byte_cursor subscription_topic_filter_rejected_cursor =
408 aws_byte_cursor_from_c_str(subscription_topic_filter_rejected);
409
410 struct aws_byte_cursor subscription_topic_filters[] = {
411 subscription_topic_filter_accepted_cursor,
412 subscription_topic_filter_rejected_cursor,
413 };
414
415 char accepted_path[128];
416 snprintf(
417 accepted_path,
418 AWS_ARRAY_SIZE(accepted_path),
419 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/update/accepted",
420 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
421 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
422
423 char rejected_path[128];
424 snprintf(
425 rejected_path,
426 AWS_ARRAY_SIZE(rejected_path),
427 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/update/rejected",
428 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
429 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
430
431 struct aws_byte_cursor correlation_token_path = aws_byte_cursor_from_c_str("clientToken");
432 struct aws_mqtt_request_operation_response_path response_paths[] = {
433 {
434 .topic = aws_byte_cursor_from_c_str(accepted_path),
435 .correlation_token_json_path = correlation_token_path,
436 },
437 {
438 .topic = aws_byte_cursor_from_c_str(rejected_path),
439 .correlation_token_json_path = correlation_token_path,
440 },
441 };
442
443 char publish_topic[128];
444 snprintf(
445 publish_topic,
446 AWS_ARRAY_SIZE(publish_topic),
447 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/update",
448 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
449 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
450
451 struct aws_string *correlation_token_string = aws_string_new_from_cursor(allocator, &correlation_token);
452
453 struct aws_mqtt_request_operation_options get_options = {
454 .subscription_topic_filters = subscription_topic_filters,
455 .subscription_topic_filter_count = 2,
456 .response_paths = response_paths,
457 .response_path_count = 2,
458 .publish_topic = aws_byte_cursor_from_c_str(publish_topic),
459 .serialized_request = desired_state,
460 .correlation_token = correlation_token,
461 .completion_callback = s_on_update_shadow_complete,
462 .user_data = correlation_token_string,
463 };
464
465 printf(
466 "Submitting UpdateNamedShadow request for shadow '" PRInSTR "' of thing '" PRInSTR
467 "' using correlation token '" PRInSTR "'...\n",
468 AWS_BYTE_CURSOR_PRI(shadow_name_cursor),
469 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
470 AWS_BYTE_CURSOR_PRI(correlation_token));
471
472 if (aws_mqtt_request_response_client_submit_request(context->rr_client, &get_options) == AWS_OP_ERR) {
473 int error_code = aws_last_error();
474 printf("UpdateNamedShadow synchronous failure: %d(%s)\n", error_code, aws_error_debug_str(error_code));
475 aws_string_destroy(correlation_token_string);
476 }
477
478 printf("\n");
479 }
480
481 static void s_handle_update_desired(
482 struct app_ctx *context,
483 struct aws_allocator *allocator,
484 struct aws_array_list *arguments,
485 struct aws_byte_cursor line_cursor) {
486
487 size_t argument_count = aws_array_list_length(arguments) - 1;
488 if (argument_count < 3) {
489 printf("invalid update-named-shadow-desired options:\n");
490 printf(" update-named-shadow-desired <thing-name> <shadow-name> <desired state JSON blob>\n\n");
491 return;
492 }
493
494 struct aws_byte_cursor desired_state_cursor;
495 aws_array_list_get_at(arguments, &desired_state_cursor, 3);
496 desired_state_cursor.len = (size_t)(line_cursor.ptr + line_cursor.len - desired_state_cursor.ptr);
497
498 char correlation_token[128];
499 s_write_correlation_token_string(aws_byte_cursor_from_array(correlation_token, AWS_ARRAY_SIZE(correlation_token)));
500
501 char request[256];
502 snprintf(
503 request,
504 AWS_ARRAY_SIZE(request),
505 "{\"clientToken\":\"%s\",\"state\":{\"desired\":" PRInSTR "}}",
506 correlation_token,
507 AWS_BYTE_CURSOR_PRI(desired_state_cursor));
508
509 s_handle_update(
510 context,
511 allocator,
512 arguments,
513 aws_byte_cursor_from_c_str(request),
514 aws_byte_cursor_from_c_str(correlation_token));
515 }
516
517 static void s_handle_update_reported(
518 struct app_ctx *context,
519 struct aws_allocator *allocator,
520 struct aws_array_list *arguments,
521 struct aws_byte_cursor line_cursor) {
522
523 size_t argument_count = aws_array_list_length(arguments) - 1;
524 if (argument_count < 3) {
525 printf("invalid update-named-shadow-reported options:\n");
526 printf(" update-named-shadow-reported <thing-name> <shadow-name> <reported state JSON blob>\n\n");
527 return;
528 }
529
530 struct aws_byte_cursor reported_state_cursor;
531 aws_array_list_get_at(arguments, &reported_state_cursor, 3);
532 reported_state_cursor.len = (size_t)(line_cursor.ptr + line_cursor.len - reported_state_cursor.ptr);
533
534 char correlation_token[128];
535 s_write_correlation_token_string(aws_byte_cursor_from_array(correlation_token, AWS_ARRAY_SIZE(correlation_token)));
536
537 char request[256];
538 snprintf(
539 request,
540 AWS_ARRAY_SIZE(request),
541 "{\"clientToken\":\"%s\",\"state\":{\"reported\":" PRInSTR "}}",
542 correlation_token,
543 AWS_BYTE_CURSOR_PRI(reported_state_cursor));
544
545 s_handle_update(
546 context,
547 allocator,
548 arguments,
549 aws_byte_cursor_from_c_str(request),
550 aws_byte_cursor_from_c_str(correlation_token));
551 }
552
553 static void s_on_delete_shadow_complete(
554 const struct aws_mqtt_rr_incoming_publish_event *publish_event,
555 int error_code,
556 void *user_data) {
557
558 struct aws_string *correlation_token = user_data;
559
560 if (publish_event != NULL) {
561 printf(
562 "DeleteNamedShadow request '%s' response received on topic '" PRInSTR "' with body:\n " PRInSTR "\n\n",
563 correlation_token->bytes,
564 AWS_BYTE_CURSOR_PRI(publish_event->topic),
565 AWS_BYTE_CURSOR_PRI(publish_event->payload));
566 } else {
567 printf(
568 "DeleteNamedShadow request '%s' failed with error code %d(%s)\n\n",
569 correlation_token->bytes,
570 error_code,
571 aws_error_debug_str(error_code));
572 }
573
574 aws_string_destroy(correlation_token);
575 }
576
577 static void s_handle_delete(
578 struct app_ctx *context,
579 struct aws_allocator *allocator,
580 struct aws_array_list *arguments) {
581
582 size_t argument_count = aws_array_list_length(arguments) - 1;
583 if (argument_count != 2) {
584 printf("invalid delete-named-shadow options:\n");
585 printf(" delete-named-shadow <thing-name> <shadow-name>\n\n");
586 return;
587 }
588
589 struct aws_byte_cursor thing_name_cursor;
590 AWS_ZERO_STRUCT(thing_name_cursor);
591 aws_array_list_get_at(arguments, &thing_name_cursor, 1);
592
593 struct aws_byte_cursor shadow_name_cursor;
594 AWS_ZERO_STRUCT(shadow_name_cursor);
595 aws_array_list_get_at(arguments, &shadow_name_cursor, 2);
596
597 char subscription_topic_filter[128];
598 snprintf(
599 subscription_topic_filter,
600 AWS_ARRAY_SIZE(subscription_topic_filter),
601 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/delete/+",
602 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
603 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
604 struct aws_byte_cursor subscription_topic_filter_cursor = aws_byte_cursor_from_c_str(subscription_topic_filter);
605
606 char accepted_path[128];
607 snprintf(
608 accepted_path,
609 AWS_ARRAY_SIZE(accepted_path),
610 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/delete/accepted",
611 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
612 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
613
614 char rejected_path[128];
615 snprintf(
616 rejected_path,
617 AWS_ARRAY_SIZE(rejected_path),
618 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/delete/rejected",
619 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
620 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
621
622 struct aws_byte_cursor correlation_token_path = aws_byte_cursor_from_c_str("clientToken");
623 struct aws_mqtt_request_operation_response_path response_paths[] = {
624 {
625 .topic = aws_byte_cursor_from_c_str(accepted_path),
626 .correlation_token_json_path = correlation_token_path,
627 },
628 {
629 .topic = aws_byte_cursor_from_c_str(rejected_path),
630 .correlation_token_json_path = correlation_token_path,
631 },
632 };
633
634 char publish_topic[128];
635 snprintf(
636 publish_topic,
637 AWS_ARRAY_SIZE(publish_topic),
638 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/delete",
639 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
640 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
641
642 char correlation_token[128];
643 struct aws_byte_buf correlation_token_buf =
644 aws_byte_buf_from_empty_array(correlation_token, AWS_ARRAY_SIZE(correlation_token));
645
646 struct aws_uuid uuid;
647 aws_uuid_init(&uuid);
648 aws_uuid_to_str(&uuid, &correlation_token_buf);
649
650 char request[256];
651 snprintf(request, AWS_ARRAY_SIZE(request), "{\"clientToken\":\"%s\"}", correlation_token);
652 struct aws_string *correlation_token_string = aws_string_new_from_c_str(allocator, correlation_token);
653
654 struct aws_mqtt_request_operation_options get_options = {
655 .subscription_topic_filters = &subscription_topic_filter_cursor,
656 .subscription_topic_filter_count = 1,
657 .response_paths = response_paths,
658 .response_path_count = 2,
659 .publish_topic = aws_byte_cursor_from_c_str(publish_topic),
660 .serialized_request = aws_byte_cursor_from_c_str(request),
661 .correlation_token = aws_byte_cursor_from_c_str(correlation_token),
662 .completion_callback = s_on_delete_shadow_complete,
663 .user_data = correlation_token_string,
664 };
665
666 printf(
667 "Submitting DeleteNamedShadow request for shadow '" PRInSTR "' of thing '" PRInSTR
668 "' using correlation token %s...\n",
669 AWS_BYTE_CURSOR_PRI(shadow_name_cursor),
670 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
671 correlation_token);
672
673 if (aws_mqtt_request_response_client_submit_request(context->rr_client, &get_options) == AWS_OP_ERR) {
674 int error_code = aws_last_error();
675 printf("DeleteNamedShadow synchronous failure: %d(%s)\n", error_code, aws_error_debug_str(error_code));
676 aws_string_destroy(correlation_token_string);
677 }
678
679 printf("\n");
680 }
681
682 static int s_print_streaming_operation(void *context, struct aws_hash_element *elem) {
683 (void)context;
684 struct aws_shadow_streaming_operation *operation = elem->value;
685
686 struct aws_byte_cursor thing_cursor = aws_byte_cursor_from_buf(&operation->thing);
687 struct aws_byte_cursor shadow_cursor = aws_byte_cursor_from_buf(&operation->shadow);
688 struct aws_byte_cursor topic_filter_cursor = aws_byte_cursor_from_buf(&operation->topic_filter);
689
690 printf(
691 " %" PRIu64 " Thing:'" PRInSTR "', Shadow: '" PRInSTR "', TopicFilter:'" PRInSTR "'\n",
692 operation->id,
693 AWS_BYTE_CURSOR_PRI(thing_cursor),
694 AWS_BYTE_CURSOR_PRI(shadow_cursor),
695 AWS_BYTE_CURSOR_PRI(topic_filter_cursor));
696
697 return AWS_COMMON_HASH_TABLE_ITER_CONTINUE;
698 }
699
700 static void s_handle_list_streams(
701 struct app_ctx *context,
702 struct aws_allocator *allocator,
703 struct aws_array_list *arguments) {
704 (void)allocator;
705 (void)arguments;
706
707 printf("Open Streams:\n");
708 aws_hash_table_foreach(&context->streaming_operations, s_print_streaming_operation, NULL);
709 printf("\n");
710 }
711
712 static const char *s_rr_streaming_subscription_event_type_to_c_str(
713 enum aws_rr_streaming_subscription_event_type status) {
714 switch (status) {
715 case ARRSSET_SUBSCRIPTION_ESTABLISHED:
716 return "SubscriptionEstablished";
717
718 case ARRSSET_SUBSCRIPTION_LOST:
719 return "SubscriptionLost";
720
721 case ARRSSET_SUBSCRIPTION_HALTED:
722 return "SubscriptionHalted";
723
724 default:
725 return "Unknown";
726 }
727 }
728
729 static void s_stream_subscription_status_fn(
730 enum aws_rr_streaming_subscription_event_type status,
731 int error_code,
732 void *user_data) {
733
734 struct aws_shadow_streaming_operation *operation = user_data;
735
736 struct aws_byte_cursor topic_filter_cursor = aws_byte_cursor_from_buf(&operation->topic_filter);
737
738 printf(
739 "Streaming operation %" PRIu64 " received subscription status event on topic filter '" PRInSTR "':\n",
740 operation->id,
741 AWS_BYTE_CURSOR_PRI(topic_filter_cursor));
742 printf(
743 " Status: %d(%s), ErrorCode: %d(%s)\n\n",
744 status,
745 s_rr_streaming_subscription_event_type_to_c_str(status),
746 error_code,
747 aws_error_debug_str(error_code));
748 }
749
750 static void s_stream_incoming_publish_fn(
751 const struct aws_mqtt_rr_incoming_publish_event *publish_event,
752 void *user_data) {
753 struct aws_shadow_streaming_operation *operation = user_data;
754
755 struct aws_byte_cursor thing_cursor = aws_byte_cursor_from_buf(&operation->thing);
756 struct aws_byte_cursor shadow_cursor = aws_byte_cursor_from_buf(&operation->shadow);
757 struct aws_byte_cursor topic_filter_cursor = aws_byte_cursor_from_buf(&operation->topic_filter);
758
759 printf(
760 "Streaming operation %" PRIu64 " ('" PRInSTR "', ' " PRInSTR "') received publish on topic filter '" PRInSTR
761 "':\n",
762 operation->id,
763 AWS_BYTE_CURSOR_PRI(thing_cursor),
764 AWS_BYTE_CURSOR_PRI(shadow_cursor),
765 AWS_BYTE_CURSOR_PRI(topic_filter_cursor));
766 printf(" " PRInSTR "\n\n", AWS_BYTE_CURSOR_PRI(publish_event->payload));
767 }
768
769 static void s_stream_terminated_fn(void *user_data) {
770 struct aws_shadow_streaming_operation *operation = user_data;
771
772 printf("Stream %" PRIu64 " terminated\n\n", operation->id);
773
774 s_aws_shadow_streaming_operation_destroy(operation);
775 }
776
777 static void s_handle_open_delta_stream(
778 struct app_ctx *context,
779 struct aws_allocator *allocator,
780 struct aws_array_list *arguments) {
781
782 size_t argument_count = aws_array_list_length(arguments) - 1;
783 if (argument_count != 2) {
784 printf("invalid open-named-shadow-delta-stream options:\n");
785 printf(" open-named-shadow-delta-stream <thing-name> <shadow-name>\n\n");
786 return;
787 }
788
789 struct aws_byte_cursor thing_name_cursor;
790 AWS_ZERO_STRUCT(thing_name_cursor);
791 aws_array_list_get_at(arguments, &thing_name_cursor, 1);
792
793 struct aws_byte_cursor shadow_name_cursor;
794 AWS_ZERO_STRUCT(shadow_name_cursor);
795 aws_array_list_get_at(arguments, &shadow_name_cursor, 2);
796
797 char subscription_topic_filter[128];
798 snprintf(
799 subscription_topic_filter,
800 AWS_ARRAY_SIZE(subscription_topic_filter),
801 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/update/delta",
802 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
803 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
804
805 struct aws_shadow_streaming_operation *operation = s_aws_shadow_streaming_operation_new(
806 allocator,
807 context,
808 thing_name_cursor,
809 shadow_name_cursor,
810 aws_byte_cursor_from_c_str(subscription_topic_filter));
811 aws_hash_table_put(&context->streaming_operations, &operation->id, operation, NULL);
812
813 struct aws_mqtt_streaming_operation_options open_stream_options = {
814 .topic_filter = aws_byte_cursor_from_c_str(subscription_topic_filter),
815 .subscription_status_callback = s_stream_subscription_status_fn,
816 .incoming_publish_callback = s_stream_incoming_publish_fn,
817 .terminated_callback = s_stream_terminated_fn,
818 .user_data = operation,
819 };
820
821 printf(
822 "Opening NamedShadow delta stream with id %" PRIu64 " for shadow '" PRInSTR "' of thing '" PRInSTR "'...\n",
823 operation->id,
824 AWS_BYTE_CURSOR_PRI(shadow_name_cursor),
825 AWS_BYTE_CURSOR_PRI(thing_name_cursor));
826
827 operation->streaming_operation =
828 aws_mqtt_request_response_client_create_streaming_operation(context->rr_client, &open_stream_options);
829 if (operation->streaming_operation == NULL ||
830 aws_mqtt_rr_client_operation_activate(operation->streaming_operation)) {
831 int error_code = aws_last_error();
832 printf(
833 "NamedShadow delta stream synchronous open failure: %d(%s)\n", error_code, aws_error_debug_str(error_code));
834
835 aws_hash_table_remove(&context->streaming_operations, &operation->id, NULL, NULL);
836 }
837
838 printf("\n");
839 }
840
841 static void s_handle_open_document_stream(
842 struct app_ctx *context,
843 struct aws_allocator *allocator,
844 struct aws_array_list *arguments) {
845
846 size_t argument_count = aws_array_list_length(arguments) - 1;
847 if (argument_count != 2) {
848 printf("invalid open-named-shadow-document-stream options:\n");
849 printf(" open-named-shadow-document-stream <thing-name> <shadow-name>\n\n");
850 return;
851 }
852
853 struct aws_byte_cursor thing_name_cursor;
854 AWS_ZERO_STRUCT(thing_name_cursor);
855 aws_array_list_get_at(arguments, &thing_name_cursor, 1);
856
857 struct aws_byte_cursor shadow_name_cursor;
858 AWS_ZERO_STRUCT(shadow_name_cursor);
859 aws_array_list_get_at(arguments, &shadow_name_cursor, 2);
860
861 char subscription_topic_filter[128];
862 snprintf(
863 subscription_topic_filter,
864 AWS_ARRAY_SIZE(subscription_topic_filter),
865 "$aws/things/" PRInSTR "/shadow/name/" PRInSTR "/update/document",
866 AWS_BYTE_CURSOR_PRI(thing_name_cursor),
867 AWS_BYTE_CURSOR_PRI(shadow_name_cursor));
868
869 struct aws_shadow_streaming_operation *operation = s_aws_shadow_streaming_operation_new(
870 allocator,
871 context,
872 thing_name_cursor,
873 shadow_name_cursor,
874 aws_byte_cursor_from_c_str(subscription_topic_filter));
875 aws_hash_table_put(&context->streaming_operations, &operation->id, operation, NULL);
876
877 struct aws_mqtt_streaming_operation_options open_stream_options = {
878 .topic_filter = aws_byte_cursor_from_c_str(subscription_topic_filter),
879 .subscription_status_callback = s_stream_subscription_status_fn,
880 .incoming_publish_callback = s_stream_incoming_publish_fn,
881 .terminated_callback = s_stream_terminated_fn,
882 .user_data = operation,
883 };
884
885 printf(
886 "Opening NamedShadow document stream with id %" PRIu64 " for shadow '" PRInSTR "' of thing '" PRInSTR "'...\n",
887 operation->id,
888 AWS_BYTE_CURSOR_PRI(shadow_name_cursor),
889 AWS_BYTE_CURSOR_PRI(thing_name_cursor));
890
891 operation->streaming_operation =
892 aws_mqtt_request_response_client_create_streaming_operation(context->rr_client, &open_stream_options);
893 if (operation->streaming_operation == NULL ||
894 aws_mqtt_rr_client_operation_activate(operation->streaming_operation)) {
895 int error_code = aws_last_error();
896 printf(
897 "NamedShadow document stream synchronous open failure: %d(%s)\n",
898 error_code,
899 aws_error_debug_str(error_code));
900
901 aws_hash_table_remove(&context->streaming_operations, &operation->id, NULL, NULL);
902 }
903
904 printf("\n");
905 }
906
907 static void s_handle_close_stream(
908 struct app_ctx *context,
909 struct aws_allocator *allocator,
910 struct aws_array_list *arguments) {
911 (void)allocator;
912
913 size_t argument_count = aws_array_list_length(arguments) - 1;
914 if (argument_count != 1) {
915 printf("invalid close-stream options:\n");
916 printf(" close-stream <id>\n\n");
917 return;
918 }
919
920 struct aws_byte_cursor id_cursor;
921 AWS_ZERO_STRUCT(id_cursor);
922 aws_array_list_get_at(arguments, &id_cursor, 1);
923
924 char id_buffer[32];
925 snprintf(id_buffer, AWS_ARRAY_SIZE(id_buffer), PRInSTR, AWS_BYTE_CURSOR_PRI(id_cursor));
926 uint64_t id = atoi(id_buffer);
927
928 int was_present = 0;
929 aws_hash_table_remove(&context->streaming_operations, &id, NULL, &was_present);
930
931 if (was_present == 0) {
932 printf("Stream %" PRIu64 " does not exist\n\n", id);
933 } else {
934 printf("Closing stream %" PRIu64 "\n\n", id);
935 }
936 }
937
938 static bool s_handle_input(struct app_ctx *context, struct aws_allocator *allocator, const char *input_line) {
939
940 struct aws_mqtt5_client *client = context->client;
941
942 struct aws_byte_cursor quit_cursor = aws_byte_cursor_from_c_str("quit");
943 struct aws_byte_cursor start_cursor = aws_byte_cursor_from_c_str("start");
944 struct aws_byte_cursor stop_cursor = aws_byte_cursor_from_c_str("stop");
945 struct aws_byte_cursor get_cursor = aws_byte_cursor_from_c_str("get-named-shadow");
946 struct aws_byte_cursor update_reported_cursor = aws_byte_cursor_from_c_str("update-named-shadow-reported");
947 struct aws_byte_cursor update_desired_cursor = aws_byte_cursor_from_c_str("update-named-shadow-desired");
948 struct aws_byte_cursor delete_cursor = aws_byte_cursor_from_c_str("delete-named-shadow");
949 struct aws_byte_cursor list_streams_cursor = aws_byte_cursor_from_c_str("list-streams");
950 struct aws_byte_cursor open_delta_stream_cursor = aws_byte_cursor_from_c_str("open-named-shadow-delta-stream");
951 struct aws_byte_cursor open_document_stream_cursor =
952 aws_byte_cursor_from_c_str("open-named-shadow-document-stream");
953 struct aws_byte_cursor close_stream_cursor = aws_byte_cursor_from_c_str("close-stream");
954
955 struct aws_array_list words;
956 aws_array_list_init_dynamic(&words, allocator, 10, sizeof(struct aws_byte_cursor));
957
958 struct aws_byte_cursor line_cursor = aws_byte_cursor_from_c_str(input_line);
959 line_cursor = aws_byte_cursor_trim_pred(&line_cursor, &s_skip_whitespace);
960
961 bool done = false;
962
963 s_split_command_line(line_cursor, &words);
964 if (aws_array_list_length(&words) == 0) {
965 printf("Empty command line\n");
966 goto done;
967 }
968
969 struct aws_byte_cursor command_cursor;
970 AWS_ZERO_STRUCT(command_cursor);
971 aws_array_list_get_at(&words, &command_cursor, 0);
972
973 if (aws_byte_cursor_eq_ignore_case(&command_cursor, &quit_cursor)) {
974 printf("Quitting!\n");
975 done = true;
976 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &start_cursor)) {
977 printf("Starting client!\n");
978 aws_mqtt5_client_start(client);
979 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &stop_cursor)) {
980 printf("Stopping client!\n");
981 aws_mqtt5_client_stop(client, NULL, NULL);
982 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &get_cursor)) {
983 s_handle_get(context, allocator, &words);
984 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &update_reported_cursor)) {
985 s_handle_update_reported(context, allocator, &words, line_cursor);
986 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &update_desired_cursor)) {
987 s_handle_update_desired(context, allocator, &words, line_cursor);
988 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &delete_cursor)) {
989 s_handle_delete(context, allocator, &words);
990 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &list_streams_cursor)) {
991 s_handle_list_streams(context, allocator, &words);
992 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &open_delta_stream_cursor)) {
993 s_handle_open_delta_stream(context, allocator, &words);
994 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &open_document_stream_cursor)) {
995 s_handle_open_document_stream(context, allocator, &words);
996 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &close_stream_cursor)) {
997 s_handle_close_stream(context, allocator, &words);
998 } else {
999 printf("Unknown command: " PRInSTR "\n", AWS_BYTE_CURSOR_PRI(command_cursor));
1000 printf("\nValid commands:\n");
1001 printf(" get-named-shadow - gets the full state of a named shadow\n");
1002 printf(" delete-named-shadow - deletes a named shadow\n");
1003 printf(" update-named-shadow-reported - updates the reported state of a named shadow\n");
1004 printf(" update-named-shadow-desired - updates the desired state of a named shadow\n");
1005 printf("\n");
1006 printf(" list-streams - lists all open shadow streams\n");
1007 printf(" open-named-shadow-delta-stream - creates and opens a new shadow delta stream\n");
1008 printf(" open-named-shadow-document-stream - creates and opens a new shadow document stream\n");
1009 printf(" close-stream - closes a specific shadow stream\n");
1010 printf("\n");
1011 printf(" start - starts the mqtt5 client underlying the request-response client\n");
1012 printf(" stop - starts the mqtt5 client underlying the request-response client\n");
1013 printf(" quit - quits the program\n");
1014 printf("\n");
1015 }
1016
1017 done:
1018
1019 aws_array_list_clean_up(&words);
1020 return done;
1021 }
1022
1023 static void s_on_publish_received(const struct aws_mqtt5_packet_publish_view *publish, void *user_data) {
1024 (void)publish;
1025 (void)user_data;
1026 }
1027
1028 static void s_lifecycle_event_callback(const struct aws_mqtt5_client_lifecycle_event *event) {
1029
1030 switch (event->event_type) {
1031 case AWS_MQTT5_CLET_STOPPED:
1032 printf("Lifecycle event: Stopped!\n");
1033 break;
1034
1035 case AWS_MQTT5_CLET_ATTEMPTING_CONNECT:
1036 printf("Lifecycle event: Attempting Connect!\n");
1037 break;
1038
1039 case AWS_MQTT5_CLET_CONNECTION_FAILURE:
1040 printf("Lifecycle event: Connection Failure!\n");
1041 printf(" Error Code: %d(%s)\n", event->error_code, aws_error_debug_str(event->error_code));
1042 break;
1043
1044 case AWS_MQTT5_CLET_CONNECTION_SUCCESS:
1045 printf("Lifecycle event: Connection Success!\n");
1046 break;
1047
1048 case AWS_MQTT5_CLET_DISCONNECTION:
1049 printf("Lifecycle event: Disconnect!\n");
1050 printf(" Error Code: %d(%s)\n", event->error_code, aws_error_debug_str(event->error_code));
1051 break;
1052 }
1053
1054 fflush(stdout);
1055 }
1056
1057 AWS_STATIC_STRING_FROM_LITERAL(s_client_id, "HelloWorld");
1058
1059 int main(int argc, char **argv) {
1060 struct aws_allocator *allocator = aws_mem_tracer_new(aws_default_allocator(), NULL, AWS_MEMTRACE_STACKS, 15);
1061
1062 aws_mqtt_library_init(allocator);
1063
1064 struct app_ctx app_ctx;
1065 AWS_ZERO_STRUCT(app_ctx);
1066 app_ctx.allocator = allocator;
1067 app_ctx.signal = (struct aws_condition_variable)AWS_CONDITION_VARIABLE_INIT;
1068 aws_mutex_init(&app_ctx.lock);
1069 app_ctx.port = 1883;
1070
1071 aws_hash_table_init(
1072 &app_ctx.streaming_operations,
1073 allocator,
1074 10,
1075 aws_hash_uint64_t_by_identity,
1076 aws_hash_compare_uint64_t_eq,
1077 NULL,
1078 s_release_streaming_operation);
1079
1080 s_parse_options(argc, argv, &app_ctx);
1081 if (app_ctx.uri.port) {
1082 app_ctx.port = app_ctx.uri.port;
1083 }
1084
1085 struct aws_logger logger;
1086 AWS_ZERO_STRUCT(logger);
1087
1088 struct aws_logger_standard_options options = {
1089 .level = app_ctx.log_level,
1090 };
1091
1092 if (app_ctx.log_level) {
1093 if (app_ctx.log_filename) {
1094 options.filename = app_ctx.log_filename;
1095 } else {
1096 options.file = stderr;
1097 }
1098
1099 if (aws_logger_init_standard(&logger, allocator, &options)) {
1100 fprintf(stderr, "Failed to initialize logger with error %s\n", aws_error_debug_str(aws_last_error()));
1101 exit(1);
1102 }
1103
1104 aws_logger_set(&logger);
1105 }
1106
1107 if (!app_ctx.cert || !app_ctx.key) {
1108 fprintf(stderr, "Elastishadow requires mtls connections. You must specify a cert and key to use.\n");
1109 exit(1);
1110 }
1111
1112 struct aws_tls_ctx *tls_ctx = NULL;
1113 struct aws_tls_ctx_options tls_ctx_options;
1114 AWS_ZERO_STRUCT(tls_ctx_options);
1115 struct aws_tls_connection_options tls_connection_options;
1116 AWS_ZERO_STRUCT(tls_connection_options);
1117
1118 if (aws_tls_ctx_options_init_client_mtls_from_path(&tls_ctx_options, allocator, app_ctx.cert, app_ctx.key)) {
1119 fprintf(
1120 stderr,
1121 "Failed to load %s and %s with error %s.",
1122 app_ctx.cert,
1123 app_ctx.key,
1124 aws_error_debug_str(aws_last_error()));
1125 exit(1);
1126 }
1127
1128 if (aws_tls_ctx_options_set_alpn_list(&tls_ctx_options, "x-amzn-mqtt-ca")) {
1129 fprintf(stderr, "Failed to set alpn list with error %s.", aws_error_debug_str(aws_last_error()));
1130 exit(1);
1131 }
1132
1133 tls_ctx = aws_tls_client_ctx_new(allocator, &tls_ctx_options);
1134
1135 if (!tls_ctx) {
1136 fprintf(stderr, "Failed to initialize TLS context with error %s.", aws_error_debug_str(aws_last_error()));
1137 exit(1);
1138 }
1139
1140 aws_tls_connection_options_init_from_ctx(&tls_connection_options, tls_ctx);
1141 if (aws_tls_connection_options_set_server_name(&tls_connection_options, allocator, &app_ctx.uri.host_name)) {
1142 fprintf(stderr, "Failed to set servername with error %s.", aws_error_debug_str(aws_last_error()));
1143 exit(1);
1144 }
1145
1146 struct aws_event_loop_group *el_group = aws_event_loop_group_new_default(allocator, 2, NULL);
1147
1148 struct aws_host_resolver_default_options resolver_options = {
1149 .el_group = el_group,
1150 .max_entries = 8,
1151 };
1152
1153 struct aws_host_resolver *resolver = aws_host_resolver_new_default(allocator, &resolver_options);
1154
1155 struct aws_client_bootstrap_options bootstrap_options = {
1156 .event_loop_group = el_group,
1157 .host_resolver = resolver,
1158 };
1159
1160 struct aws_client_bootstrap *bootstrap = aws_client_bootstrap_new(allocator, &bootstrap_options);
1161
1162 struct aws_socket_options socket_options = {
1163 .type = AWS_SOCKET_STREAM,
1164 .connect_timeout_ms = (uint32_t)10000,
1165 .keep_alive_timeout_sec = 0,
1166 .keepalive = false,
1167 .keep_alive_interval_sec = 0,
1168 };
1169
1170 struct aws_mqtt5_packet_connect_view connect_options = {
1171 .keep_alive_interval_seconds = 30,
1172 .client_id = aws_byte_cursor_from_string(s_client_id),
1173 };
1174
1175 struct aws_mqtt5_client_options client_options = {
1176 .host_name = app_ctx.uri.host_name,
1177 .port = app_ctx.port,
1178 .bootstrap = bootstrap,
1179 .socket_options = &socket_options,
1180 .tls_options = &tls_connection_options,
1181 .connect_options = &connect_options,
1182 .session_behavior = AWS_MQTT5_CSBT_CLEAN,
1183 .lifecycle_event_handler = s_lifecycle_event_callback,
1184 .lifecycle_event_handler_user_data = NULL,
1185 .retry_jitter_mode = AWS_EXPONENTIAL_BACKOFF_JITTER_NONE,
1186 .min_reconnect_delay_ms = 1000,
1187 .max_reconnect_delay_ms = 120000,
1188 .min_connected_time_to_reset_reconnect_delay_ms = 30000,
1189 .ping_timeout_ms = 10000,
1190 .publish_received_handler = s_on_publish_received,
1191 };
1192
1193 app_ctx.client = aws_mqtt5_client_new(allocator, &client_options);
1194
1195 struct aws_mqtt_request_response_client_options rr_client_options = {
1196 .max_request_response_subscriptions = 10,
1197 .max_streaming_subscriptions = 5,
1198 .operation_timeout_seconds = 60,
1199 };
1200
1201 app_ctx.rr_client =
1202 aws_mqtt_request_response_client_new_from_mqtt5_client(allocator, app_ctx.client, &rr_client_options);
1203
1204 bool done = false;
1205 while (!done) {
1206 printf("Enter command:\n");
1207
1208 char input_buffer[4096];
1209 #ifdef WIN32
1210 char *line = gets_s(input_buffer, AWS_ARRAY_SIZE(input_buffer));
1211 #else
1212 char *line = fgets(input_buffer, AWS_ARRAY_SIZE(input_buffer), stdin);
1213 #endif
1214 done = s_handle_input(&app_ctx, allocator, line);
1215 }
1216
1217 aws_hash_table_clean_up(&app_ctx.streaming_operations);
1218
1219 aws_mqtt_request_response_client_release(app_ctx.rr_client);
1220 aws_mqtt5_client_release(app_ctx.client);
1221
1222 aws_client_bootstrap_release(bootstrap);
1223 aws_host_resolver_release(resolver);
1224 aws_event_loop_group_release(el_group);
1225
1226 if (tls_ctx) {
1227 aws_tls_connection_options_clean_up(&tls_connection_options);
1228 aws_tls_ctx_release(tls_ctx);
1229 aws_tls_ctx_options_clean_up(&tls_ctx_options);
1230 }
1231
1232 aws_thread_join_all_managed();
1233
1234 const size_t outstanding_bytes = aws_mem_tracer_bytes(allocator);
1235 printf("Summary:\n");
1236 printf(" Outstanding bytes: %zu\n\n", outstanding_bytes);
1237
1238 if (app_ctx.log_level) {
1239 aws_logger_set(NULL);
1240 aws_logger_clean_up(&logger);
1241 }
1242
1243 aws_uri_clean_up(&app_ctx.uri);
1244
1245 aws_mqtt_library_clean_up();
1246
1247 const size_t leaked_bytes = aws_mem_tracer_bytes(allocator);
1248 if (leaked_bytes) {
1249 struct aws_logger memory_logger;
1250 AWS_ZERO_STRUCT(memory_logger);
1251
1252 aws_logger_init_noalloc(&memory_logger, aws_default_allocator(), &options);
1253 aws_logger_set(&memory_logger);
1254
1255 aws_mqtt_library_init(aws_default_allocator());
1256
1257 printf("Writing memory leaks to log.\n");
1258 aws_mem_tracer_dump(allocator);
1259
1260 aws_logger_set(NULL);
1261 aws_logger_clean_up(&memory_logger);
1262
1263 aws_mqtt_library_clean_up();
1264 } else {
1265 printf("Finished, with no memory leaks\n");
1266 }
1267
1268 aws_mem_tracer_destroy(allocator);
1269
1270 return 0;
1271 }