Skip to content

Commit

Permalink
Add TLS support
Browse files Browse the repository at this point in the history
  • Loading branch information
cpq committed Dec 20, 2024
1 parent 6147e86 commit 553aeee
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 4 deletions.
1 change: 1 addition & 0 deletions tutorials/websocket/websocket-client/Makefile
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
31 changes: 27 additions & 4 deletions tutorials/websocket/websocket-client/main.c
Original file line number Diff line number Diff line change
Expand Up @@ -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));
Expand All @@ -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;
Expand Down

0 comments on commit 553aeee

Please sign in to comment.