Debian Codegraph @

crt/aws-c-mqtt/bin/elastipubsub5/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/clock.h>
7 #include <aws/common/command_line_parser.h>
8 #include <aws/common/condition_variable.h>
9 #include <aws/common/hash_table.h>
10 #include <aws/common/log_channel.h>
11 #include <aws/common/log_formatter.h>
12 #include <aws/common/log_writer.h>
13 #include <aws/common/mutex.h>
14 #include <aws/common/string.h>
15
16 #include <aws/io/channel_bootstrap.h>
17 #include <aws/io/event_loop.h>
18 #include <aws/io/logging.h>
19 #include <aws/io/socket.h>
20 #include <aws/io/stream.h>
21 #include <aws/io/tls_channel_handler.h>
22 #include <aws/io/uri.h>
23
24 #include <aws/mqtt/private/v5/mqtt5_utils.h>
25 #include <aws/mqtt/v5/mqtt5_client.h>
26 #include <aws/mqtt/v5/mqtt5_types.h>
27
28 #include <inttypes.h>
29
30 #ifdef _MSC_VER
31 # pragma warning(disable : 4996) /* Disable warnings about fopen() being insecure */
32 # pragma warning(disable : 4204) /* Declared initializers */
33 # pragma warning(disable : 4221) /* Local var in declared initializer */
34 #endif
35
36 #ifdef WIN32
37 // Windows does not need specific imports
38 #else
39 # include <stdio.h>
40 #endif
41
42 struct app_ctx {
43 struct aws_allocator *allocator;
44 struct aws_mutex lock;
45 struct aws_condition_variable signal;
46 struct aws_uri uri;
47 uint32_t port;
48 const char *cacert;
49 const char *cert;
50 const char *key;
51 int connect_timeout;
52 bool use_websockets;
53
54 struct aws_tls_connection_options tls_connection_options;
55
56 const char *log_filename;
57 enum aws_log_level log_level;
58 };
59
60 static void s_usage(int exit_code) {
61
62 fprintf(stderr, "usage: elastipubsub5 [options] endpoint\n");
63 fprintf(stderr, " endpoint: url to connect to\n");
64 fprintf(stderr, "\n Options:\n\n");
65 fprintf(stderr, " --cacert FILE: path to a CA certficate file.\n");
66 fprintf(stderr, " --cert FILE: path to a PEM encoded certificate to use with mTLS\n");
67 fprintf(stderr, " --key FILE: Path to a PEM encoded private key that matches cert.\n");
68 fprintf(stderr, " --connect-timeout INT: time in milliseconds to wait for a connection.\n");
69 fprintf(stderr, " -l, --log FILE: dumps logs to FILE instead of stderr.\n");
70 fprintf(stderr, " -v, --verbose: ERROR|INFO|DEBUG|TRACE: log level to configure. Default is none.\n");
71 fprintf(stderr, " -w, --websockets: use mqtt-over-websockets rather than direct mqtt\n");
72 fprintf(stderr, " -h, --help\n");
73 fprintf(stderr, " Display this message and quit.\n");
74 exit(exit_code);
75 }
76
77 static struct aws_cli_option s_long_options[] = {
78 {"cacert", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'a'},
79 {"cert", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'c'},
80 {"key", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'e'},
81 {"connect-timeout", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'f'},
82 {"log", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'l'},
83 {"verbose", AWS_CLI_OPTIONS_REQUIRED_ARGUMENT, NULL, 'v'},
84 {"websockets", AWS_CLI_OPTIONS_NO_ARGUMENT, NULL, 'w'},
85 {"help", AWS_CLI_OPTIONS_NO_ARGUMENT, NULL, 'h'},
86 /* Per getopt(3) the last element of the array has to be filled with all zeros */
87 {NULL, AWS_CLI_OPTIONS_NO_ARGUMENT, NULL, 0},
88 };
89
90 static void s_parse_options(int argc, char **argv, struct app_ctx *ctx) {
91 bool uri_found = false;
92
93 while (true) {
94 int option_index = 0;
95 int c = aws_cli_getopt_long(argc, argv, "a:c:e:f:l:v:wh", s_long_options, &option_index);
96 if (c == -1) {
97 break;
98 }
99
100 switch (c) {
101 case 0:
102 /* getopt_long() returns 0 if an option.flag is non-null */
103 break;
104 case 'a':
105 ctx->cacert = aws_cli_optarg;
106 break;
107 case 'c':
108 ctx->cert = aws_cli_optarg;
109 break;
110 case 'e':
111 ctx->key = aws_cli_optarg;
112 break;
113 case 'f':
114 ctx->connect_timeout = atoi(aws_cli_optarg);
115 break;
116 case 'l':
117 ctx->log_filename = aws_cli_optarg;
118 break;
119 case 'v':
120 if (!strcmp(aws_cli_optarg, "TRACE")) {
121 ctx->log_level = AWS_LL_TRACE;
122 } else if (!strcmp(aws_cli_optarg, "INFO")) {
123 ctx->log_level = AWS_LL_INFO;
124 } else if (!strcmp(aws_cli_optarg, "DEBUG")) {
125 ctx->log_level = AWS_LL_DEBUG;
126 } else if (!strcmp(aws_cli_optarg, "ERROR")) {
127 ctx->log_level = AWS_LL_ERROR;
128 } else {
129 fprintf(stderr, "unsupported log level %s.\n", aws_cli_optarg);
130 s_usage(1);
131 }
132 break;
133 case 'h':
134 s_usage(0);
135 break;
136 case 'w':
137 ctx->use_websockets = true;
138 break;
139 case 0x02: {
140 struct aws_byte_cursor uri_cursor = aws_byte_cursor_from_c_str(aws_cli_positional_arg);
141 if (aws_uri_init_parse(&ctx->uri, ctx->allocator, &uri_cursor)) {
142 fprintf(
143 stderr,
144 "Failed to parse uri %s with error %s\n",
145 (char *)uri_cursor.ptr,
146 aws_error_debug_str(aws_last_error()));
147 s_usage(1);
148 }
149 uri_found = true;
150 break;
151 }
152
153 default:
154 fprintf(stderr, "Unknown option\n");
155 s_usage(1);
156 }
157 }
158
159 if (!uri_found) {
160 fprintf(stderr, "A URI for the request must be supplied.\n");
161 s_usage(1);
162 }
163 }
164
165 static void s_on_subscribe_complete_fn(
166 const struct aws_mqtt5_packet_suback_view *suback,
167 int error_code,
168 void *complete_ctx) {
169
170 (void)error_code;
171 (void)complete_ctx;
172
173 printf("SUBACK received!\n");
174 for (size_t i = 0; i < suback->reason_code_count; ++i) {
175 printf("Subscription %d: %s\n", (int)i, aws_mqtt5_suback_reason_code_to_c_string(suback->reason_codes[i]));
176 }
177 fflush(stdout);
178 }
179
180 static void s_on_unsubscribe_complete_fn(
181 const struct aws_mqtt5_packet_unsuback_view *unsuback,
182 int error_code,
183 void *complete_ctx) {
184
185 (void)error_code;
186 (void)complete_ctx;
187
188 printf("UNSUBACK received!\n");
189 for (size_t i = 0; i < unsuback->reason_code_count; ++i) {
190 printf("Topic Filter %d: %s\n", (int)i, aws_mqtt5_unsuback_reason_code_to_c_string(unsuback->reason_codes[i]));
191 }
192 fflush(stdout);
193 }
194
195 static void s_on_publish_complete_fn(
196 enum aws_mqtt5_packet_type packet_type,
197 const void *packet,
198 int error_code,
199 void *complete_ctx) {
200 (void)complete_ctx;
201
202 switch (error_code) {
203 case AWS_ERROR_MQTT5_OPERATION_FAILED_DUE_TO_OFFLINE_QUEUE_POLICY:
204 printf("PUBLISH FAILED due to disconnect and offline queue policy");
205 break;
206 case AWS_ERROR_MQTT_TIMEOUT:
207 printf("PUBLISH FAILED due to MQTT Timeout");
208 break;
209 case AWS_ERROR_SUCCESS:
210 printf("PUBLISH SUCCESS\n");
211 break;
212 default:
213 break;
214 }
215
216 if (packet_type == AWS_MQTT5_PT_PUBACK) {
217 const struct aws_mqtt5_packet_puback_view *puback = packet;
218 printf("PUBACK received!\n");
219 printf("PUBACK id:%d %s\n", puback->packet_id, aws_mqtt5_puback_reason_code_to_c_string(puback->reason_code));
220 } else {
221 printf("PUBLISH Complete with no PUBACK\n");
222 }
223
224 fflush(stdout);
225 }
226
227 static void s_on_publish_received(const struct aws_mqtt5_packet_publish_view *publish, void *user_data) {
228 (void)publish;
229 (void)user_data;
230
231 printf("PUBLISH received!\n");
232 printf(
233 "Publish received to topic:'" PRInSTR "' payload '" PRInSTR "'\n",
234 AWS_BYTE_CURSOR_PRI(publish->topic),
235 AWS_BYTE_CURSOR_PRI(publish->payload));
236 }
237
238 static void s_lifecycle_event_callback(const struct aws_mqtt5_client_lifecycle_event *event) {
239
240 switch (event->event_type) {
241 case AWS_MQTT5_CLET_STOPPED:
242 printf("Lifecycle event: Stopped!\n");
243 break;
244
245 case AWS_MQTT5_CLET_ATTEMPTING_CONNECT:
246 printf("Lifecycle event: Attempting Connect!\n");
247 break;
248
249 case AWS_MQTT5_CLET_CONNECTION_FAILURE:
250 printf("Lifecycle event: Connection Failure!\n");
251 printf(" Error Code: %d(%s)\n", event->error_code, aws_error_debug_str(event->error_code));
252 break;
253
254 case AWS_MQTT5_CLET_CONNECTION_SUCCESS:
255 printf("Lifecycle event: Connection Success!\n");
256 break;
257
258 case AWS_MQTT5_CLET_DISCONNECTION:
259 printf("Lifecycle event: Disconnect!\n");
260 printf(" Error Code: %d(%s)\n", event->error_code, aws_error_debug_str(event->error_code));
261 break;
262 }
263
264 fflush(stdout);
265 }
266
267 static bool s_skip_whitespace(uint8_t value) {
268 return value == '\n' || value == '\r' || value == '\t' || value == ' ';
269 }
270
271 static void s_split_command_line(struct aws_byte_cursor cursor, struct aws_array_list *words) {
272 struct aws_byte_cursor split_cursor;
273 AWS_ZERO_STRUCT(split_cursor);
274
275 while (aws_byte_cursor_next_split(&cursor, ' ', &split_cursor)) {
276 struct aws_byte_cursor word_cursor = aws_byte_cursor_trim_pred(&split_cursor, &s_skip_whitespace);
277 if (word_cursor.len > 0) {
278 aws_array_list_push_back(words, &word_cursor);
279 }
280 }
281 }
282
283 static void s_handle_subscribe(
284 struct aws_mqtt5_client *client,
285 struct aws_allocator *allocator,
286 struct aws_array_list *arguments) {
287 struct aws_mqtt5_subscribe_completion_options subscribe_completion_options = {
288 .completion_callback = &s_on_subscribe_complete_fn,
289 .completion_user_data = NULL,
290 };
291
292 size_t argument_count = aws_array_list_length(arguments) - 1;
293 if (argument_count < 2) {
294 printf("invalid subscribe options:\n");
295 printf(" subscribe <qos: [0, 1, 2]> topic1 topic2 ....\n");
296 return;
297 }
298
299 struct aws_byte_cursor qos_cursor;
300 AWS_ZERO_STRUCT(qos_cursor);
301 aws_array_list_get_at(arguments, &qos_cursor, 1);
302
303 struct aws_string *qos_string = aws_string_new_from_cursor(allocator, &qos_cursor);
304
305 int qos_value = atoi((const char *)qos_string->bytes);
306 enum aws_mqtt5_qos qos = qos_value;
307
308 size_t topic_count = aws_array_list_length(arguments) - 2;
309
310 struct aws_array_list subscriptions;
311 aws_array_list_init_dynamic(&subscriptions, allocator, topic_count, sizeof(struct aws_mqtt5_subscription_view));
312
313 printf("Subscribing to:\n");
314
315 for (size_t i = 0; i < topic_count; ++i) {
316 size_t topic_index = i + 2;
317 struct aws_byte_cursor topic_filter_cursor;
318
319 aws_array_list_get_at(arguments, &topic_filter_cursor, topic_index);
320
321 struct aws_mqtt5_subscription_view subscription = {
322 .topic_filter = topic_filter_cursor,
323 .qos = qos,
324 .no_local = false,
325 .retain_as_published = false,
326 .retain_handling_type = AWS_MQTT5_RHT_DONT_SEND,
327 };
328
329 printf(" %d:" PRInSTR "\n", (int)i, AWS_BYTE_CURSOR_PRI(topic_filter_cursor));
330 aws_array_list_push_back(&subscriptions, &subscription);
331 }
332
333 struct aws_mqtt5_packet_subscribe_view packet_subscribe_view = {
334 .subscription_count = aws_array_list_length(&subscriptions),
335 .subscriptions = subscriptions.data,
336 };
337
338 aws_mqtt5_client_subscribe(client, &packet_subscribe_view, &subscribe_completion_options);
339
340 aws_array_list_clean_up(&subscriptions);
341 aws_string_destroy(qos_string);
342 }
343
344 static void s_handle_unsubscribe(struct aws_mqtt5_client *client, struct aws_array_list *arguments) {
345 struct aws_mqtt5_unsubscribe_completion_options unsubscribe_completion_options = {
346 .completion_callback = &s_on_unsubscribe_complete_fn,
347 .completion_user_data = NULL,
348 };
349
350 size_t argument_count = aws_array_list_length(arguments) - 1;
351 if (argument_count < 1) {
352 printf("invalid unsubscribe options:\n");
353 printf(" unsubscribe topic1 topic2 ....\n");
354 return;
355 }
356
357 size_t topic_count = aws_array_list_length(arguments) - 1;
358
359 printf("Unsubscribing to:\n");
360
361 for (size_t i = 0; i < topic_count; ++i) {
362 size_t topic_index = i + 1;
363 struct aws_byte_cursor topic_filter_cursor;
364
365 aws_array_list_get_at(arguments, &topic_filter_cursor, topic_index);
366
367 printf(" %d:" PRInSTR "\n", (int)i, AWS_BYTE_CURSOR_PRI(topic_filter_cursor));
368 }
369
370 struct aws_mqtt5_packet_unsubscribe_view packet_unsubscribe_view = {
371 .topic_filter_count = topic_count,
372 .topic_filters = ((struct aws_byte_cursor *)arguments->data) + 1,
373 };
374
375 aws_mqtt5_client_unsubscribe(client, &packet_unsubscribe_view, &unsubscribe_completion_options);
376 }
377
378 static void s_handle_publish(
379 struct aws_mqtt5_client *client,
380 struct aws_allocator *allocator,
381 struct aws_array_list *arguments,
382 struct aws_byte_cursor *full_argument) {
383 struct aws_mqtt5_publish_completion_options publish_completion_options = {
384 .completion_callback = &s_on_publish_complete_fn,
385 .completion_user_data = NULL,
386 };
387
388 size_t argument_count = aws_array_list_length(arguments) - 1;
389 if (argument_count < 2) {
390 printf("invalid publish call:\n");
391 printf(" publish <qos: [0, 1, 2]> topic <text to publish>\n");
392 return;
393 }
394
395 /* QoS */
396 struct aws_byte_cursor qos_cursor;
397 AWS_ZERO_STRUCT(qos_cursor);
398 aws_array_list_get_at(arguments, &qos_cursor, 1);
399 struct aws_string *qos_string = aws_string_new_from_cursor(allocator, &qos_cursor);
400 int qos_value = atoi((const char *)qos_string->bytes);
401 enum aws_mqtt5_qos qos = qos_value;
402
403 /* TOPIC */
404 struct aws_byte_cursor topic_cursor;
405 AWS_ZERO_STRUCT(topic_cursor);
406 aws_array_list_get_at(arguments, &topic_cursor, 2);
407
408 /* PAYLOAD */
409 struct aws_byte_cursor payload_cursor;
410 AWS_ZERO_STRUCT(payload_cursor);
411 /* account for empty payload */
412
413 if (argument_count > 2) {
414 aws_array_list_get_at(arguments, &payload_cursor, 3);
415 payload_cursor.len = (size_t)(full_argument->ptr + full_argument->len - payload_cursor.ptr);
416 }
417
418 printf(
419 "Publishing to Topic:'" PRInSTR "' Payload:'" PRInSTR "'\n",
420 AWS_BYTE_CURSOR_PRI(topic_cursor),
421 AWS_BYTE_CURSOR_PRI(payload_cursor));
422
423 struct aws_mqtt5_packet_publish_view packet_publish_view = {
424 .qos = qos,
425 .topic = topic_cursor,
426 .retain = false,
427 .duplicate = false,
428 .payload = payload_cursor,
429 };
430
431 aws_mqtt5_client_publish(client, &packet_publish_view, &publish_completion_options);
432
433 aws_string_destroy(qos_string);
434 }
435
436 static void s_on_disconnect_completion(int error_code, void *user_data) {
437 (void)user_data;
438
439 printf("DISCONNECT complete with error code %d(%s)!", error_code, aws_error_debug_str(error_code));
440 fflush(stdout);
441 }
442
443 static void s_handle_stop(
444 struct aws_mqtt5_client *client,
445 struct aws_allocator *allocator,
446 struct aws_array_list *arguments) {
447
448 size_t argument_count = aws_array_list_length(arguments) - 1;
449 switch (argument_count) {
450 case 0:
451 printf("Stopping client by shutting down channel!\n");
452 aws_mqtt5_client_stop(client, NULL, NULL);
453 break;
454
455 case 1: {
456 struct aws_byte_cursor reason_code_cursor;
457 AWS_ZERO_STRUCT(reason_code_cursor);
458 aws_array_list_get_at(arguments, &reason_code_cursor, 1);
459
460 struct aws_string *reason_code_string = aws_string_new_from_cursor(allocator, &reason_code_cursor);
461
462 int reason_code_value = atoi((const char *)reason_code_string->bytes);
463 enum aws_mqtt5_disconnect_reason_code reason_code = reason_code_value;
464 aws_string_destroy(reason_code_string);
465
466 struct aws_mqtt5_packet_disconnect_view disconnect_options = {
467 .reason_code = reason_code,
468 };
469
470 struct aws_mqtt5_disconnect_completion_options completion_options = {
471 .completion_callback = s_on_disconnect_completion,
472 .completion_user_data = client,
473 };
474
475 printf(
476 "Stopping client cleanly by sending DISCONNECT packet with reason code %d(%s)!\n",
477 reason_code_value,
478 aws_mqtt5_disconnect_reason_code_to_c_string(reason_code, NULL));
479 aws_mqtt5_client_stop(client, &disconnect_options, &completion_options);
480 break;
481 }
482
483 default:
484 printf("invalid stop options:\n");
485 printf(" stop [optional int: reason_code]\n");
486 break;
487 }
488 }
489
490 static bool s_handle_input(struct aws_mqtt5_client *client, struct aws_allocator *allocator, const char *input_line) {
491
492 struct aws_byte_cursor quit_cursor = aws_byte_cursor_from_c_str("quit");
493 struct aws_byte_cursor start_cursor = aws_byte_cursor_from_c_str("start");
494 struct aws_byte_cursor stop_cursor = aws_byte_cursor_from_c_str("stop");
495 struct aws_byte_cursor subscribe_cursor = aws_byte_cursor_from_c_str("subscribe");
496 struct aws_byte_cursor unsubscribe_cursor = aws_byte_cursor_from_c_str("unsubscribe");
497 struct aws_byte_cursor publish_cursor = aws_byte_cursor_from_c_str("publish");
498
499 struct aws_array_list words;
500 aws_array_list_init_dynamic(&words, allocator, 10, sizeof(struct aws_byte_cursor));
501
502 struct aws_byte_cursor line_cursor = aws_byte_cursor_from_c_str(input_line);
503 line_cursor = aws_byte_cursor_trim_pred(&line_cursor, &s_skip_whitespace);
504
505 bool done = false;
506
507 s_split_command_line(line_cursor, &words);
508 if (aws_array_list_length(&words) == 0) {
509 printf("Empty command line\n");
510 goto done;
511 }
512
513 struct aws_byte_cursor command_cursor;
514 AWS_ZERO_STRUCT(command_cursor);
515 aws_array_list_get_at(&words, &command_cursor, 0);
516
517 if (aws_byte_cursor_eq_ignore_case(&command_cursor, &quit_cursor)) {
518 printf("Quitting!\n");
519 done = true;
520 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &start_cursor)) {
521 printf("Starting client!\n");
522 aws_mqtt5_client_start(client);
523 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &stop_cursor)) {
524 s_handle_stop(client, allocator, &words);
525 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &subscribe_cursor)) {
526 s_handle_subscribe(client, allocator, &words);
527 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &unsubscribe_cursor)) {
528 s_handle_unsubscribe(client, &words);
529 } else if (aws_byte_cursor_eq_ignore_case(&command_cursor, &publish_cursor)) {
530 s_handle_publish(client, allocator, &words, &line_cursor);
531 } else {
532 printf("Unknown command: " PRInSTR "\n", AWS_BYTE_CURSOR_PRI(command_cursor));
533 }
534
535 done:
536
537 aws_array_list_clean_up(&words);
538 return done;
539 }
540
541 static void s_aws_mqtt5_transform_websocket_handshake_fn(
542 struct aws_http_message *request,
543 void *user_data,
544 aws_mqtt5_transform_websocket_handshake_complete_fn *complete_fn,
545 void *complete_ctx) {
546
547 (void)user_data;
548
549 (*complete_fn)(request, AWS_ERROR_SUCCESS, complete_ctx);
550 }
551
552 AWS_STATIC_STRING_FROM_LITERAL(s_client_id, "HelloWorld");
553
554 int main(int argc, char **argv) {
555 struct aws_allocator *allocator = aws_mem_tracer_new(aws_default_allocator(), NULL, AWS_MEMTRACE_STACKS, 15);
556
557 aws_mqtt_library_init(allocator);
558
559 struct app_ctx app_ctx;
560 AWS_ZERO_STRUCT(app_ctx);
561 app_ctx.allocator = allocator;
562 app_ctx.signal = (struct aws_condition_variable)AWS_CONDITION_VARIABLE_INIT;
563 app_ctx.connect_timeout = 3000;
564 aws_mutex_init(&app_ctx.lock);
565 app_ctx.port = 1883;
566
567 s_parse_options(argc, argv, &app_ctx);
568 if (app_ctx.uri.port) {
569 app_ctx.port = app_ctx.uri.port;
570 }
571
572 struct aws_logger logger;
573 AWS_ZERO_STRUCT(logger);
574
575 struct aws_logger_standard_options options = {
576 .level = app_ctx.log_level,
577 };
578
579 if (app_ctx.log_level) {
580 if (app_ctx.log_filename) {
581 options.filename = app_ctx.log_filename;
582 } else {
583 options.file = stderr;
584 }
585
586 if (aws_logger_init_standard(&logger, allocator, &options)) {
587 fprintf(stderr, "Failed to initialize logger with error %s\n", aws_error_debug_str(aws_last_error()));
588 exit(1);
589 }
590
591 aws_logger_set(&logger);
592 }
593
594 bool use_tls = false;
595 struct aws_tls_ctx *tls_ctx = NULL;
596 struct aws_tls_ctx_options tls_ctx_options;
597 AWS_ZERO_STRUCT(tls_ctx_options);
598 struct aws_tls_connection_options tls_connection_options;
599 AWS_ZERO_STRUCT(tls_connection_options);
600
601 if (app_ctx.cert && app_ctx.key) {
602 if (aws_tls_ctx_options_init_client_mtls_from_path(&tls_ctx_options, allocator, app_ctx.cert, app_ctx.key)) {
603 fprintf(
604 stderr,
605 "Failed to load %s and %s with error %s.",
606 app_ctx.cert,
607 app_ctx.key,
608 aws_error_debug_str(aws_last_error()));
609 exit(1);
610 }
611
612 if (app_ctx.cacert) {
613 if (aws_tls_ctx_options_override_default_trust_store_from_path(&tls_ctx_options, NULL, app_ctx.cacert)) {
614 fprintf(
615 stderr, "Failed to load %s with error %s", app_ctx.cacert, aws_error_debug_str(aws_last_error()));
616 exit(1);
617 }
618 }
619
620 if (aws_tls_ctx_options_set_alpn_list(&tls_ctx_options, "x-amzn-mqtt-ca")) {
621 fprintf(stderr, "Failed to set alpn list with error %s.", aws_error_debug_str(aws_last_error()));
622 exit(1);
623 }
624
625 tls_ctx = aws_tls_client_ctx_new(allocator, &tls_ctx_options);
626
627 if (!tls_ctx) {
628 fprintf(stderr, "Failed to initialize TLS context with error %s.", aws_error_debug_str(aws_last_error()));
629 exit(1);
630 }
631
632 aws_tls_connection_options_init_from_ctx(&tls_connection_options, tls_ctx);
633 if (aws_tls_connection_options_set_server_name(&tls_connection_options, allocator, &app_ctx.uri.host_name)) {
634 fprintf(stderr, "Failed to set servername with error %s.", aws_error_debug_str(aws_last_error()));
635 exit(1);
636 }
637
638 use_tls = true;
639 }
640
641 struct aws_event_loop_group *el_group = aws_event_loop_group_new_default(allocator, 2, NULL);
642
643 struct aws_host_resolver_default_options resolver_options = {
644 .el_group = el_group,
645 .max_entries = 8,
646 };
647
648 struct aws_host_resolver *resolver = aws_host_resolver_new_default(allocator, &resolver_options);
649
650 struct aws_client_bootstrap_options bootstrap_options = {
651 .event_loop_group = el_group,
652 .host_resolver = resolver,
653 };
654
655 struct aws_client_bootstrap *bootstrap = aws_client_bootstrap_new(allocator, &bootstrap_options);
656
657 struct aws_socket_options socket_options = {
658 .type = AWS_SOCKET_STREAM,
659 .connect_timeout_ms = (uint32_t)app_ctx.connect_timeout,
660 .keep_alive_timeout_sec = 0,
661 .keepalive = false,
662 .keep_alive_interval_sec = 0,
663 };
664
665 uint16_t receive_maximum = 9;
666 uint32_t maximum_packet_size = 128 * 1024;
667
668 struct aws_mqtt5_packet_connect_view connect_options = {
669 .keep_alive_interval_seconds = 30,
670 .client_id = aws_byte_cursor_from_string(s_client_id),
671 .clean_start = true,
672 .maximum_packet_size_bytes = &maximum_packet_size,
673 .receive_maximum = &receive_maximum,
674 };
675
676 aws_mqtt5_transform_websocket_handshake_fn *websocket_handshake_transform = NULL;
677 void *websocket_handshake_transform_user_data = NULL;
678 if (app_ctx.use_websockets) {
679 websocket_handshake_transform = &s_aws_mqtt5_transform_websocket_handshake_fn;
680 }
681
682 struct aws_mqtt5_client_options client_options = {
683 .host_name = app_ctx.uri.host_name,
684 .port = app_ctx.port,
685 .bootstrap = bootstrap,
686 .socket_options = &socket_options,
687 .tls_options = (use_tls) ? &tls_connection_options : NULL,
688 .connect_options = &connect_options,
689 .session_behavior = AWS_MQTT5_CSBT_CLEAN,
690 .lifecycle_event_handler = s_lifecycle_event_callback,
691 .lifecycle_event_handler_user_data = NULL,
692 .retry_jitter_mode = AWS_EXPONENTIAL_BACKOFF_JITTER_NONE,
693 .min_reconnect_delay_ms = 1000,
694 .max_reconnect_delay_ms = 120000,
695 .min_connected_time_to_reset_reconnect_delay_ms = 30000,
696 .ping_timeout_ms = 10000,
697 .websocket_handshake_transform = websocket_handshake_transform,
698 .websocket_handshake_transform_user_data = websocket_handshake_transform_user_data,
699 .publish_received_handler = s_on_publish_received,
700 };
701
702 struct aws_mqtt5_client *client = aws_mqtt5_client_new(allocator, &client_options);
703 aws_mqtt5_client_start(client);
704
705 bool done = false;
706 while (!done) {
707 printf("Enter command:\n");
708
709 char input_buffer[4096];
710 #ifdef WIN32
711 char *line = gets_s(input_buffer, AWS_ARRAY_SIZE(input_buffer));
712 #else
713 char *line = fgets(input_buffer, AWS_ARRAY_SIZE(input_buffer), stdin);
714 #endif
715 done = s_handle_input(client, allocator, line);
716 }
717
718 aws_mqtt5_client_release(client);
719
720 aws_client_bootstrap_release(bootstrap);
721 aws_host_resolver_release(resolver);
722 aws_event_loop_group_release(el_group);
723
724 if (tls_ctx) {
725 aws_tls_connection_options_clean_up(&tls_connection_options);
726 aws_tls_ctx_release(tls_ctx);
727 aws_tls_ctx_options_clean_up(&tls_ctx_options);
728 }
729
730 aws_thread_join_all_managed();
731
732 const size_t outstanding_bytes = aws_mem_tracer_bytes(allocator);
733 printf("Summary:\n");
734 printf(" Outstanding bytes: %zu\n\n", outstanding_bytes);
735
736 if (app_ctx.log_level) {
737 aws_logger_set(NULL);
738 aws_logger_clean_up(&logger);
739 }
740
741 aws_uri_clean_up(&app_ctx.uri);
742
743 aws_mqtt_library_clean_up();
744
745 const size_t leaked_bytes = aws_mem_tracer_bytes(allocator);
746 if (leaked_bytes) {
747 struct aws_logger memory_logger;
748 AWS_ZERO_STRUCT(memory_logger);
749
750 aws_logger_init_noalloc(&memory_logger, aws_default_allocator(), &options);
751 aws_logger_set(&memory_logger);
752
753 aws_mqtt_library_init(aws_default_allocator());
754
755 printf("Writing memory leaks to log.\n");
756 aws_mem_tracer_dump(allocator);
757
758 aws_logger_set(NULL);
759 aws_logger_clean_up(&memory_logger);
760
761 aws_mqtt_library_clean_up();
762 } else {
763 printf("Finished, with no memory leaks\n");
764 }
765
766 aws_mem_tracer_destroy(allocator);
767
768 return 0;
769 }