mirror of
https://github.com/cesanta/mongoose.git
synced 2026-10-18 10:59:45 +00:00
move to new skeleton
This commit is contained in:
1 parent
290d48e1aa
commit
8c5dfa4227
82 files changed
+34
-34
No files matched your search
@@ -0,0 +1,39 @@
|
||||
PROG ?= example # Program we are building
|
||||
PACK ?= ./pack # Packing executable
|
||||
DELETE = rm -rf # Command to remove files
|
||||
OUT ?= -o $(PROG) # Compiler argument for output file
|
||||
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
|
||||
CFLAGS = -W -Wall -Wextra -g -I. # Build options
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
PACK = pack.exe # Packing executable
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
MAKE += WINDOWS=1 CC=$(CC)
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls $(PACK)
|
||||
|
||||
# Generate packed filesystem for serving cert
|
||||
packed_fs.c: $(wildcard certs/*) Makefile
|
||||
$(CC) ../../../test/pack.c -o $(PACK)
|
||||
$(PACK) $(wildcard certs/*) > $@
|
||||
|
||||
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
|
||||
|
||||
mbedtls: # Pull and build mbedTLS library
|
||||
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
|
||||
$(MAKE) -C mbedtls/library
|
||||
@@ -0,0 +1 @@
|
||||
See detailed tutorial at https://mongoose.ws/tutorials/http/http-client/
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../../test/data/ca.pem
|
||||
@@ -0,0 +1,72 @@
|
||||
// Copyright (c) 2021 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Example HTTP client. Connect to `s_url`, send request, wait for a response,
|
||||
// print the response and exit.
|
||||
// You can change `s_url` from the command line by executing: ./example YOUR_URL
|
||||
//
|
||||
// To enable SSL/TLS, , see https://mongoose.ws/tutorials/tls/#how-to-build
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
// The very first web page in history. You can replace it from command line
|
||||
static const char *s_url = "http://info.cern.ch/";
|
||||
static const char *s_post_data = NULL; // POST data
|
||||
static const uint64_t s_timeout_ms = 1500; // Connect timeout in milliseconds
|
||||
|
||||
// Print HTTP response and signal that we're done
|
||||
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_OPEN) {
|
||||
// Connection created. Store connect expiration time in c->data
|
||||
*(uint64_t *) c->data = mg_millis() + s_timeout_ms;
|
||||
} else if (ev == MG_EV_POLL) {
|
||||
if (mg_millis() > *(uint64_t *) c->data &&
|
||||
(c->is_connecting || c->is_resolving)) {
|
||||
mg_error(c, "Connect timeout");
|
||||
}
|
||||
} else if (ev == MG_EV_CONNECT) {
|
||||
// Connected to server. Extract host name from URL
|
||||
struct mg_str host = mg_url_host(s_url);
|
||||
|
||||
if (mg_url_is_ssl(s_url)) {
|
||||
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
|
||||
.name = mg_url_host(s_url)};
|
||||
mg_tls_init(c, &opts);
|
||||
}
|
||||
|
||||
// Send request
|
||||
int content_length = s_post_data ? strlen(s_post_data) : 0;
|
||||
mg_printf(c,
|
||||
"%s %s HTTP/1.0\r\n"
|
||||
"Host: %.*s\r\n"
|
||||
"Content-Type: octet-stream\r\n"
|
||||
"Content-Length: %d\r\n"
|
||||
"\r\n",
|
||||
s_post_data ? "POST" : "GET", mg_url_uri(s_url), (int) host.len,
|
||||
host.buf, content_length);
|
||||
mg_send(c, s_post_data, content_length);
|
||||
} else if (ev == MG_EV_HTTP_MSG) {
|
||||
// Response is received. Print it
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
printf("%.*s", (int) hm->message.len, hm->message.buf);
|
||||
c->is_draining = 1; // Tell mongoose to close this connection
|
||||
*(bool *) c->fn_data = true; // Tell event loop to stop
|
||||
} else if (ev == MG_EV_ERROR) {
|
||||
*(bool *) c->fn_data = true; // Error, tell event loop to stop
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
const char *log_level = getenv("LOG_LEVEL"); // Allow user to set log level
|
||||
if (log_level == NULL) log_level = "4"; // Default is verbose
|
||||
|
||||
struct mg_mgr mgr; // Event manager
|
||||
bool done = false; // Event handler flips it to true
|
||||
if (argc > 1) s_url = argv[1]; // Use URL provided in the command line
|
||||
mg_log_set(atoi(log_level)); // Set to 0 to disable debug
|
||||
mg_mgr_init(&mgr); // Initialise event manager
|
||||
mg_http_connect(&mgr, s_url, fn, &done); // Create client connection
|
||||
while (!done) mg_mgr_poll(&mgr, 50); // Event manager loops until 'done'
|
||||
mg_mgr_free(&mgr); // Free resources
|
||||
return 0;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../mongoose.c
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../mongoose.h
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,35 @@
|
||||
PROG ?= example # Program we are building
|
||||
DELETE = rm -rf # Command to remove files
|
||||
OUT ?= -o $(PROG) # Compiler argument for output file
|
||||
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
|
||||
CFLAGS = -W -Wall -Wextra -g -I. # Build options
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
|
||||
|
||||
# See tutorial at https://mongoose.ws/tutorials/http-proxy-client/
|
||||
ARGS ?= 167.235.63.238:3128 http://info.cern.ch/ # default call arguments
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
MAKE += WINDOWS=1 CC=$(CC)
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
|
||||
|
||||
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
|
||||
|
||||
mbedtls: # Pull and build mbedTLS library
|
||||
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
|
||||
$(MAKE) -C mbedtls/library
|
||||
@@ -0,0 +1 @@
|
||||
See detailed tutorial at https://mongoose.ws/tutorials/http/http-proxy-client/
|
||||
@@ -0,0 +1,68 @@
|
||||
// Copyright (c) 2020 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Example HTTP client that uses a proxy server. Usage:
|
||||
// make
|
||||
// ./example PROXY:PORT http://www.ladyada.net
|
||||
//
|
||||
// To enable SSL/TLS, see https://mongoose.ws/tutorials/tls/#how-to-build
|
||||
//
|
||||
#include "mongoose.h"
|
||||
|
||||
// Print HTTP response and signal that we're done
|
||||
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
const char *url = c->fn_data;
|
||||
static bool connected;
|
||||
if (ev == MG_EV_HTTP_MSG) {
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
printf("%.*s", (int) hm->message.len, hm->message.buf);
|
||||
exit(EXIT_SUCCESS);
|
||||
} else if (ev == MG_EV_CONNECT) {
|
||||
// Proxy TCP connection established. Send CONNECT request
|
||||
struct mg_str host = mg_url_host(url);
|
||||
|
||||
if (mg_url_is_ssl(url)) {
|
||||
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
|
||||
.name = host};
|
||||
mg_tls_init(c, &opts);
|
||||
}
|
||||
|
||||
// c->is_hexdumping = 1;
|
||||
mg_printf(c, "CONNECT %.*s:%hu HTTP/1.1\r\nHost: %.*s:%hu\r\n\r\n",
|
||||
(int) host.len, host.buf, mg_url_port(url), (int) host.len,
|
||||
host.buf, mg_url_port(url));
|
||||
} else if (!connected && ev == MG_EV_READ) {
|
||||
struct mg_http_message hm;
|
||||
int n = mg_http_parse((char *) c->recv.buf, c->recv.len, &hm);
|
||||
if (n > 0) {
|
||||
struct mg_str host = mg_url_host(url);
|
||||
// CONNECT response - tunnel is established
|
||||
connected = true;
|
||||
MG_DEBUG(
|
||||
("Connected to proxy, status: %.*s", (int) hm.uri.len, hm.uri.buf));
|
||||
mg_iobuf_del(&c->recv, 0, n);
|
||||
// Send request to the target server
|
||||
mg_printf(c,
|
||||
"GET %s HTTP/1.0\r\n"
|
||||
"Host: %.*s\r\n"
|
||||
"\r\n",
|
||||
mg_url_uri(url), (int) host.len, host.buf);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
struct mg_mgr mgr;
|
||||
|
||||
if (argc != 3) {
|
||||
fprintf(stderr, "Usage: %s PROXY_URL URL\n", argv[0]);
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
mg_mgr_init(&mgr); // Initialise event manager
|
||||
mg_http_connect(&mgr, argv[1], fn, argv[2]); // Connect to the proxy
|
||||
for (;;) mg_mgr_poll(&mgr, 1000); // Event loop
|
||||
mg_mgr_free(&mgr);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.c
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.h
|
||||
@@ -0,0 +1 @@
|
||||
../http-client/packed_fs.c
|
||||
@@ -0,0 +1,32 @@
|
||||
PROG ?= example # Program we are building
|
||||
DELETE = rm -rf # Command to remove files
|
||||
OUT ?= -o $(PROG) # Compiler argument for output file
|
||||
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
|
||||
CFLAGS = -W -Wall -Wextra -g -I. # Build options
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
|
||||
CFLAGS_MONGOOSE += -DMG_IO_SIZE=128 -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
MAKE += WINDOWS=1 CC=$(CC)
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
|
||||
|
||||
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
|
||||
|
||||
mbedtls: # Pull and build mbedTLS library
|
||||
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
|
||||
$(MAKE) -C mbedtls/library
|
||||
@@ -0,0 +1 @@
|
||||
See detailed tutorial at https://mongoose.ws/tutorials/http/http-reverse-proxy/
|
||||
@@ -0,0 +1,87 @@
|
||||
// Copyright (c) 2020 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Example HTTP reverse proxy
|
||||
// 1. Run `make`. This builds and starts a proxy on port 8000
|
||||
// 2. Start your browser, go to https://localhost:8000
|
||||
//
|
||||
// To enable SSL/TLS, see https://mongoose.ws/tutorials/tls/#how-to-build
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
static const char *s_backend_url =
|
||||
#if MG_TLS
|
||||
"https://cesanta.com";
|
||||
#else
|
||||
"http://info.cern.ch";
|
||||
#endif
|
||||
static const char *s_listen_url = "http://localhost:8000";
|
||||
|
||||
// Forward client request to the backend connection, rewriting the Host header
|
||||
static void forward_request(struct mg_http_message *hm,
|
||||
struct mg_connection *c) {
|
||||
size_t i, max = sizeof(hm->headers) / sizeof(hm->headers[0]);
|
||||
struct mg_str host = mg_url_host(s_backend_url);
|
||||
mg_printf(c, "%.*s\r\n",
|
||||
(int) (hm->proto.buf + hm->proto.len - hm->message.buf),
|
||||
hm->message.buf);
|
||||
for (i = 0; i < max && hm->headers[i].name.len > 0; i++) {
|
||||
struct mg_str *k = &hm->headers[i].name, *v = &hm->headers[i].value;
|
||||
if (mg_strcmp(*k, mg_str("Host")) == 0) v = &host;
|
||||
mg_printf(c, "%.*s: %.*s\r\n", (int) k->len, k->buf, (int) v->len, v->buf);
|
||||
}
|
||||
mg_send(c, "\r\n", 2);
|
||||
mg_send(c, hm->body.buf, hm->body.len);
|
||||
MG_DEBUG(("FORWARDING: %.*s %.*s", (int) hm->method.len, hm->method.buf,
|
||||
(int) hm->uri.len, hm->uri.buf));
|
||||
}
|
||||
|
||||
static void fn2(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct mg_connection *c2 = (struct mg_connection *) c->fn_data;
|
||||
if (ev == MG_EV_READ) {
|
||||
// All incoming data from the backend, forward to the client
|
||||
if (c2 != NULL) mg_send(c2, c->recv.buf, c->recv.len);
|
||||
mg_iobuf_del(&c->recv, 0, c->recv.len);
|
||||
} else if (ev == MG_EV_CLOSE) {
|
||||
if (c2 != NULL) c2->fn_data = NULL;
|
||||
}
|
||||
(void) ev_data;
|
||||
}
|
||||
|
||||
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
struct mg_connection *c2 = c->fn_data;
|
||||
if (ev == MG_EV_HTTP_MSG) {
|
||||
struct mg_http_message *hm = (struct mg_http_message *) ev_data;
|
||||
// Client request, create backend connection Note that we're passing
|
||||
// client connection `c` as fn_data for the created backend connection.
|
||||
c2 = mg_connect(c->mgr, s_backend_url, fn2, c);
|
||||
if (c2 == NULL) {
|
||||
mg_error(c, "Cannot create backend connection");
|
||||
} else {
|
||||
if (mg_url_is_ssl(s_backend_url)) {
|
||||
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
|
||||
.name = mg_url_host(s_backend_url)};
|
||||
mg_tls_init(c2, &opts);
|
||||
}
|
||||
c->fn_data = c2;
|
||||
forward_request(hm, c2);
|
||||
c->is_resp = 0; // process further msgs in keep-alive connection
|
||||
c2->is_hexdumping = 1;
|
||||
}
|
||||
} else if (ev == MG_EV_CLOSE) {
|
||||
if (c2 != NULL) c2->is_closing = 1;
|
||||
if (c2 != NULL) c2->fn_data = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
struct mg_mgr mgr;
|
||||
|
||||
mg_log_set(MG_LL_DEBUG); // Set log level
|
||||
mg_mgr_init(&mgr); // Initialise event manager
|
||||
mg_http_listen(&mgr, s_listen_url, fn, NULL); // Start proxy
|
||||
for (;;) mg_mgr_poll(&mgr, 1000); // Event loop
|
||||
mg_mgr_free(&mgr);
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.c
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.h
|
||||
@@ -0,0 +1 @@
|
||||
../http-client/packed_fs.c
|
||||
@@ -0,0 +1,32 @@
|
||||
PROG ?= example # Program we are building
|
||||
DELETE = rm -rf # Command to remove files
|
||||
OUT ?= -o $(PROG) # Compiler argument for output file
|
||||
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
|
||||
CFLAGS = -W -Wall -Wextra -g -I. # Build options
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
MAKE += WINDOWS=1 CC=$(CC)
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
|
||||
|
||||
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
|
||||
|
||||
mbedtls: # Pull and build mbedTLS library
|
||||
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
|
||||
$(MAKE) -C mbedtls/library
|
||||
@@ -0,0 +1,70 @@
|
||||
// Copyright (c) 2021 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Example streaming HTTP client.
|
||||
// The default HTTP handler waits until the whole HTTP message is buffered in
|
||||
// c->recv IO buffer. It can be large. This example shows how to receive
|
||||
// a potentially large response in chunks by handling the MG_EV_READ events.
|
||||
//
|
||||
// You can change `s_url` from the command line by executing: ./example YOUR_URL
|
||||
// To enable SSL/TLS, see https://mongoose.ws/tutorials/tls/#how-to-build
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
// The very first web page in history. You can replace it from command line
|
||||
static const char *s_url = "http://info.cern.ch";
|
||||
|
||||
// Print HTTP response and signal that we're done
|
||||
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_CONNECT) {
|
||||
// Connected to server. Extract host name from URL
|
||||
struct mg_str host = mg_url_host(s_url);
|
||||
if (mg_url_is_ssl(s_url)) {
|
||||
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
|
||||
.name = host};
|
||||
mg_tls_init(c, &opts);
|
||||
}
|
||||
// Send request
|
||||
mg_printf(c,
|
||||
"GET %s HTTP/1.1\r\n"
|
||||
"Connection: close\r\n"
|
||||
"Host: %.*s\r\n"
|
||||
"\r\n",
|
||||
mg_url_uri(s_url), (int) host.len, host.buf);
|
||||
} else if (ev == MG_EV_READ) {
|
||||
// c->data[0] holds a flag, whether we have parsed the request already
|
||||
if (c->data[0] == 0) {
|
||||
struct mg_http_message hm;
|
||||
int n = mg_http_parse((char *) c->recv.buf, c->recv.len, &hm);
|
||||
if (n < 0) mg_error(c, "Bad response");
|
||||
if (n > 0) {
|
||||
fwrite(c->recv.buf + n, 1, c->recv.len - n, stdout); // Print body
|
||||
c->recv.len = 0; // Cleanup receive buffer
|
||||
c->data[0] = 1; // Request parsed, set the flag
|
||||
}
|
||||
} else {
|
||||
fwrite(c->recv.buf, 1, c->recv.len, stdout);
|
||||
c->recv.len = 0; // Cleanup the receive buffer
|
||||
}
|
||||
} else if (ev == MG_EV_CLOSE) {
|
||||
*(bool *) c->fn_data = true; // Done, tell event loop to stop
|
||||
} else if (ev == MG_EV_ERROR) {
|
||||
*(bool *) c->fn_data = true; // Error, Tell event loop to stop
|
||||
}
|
||||
(void) ev_data;
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
struct mg_mgr mgr; // Event manager
|
||||
bool done = false; // Event handler flips it to true
|
||||
|
||||
mg_mgr_init(&mgr); // Initialise event manager
|
||||
mg_log_set(MG_LL_INFO); // Set to 0 to disable debug log
|
||||
|
||||
if (argc > 1) s_url = argv[1]; // Use URL from command line
|
||||
mg_connect(&mgr, s_url, fn, &done); // Create client connection
|
||||
while (!done) mg_mgr_poll(&mgr, 1000); // Infinite event loop
|
||||
mg_mgr_free(&mgr); // Free resources
|
||||
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.c
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.h
|
||||
@@ -0,0 +1 @@
|
||||
../http-client/packed_fs.c
|
||||
@@ -0,0 +1,32 @@
|
||||
PROG ?= example # Program we are building
|
||||
DELETE = rm -rf # Command to remove files
|
||||
OUT ?= -o $(PROG) # Compiler argument for output file
|
||||
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
|
||||
CFLAGS = -W -Wall -Wextra -g -I. # Build options
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
MAKE += WINDOWS=1 CC=$(CC)
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
|
||||
|
||||
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
|
||||
|
||||
mbedtls: # Pull and build mbedTLS library
|
||||
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
|
||||
$(MAKE) -C mbedtls/library
|
||||
@@ -0,0 +1,2 @@
|
||||
- This example requires generating AWS and user credentials and downloading certificates
|
||||
- This example requires building with TLS support; before running, see detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-client-aws-iot/
|
||||
@@ -0,0 +1,101 @@
|
||||
// Copyright (c) 2020 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Example MQTT client. It performs the following steps:
|
||||
// 1. Connects to the AWS IoT MQTT server
|
||||
// 2. When connected, subscribes to the topic `s_rx_topic`
|
||||
// 3. Publishes message `hello` to the `s_tx_topic` periodically
|
||||
//
|
||||
// This example requires TLS support. By default, it is built with mbedTLS,
|
||||
// therefore make sure mbedTLS is installed. To build with OpenSSL, execute:
|
||||
// make clean all CFLAGS="-W -Wall -DMG_ENABLE_OPENSSL=1 -lssl"
|
||||
|
||||
// In order to get MQTT URL, login to AWS IoT, click on "Settings" on the left
|
||||
// bar, copy the "Endpoint" URL.
|
||||
static const char *s_url =
|
||||
"mqtts://a1pjwh2bop1ojt-ats.iot.eu-west-1.amazonaws.com";
|
||||
|
||||
// To create certificates:
|
||||
// 1. Click Policies -> Create, fill fields:
|
||||
// Name : Policy1
|
||||
// Action : iot:*
|
||||
// Resource ARN: *
|
||||
// Effect : allow
|
||||
// then, click "Create"
|
||||
// 2. Click Manage -> Things -> Create things -> Create single thing -> Next
|
||||
// Thing name: t1, no shadow, Next
|
||||
// Auto-generate new certificate, Next
|
||||
// Select policy Policy1, Create thing
|
||||
// 3. From the dialog box that appears, download:
|
||||
// xxx-certificate.pem.crt as cert.pem to the example directory
|
||||
// xxx-private.pem.key as key.pem to the example directory
|
||||
// static const char *s_cert = "cert.pem";
|
||||
// static const char *s_key = "key.pem";
|
||||
|
||||
static const char *s_rx_topic = "d/rx";
|
||||
static const char *s_tx_topic = "d/tx";
|
||||
static int s_qos = 1;
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
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) {
|
||||
if (mg_url_is_ssl(s_url)) {
|
||||
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
|
||||
.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));
|
||||
} else if (ev == MG_EV_MQTT_OPEN) {
|
||||
// MQTT connect is successful
|
||||
struct mg_str topic = mg_str(s_rx_topic);
|
||||
MG_INFO(("Connected to %s", s_url));
|
||||
MG_INFO(("Subscribing to %s", s_rx_topic));
|
||||
struct mg_mqtt_opts sub_opts;
|
||||
memset(&sub_opts, 0, sizeof(sub_opts));
|
||||
sub_opts.topic = topic;
|
||||
sub_opts.qos = s_qos;
|
||||
mg_mqtt_sub(c, &sub_opts);
|
||||
c->data[0] = 'X'; // Set a label that we're logged in
|
||||
} else if (ev == MG_EV_MQTT_MSG) {
|
||||
// When we receive MQTT message, print it
|
||||
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
|
||||
MG_INFO(("Received on %.*s : %.*s", (int) mm->topic.len, mm->topic.buf,
|
||||
(int) mm->data.len, mm->data.buf));
|
||||
} else if (ev == MG_EV_POLL && c->data[0] == 'X') {
|
||||
static unsigned long prev_second;
|
||||
unsigned long now_second = (*(unsigned long *) ev_data) / 1000;
|
||||
if (now_second != prev_second) {
|
||||
struct mg_str topic = mg_str(s_tx_topic), data = mg_str("{\"a\":123}");
|
||||
MG_INFO(("Publishing to %s", s_tx_topic));
|
||||
struct mg_mqtt_opts pub_opts;
|
||||
memset(&pub_opts, 0, sizeof(pub_opts));
|
||||
pub_opts.topic = topic;
|
||||
pub_opts.message = data;
|
||||
pub_opts.qos = s_qos, pub_opts.retain = false;
|
||||
mg_mqtt_pub(c, &pub_opts);
|
||||
prev_second = now_second;
|
||||
}
|
||||
}
|
||||
|
||||
if (ev == MG_EV_ERROR || ev == MG_EV_CLOSE) {
|
||||
MG_INFO(("Got event %d, stopping...", ev));
|
||||
*(bool *) c->fn_data = true; // Signal that we're done
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
struct mg_mgr mgr;
|
||||
struct mg_mqtt_opts opts = {.clean = true};
|
||||
bool done = false;
|
||||
mg_mgr_init(&mgr); // Initialise event manager
|
||||
MG_INFO(("Connecting to %s", s_url)); // Inform that we're starting
|
||||
mg_mqtt_connect(&mgr, s_url, &opts, fn, &done); // Create client connection
|
||||
while (!done) mg_mgr_poll(&mgr, 1000); // Loop until done
|
||||
mg_mgr_free(&mgr); // Finished, cleanup
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.c
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.h
|
||||
@@ -0,0 +1 @@
|
||||
../../http/http-client/packed_fs.c
|
||||
@@ -0,0 +1,32 @@
|
||||
PROG ?= example # Program we are building
|
||||
DELETE = rm -rf # Command to remove files
|
||||
OUT ?= -o $(PROG) # Compiler argument for output file
|
||||
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
|
||||
CFLAGS = -W -Wall -Wextra -g -I. # Build options
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
MAKE += WINDOWS=1 CC=$(CC)
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
|
||||
|
||||
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
|
||||
|
||||
mbedtls: # Pull and build mbedTLS library
|
||||
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
|
||||
$(MAKE) -C mbedtls/library
|
||||
@@ -0,0 +1 @@
|
||||
See detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-client/
|
||||
@@ -0,0 +1,114 @@
|
||||
// Copyright (c) 2023 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Example MQTT client. It performs the following steps:
|
||||
// 1. Connects to the MQTT server specified by `s_url` variable
|
||||
// 2. When connected, subscribes to the topic `s_sub_topic`
|
||||
// 3. Publishes message `hello` to the `s_pub_topic`
|
||||
// 4. Receives that message back from the subscribed topic and closes
|
||||
// 5. Timer-based reconnection logic revives the connection when it is down
|
||||
//
|
||||
// To enable SSL/TLS, see https://mongoose.ws/tutorials/tls/#how-to-build
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
static const char *s_url = "mqtt://broker.hivemq.com:1883";
|
||||
static const char *s_sub_topic = "mg/+/test"; // Publish topic
|
||||
static const char *s_pub_topic = "mg/clnt/test"; // Subscribe topic
|
||||
static int s_qos = 1; // MQTT QoS
|
||||
static struct mg_connection *s_conn; // Client connection
|
||||
|
||||
// Handle interrupts, like Ctrl-C
|
||||
static int s_signo;
|
||||
static void signal_handler(int signo) {
|
||||
s_signo = signo;
|
||||
}
|
||||
|
||||
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_OPEN) {
|
||||
MG_INFO(("%lu CREATED", c->id));
|
||||
// c->is_hexdumping = 1;
|
||||
} else if (ev == MG_EV_CONNECT) {
|
||||
if (mg_url_is_ssl(s_url)) {
|
||||
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
|
||||
.name = mg_url_host(s_url)};
|
||||
mg_tls_init(c, &opts);
|
||||
}
|
||||
} else if (ev == MG_EV_ERROR) {
|
||||
// On error, log error message
|
||||
MG_ERROR(("%lu ERROR %s", c->id, (char *) ev_data));
|
||||
} else if (ev == MG_EV_MQTT_OPEN) {
|
||||
// MQTT connect is successful
|
||||
struct mg_str subt = mg_str(s_sub_topic);
|
||||
struct mg_str pubt = mg_str(s_pub_topic), data = mg_str("hello");
|
||||
MG_INFO(("%lu CONNECTED to %s", c->id, s_url));
|
||||
struct mg_mqtt_opts sub_opts;
|
||||
memset(&sub_opts, 0, sizeof(sub_opts));
|
||||
sub_opts.topic = subt;
|
||||
sub_opts.qos = s_qos;
|
||||
mg_mqtt_sub(c, &sub_opts);
|
||||
MG_INFO(("%lu SUBSCRIBED to %.*s", c->id, (int) subt.len, subt.buf));
|
||||
struct mg_mqtt_opts pub_opts;
|
||||
memset(&pub_opts, 0, sizeof(pub_opts));
|
||||
pub_opts.topic = pubt;
|
||||
pub_opts.message = data;
|
||||
pub_opts.qos = s_qos, pub_opts.retain = false;
|
||||
mg_mqtt_pub(c, &pub_opts);
|
||||
MG_INFO(("%lu PUBLISHED %.*s -> %.*s", c->id, (int) data.len, data.buf,
|
||||
(int) pubt.len, pubt.buf));
|
||||
} else if (ev == MG_EV_MQTT_MSG) {
|
||||
// When we get echo response, print it
|
||||
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
|
||||
MG_INFO(("%lu RECEIVED %.*s <- %.*s", c->id, (int) mm->data.len,
|
||||
mm->data.buf, (int) mm->topic.len, mm->topic.buf));
|
||||
} else if (ev == MG_EV_CLOSE) {
|
||||
MG_INFO(("%lu CLOSED", c->id));
|
||||
s_conn = NULL; // Mark that we're closed
|
||||
}
|
||||
}
|
||||
|
||||
// Timer function - recreate client connection if it is closed
|
||||
static void timer_fn(void *arg) {
|
||||
struct mg_mgr *mgr = (struct mg_mgr *) arg;
|
||||
struct mg_mqtt_opts opts = {.clean = true,
|
||||
.qos = s_qos,
|
||||
.topic = mg_str(s_pub_topic),
|
||||
.version = 4,
|
||||
.message = mg_str("bye")};
|
||||
if (s_conn == NULL) s_conn = mg_mqtt_connect(mgr, s_url, &opts, fn, NULL);
|
||||
}
|
||||
|
||||
int main(int argc, char *argv[]) {
|
||||
struct mg_mgr mgr;
|
||||
int i;
|
||||
|
||||
// Parse command-line flags
|
||||
for (i = 1; i < argc; i++) {
|
||||
if (strcmp(argv[i], "-u") == 0 && argv[i + 1] != NULL) {
|
||||
s_url = argv[++i];
|
||||
} else if (strcmp(argv[i], "-p") == 0 && argv[i + 1] != NULL) {
|
||||
s_pub_topic = argv[++i];
|
||||
} else if (strcmp(argv[i], "-s") == 0 && argv[i + 1] != NULL) {
|
||||
s_sub_topic = argv[++i];
|
||||
} else if (strcmp(argv[i], "-v") == 0 && argv[i + 1] != NULL) {
|
||||
mg_log_set(atoi(argv[++i]));
|
||||
} else {
|
||||
MG_ERROR(("Unknown option: %s. Usage:", argv[i]));
|
||||
MG_ERROR(
|
||||
("%s [-u mqtts://SERVER:PORT] [-p PUB_TOPIC] [-s SUB_TOPIC] "
|
||||
"[-v DEBUG_LEVEL]",
|
||||
argv[0], argv[i]));
|
||||
return 1;
|
||||
}
|
||||
}
|
||||
|
||||
signal(SIGINT, signal_handler); // Setup signal handlers - exist event
|
||||
signal(SIGTERM, signal_handler); // manager loop on SIGINT and SIGTERM
|
||||
|
||||
mg_mgr_init(&mgr);
|
||||
mg_timer_add(&mgr, 3000, MG_TIMER_REPEAT | MG_TIMER_RUN_NOW, timer_fn, &mgr);
|
||||
while (s_signo == 0) mg_mgr_poll(&mgr, 1000); // Event loop, 1s timeout
|
||||
mg_mgr_free(&mgr); // Finished, cleanup
|
||||
|
||||
return 0;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../mongoose.c
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../mongoose.h
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../http/http-client/packed_fs.c
|
||||
@@ -0,0 +1,32 @@
|
||||
PROG ?= example # Program we are building
|
||||
DELETE = rm -rf # Command to remove files
|
||||
OUT ?= -o $(PROG) # Compiler argument for output file
|
||||
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
|
||||
CFLAGS = -W -Wall -Wextra -g -I. # Build options
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
MAKE += WINDOWS=1 CC=$(CC)
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
|
||||
|
||||
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
|
||||
|
||||
mbedtls: # Pull and build mbedTLS library
|
||||
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
|
||||
$(MAKE) -C mbedtls/library
|
||||
@@ -0,0 +1 @@
|
||||
See detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-over-ws-client/
|
||||
@@ -0,0 +1,106 @@
|
||||
// Copyright (c) 2020 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Example MQTT client. It performs the following steps:
|
||||
// 1. Connects to the MQTT server specified by `s_url` variable
|
||||
// 2. When connected, subscribes to the topic `s_topic`
|
||||
// 3. Publishes message `hello` to the `s_topic`
|
||||
// 4. Receives that message back from the subscribed topic and exits
|
||||
//
|
||||
// To enable SSL/TLS, see https://mongoose.ws/tutorials/tls/#how-to-build
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
static const char *s_url =
|
||||
#if MG_TLS
|
||||
"wss://broker.hivemq.com:8884/mqtt";
|
||||
#else
|
||||
"ws://broker.hivemq.com:8000/mqtt";
|
||||
#endif
|
||||
|
||||
static const char *s_topic = "mg/test";
|
||||
|
||||
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_ERROR) {
|
||||
// On error, log error message
|
||||
MG_ERROR(("%p %s", c->fd, (char *) ev_data));
|
||||
} else if (ev == MG_EV_CONNECT) {
|
||||
if (mg_url_is_ssl(s_url)) {
|
||||
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
|
||||
.name = mg_url_host(s_url)};
|
||||
mg_tls_init(c, &opts);
|
||||
}
|
||||
} else if (ev == MG_EV_WS_OPEN) {
|
||||
// WS connection established. Perform MQTT login
|
||||
MG_INFO(("Connected to WS. Logging in to MQTT..."));
|
||||
struct mg_mqtt_opts opts = {
|
||||
.qos = 1, .topic = mg_str(s_topic), .message = mg_str("goodbye")};
|
||||
size_t len = c->send.len;
|
||||
mg_mqtt_login(c, &opts);
|
||||
mg_ws_wrap(c, c->send.len - len, WEBSOCKET_OP_BINARY);
|
||||
c->is_hexdumping = 1;
|
||||
} else if (ev == MG_EV_WS_MSG) {
|
||||
struct mg_mqtt_message mm;
|
||||
struct mg_ws_message *wm = (struct mg_ws_message *) ev_data;
|
||||
uint8_t version = c->is_mqtt5 ? 5 : 4;
|
||||
MG_INFO(("GOT %d bytes WS msg", (int) wm->data.len));
|
||||
while ((mg_mqtt_parse((uint8_t *) wm->data.buf, wm->data.len, version,
|
||||
&mm)) == MQTT_OK) {
|
||||
switch (mm.cmd) {
|
||||
case MQTT_CMD_CONNACK:
|
||||
mg_call(c, MG_EV_MQTT_OPEN, &mm.ack);
|
||||
if (mm.ack == 0) {
|
||||
struct mg_str topic = mg_str(s_topic), data = mg_str("hello");
|
||||
size_t len = c->send.len;
|
||||
MG_INFO(("CONNECTED to %s", s_url));
|
||||
struct mg_mqtt_opts sub_opts;
|
||||
memset(&sub_opts, 0, sizeof(sub_opts));
|
||||
sub_opts.topic = topic;
|
||||
sub_opts.qos = 1;
|
||||
mg_mqtt_sub(c, &sub_opts);
|
||||
len = mg_ws_wrap(c, c->send.len - len, WEBSOCKET_OP_BINARY);
|
||||
MG_INFO(("SUBSCRIBED to %.*s", (int) topic.len, topic.buf));
|
||||
struct mg_mqtt_opts pub_opts;
|
||||
memset(&pub_opts, 0, sizeof(pub_opts));
|
||||
pub_opts.topic = topic;
|
||||
pub_opts.message = data;
|
||||
pub_opts.qos = 1, pub_opts.retain = false;
|
||||
mg_mqtt_pub(c, &pub_opts);
|
||||
MG_INFO(("PUBLISHED %.*s -> %.*s", (int) data.len, data.buf,
|
||||
(int) topic.len, topic.buf));
|
||||
len = mg_ws_wrap(c, c->send.len - len, WEBSOCKET_OP_BINARY);
|
||||
} else {
|
||||
MG_ERROR(("%lu MQTT auth failed, code %d", c->id, mm.ack));
|
||||
c->is_draining = 1;
|
||||
}
|
||||
break;
|
||||
case MQTT_CMD_PUBLISH: {
|
||||
MG_DEBUG(("%lu [%.*s] -> [%.*s]", c->id, (int) mm.topic.len,
|
||||
mm.topic.buf, (int) mm.data.len, mm.data.buf));
|
||||
MG_INFO(("RECEIVED %.*s <- %.*s", (int) mm.data.len, mm.data.buf,
|
||||
(int) mm.topic.len, mm.topic.buf));
|
||||
c->is_draining = 1;
|
||||
break;
|
||||
}
|
||||
}
|
||||
wm->data.buf += mm.dgram.len;
|
||||
wm->data.len -= mm.dgram.len;
|
||||
}
|
||||
}
|
||||
|
||||
if (ev == MG_EV_ERROR || ev == MG_EV_CLOSE) {
|
||||
*(bool *) c->fn_data = true; // Signal that we're done
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
struct mg_mgr mgr; // Event manager
|
||||
bool done = false; // Event handler flips it to true when done
|
||||
mg_mgr_init(&mgr); // Initialise event manager
|
||||
mg_log_set(MG_LL_DEBUG); // Set log level
|
||||
mg_ws_connect(&mgr, s_url, fn, &done, "%s", // Create client connection
|
||||
"Sec-Websocket-Protocol: mqtt\r\n"); // Request MQTT protocol
|
||||
while (done == false) mg_mgr_poll(&mgr, 1000); // Event loop
|
||||
mg_mgr_free(&mgr); // Finished, cleanup
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.c
|
||||
@@ -0,0 +1 @@
|
||||
../../../mongoose.h
|
||||
@@ -0,0 +1 @@
|
||||
../../http/http-client/packed_fs.c
|
||||
@@ -0,0 +1,25 @@
|
||||
PROG ?= example # Program we are building
|
||||
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
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM
|
||||
@@ -0,0 +1 @@
|
||||
See detailed tutorial at https://mongoose.ws/tutorials/mqtt/mqtt-server/
|
||||
@@ -0,0 +1,146 @@
|
||||
// Copyright (c) 2020 Cesanta Software Limited
|
||||
// All rights reserved
|
||||
//
|
||||
// Example MQTT server. Usage:
|
||||
// 1. Start this server, type `make`
|
||||
// 2. Install mosquitto MQTT client
|
||||
// 3. In one terminal, run: mosquitto_sub -h localhost -t foo -t bar
|
||||
// 4. In another, run: mosquitto_pub -h localhost -t foo -m hi
|
||||
|
||||
#include "mongoose.h"
|
||||
|
||||
static const char *s_listen_on = "mqtt://0.0.0.0:1883";
|
||||
|
||||
// A list of subscription, held in memory
|
||||
struct sub {
|
||||
struct sub *next;
|
||||
struct mg_connection *c;
|
||||
struct mg_str topic;
|
||||
uint8_t qos;
|
||||
};
|
||||
static struct sub *s_subs = NULL;
|
||||
|
||||
// Handle interrupts, like Ctrl-C
|
||||
static int s_signo;
|
||||
static void signal_handler(int signo) {
|
||||
s_signo = signo;
|
||||
}
|
||||
|
||||
static size_t mg_mqtt_next_topic(struct mg_mqtt_message *msg,
|
||||
struct mg_str *topic, uint8_t *qos,
|
||||
size_t pos) {
|
||||
unsigned char *buf = (unsigned char *) msg->dgram.buf + pos;
|
||||
size_t new_pos;
|
||||
if (pos >= msg->dgram.len) return 0;
|
||||
|
||||
topic->len = (size_t) (((unsigned) buf[0]) << 8 | buf[1]);
|
||||
topic->buf = (char *) buf + 2;
|
||||
new_pos = pos + 2 + topic->len + (qos == NULL ? 0 : 1);
|
||||
if ((size_t) new_pos > msg->dgram.len) return 0;
|
||||
if (qos != NULL) *qos = buf[2 + topic->len];
|
||||
return new_pos;
|
||||
}
|
||||
|
||||
size_t mg_mqtt_next_sub(struct mg_mqtt_message *msg, struct mg_str *topic,
|
||||
uint8_t *qos, size_t pos) {
|
||||
uint8_t tmp;
|
||||
return mg_mqtt_next_topic(msg, topic, qos == NULL ? &tmp : qos, pos);
|
||||
}
|
||||
|
||||
size_t mg_mqtt_next_unsub(struct mg_mqtt_message *msg, struct mg_str *topic,
|
||||
size_t pos) {
|
||||
return mg_mqtt_next_topic(msg, topic, NULL, pos);
|
||||
}
|
||||
|
||||
// Event handler function
|
||||
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
if (ev == MG_EV_MQTT_CMD) {
|
||||
struct mg_mqtt_message *mm = (struct mg_mqtt_message *) ev_data;
|
||||
MG_DEBUG(("cmd %d qos %d", mm->cmd, mm->qos));
|
||||
switch (mm->cmd) {
|
||||
case MQTT_CMD_CONNECT: {
|
||||
// Client connects
|
||||
if (mm->dgram.len < 9) {
|
||||
mg_error(c, "Malformed MQTT frame");
|
||||
} else if (mm->dgram.buf[8] != 4) {
|
||||
mg_error(c, "Unsupported MQTT version %d", mm->dgram.buf[8]);
|
||||
} else {
|
||||
uint8_t response[] = {0, 0};
|
||||
mg_mqtt_send_header(c, MQTT_CMD_CONNACK, 0, sizeof(response));
|
||||
mg_send(c, response, sizeof(response));
|
||||
}
|
||||
break;
|
||||
}
|
||||
case MQTT_CMD_SUBSCRIBE: {
|
||||
// Client subscribes
|
||||
size_t pos = 4; // Initial topic offset, where ID ends
|
||||
uint8_t qos, resp[256];
|
||||
struct mg_str topic;
|
||||
int num_topics = 0;
|
||||
while ((pos = mg_mqtt_next_sub(mm, &topic, &qos, pos)) > 0) {
|
||||
struct sub *sub = calloc(1, sizeof(*sub));
|
||||
sub->c = c;
|
||||
sub->topic = mg_strdup(topic);
|
||||
sub->qos = qos;
|
||||
LIST_ADD_HEAD(struct sub, &s_subs, sub);
|
||||
MG_INFO(
|
||||
("SUB %p [%.*s]", c->fd, (int) sub->topic.len, sub->topic.buf));
|
||||
// Change '+' to '*' for topic matching using mg_match
|
||||
for (size_t i = 0; i < sub->topic.len; i++) {
|
||||
if (sub->topic.buf[i] == '+') ((char *) sub->topic.buf)[i] = '*';
|
||||
}
|
||||
resp[num_topics++] = qos;
|
||||
}
|
||||
mg_mqtt_send_header(c, MQTT_CMD_SUBACK, 0, num_topics + 2);
|
||||
uint16_t id = mg_htons(mm->id);
|
||||
mg_send(c, &id, 2);
|
||||
mg_send(c, resp, num_topics);
|
||||
break;
|
||||
}
|
||||
case MQTT_CMD_PUBLISH: {
|
||||
// Client published message. Push to all subscribed channels
|
||||
MG_INFO(("PUB %p [%.*s] -> [%.*s]", c->fd, (int) mm->data.len,
|
||||
mm->data.buf, (int) mm->topic.len, mm->topic.buf));
|
||||
for (struct sub *sub = s_subs; sub != NULL; sub = sub->next) {
|
||||
if (mg_match(mm->topic, sub->topic, NULL)) {
|
||||
struct mg_mqtt_opts pub_opts;
|
||||
memset(&pub_opts, 0, sizeof(pub_opts));
|
||||
pub_opts.topic = mm->topic;
|
||||
pub_opts.message = mm->data;
|
||||
pub_opts.qos = 1, pub_opts.retain = false;
|
||||
mg_mqtt_pub(sub->c, &pub_opts);
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
case MQTT_CMD_PINGREQ: {
|
||||
// The server must send a PINGRESP packet in response to a PINGREQ packet [MQTT-3.12.4-1]
|
||||
MG_INFO(("PINGREQ %p -> PINGRESP", c->fd));
|
||||
mg_mqtt_send_header(c, MQTT_CMD_PINGRESP, 0, 0);
|
||||
break;
|
||||
}
|
||||
}
|
||||
} else if (ev == MG_EV_ACCEPT) {
|
||||
// c->is_hexdumping = 1;
|
||||
} else if (ev == MG_EV_CLOSE) {
|
||||
// Client disconnects. Remove from the subscription list
|
||||
for (struct sub *next, *sub = s_subs; sub != NULL; sub = next) {
|
||||
next = sub->next;
|
||||
if (c != sub->c) continue;
|
||||
MG_INFO(("UNSUB %p [%.*s]", c->fd, (int) sub->topic.len, sub->topic.buf));
|
||||
LIST_DELETE(struct sub, &s_subs, sub);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
struct mg_mgr mgr; // Event manager
|
||||
signal(SIGINT, signal_handler); // Setup signal handlers - exist event
|
||||
signal(SIGTERM, signal_handler); // manager loop on SIGINT and SIGTERM
|
||||
mg_mgr_init(&mgr); // Initialise event manager
|
||||
MG_INFO(("Starting on %s", s_listen_on)); // Inform that we're starting
|
||||
mg_mqtt_listen(&mgr, s_listen_on, fn, NULL); // Create MQTT listener
|
||||
while (s_signo == 0) mg_mgr_poll(&mgr, 1000); // Event loop, 1s timeout
|
||||
mg_mgr_free(&mgr); // Cleanup
|
||||
return 0;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../mongoose.c
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../mongoose.h
|
||||
@@ -0,0 +1,32 @@
|
||||
PROG ?= example # Program we are building
|
||||
DELETE = rm -rf # Command to remove files
|
||||
OUT ?= -o $(PROG) # Compiler argument for output file
|
||||
SOURCES = main.c mongoose.c packed_fs.c # Source code files, packed_fs.c contains ca.pem, which contains CA certs for TLS
|
||||
CFLAGS = -W -Wall -Wextra -g -I. # Build options
|
||||
|
||||
# Mongoose build options. See https://mongoose.ws/documentation/#build-options
|
||||
CFLAGS_MONGOOSE += -DMG_ENABLE_LINES=1 -DMG_ENABLE_PACKED_FS=1
|
||||
|
||||
ifeq ($(OS),Windows_NT) # Windows settings. Assume MinGW compiler. To use VC: make CC=cl CFLAGS=/MD OUT=/Feprog.exe
|
||||
PROG ?= example.exe # Use .exe suffix for the binary
|
||||
CC = gcc # Use MinGW gcc compiler
|
||||
CFLAGS += -lws2_32 # Link against Winsock library
|
||||
DELETE = cmd /C del /Q /F /S # Command prompt command to delete files
|
||||
OUT ?= -o $(PROG) # Build output
|
||||
MAKE += WINDOWS=1 CC=$(CC)
|
||||
endif
|
||||
|
||||
all: $(PROG) # Default target. Build and run program
|
||||
$(RUN) ./$(PROG) $(ARGS)
|
||||
|
||||
$(PROG): $(SOURCES) # Build program from sources
|
||||
$(CC) $(SOURCES) $(CFLAGS) $(CFLAGS_MONGOOSE) $(CFLAGS_EXTRA) $(OUT)
|
||||
|
||||
clean: # Cleanup. Delete built program and all build artifacts
|
||||
$(DELETE) $(PROG) *.o *.obj *.exe *.dSYM mbedtls
|
||||
|
||||
# see https://mongoose.ws/tutorials/tls/#how-to-build for TLS build options
|
||||
|
||||
mbedtls: # Pull and build mbedTLS library
|
||||
git clone --depth 1 -b v2.28.2 https://github.com/mbed-tls/mbedtls $@
|
||||
$(MAKE) -C mbedtls/library
|
||||
@@ -0,0 +1,2 @@
|
||||
- This example requires changing server name and user credentials in `main.c`
|
||||
- This example requires building with TLS support; before running, please see its detailed tutorial at https://mongoose.ws/tutorials/smtp/smtp-client/
|
||||
@@ -0,0 +1,82 @@
|
||||
#include "mongoose.h"
|
||||
|
||||
static const char *server = "tcp://smtp.gmail.com:587";
|
||||
static const char *user = "aaa@domain.com"; // Change this! Your mail account
|
||||
static const char *pass = "xxxxxxxxxxxxxx"; // Change this! Your mail password
|
||||
static const char *to = "bbb@domain.com"; // Change this! Destination email
|
||||
|
||||
static const char *from = "My Mail Sender";
|
||||
static const char *subj = "Test email from Mongoose library!";
|
||||
static const char *mesg = "Hi!\nThis is a test message.\nBye.";
|
||||
|
||||
static bool s_quit;
|
||||
|
||||
enum { EHLO, STARTTLS, STARTTLS_WAIT, AUTH, FROM, TO, DATA, BODY, QUIT, END };
|
||||
|
||||
static void fn(struct mg_connection *c, int ev, void *ev_data) {
|
||||
uint8_t *state = (uint8_t *) c->data;
|
||||
if (ev == MG_EV_OPEN) {
|
||||
// c->is_hexdumping = 1;
|
||||
} else if (ev == MG_EV_READ) {
|
||||
if (c->recv.len > 0 && c->recv.buf[c->recv.len - 1] == '\n') {
|
||||
MG_INFO(("<-- %.*s", (int) c->recv.len - 2, c->recv.buf));
|
||||
c->recv.len = 0;
|
||||
if (*state == EHLO) {
|
||||
mg_printf(c, "EHLO myname\r\n");
|
||||
*state = STARTTLS;
|
||||
} else if (*state == STARTTLS) {
|
||||
mg_printf(c, "STARTTLS\r\n");
|
||||
*state = STARTTLS_WAIT;
|
||||
} else if (*state == STARTTLS_WAIT) {
|
||||
struct mg_tls_opts opts = {.ca = mg_unpacked("/certs/ca.pem"),
|
||||
.name = mg_url_host(server)};
|
||||
mg_tls_init(c, &opts);
|
||||
*state = AUTH;
|
||||
} else if (*state == AUTH) {
|
||||
char a[100], b[300] = "";
|
||||
size_t n = mg_snprintf(a, sizeof(a), "%c%s%c%s", 0, user, 0, pass);
|
||||
mg_base64_encode((uint8_t *) a, n, b, sizeof(b));
|
||||
mg_printf(c, "AUTH PLAIN %s\r\n", b);
|
||||
*state = FROM;
|
||||
} else if (*state == FROM) {
|
||||
mg_printf(c, "MAIL FROM: <%s>\r\n", user);
|
||||
*state = TO;
|
||||
} else if (*state == TO) {
|
||||
mg_printf(c, "RCPT TO: <%s>\r\n", to);
|
||||
*state = DATA;
|
||||
} else if (*state == DATA) {
|
||||
mg_printf(c, "DATA\r\n");
|
||||
*state = BODY;
|
||||
} else if (*state == BODY) {
|
||||
mg_printf(c, "From: %s <%s>\r\n", from, user); // Mail header
|
||||
mg_printf(c, "Subject: %s\r\n", subj); // Mail header
|
||||
mg_printf(c, "\r\n"); // End of headers
|
||||
mg_printf(c, "%s\r\n", mesg); // Mail body
|
||||
mg_printf(c, ".\r\n"); // End of body
|
||||
*state = QUIT;
|
||||
} else if (*state == QUIT) {
|
||||
mg_printf(c, "QUIT\r\n");
|
||||
*state = END;
|
||||
} else {
|
||||
c->is_draining = 1;
|
||||
MG_INFO(("end"));
|
||||
}
|
||||
MG_INFO(("--> %.*s", (int) c->send.len - 2, c->send.buf));
|
||||
}
|
||||
} else if (ev == MG_EV_CLOSE) {
|
||||
s_quit = true;
|
||||
} else if (ev == MG_EV_TLS_HS) {
|
||||
MG_INFO(("TLS handshake done! Sending EHLO again"));
|
||||
mg_printf(c, "EHLO myname\r\n");
|
||||
}
|
||||
(void) ev_data;
|
||||
}
|
||||
|
||||
int main(void) {
|
||||
struct mg_mgr mgr;
|
||||
mg_mgr_init(&mgr);
|
||||
mg_log_set(MG_LL_DEBUG);
|
||||
mg_connect(&mgr, server, fn, NULL);
|
||||
while (s_quit == false) mg_mgr_poll(&mgr, 1000);
|
||||
return 0;
|
||||
}
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../mongoose.c
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../../mongoose.h
|
||||
+1
@@ -0,0 +1 @@
|
||||
../../http/http-client/packed_fs.c
|
||||
Reference in new issue
Block a user