From 553aeeef773b13f54eca9853f7b26839f0dae680 Mon Sep 17 00:00:00 2001 From: Sergey Lyubka Date: Fri, 20 Dec 2024 06:47:31 +0000 Subject: [PATCH] Add TLS support --- tutorials/websocket/websocket-client/Makefile | 1 + tutorials/websocket/websocket-client/main.c | 31 ++++++++++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/tutorials/websocket/websocket-client/Makefile b/tutorials/websocket/websocket-client/Makefile index a990a02a..fc94d10d 100644 --- a/tutorials/websocket/websocket-client/Makefile +++ b/tutorials/websocket/websocket-client/Makefile @@ -3,6 +3,7 @@ DELETE = rm -rf # Command to remove files OUT ?= -o $(PROG) # Compiler argument for output file SOURCES = main.c mongoose.c # Source code files CFLAGS = -W -Wall -Wextra -g -I. # Build options +CFLAGS_MONGOOSE ?= -DMG_TLS=MG_TLS_BUILTIN # Mongoose build options. See https://mongoose.ws/documentation/#build-options #CFLAGS_MONGOOSE += -DMG_ENABLE_LINES diff --git a/tutorials/websocket/websocket-client/main.c b/tutorials/websocket/websocket-client/main.c index fab7bd00..b049c14e 100644 --- a/tutorials/websocket/websocket-client/main.c +++ b/tutorials/websocket/websocket-client/main.c @@ -8,11 +8,16 @@ #include "mongoose.h" static const char *s_url = "ws://localhost:8000/websocket"; +static const char *s_ca_path = "ca.pem"; // Print websocket response and signal that we're done static void fn(struct mg_connection *c, int ev, void *ev_data) { if (ev == MG_EV_OPEN) { c->is_hexdumping = 1; + } else if (ev == MG_EV_CONNECT && mg_url_is_ssl(s_url)) { + struct mg_str ca = mg_file_read(&mg_fs_posix, s_ca_path); + struct mg_tls_opts opts = {.ca = ca, .name = mg_url_host(s_url)}; + mg_tls_init(c, &opts); } else if (ev == MG_EV_ERROR) { // On error, log error message MG_ERROR(("%p %s", c->fd, (char *) ev_data)); @@ -30,13 +35,31 @@ static void fn(struct mg_connection *c, int ev, void *ev_data) { } } -int main(void) { +int main(int argc, char *argv[]) { struct mg_mgr mgr; // Event manager bool done = false; // Event handler flips it to true struct mg_connection *c; // Client connection - mg_mgr_init(&mgr); // Initialise event manager - mg_log_set(MG_LL_DEBUG); // Set log level - c = mg_ws_connect(&mgr, s_url, fn, &done, NULL); // Create client + int i; + + // Parse command-line flags + for (i = 1; i < argc; i++) { + if (strcmp(argv[i], "-url") == 0 && argv[i + 1] != NULL) { + s_url = argv[++i]; + } else if (strcmp(argv[i], "-ca") == 0 && argv[i + 1] != NULL) { + s_ca_path = argv[++i]; + } else { + printf( + "Usage: %s OPTIONS\n" + " -ca PATH - Path to the CA file, default: '%s'\n" + " -url URL - Destination URL, default: '%s'\n", + argv[0], s_ca_path, s_url); + return 1; + } + } + + mg_mgr_init(&mgr); // Initialise event manager + mg_log_set(MG_LL_DEBUG); // Set log level + c = mg_ws_connect(&mgr, s_url, fn, &done, NULL); // Create client while (c && done == false) mg_mgr_poll(&mgr, 1000); // Wait for echo mg_mgr_free(&mgr); // Deallocate resources return 0;