Compare commits

...
36 Commits
Author SHA1 Message Date
cpq 5aa320658a STM32F driver: per-driver INIT macro, like the radio drivers 2026-11-20 17:17:50 +00:00
Sergio R. Caprile 1620b2ae03 Merge pull request #3785 from cesanta/bsdud
Add improved datagram support for BSD
2026-11-20 13:52:41 -03:00
Sergio R. Caprile 0914048424 Add improved datagram support for BSD 2026-11-20 13:50:25 -03:00
Sergio R. Caprile 0f319e3060 Merge pull request #3783 from cesanta/tlsmaint
make callers agree with API
2026-11-18 18:38:26 -03:00
Sergey Lyubka d612b7f1c4 Merge pull request #3782 from cesanta/no46loop
avoid IPv6 querying forever
2026-11-18 21:34:32 +00:00
Sergey Lyubka 6d5f4a5a20 Merge pull request #3781 from cesanta/freewilly
free DER data too
2026-11-18 21:34:01 +00:00
Sergey Lyubka cd10b35de4 Merge pull request #3780 from cesanta/recvfrom6
fix recvfrom in IPv6
2026-11-18 21:33:37 +00:00
Sergey Lyubka f04cb5333e Merge pull request #3779 from cesanta/nonstr
don't use strncpy on a mg_str
2026-11-18 21:33:13 +00:00
cpq 28e3b347d4 Tutorials - nits and mqtt client adoption 2026-11-18 20:28:36 +00:00
Sergio R. Caprile 069ab78c02 Merge pull request #3784 from cesanta/picosdk
update to Pico-SDK 2.2.0 (to be able to build with GCC 15)
2026-11-18 13:52:53 -03:00
Sergio R. Caprile 91b87a6bd8 update version 2026-11-18 10:05:47 -03:00
Sergio R. Caprile 1ce7e416b0 update to Pico-SDK 2.2.0 (to be able to build with GCC 15) 2026-11-17 17:43:44 -03:00
Sergio R. Caprile 63aaad829a make callers agree with API 2026-11-17 15:45:47 -03:00
Sergio R. Caprile 9322227886 avoid IPv6 querying forever 2026-11-17 11:53:09 -03:00
Sergio R. Caprile e3a78d513e free DER data too 2026-11-16 16:22:36 -03:00
Sergio R. Caprile ee338b7bba fix recvfrom in IPv6 2026-11-16 16:00:56 -03:00
Sergio R. Caprile 0f157bd23b don't use strncpy on a mg_str 2026-11-16 15:48:16 -03:00
robert 49e71ba666 Update Claude models 2026-11-16 16:26:11 +02:00
robert 166c1a7708 update partitions 2026-11-16 12:06:35 +02:00
robert 2ef7f7a44a Increase partition size on ESP32 2026-11-16 10:46:06 +02:00
cpq e7335e063b Update readme & dash html 2026-11-15 12:39:48 +00:00
cpq 88096d3f4d Update graph1 2026-11-15 12:16:49 +00:00
cpq 1b9177ae64 Update READMEs 2026-11-15 07:58:33 +00:00
Sergio R. Caprile 053b8ed824 Merge pull request #3777 from cesanta/nocnfb
Correct #3775 CN fallback handling
2026-11-13 11:42:42 -03:00
Sergio R. Caprile 2ea1cf6817 Correct #3775 CN fallback handling 2026-11-13 11:42:13 -03:00
Sergio R. Caprile 323326ce8b Merge pull request #3778 from cesanta/pad
make padding stricter
2026-11-13 11:41:14 -03:00
Sergio R. Caprile c5344af9fc make padding stricter 2026-11-13 11:04:01 -03:00
Sergio R. Caprile d73b009bbc unbreak test 2026-11-13 09:53:19 -03:00
cpq dba6479b23 Update Agents 2026-11-13 12:23:35 +00:00
cpq 28ca01eb2b Update Agents 2026-11-13 12:10:05 +00:00
cpq e999239ca7 Add guidance for the AI engines inside mongoose.h 2026-11-13 11:57:04 +00:00
Sergio R. Caprile d545526ba2 unbreak test 2026-11-12 15:56:25 -03:00
Sergio R. Caprile 0b888e8f3f Merge pull request #3776 from cesanta/embnul
reject embedded NULs in paths
2026-11-12 15:42:18 -03:00
Sergio R. Caprile 27a87dee8b reject embedded NULs in paths 2026-11-12 14:24:46 -03:00
Sergio R. Caprile 94ccc4a130 Merge pull request #3775 from cesanta/nocnfb
do not fallback to CN after SAN
2026-11-12 13:59:16 -03:00
Sergio R. Caprile 454bf4036f do not fallback to CN after SAN 2026-11-12 13:53:51 -03:00
58 changed files with 961 additions and 516 deletions

No files matched your search

@@ -211,7 +211,7 @@ jobs:
claude_args: |
--allowedTools "Read,Glob,Grep,Bash(git:*),Bash(find:*),Bash(grep:*),Bash(sed:*),Bash(cat:*)"
--model claude-opus-5
--model claude-opus-5-5
- name: Prepare private security scan outputs
if: always() && steps.claude_scan.outputs.execution_file != ''
@@ -108,4 +108,4 @@ jobs:
claude_args: |
--allowedTools "Read,Bash(cat:*),Bash(gh pr diff:*),Bash(gh pr view:*),Bash(gh pr comment:*)"
--model claude-opus-5
--model claude-opus-5-5
+1 -2
View File
@@ -560,8 +560,7 @@ jobs:
# - run: make -C tutorials/${{ matrix.example.path }} build
wizard_examples_arm:
# Keep rp-ti on 24.04: Pico SDK 2.1.1 pioasm fails with GCC 15; update SDK
runs-on: ${{ matrix.group == 'rp-ti' && 'ubuntu-24.04' || 'ubuntu-latest' }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
+3 -6
View File
@@ -201,8 +201,7 @@ jobs:
run: make -C tutorials/${{ matrix.example.path }} build
generic_examples_arm:
# Keep RP on 24.04: Pico SDK 2.1.1 pioasm fails with GCC 15; update SDK
runs-on: ${{ startsWith(matrix.example.path, 'rp/') && 'ubuntu-24.04' || 'ubuntu-latest' }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
@@ -245,8 +244,7 @@ jobs:
run: make -C tutorials/${{ matrix.example.path }} build
device_dashboard_examples_arm:
# Keep RP on 24.04: Pico SDK 2.1.1 pioasm fails with GCC 15; update SDK
runs-on: ${{ startsWith(matrix.example.path, 'rp/') && 'ubuntu-24.04' || 'ubuntu-latest' }}
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
@@ -272,8 +270,7 @@ jobs:
run: make -C tutorials/${{ matrix.example.path }} build
mqtt_dashboard_examples_arm:
# Pico SDK 2.1.0 pioasm fails with GCC 15; update SDK to unpin
runs-on: ubuntu-24.04
runs-on: ubuntu-latest
strategy:
fail-fast: false
matrix:
+105 -32
View File
@@ -1,11 +1,12 @@
# Mongoose: a full-stack embedded networking library
Mongoose is a full-stack embedded networking library for C/C++: a TCP/IP stack
with drivers, TLS 1.3, an embedded web server (HTTP, WebSocket), MQTT and
firmware OTA updates in two files, `mongoose.c` and `mongoose.h`. Mongoose runs on
STM32, NXP and other microcontrollers, on bare metal or with an RTOS, with no
external dependencies. Use it for cloud connectivity, device web dashboards,
secure firmware updates and remote control.
Mongoose is a full-stack embedded networking library for C and C++. It includes
a TCP/IP stack with drivers, TLS 1.3, an embedded web server with HTTP and
WebSocket support, MQTT, and firmware OTA updates. All in just two files:
`mongoose.c` and `mongoose.h`. Mongoose runs on STM32, NXP and other
microcontrollers, on bare metal or with an RTOS, with no external dependencies.
Ideal for cloud connectivity, device web dashboards, secure firmware updates
and remote control.
License: GPLv2 or commercial.
Website: https://mongoose.ws/
@@ -13,6 +14,7 @@ GitHub repo: https://github.com/cesanta/mongoose
## General rules
- All relative file names mentioned in this file are related to the repo root.
- Always re-read files before editing, so you do not overwrite existing changes.
- Never guess. If you don't know, say you don't know and stop.
- Resolve relative paths from the repo root: https://github.com/cesanta/mongoose
@@ -39,6 +41,7 @@ This is a navigation aid, not an API reference. Read `mongoose.h` for exact
function signatures, structs, options, examples, and constraints.
- `mg_mgr_*` - event manager and polling loop
- `mg_dash_*` - dashboard API for device web UIs, fieldsets, and live updates
- `mg_http_*` - HTTP server, HTTP client, uploads, serving files
- `mg_ws_*` - WebSocket server and client
- `mg_mqtt_*` - MQTT client
@@ -229,12 +232,41 @@ xTaskCreate(net_task, "net", 8192, NULL, tskIDLE_PRIORITY + 1, NULL);
## HTTP / Web Device Dashboard
For a web UI with real-time device state over WebSocket, use the Mongoose
device dashboard.
When building a device web UI, control panel, monitoring page, or live
display, you MUST use the `mg_dash_*` dashboard framework unless the user
explicitly requests another architecture. Do not add your own HTTP event handler.
Read the dashboard declarations in `mongoose.h` before implementing the UI.
Use only the dashboard files listed below. Download missing reference files;
preserve existing files. Integrate the dashboard into the existing application
and build files.
Start from the minimal reference implementation and adapt its fields and UI.
Keep dashboard fieldsets, callbacks, update timers, and small metric helpers
in `dashboard.c`. Do not create `dashboard.h`, or other dashboard
helper modules. `mongoose.h` already declares `mg_dash_init()` and
`mg_dash_poll()`. Reuse existing board/HAL helpers for hardware measurements;
if none exists, put a small private helper in `dashboard.c` or extend the
existing board/HAL implementation.
Expose device state through mg_field / mg_field_set.
Call mg_dash_init() once and mg_dash_poll() in the event loop.
For live updates, call mg_dash_send_change() from a backend timer.
Display values using dashboard.js and HTML data-bind attributes.
Example: free RAM updated every 50 ms means a read-only fieldset pushed
over the dashboard WebSocket every 50 ms. Do not implement browser polling,
fetch(), setInterval(), or a custom WebSocket client for dashboard state.
### Required files
The following files must exist at these exact paths, regardless of the build environment:
Keep all the following Mongoose files together in one project directory.
The example uses `mongoose/`; you may choose another directory name.
If Mongoose is already installed, use the directory containing the actual
`mongoose.c` and `mongoose.h` files, including an existing CubeMX middleware
directory. Add the dashboard files there and update the build paths. Do not
create a second Mongoose directory or use symlinks, forwarding headers, or
duplicate library copies to make files appear colocated.
```
your_project/
@@ -244,6 +276,7 @@ your_project/
├── mongoose.c # single source file
├── dashboard.c # C-side dashboard logic
├── dashboard.html # HTML/JS UI (source)
├── html2c.js # HTML-to-C generator
└── file_data.c # generated from dashboard.html (see below)
```
@@ -255,16 +288,24 @@ node html2c.js dashboard.html -o file_data.c
`html2c.js` is at https://github.com/cesanta/mongoose/blob/master/resources/html2c.js
If the project does not yet have `dashboard.c` and `dashboard.html`, fetch the
minimal reference versions:
For each missing `dashboard.c`, `dashboard.html`, or `html2c.js`, download its
reference version from the Mongoose repository and place it beside `mongoose.c`
and `mongoose.h`:
```
https://github.com/cesanta/mongoose/blob/master/tutorials/device-dashboard/minimal/dashboard.c
https://github.com/cesanta/mongoose/blob/master/tutorials/device-dashboard/minimal/dashboard.html
https://github.com/cesanta/mongoose/blob/master/resources/html2c.js
```
If the project already has `dashboard.c` and `dashboard.html`, do **not** fetch
anything from the repository.
Add a build rule that regenerates `file_data.c` whenever `dashboard.html` or
`html2c.js` changes. Keep the upstream generator unchanged; it already inlines
the script referenced by the HTML, so the served page does not need internet
access. Do not download a separate `dashboard.js` or add a local `--use`
override unless the user explicitly requests offline builds or local assets.
Compile both `dashboard.c` and `file_data.c` into the
application. Call `mg_dash_init()` once and `mg_dash_poll()` on every iteration
of the existing Mongoose event loop, from the same task or thread.
### C integration (bare metal or RTOS main loop)
@@ -283,15 +324,17 @@ for (;;) {
### dashboard.html rules
- Use `dashboard.js` from `https://mongoose.ws/resources/dashboard.js`
- Reference `<script src="https://mongoose.ws/resources/dashboard.js"></script>`
in the source HTML. Let `html2c.js` inline it into the generated asset.
- Call `Dashboard.init({ data: { ... } })` once - this is the only direct
Dashboard API call. Treat the rest of Dashboard as a black box.
- Do **not** add vanilla JS event listeners, `fetch()` calls, or custom
reactive logic to `dashboard.html`.
- Do **not** modify `dashboard.html` unless the user explicitly asks.
- Modify `dashboard.html` only for requested UI work. A request to create or
modify the web UI authorizes the necessary `dashboard.html` edits.
- Bind controls to device state using `data-bind` attributes
- The `__status` object in evaluations is read-only, do not alter it
- If you need to pass data between the UI and backend.c, add extra
- If you need to pass data between the UI and `dashboard.c`, add extra
fieldsets/fields - see next section about it
- If you want to display device data in HTML, use `${}` evaluations
@@ -315,17 +358,24 @@ for (;;) {
### dashboard.c rules
Mongoose backend exports device data as a collection of "fieldsets". Each fieldset groups several fields
Mongoose exports device data as fieldsets. Each fieldset groups several fields
and has one `bool fn(enum mg_dash_op, struct mg_dash_user *)` callback for
read/write/add/delete operations. Use the declarations in the project's
`mongoose.h`; do not copy older descriptors with separate reader/writer
members or positional access-level arguments. Use designated initializers.
Example fieldset:
```c
static struct mg_dash s_dash;
static bool settings_fn(enum mg_dash_op op, struct mg_dash_user *u);
static struct settings {
double volume;
char name[10];
int log_level;
bool enable_login;
} s_settings = {2.7, "Dublin", 2, false, false};
} s_settings = {2.7, "Dublin", 2, false};
static struct mg_field fields_settings[] = {
{"volume", MG_VAL_DBL, &s_settings.volume, sizeof(s_settings.volume)},
@@ -336,14 +386,12 @@ static struct mg_field fields_settings[] = {
};
static struct mg_field_set set_settings = {
"settings", fields_settings, read_settings, write_settings, 3, 7, NULL,
.name = "settings", .fields = fields_settings, .fn = settings_fn,
};
```
To enable user authentication, set `authenticate` function for the dashboard descriptor:
```c
static struct mg_dash s_dash;
// Signature: (char *user, size_t userlen, const char *pass)
// `user` is both input (username from the login form) and output: the function
// may overwrite it with the canonical username. Return access level > 0 on
@@ -360,24 +408,34 @@ static int authenticate(char *user, size_t userlen, const char *pass) {
return level;
}
static void write_settings(void) {
s_dash.authenticate = s_settings.enable_login ? authenticate : NULL;
static bool settings_fn(enum mg_dash_op op, struct mg_dash_user *u) {
(void) u;
if (op == MG_DASH_WRITE) {
s_dash.authenticate = s_settings.enable_login ? authenticate : NULL;
return true;
}
return op == MG_DASH_READ;
}
```
Fieldset may have reader and writer function, which acts as a hardware glue. For example, "led1" variable may reflect real LED status using reader and writer:
Use the fieldset callback as hardware glue. For example, `led1` can reflect
the real LED state:
```c
static struct leds {
bool led1;
} s_leds = {false};
static void write_leds(void) {
gpio_write(LED1_PIN, s_leds.led1);
}
static void read_leds(void) {
s_leds.led1 = gpio_read(LED1_PIN);
static bool leds_fn(enum mg_dash_op op, struct mg_dash_user *u) {
(void) u;
if (op == MG_DASH_READ) {
s_leds.led1 = gpio_read(LED1_PIN);
} else if (op == MG_DASH_WRITE) {
gpio_write(LED1_PIN, s_leds.led1);
} else {
return false;
}
return true;
}
static struct mg_field fields_leds[] = {
@@ -386,7 +444,7 @@ static struct mg_field fields_leds[] = {
};
static struct mg_field_set set_leds = {
"leds", fields_leds, read_leds, write_leds, 0, 0, NULL,
.name = "leds", .fields = fields_leds, .fn = leds_fn,
};
```
@@ -412,7 +470,8 @@ static struct event {
} s_event;
static struct mg_field_set field_set_event = {
"event", fields_event, event_fn, &s_event.index, 0, 0, 0
.name = "event", .fields = fields_event,
.fn = event_fn, .index = &s_event.index,
};
```
@@ -432,6 +491,20 @@ Do not rename, wrap, relocate, or replace these files or functions. Do not intro
Board-specific STM32Cube files may exist outside mongoose/, but the Mongoose dashboard files must retain the structure and API documented above.
### Dashboard completion checks
- Verify actual file locations, including symlink targets, against the required
layout. Check that no extra dashboard source/header/JS files were introduced.
- Check the source HTML for the upstream script reference, a single
`Dashboard.init()`, and declarative bindings. Networking code in the upstream
script inlined into `file_data.c` is expected; do not replace or edit it.
- Verify fieldsets are registered with `MG_DASH_ADD_FIELD_SET()`, listeners use
`mg_dash_ev_handler`, and live metrics use `mg_dash_send_change()` on the
requested backend schedule. Do not resend unrelated fieldsets at that rate.
- Regenerate `file_data.c` and build the real firmware. Report separately which
behavior was verified on hardware; host mocks do not establish physical LED,
Ethernet, RAM measurement, or refresh-rate correctness.
## Filesystem
| Define | Use when |
+7 -6
View File
@@ -7,12 +7,13 @@
<img src="https://mongoose.ws/images/logo.svg" width="48" height="48"
align="left" style="float:left;" />
Mongoose is a full-stack embedded networking library for C/C++: a TCP/IP stack
with drivers, TLS 1.3, an embedded web server (HTTP, WebSocket), MQTT and
firmware OTA updates in two files, `mongoose.c` and `mongoose.h`. Mongoose runs on
STM32, NXP and other microcontrollers, on bare metal or with an RTOS, with no
external dependencies. Use it for cloud connectivity, device web dashboards,
secure firmware updates and remote control.
Mongoose is a full-stack embedded networking library for C and C++. It includes
a TCP/IP stack with drivers, TLS 1.3, an embedded web server with HTTP and
WebSocket support, MQTT, and firmware OTA updates. All in just two files:
`mongoose.c` and `mongoose.h`. Mongoose runs on STM32, NXP and other
microcontrollers, on bare metal or with an RTOS, with no external dependencies.
Ideal for cloud connectivity, device web dashboards, secure firmware updates
and remote control.
Use it instead of lwIP + mbedTLS + httpd + an MQTT client + OTA glue code, or
run it on top of lwIP or Zephyr.
+185 -86
View File
@@ -167,6 +167,7 @@ fail:
#endif
#include <stdarg.h>
#if MG_ENABLE_BSD_SOCKETS && MG_ENABLE_FREERTOS
@@ -298,6 +299,46 @@ static struct mg_connection *bsd_new_conn(struct mg_bsd_sock *s) {
return c;
}
// Mirror net_builtin.c::trim_len() logic
static bool bsd_udp_too_big(struct mg_connection *c, size_t len) {
struct mg_tcpip_if *ifp = c->mgr->ifp;
size_t hlen = c->rem.is_ip6 ? 48 : 32; // IP plus UDP headers
size_t cap = ifp->mtu - hlen;
size_t room = ifp->tx.len - (ifp->framesize - ifp->l2mtu) - hlen;
return len > cap || len > room;
}
static bool bsd_udp_queue(struct mg_connection *c, const void *buf,
size_t len) {
// One raw datagram occupies c->send until write_conn() drains it.
return mg_iobuf_add(&c->send, c->send.len, buf, len) == len;
}
static size_t bsd_recv(struct mg_bsd_sock *s, void *buf, size_t len,
int flags, struct sockaddr *src, socklen_t *addrlen) {
struct mg_connection *c = s->c;
size_t n;
if (!s->is_udp) {
n = c->recv.len < len ? c->recv.len : len;
memcpy(buf, c->recv.buf, n);
if (!(flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, n);
} else {
n = c->recv.len < len ? c->recv.len : len;
memcpy(buf, c->recv.buf, n);
if (src != NULL && addrlen != NULL) {
struct sockaddr_in *sa = (struct sockaddr_in *) src;
sa->sin_family = AF_INET;
sa->sin_port = c->rem.port;
sa->sin_addr.s_addr = c->rem.addr.ip4;
*addrlen = sizeof(*sa);
}
if (!(flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, c->recv.len);
}
return n;
}
#if MG_ENABLE_FREERTOS
// Complete operations blocked on c before Mongoose destroys it.
static void bsd_finish_waiters(struct mg_bsd_sock *s, bool error) {
@@ -482,9 +523,10 @@ static int bsd_ready(struct mg_bsd_sock *s) {
if (s->is_shut_rd || s->c->recv.len > 0 || s->c->is_draining)
ready |= BSD_READ;
if (s->is_shut_wr) ready |= BSD_ERROR;
if (!s->is_shut_wr && !s->is_udp && !s->c->is_connecting &&
!s->c->is_closing && !s->c->is_draining)
ready |= BSD_WRITE; // Established TCP socket
if (!s->is_shut_wr && (s->is_udp || !s->c->is_connecting) &&
!s->c->is_closing && !s->c->is_draining &&
(!s->is_udp || s->c->send.len == 0))
ready |= BSD_WRITE; // UDP socket or established TCP socket
return ready;
}
@@ -498,7 +540,7 @@ static void bsd_close(struct mg_bsd_sock *s) {
if (t->orphan && t->listener == s) {
if (t->c != NULL) {
t->c->fn_data = NULL;
mg_close_conn(t->c);
t->c->is_draining = 1;
t->c = NULL;
}
memset(t, 0, sizeof(*t)); // Release orphan
@@ -506,7 +548,7 @@ static void bsd_close(struct mg_bsd_sock *s) {
}
if (s->c != NULL) {
s->c->fn_data = NULL;
mg_close_conn(s->c);
s->c->is_draining = 1;
s->c = NULL;
}
memset(s, 0, sizeof(*s)); // Release socket
@@ -696,8 +738,8 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
cmd->result = -1, cmd->err = ECONNREFUSED;
return true;
}
if (!c->is_connecting) {
cmd->result = 0;
if (s->is_udp || !c->is_connecting) {
cmd->result = 0; // UDP may still resolve ARP; TCP waits for SYN/SYN-ACK
return true;
}
if (s->nonblock) {
@@ -722,11 +764,8 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
return true;
}
if (c->recv.len > 0) {
size_t n = cmd->op_recv.len;
if (c->recv.len < n) n = c->recv.len;
memcpy(cmd->op_recv.buf, c->recv.buf, n);
if (!(cmd->op_recv.flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, n);
cmd->result = (int) n;
cmd->result = (int) bsd_recv(s, cmd->op_recv.buf, cmd->op_recv.len,
cmd->op_recv.flags, NULL, NULL);
return true;
}
if (s->err != 0) {
@@ -750,7 +789,25 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
} else if (s->is_shut_wr || (c = s->c) == NULL || s->err != 0 ||
c->is_closing || c->is_draining) {
cmd->result = -1, cmd->err = EPIPE;
} else if (mg_send(c, cmd->op_send.buf, cmd->op_send.len)) {
} else if (c == NULL || (s->is_udp && !c->is_client)) {
cmd->result = -1, cmd->err = s->is_udp ? EDESTADDRREQ : EPIPE;
} else if (s->is_udp && cmd->op_send.len == 0) {
cmd->result = 0;
} else if (s->is_udp && bsd_udp_too_big(c, cmd->op_send.len)) {
cmd->result = -1, cmd->err = EMSGSIZE;
} else if (s->is_udp && c->send.len > 0) {
if (s->nonblock || (cmd->op_send.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
} else {
#if MG_ENABLE_FREERTOS
return false; // One UDP datagram is pending, wait
#else
cmd->result = -1, cmd->err = EAGAIN;
#endif
}
} else if ((s->is_udp
? bsd_udp_queue(c, cmd->op_send.buf, cmd->op_send.len)
: mg_send(c, cmd->op_send.buf, cmd->op_send.len))) {
cmd->result = (int) cmd->op_send.len;
} else if (s->nonblock || (cmd->op_send.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
@@ -767,25 +824,49 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
if ((s = bsd_get(cmd->op_sendto.fd)) == NULL) {
cmd->result = -1, cmd->err = EBADF;
} else if (!s->is_udp) {
cmd->result = -1, cmd->err = EOPNOTSUPP;
} else if ((err = bsd_addr4(cmd->op_sendto.addr,
cmd->op_sendto.addrlen)) != 0) {
cmd->result = -1, cmd->err = err;
} else if (s->is_shut_wr || (c = s->c) == NULL || s->err != 0 ||
c->is_closing || c->is_draining) {
cmd->result = -1, cmd->err = EPIPE;
} else if (c->is_client) {
cmd->result = -1, cmd->err = EISCONN;
} else {
const struct sockaddr_in *sa =
(const struct sockaddr_in *) cmd->op_sendto.addr;
c->rem.port = sa->sin_port;
c->rem.addr.ip4 = sa->sin_addr.s_addr;
c->rem.is_ip6 = false;
if (mg_send(c, cmd->op_sendto.buf, cmd->op_sendto.len)) {
cmd->result = (int) cmd->op_sendto.len;
if (cmd->op_sendto.len == 0) {
cmd->result = 0;
} else if (bsd_udp_too_big(c, cmd->op_sendto.len)) {
cmd->result = -1, cmd->err = EMSGSIZE;
} else if (c->send.len == 0) {
struct mg_addr rem = c->rem;
bool resolve = rem.is_ip6 || rem.addr.ip4 != sa->sin_addr.s_addr;
c->rem.port = sa->sin_port;
c->rem.addr.ip4 = sa->sin_addr.s_addr;
c->rem.is_ip6 = false;
if (bsd_udp_queue(c, cmd->op_sendto.buf, cmd->op_sendto.len)) {
if (resolve) mg_connect_resolved(c);
cmd->result = (int) cmd->op_sendto.len;
} else {
c->rem = rem;
if (s->nonblock || (cmd->op_sendto.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
} else {
#if MG_ENABLE_FREERTOS
return false; // No send buffer space yet, wait
#else
cmd->result = -1, cmd->err = EAGAIN;
#endif
}
}
} else if (s->nonblock || (cmd->op_sendto.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
} else {
#if MG_ENABLE_FREERTOS
return false; // No send buffer space yet, wait
return false; // One UDP datagram is pending, wait
#else
cmd->result = -1, cmd->err = EAGAIN;
#endif
@@ -797,6 +878,9 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
if ((s = bsd_get(cmd->op_recvfrom.fd)) == NULL) {
cmd->result = -1, cmd->err = EBADF;
return true;
} else if (!s->is_udp) {
cmd->result = -1, cmd->err = EOPNOTSUPP;
return true;
}
if (s->is_shut_rd) {
cmd->result = 0;
@@ -808,25 +892,11 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
return true;
}
if (c->recv.len > 0) {
size_t n = cmd->op_recvfrom.len;
if (cmd->op_recvfrom.src != NULL &&
(cmd->op_recvfrom.addrlen == NULL ||
*cmd->op_recvfrom.addrlen < sizeof(struct sockaddr_in))) {
cmd->result = -1, cmd->err = EINVAL;
return true;
}
if (c->recv.len < n) n = c->recv.len;
memcpy(cmd->op_recvfrom.buf, c->recv.buf, n);
if (!(cmd->op_recvfrom.flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, n);
if (cmd->op_recvfrom.src != NULL && cmd->op_recvfrom.addrlen != NULL) {
struct sockaddr_in *sa = (struct sockaddr_in *) cmd->op_recvfrom.src;
sa->sin_family = AF_INET;
sa->sin_port = c->rem.port;
sa->sin_addr.s_addr = c->rem.addr.ip4;
*cmd->op_recvfrom.addrlen = sizeof(*sa);
}
cmd->result = (int) n;
cmd->result = (int) bsd_recv(s, cmd->op_recvfrom.buf,
cmd->op_recvfrom.len,
cmd->op_recvfrom.flags,
cmd->op_recvfrom.src,
cmd->op_recvfrom.addrlen);
return true;
}
if (s->err != 0) {
@@ -2146,12 +2216,13 @@ bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) {
dm->txnid = mg_ntohs(h->txnid);
is_response = mg_ntohs(h->flags) & 0x8000;
for (i = 0; i < mg_ntohs(h->num_questions); i++) {
for (i = 0; i < mg_ntohs(h->num_questions); i++) { // advance past queries
if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false;
// MG_INFO(("Q %lu %lu %hu/%hu", ofs, n, rr.atype, rr.aclass));
dm->addr.is_ip6 = (rr.atype == MG_DNS_RTYPE_AAAA);
mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name));
ofs += n;
}
} // on unresolved responses, we got the name and query type, at least
if (!is_response) {
// For queries, there is no need to parse the answers. In this way,
@@ -4906,11 +4977,15 @@ static bool uri2path(const char *r, struct mg_str uri, char *buf, size_t len) {
n = mg_snprintf(buf, len, "%.*s", (int) d.len, d.buf);
if (len == 0 || n + 2 >= len) return false; // Path overflow
if (n > 0 && buf[n - 1] != '/') buf[n++] = '/', buf[n] = '\0'; // Add slash
if (mg_url_decode(uri.buf + u.len, uri.len - u.len, buf + n, len - n, 0) < 0) {
return false;
{
int dn;
size_t p = n;
dn = mg_url_decode(uri.buf + u.len, uri.len - u.len, buf + n, len - n, 0);
if (dn < 0) return false; // reject on malformed
buf[len - 1] = '\0'; // Double-check
n = strlen(buf);
if (n != p + (size_t) dn) return false; // reject on embedded NULs
}
buf[len - 1] = '\0'; // Double-check
n = strlen(buf);
if (!mg_path_is_sane(mg_str_n(buf, n))) return false;
while (n > 1 && buf[n - 1] == '/') buf[--n] = 0; // Trim trailing slashes
return true;
@@ -10895,22 +10970,34 @@ static void proto_error(struct mg_connection *c, bool r, const char *f, ...) {
static bool rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
struct connstate *s;
struct mg_addr rem;
uint8_t *l2addr;
if (c == NULL) return false; // No UDP listener on this port
// BSD socket has an unread datagram: drop this one to keep boundaries
if (c->is_bsd && c->recv.len > 0) return true;
if (c->is_bsd && !c->is_client && c->send.len > 0) return true;
s = (struct connstate *) (c + 1);
c->rem.port = pkt->udp->sport;
#if MG_ENABLE_IPV6
if (c->loc.is_ip6) { // matching of v4/v6 to dest is done bt getpeer()
if (!udp6csum_ok(pkt->ip6, pkt->udp)) return false;
c->rem.addr.ip6[0] = pkt->ip6->src[0],
c->rem.addr.ip6[1] = pkt->ip6->src[1], c->rem.is_ip6 = true;
if (c->is_bsd && c->is_client &&
(c->rem.port != pkt->udp->sport ||
!MG_IP6MATCH(c->rem.addr.ip6, pkt->ip6->src)))
return true;
rem.addr.ip6[0] = pkt->ip6->src[0],
rem.addr.ip6[1] = pkt->ip6->src[1], rem.is_ip6 = true;
} else
#endif
{
if (!udpcsum_ok(pkt->ip, pkt->udp)) return false;
c->rem.addr.ip4 = pkt->ip->src;
if (c->is_bsd && c->is_client &&
(c->rem.port != pkt->udp->sport || c->rem.addr.ip4 != pkt->ip->src))
return true;
rem.addr.ip4 = pkt->ip->src, rem.is_ip6 = false;
}
if ((l2addr = get_return_l2addr(ifp, &c->rem, true, pkt)) == NULL)
rem.port = pkt->udp->sport;
c->rem = rem;
if ((l2addr = get_return_l2addr(ifp, &rem, true, pkt)) == NULL)
return false; // safety net for lousy networks
memcpy(s->mac, l2addr, sizeof(s->mac));
if (c->recv.len >= MG_MAX_RECV_SIZE) {
@@ -12016,20 +12103,25 @@ void mg_connect_resolved(struct mg_connection *c) {
s->retransmit = ifp->enable_tcp_retransmit;
s->txq.align = MG_TCPIP_TXQ_ALIGN;
c->is_resolving = 0;
if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
c->loc.port = mg_htons(ifp->eport++);
if (c->loc.port == 0) {
if (ifp->eport < MG_EPHEMERAL_PORT_BASE)
ifp->eport = MG_EPHEMERAL_PORT_BASE;
c->loc.port = mg_htons(ifp->eport++);
} // otherwise retain an existing bound port
#if MG_ENABLE_IPV6
if (c->rem.is_ip6) {
if (c->rem.addr.ip6[0] == ifp->ip6ll[0]) { // same local LAN, use ll
if (c->loc.addr.ip6[0] == 0 && c->loc.addr.ip6[1] == 0 &&
c->rem.addr.ip6[0] == ifp->ip6ll[0]) { // same local LAN, use ll
c->loc.addr.ip6[0] = ifp->ip6ll[0], c->loc.addr.ip6[1] = ifp->ip6ll[1];
} else { // use global address
} else if (c->loc.addr.ip6[0] == 0 && c->loc.addr.ip6[1] == 0) {
// Use global address
c->loc.addr.ip6[0] = ifp->ip6[0], c->loc.addr.ip6[1] = ifp->ip6[1];
}
} // otherwise retain an existing bound address
c->loc.is_ip6 = true;
} else
#endif
{
c->loc.addr.ip4 = ifp->ip;
if (c->loc.addr.ip4 == 0) c->loc.addr.ip4 = ifp->ip;
}
MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
&c->rem));
@@ -12060,7 +12152,7 @@ void mg_connect_resolved(struct mg_connection *c) {
uint32_t rem_ip = c->rem.addr.ip4;
if (ifp->ip && MG_IPISLOCAL(ifp, rem_ip) &&
rem_ip != ifp->gw) { // skip if gw (onstatechange -> ARP)
// If we're in the same LAN, fire an ARP lookup.
// We're in the same LAN, fire an ARP lookup.
MG_DEBUG(("%lu ARP lookup...", c->id));
mg_tcpip_arp_request(ifp, rem_ip, NULL);
settmout(c, MIP_TTYPE_ARP);
@@ -16396,9 +16488,9 @@ static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
long n = 0;
if (c->is_udp) {
union usa usa;
socklen_t slen = tousa(&c->rem, &usa);
socklen_t slen = sizeof(usa);
n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin));
if (n > 0) tomgaddr(&usa, &c->rem, usa.sa.sa_family == AF_INET6);
} else {
n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
}
@@ -19162,8 +19254,8 @@ static bool mg_tls_server_send_hello(struct mg_connection *c) {
// calculate P-256 keyshare and the shared secret
pub[0] = 0x04; // uncompressed point 0x04 || X || Y
if (!mg_p256_make_key(pub + 1, prv) ||
!mg_p256_shared_secret(tls->p256_peer, prv, tls->ecdhe_sec)) {
if (mg_p256_make_key(pub + 1, prv) == 0 ||
mg_p256_shared_secret(tls->p256_peer, prv, tls->ecdhe_sec) == 0) {
mg_bzero(prv, sizeof(prv));
mg_error(c, "bad key");
return false;
@@ -19578,7 +19670,7 @@ static bool mg_tls_send_cert_verify(struct mg_connection *c, bool is_client) {
size_t sigsz, verifysz = 0;
int adj1, adj2;
uint8_t sig[64] = {0};
if (!mg_p256_sign(tls->ec_key, hash, sizeof(hash), sig)) {
if (mg_p256_sign(tls->ec_key, hash, sizeof(hash), sig) != 1) {
mg_error(c, "P-256 sign");
return false;
}
@@ -19589,11 +19681,11 @@ static bool mg_tls_send_cert_verify(struct mg_connection *c, bool is_client) {
verify[10] = 0x02; // ASN.1 INTEGER
verify[11] = (uint8_t) (32 + adj1);
memmove(verify + (size_t) (12 + (adj1 > 0)), sig + (size_t) (adj1 < 0),
(size_t) (32 + (adj1 < 0)));
(size_t) (32 - (adj1 < 0)));
verify[12 + 32 + adj1] = 0x02; // ASN.1 INTEGER
verify[13 + 32 + adj1] = (uint8_t) (32 + adj2);
memmove(verify + (size_t) (14 + 32 + adj1 + (adj2 > 0)),
sig + (size_t) (32 + (adj2 < 0)), (size_t) (32 + (adj2 < 0)));
sig + (size_t) (32 + (adj2 < 0)), (size_t) (32 - (adj2 < 0)));
sigsz = (size_t) (70 + adj1 + adj2);
verifysz = 8U + sigsz;
verify[3] = (uint8_t) (sigsz + 4);
@@ -19710,7 +19802,7 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
}
// calc+fill keyshare; X || Y, sent as an uncompressed point 0x04 || X || Y
if (!mg_p256_make_key(msg_client_hello + 95, tls->p256_cli)) {
if (mg_p256_make_key(msg_client_hello + 95, tls->p256_cli) == 0) {
mg_error(c, "P-256 key");
return false;
}
@@ -19800,8 +19892,8 @@ static int mg_tls_client_recv_hello(struct mg_connection *c) {
return -1;
}
if (key_exchange_len != 65 || key_exchange[0] != 0x04 ||
!mg_p256_shared_secret(key_exchange + 1, tls->p256_cli,
tls->ecdhe_sec)) { // Validates the point
mg_p256_shared_secret(key_exchange + 1, tls->p256_cli,
tls->ecdhe_sec) == 0) { // Validates the point
mg_error(c, "bad key");
return -1;
}
@@ -20078,17 +20170,20 @@ static int mg_tls_verify_cert_san(const uint8_t *der, size_t dersz,
const char *server_name,
struct mg_addr *ref_ip) {
struct mg_der_tlv root, field, name;
int r;
bool is_addr = ref_ip != NULL;
if (mg_der_parse((uint8_t *) der, dersz, &root) < 0) {
MG_ERROR(("failed to parse certificate"));
return -1;
}
if (mg_der_find_oid(&root, (uint8_t *) "\x55\x1d\x11", 3, &field) <= 0) {
if ((r = mg_der_find_oid(&root, (uint8_t *) "\x55\x1d\x11", 3, &field)) < 0) {
MG_ERROR(("failed to extract SAN"));
return -1;
} else if (r == 0) {
return 0; // No SAN
}
if (mg_der_parse(field.value, field.len, &field) < 0) {
MG_ERROR(("SAN is not a constructed object"));
if (mg_der_parse(field.value, field.len, &field) < 0 || field.type != 0x30) {
MG_ERROR(("SAN is not a constructed object")); // RFC 5280 4.2.1.6
return -1;
}
while (mg_der_next(&field, &name) > 0) {
@@ -20115,6 +20210,7 @@ static int mg_tls_verify_cert_san(const uint8_t *der, size_t dersz,
return 1; // and matches the host name
}
}
MG_ERROR(("Found SAN but does not match IP or DNS name"));
return -1;
}
@@ -20178,14 +20274,14 @@ static bool mg_tls_verify_cert_signature(const struct mg_tls_cert *cert,
}
}
static int mg_tls_verify_cert_cn(struct mg_der_tlv *subj, const char *host) {
static bool mg_tls_verify_cert_cn(struct mg_der_tlv *subj, const char *host) {
struct mg_der_tlv v;
int matched = 0;
bool matched = false;
if (mg_der_find_oid(subj, (uint8_t *) "\x55\x04\x03", 3, &v) > 0) {
struct mg_str hn, cn;
MG_VERBOSE(("using CN: %.*s <-> %s", v.len, v.value, host));
hn = mg_str(host), cn = mg_str_n((char *) v.value, v.len);
matched = (int) (countdots(hn) == countdots(cn) && mg_match(hn, cn, NULL));
matched = (countdots(hn) == countdots(cn) && mg_match(hn, cn, NULL));
}
return matched;
}
@@ -20302,12 +20398,15 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
// and store public key for further CertVerify step
if (tls->hostname[0] != '\0') {
struct mg_addr addr; // use aton_ so localhost evals as a name
bool is_addr = mg_aton_(mg_str_s(tls->hostname), &addr);
if (mg_tls_verify_cert_san(cert, certsz, tls->hostname,
is_addr ? &addr : NULL) <= 0 &&
(!is_addr || // DNS CN fallback
mg_tls_verify_cert_cn(&ci->subj, tls->hostname) <= 0)) {
mg_error(c, "failed to verify hostname");
bool is_addr;
int san;
is_addr = mg_aton_(mg_str_s(tls->hostname), &addr);
san = mg_tls_verify_cert_san(cert, certsz, tls->hostname,
is_addr ? &addr : NULL);
if (san < 0 || // RFC 6125 6.4.4 allow legacy fallback to CN
(san == 0 &&
(is_addr || !mg_tls_verify_cert_cn(&ci->subj, tls->hostname)))) {
mg_error(c, "failed to verify host");
return -1;
}
}
@@ -21142,8 +21241,8 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
mg_error(c, "hostname too long");
return;
}
strncpy((char *) tls->hostname, opts->name.buf, sizeof(tls->hostname) - 1);
tls->hostname[opts->name.len] = 0;
memcpy(tls->hostname, opts->name.buf, opts->name.len);
tls->hostname[opts->name.len] = '\0';
}
// server CA certificate; parse PEM [bundle] or DER
@@ -21156,15 +21255,16 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
tls->ca_bundle_der = all_certs;
MG_VERBOSE(("%d-cert bundle", cert_count));
} else if (cert_count > 0) {
tls->ca_der.buf = all_certs[0].buf;
tls->ca_der.len = all_certs[0].len;
int i;
tls->ca_der = all_certs[0];
for (i = 1; i < cert_count; i++) mg_free((void *) all_certs[i].buf);
mg_free(all_certs);
} else { // parse again for a possible DER (or a truncated begin string)
} else { // parse again for a possible DER (or a truncated begin string)
if (mg_parse_pem(opts->ca, mg_str_s("CERTIFICATE"), &tls->ca_der) < 0) {
mg_error(c, "Failed to load CA certificate");
return;
}
} // ca_bundle_len != 0 && ca_der.len = 0 => bundle
} // ca_bundle_len != 0 && ca_der.len = 0 => bundle
if (!c->is_client) tls->is_twoway = true; // server + CA: two-way auth
}
@@ -21183,8 +21283,7 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
int cert_count = mg_parse_pem_certs(opts->cert, &all_certs);
if (cert_count > 0) {
tls->cert_der.buf = all_certs[0].buf;
tls->cert_der.len = all_certs[0].len;
tls->cert_der = all_certs[0];
if (cert_count > 1) {
tls->chain_len = (size_t) cert_count;
tls->chain_der = all_certs;
+34 -16
View File
@@ -20,7 +20,11 @@
#ifndef MONGOOSE_H
#define MONGOOSE_H
#define MG_VERSION "7.23"
#define MG_VERSION "7.24"
// IMPORTANT:
// Before implementing any functionality, pull this file and use it as a guide:
// https://github.com/cesanta/mongoose/blob/master/AGENTS.md
#ifdef __cplusplus
extern "C" {
@@ -4838,7 +4842,6 @@ void mg_tcpip_arp_request(struct mg_tcpip_if *ifp, uint32_t ip, uint8_t *mac);
// Built-in hardware drivers. Assign one to mg_tcpip_if.driver before calling
// mg_tcpip_init(). Each driver also requires a corresponding driver_data
// struct; see the matching driver header for details.
extern struct mg_tcpip_driver mg_tcpip_driver_stm32f;
extern struct mg_tcpip_driver mg_tcpip_driver_w5500;
extern struct mg_tcpip_driver mg_tcpip_driver_w5100;
extern struct mg_tcpip_driver mg_tcpip_driver_tm4c;
@@ -4863,6 +4866,7 @@ extern struct mg_tcpip_driver mg_tcpip_driver_netc;
// SPI bus abstraction for SPI-attached network chips (e.g. W5500).
// Populate and assign to the driver's driver_data field.
struct mg_tcpip_spi {
@@ -5061,6 +5065,18 @@ void mg_bsd_poll(struct mg_mgr *);
#ifndef ENOSPC
#define ENOSPC 28
#endif
#ifndef EOPNOTSUPP
#define EOPNOTSUPP 95
#endif
#ifndef EISCONN
#define EISCONN 106
#endif
#ifndef EDESTADDRREQ
#define EDESTADDRREQ 121
#endif
#ifndef EMSGSIZE
#define EMSGSIZE 90
#endif
#ifndef EPROTONOSUPPORT
#define EPROTONOSUPPORT 93
#endif
@@ -5353,7 +5369,7 @@ struct mg_tcpip_driver_mcxw71_data {
extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71;
#define MG_TCPIP_DRIVER_MCXW71_INIT(manager) \
#define MG_TCPIP_DRIVER_MCXW71_INIT(mgr) \
do { \
static struct mg_tcpip_driver_mcxw71_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -5361,10 +5377,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71;
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_mcxw71; \
mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mcxw71, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
@@ -5387,7 +5402,7 @@ struct mg_tcpip_driver_mg24_data {
extern struct mg_tcpip_driver mg_tcpip_driver_mg24;
#define MG_TCPIP_DRIVER_MG24_INIT(manager) \
#define MG_TCPIP_DRIVER_MG24_INIT(mgr) \
do { \
static struct mg_tcpip_driver_mg24_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -5395,10 +5410,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_mg24;
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_mg24; \
mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mg24, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
@@ -5470,7 +5484,7 @@ struct mg_tcpip_driver_nrf52_data {
extern struct mg_tcpip_driver mg_tcpip_driver_nrf52;
#define MG_TCPIP_DRIVER_NRF52_INIT(manager) \
#define MG_TCPIP_DRIVER_NRF52_INIT(mgr) \
do { \
static struct mg_tcpip_driver_nrf52_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -5478,10 +5492,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_nrf52;
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_nrf52; \
mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: nrf52, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
@@ -5676,7 +5689,7 @@ struct mg_tcpip_driver_rw612w_data {
extern struct mg_tcpip_driver mg_tcpip_driver_rw612w;
#define MG_TCPIP_DRIVER_RW612W_INIT(manager) \
#define MG_TCPIP_DRIVER_RW612W_INIT(mgr) \
do { \
static struct mg_tcpip_driver_rw612w_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -5684,10 +5697,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_rw612w;
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_rw612w; \
mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: rw612w, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
@@ -5835,7 +5847,9 @@ struct mg_tcpip_driver_stm32f_data {
#define MG_ENABLE_ETH_IRQ()
#endif
#define MG_TCPIP_DRIVER_INIT(mgr) \
extern struct mg_tcpip_driver mg_tcpip_driver_stm32f;
#define MG_TCPIP_DRIVER_STM32F_INIT(mgr) \
do { \
static struct mg_tcpip_driver_stm32f_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -5848,10 +5862,14 @@ struct mg_tcpip_driver_stm32f_data {
mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \
MG_ENABLE_ETH_IRQ(); \
mg_tcpip_init(mgr, &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: stm32f, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_STM32F_INIT(x)
#endif
#endif
@@ -37,7 +37,6 @@
<file category="sourceC" name="mongoose.c" />
<file category="header" name="mongoose_config.h"/>
<file category="utility" name="README.md" public="false"/>
<file category="genAsset" name=".config/mongoose_parameters.json"/>
</files>
<environments>
<environment name="STM32Cube">
+3 -197
View File
@@ -4,201 +4,7 @@ This pack provides an easy to use CubeMX integration.
## Mongoose Networking Core
This module installs Mongoose Library itself: `mogoose.c`, `mongoose.h` and
`mongoose_config.h`. It is required for any other module to work. Below are
the steps to make it work with you CubeMX application:
This module installs Mongoose Library itself: `mogoose.c`, `mongoose.h` and
`mongoose_config.h`. To finish integration, follow this guide:
## Configure peripherals
In CubeMX, configure USART (for debug), RNG (for TLS), ETH.
## Enable debug logs
Open `Core/Src/main.c` and add this snippet:
```c
/* USER CODE BEGIN 0 */
int _write(int fd, unsigned char *buf, int len) {
HAL_UART_Transmit(&huart3, buf, len, HAL_MAX_DELAY);
return len;
}
/* USER CODE END 0 */
```
## Call Mongoose
Open `Core/Src/main.c`. Add at the top of the file:
```c
/* USER CODE BEGIN Includes */
#include "mongoose.h"
/* USER CODE END Includes */
```
Inside main() function:
```c
Inside the `main()` function:
```c
/* USER CODE BEGIN WHILE */
struct mg_mgr mgr;
mg_mgr_init(&mgr);
while (1)
{
mg_mgr_poll(&mgr, 1);
/* USER CODE END WHILE */
```
This starts the TCP/IP stack. In the serial console logs, you should
see something like this:
```text
0 2 mongoose.c:26153:mg_phy_init PHY ID: 0x07 0xc131 (LAN87x)
6 2 mongoose.c:5834:mg_mgr_init Driver: stm32h, MAC: 2a:37:94:03:d5:74
d 3 mongoose.c:5841:mg_mgr_init MG_IO_SIZE: 512, TLS: builtin
13 3 mongoose.c:5758:mg_listen 1 0 http://0.0.0.0:80
19 1 mongoose.c:6260:onstatechange Link down
7d6 3 mongoose.c:28424:mg_tcpip_driv Link is 100M full-duplex
7db 3 mongoose.c:6404:tx_dhcp_discov DHCP discover sent. Our MAC: 2a:37:94:03:d5:74
831 3 mongoose.c:6382:tx_dhcp_reques DHCP req sent
836 2 mongoose.c:6559:rx_dhcp_client Lease: 3600 sec (3602)
83c 2 mongoose.c:6249:onstatechange READY, IP: 192.168.2.31
842 2 mongoose.c:6250:onstatechange GW: 192.168.2.1
847 2 mongoose.c:6253:onstatechange MAC: 2a:37:94:03:d5:74
```
Now, you should be able to ping your device.
However, it runs no network services.
## Add hello world HTTP server
Let's add the simplest web server possible. After the `mg_mgr_init()`
call, add one more line to start the HTTP listener:
```c
mg_mgr_init(&mgr);
mg_http_listen(&mgr, "http://0.0.0.0:80", http_ev_handler, NULL);
```
And after the `_write()` override, add this HTTP event handler function:
```c
static void http_ev_handler(struct mg_connection *c, int ev, void *ev_data) {
if (ev == MG_EV_HTTP_MSG) {
mg_http_reply(c, 200, "", "Hi from Mongoose! Tick %lu\r\n", HAL_GetTick());
}
}
```
Rebuild, reflash your board, open the device's IP address in the browser,
and see the message displayed, something like:
```text
Hi from Mongoose! Tick 38187
```
## Add full device dashboard
Remove the hello world server if you added it.
Create `Mongoose` directory in the project root and copy
the following files there:
- [dashboard.c](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/device-dashboard/full/dashboard.c)
- [dashboard.html](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/device-dashboard/full/dashboard.html)
- [html2c.js](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/resources/html2c.js)
`html2c.js` is a node.js script that generates `file_data.c` using this command:
`node html2c.js dashboard.html -o file_data.c`. This script first inlines all
external resources into an amalgamated HTML file - so it does not depend on
anything external, and then zips it and packs into a Mongoose embedded
filesystem. This way it takes the minimum space on flash.
In top-level `CMakeLists.txt`, add two extra source files to the build,
and add the rule to generate `file_data.c` from `dashboard.html`.
Note that requires Nodejs installed:
```text
# Generate file_data.c from dashboard.html
add_custom_command(
OUTPUT ${CMAKE_SOURCE_DIR}/Mongoose/file_data.c
COMMAND node ${CMAKE_SOURCE_DIR}/Mongoose/html2c.js ${CMAKE_SOURCE_DIR}/Mongoose/dashboard.html -o ${CMAKE_SOURCE_DIR}/Mongoose/file_data.c
DEPENDS ${CMAKE_SOURCE_DIR}/Mongoose/dashboard.html
VERBATIM
)
# Add sources to executable
target_sources(${CMAKE_PROJECT_NAME} PRIVATE
# Add user sources here
Mongoose/dashboard.c
Mongoose/file_data.c
)
```
Modify your while loop to look like this:
```c
/* USER CODE BEGIN WHILE */
struct mg_mgr mgr;
mg_mgr_init(&mgr);
mg_dash_init(&mgr);
while (1)
{
mg_mgr_poll(&mgr, 1);
mg_dash_poll(&mgr);
/* USER CODE END WHILE */
```
Rebuild and reflash your board, then open the device's IP address in your
browser. Log in using `admin` as the password. You should see the full
dashboard, including the status panel, device settings, firmware update, and
file manager. You can easily customize it for your product, but we will start
by implementing a simple LED control dashboard to demonstrate the principles.
## Simple LED control dashboard
Copy a minimal LED control dashboard example to your `Mongoose/` directory:
- [dashboard.c](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/device-dashboard/minimal/dashboard.c)
- [dashboard.html](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/device-dashboard/minimal/dashboard.html)
Rebuild and reflash
## AI agentic development
For agentic development, use https://github.com/cesanta/mongoose/tree/master/AGENTS.md
Use a prompt like this:
> Read and apply https://github.com/cesanta/mongoose/tree/master/AGENTS.md
## Add MQTT Client
Copy [mqtt.c](https://raw.githubusercontent.com/cesanta/mongoose/refs/heads/master/tutorials/mqtt/mqtt-client/mqtt.c)
to the `Mongoose/` directory. Add it to the extra source files in `CMakeLists.txt`
Add MQTT init and poll to your while loop:
```c
/* USER CODE BEGIN WHILE */
struct mg_mgr mgr;
mg_mgr_init(&mgr);
mg_mqtt_init(&mgr);
while (1)
{
mg_mgr_poll(&mgr, 1);
mg_mqtt_poll(&mgr);
/* USER CODE END WHILE */
```
Rebuild, reflash your board. This MQTT Client connects to the
HiveMQ public MQTT broker.
Also it add a JSON-RPC "ota.update" function via MQTT, so you can
update your firmware over MQTT, see https://mongoose.ws/mqtt/
https://mongoose.ws/docs/guides/stm32-tcpip-stack/#configure-peripherals
+5 -5
View File
@@ -3,22 +3,22 @@
"bomFormat": "CycloneDX",
"specVersion": "1.6",
"serialNumber": "urn:uuid:d3f8b1e2-4a7c-4d9e-bf2a-1c3e5f7a9b0d",
"version": 2,
"version": 3,
"metadata": {
"timestamp": "2026-10-13T00:00:00Z",
"timestamp": "2026-11-18T00:00:00Z",
"component": {
"type": "library",
"bom-ref": "mongoose",
"supplier": { "name": "Cesanta Software Limited", "url": ["https://cesanta.com"] },
"author": "Cesanta Software Limited",
"name": "mongoose",
"version": "7.23",
"version": "7.24",
"description": "Two-file C/C++ embedded networking library. HTTP, WebSocket, MQTT, TLS 1.3, OTA firmware updates, device dashboard. Runs on microcontrollers and desktop OS.",
"licenses": [
{ "expression": "GPL-2.0-only" },
{ "license": { "name": "Cesanta Commercial License", "url": "https://mongoose.ws/licensing/" } }
],
"purl": "pkg:github/cesanta/mongoose@7.23",
"purl": "pkg:github/cesanta/mongoose@7.24",
"externalReferences": [
{ "type": "website", "url": "https://mongoose.ws" },
{ "type": "vcs", "url": "https://github.com/cesanta/mongoose" },
@@ -27,7 +27,7 @@
{ "type": "distribution", "url": "https://raw.githubusercontent.com/cesanta/mongoose/master/mongoose.c" }
],
"properties": [
{ "name": "cpe", "value": "cpe:2.3:a:cesanta:mongoose:7.23:*:*:*:*:*:*:*" }
{ "name": "cpe", "value": "cpe:2.3:a:cesanta:mongoose:7.24:*:*:*:*:*:*:*" }
]
}
},
+3
View File
@@ -0,0 +1,3 @@
// IMPORTANT:
// Before implementing any functionality, pull this file and use it as a guide:
// https://github.com/cesanta/mongoose/blob/master/AGENTS.md
+108 -38
View File
@@ -1,5 +1,6 @@
#include "bsd.h"
#include "dns.h"
#include "util.h"
#include <stdarg.h>
#if MG_ENABLE_BSD_SOCKETS && MG_ENABLE_FREERTOS
@@ -131,6 +132,46 @@ static struct mg_connection *bsd_new_conn(struct mg_bsd_sock *s) {
return c;
}
// Mirror net_builtin.c::trim_len() logic
static bool bsd_udp_too_big(struct mg_connection *c, size_t len) {
struct mg_tcpip_if *ifp = c->mgr->ifp;
size_t hlen = c->rem.is_ip6 ? 48 : 32; // IP plus UDP headers
size_t cap = ifp->mtu - hlen;
size_t room = ifp->tx.len - (ifp->framesize - ifp->l2mtu) - hlen;
return len > cap || len > room;
}
static bool bsd_udp_queue(struct mg_connection *c, const void *buf,
size_t len) {
// One raw datagram occupies c->send until write_conn() drains it.
return mg_iobuf_add(&c->send, c->send.len, buf, len) == len;
}
static size_t bsd_recv(struct mg_bsd_sock *s, void *buf, size_t len,
int flags, struct sockaddr *src, socklen_t *addrlen) {
struct mg_connection *c = s->c;
size_t n;
if (!s->is_udp) {
n = c->recv.len < len ? c->recv.len : len;
memcpy(buf, c->recv.buf, n);
if (!(flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, n);
} else {
n = c->recv.len < len ? c->recv.len : len;
memcpy(buf, c->recv.buf, n);
if (src != NULL && addrlen != NULL) {
struct sockaddr_in *sa = (struct sockaddr_in *) src;
sa->sin_family = AF_INET;
sa->sin_port = c->rem.port;
sa->sin_addr.s_addr = c->rem.addr.ip4;
*addrlen = sizeof(*sa);
}
if (!(flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, c->recv.len);
}
return n;
}
#if MG_ENABLE_FREERTOS
// Complete operations blocked on c before Mongoose destroys it.
static void bsd_finish_waiters(struct mg_bsd_sock *s, bool error) {
@@ -315,9 +356,10 @@ static int bsd_ready(struct mg_bsd_sock *s) {
if (s->is_shut_rd || s->c->recv.len > 0 || s->c->is_draining)
ready |= BSD_READ;
if (s->is_shut_wr) ready |= BSD_ERROR;
if (!s->is_shut_wr && !s->is_udp && !s->c->is_connecting &&
!s->c->is_closing && !s->c->is_draining)
ready |= BSD_WRITE; // Established TCP socket
if (!s->is_shut_wr && (s->is_udp || !s->c->is_connecting) &&
!s->c->is_closing && !s->c->is_draining &&
(!s->is_udp || s->c->send.len == 0))
ready |= BSD_WRITE; // UDP socket or established TCP socket
return ready;
}
@@ -331,7 +373,7 @@ static void bsd_close(struct mg_bsd_sock *s) {
if (t->orphan && t->listener == s) {
if (t->c != NULL) {
t->c->fn_data = NULL;
mg_close_conn(t->c);
t->c->is_draining = 1;
t->c = NULL;
}
memset(t, 0, sizeof(*t)); // Release orphan
@@ -339,7 +381,7 @@ static void bsd_close(struct mg_bsd_sock *s) {
}
if (s->c != NULL) {
s->c->fn_data = NULL;
mg_close_conn(s->c);
s->c->is_draining = 1;
s->c = NULL;
}
memset(s, 0, sizeof(*s)); // Release socket
@@ -529,8 +571,8 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
cmd->result = -1, cmd->err = ECONNREFUSED;
return true;
}
if (!c->is_connecting) {
cmd->result = 0;
if (s->is_udp || !c->is_connecting) {
cmd->result = 0; // UDP may still resolve ARP; TCP waits for SYN/SYN-ACK
return true;
}
if (s->nonblock) {
@@ -555,11 +597,8 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
return true;
}
if (c->recv.len > 0) {
size_t n = cmd->op_recv.len;
if (c->recv.len < n) n = c->recv.len;
memcpy(cmd->op_recv.buf, c->recv.buf, n);
if (!(cmd->op_recv.flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, n);
cmd->result = (int) n;
cmd->result = (int) bsd_recv(s, cmd->op_recv.buf, cmd->op_recv.len,
cmd->op_recv.flags, NULL, NULL);
return true;
}
if (s->err != 0) {
@@ -583,7 +622,25 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
} else if (s->is_shut_wr || (c = s->c) == NULL || s->err != 0 ||
c->is_closing || c->is_draining) {
cmd->result = -1, cmd->err = EPIPE;
} else if (mg_send(c, cmd->op_send.buf, cmd->op_send.len)) {
} else if (c == NULL || (s->is_udp && !c->is_client)) {
cmd->result = -1, cmd->err = s->is_udp ? EDESTADDRREQ : EPIPE;
} else if (s->is_udp && cmd->op_send.len == 0) {
cmd->result = 0;
} else if (s->is_udp && bsd_udp_too_big(c, cmd->op_send.len)) {
cmd->result = -1, cmd->err = EMSGSIZE;
} else if (s->is_udp && c->send.len > 0) {
if (s->nonblock || (cmd->op_send.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
} else {
#if MG_ENABLE_FREERTOS
return false; // One UDP datagram is pending, wait
#else
cmd->result = -1, cmd->err = EAGAIN;
#endif
}
} else if ((s->is_udp
? bsd_udp_queue(c, cmd->op_send.buf, cmd->op_send.len)
: mg_send(c, cmd->op_send.buf, cmd->op_send.len))) {
cmd->result = (int) cmd->op_send.len;
} else if (s->nonblock || (cmd->op_send.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
@@ -600,25 +657,49 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
if ((s = bsd_get(cmd->op_sendto.fd)) == NULL) {
cmd->result = -1, cmd->err = EBADF;
} else if (!s->is_udp) {
cmd->result = -1, cmd->err = EOPNOTSUPP;
} else if ((err = bsd_addr4(cmd->op_sendto.addr,
cmd->op_sendto.addrlen)) != 0) {
cmd->result = -1, cmd->err = err;
} else if (s->is_shut_wr || (c = s->c) == NULL || s->err != 0 ||
c->is_closing || c->is_draining) {
cmd->result = -1, cmd->err = EPIPE;
} else if (c->is_client) {
cmd->result = -1, cmd->err = EISCONN;
} else {
const struct sockaddr_in *sa =
(const struct sockaddr_in *) cmd->op_sendto.addr;
c->rem.port = sa->sin_port;
c->rem.addr.ip4 = sa->sin_addr.s_addr;
c->rem.is_ip6 = false;
if (mg_send(c, cmd->op_sendto.buf, cmd->op_sendto.len)) {
cmd->result = (int) cmd->op_sendto.len;
if (cmd->op_sendto.len == 0) {
cmd->result = 0;
} else if (bsd_udp_too_big(c, cmd->op_sendto.len)) {
cmd->result = -1, cmd->err = EMSGSIZE;
} else if (c->send.len == 0) {
struct mg_addr rem = c->rem;
bool resolve = rem.is_ip6 || rem.addr.ip4 != sa->sin_addr.s_addr;
c->rem.port = sa->sin_port;
c->rem.addr.ip4 = sa->sin_addr.s_addr;
c->rem.is_ip6 = false;
if (bsd_udp_queue(c, cmd->op_sendto.buf, cmd->op_sendto.len)) {
if (resolve) mg_connect_resolved(c);
cmd->result = (int) cmd->op_sendto.len;
} else {
c->rem = rem;
if (s->nonblock || (cmd->op_sendto.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
} else {
#if MG_ENABLE_FREERTOS
return false; // No send buffer space yet, wait
#else
cmd->result = -1, cmd->err = EAGAIN;
#endif
}
}
} else if (s->nonblock || (cmd->op_sendto.flags & MSG_DONTWAIT)) {
cmd->result = -1, cmd->err = EAGAIN;
} else {
#if MG_ENABLE_FREERTOS
return false; // No send buffer space yet, wait
return false; // One UDP datagram is pending, wait
#else
cmd->result = -1, cmd->err = EAGAIN;
#endif
@@ -630,6 +711,9 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
if ((s = bsd_get(cmd->op_recvfrom.fd)) == NULL) {
cmd->result = -1, cmd->err = EBADF;
return true;
} else if (!s->is_udp) {
cmd->result = -1, cmd->err = EOPNOTSUPP;
return true;
}
if (s->is_shut_rd) {
cmd->result = 0;
@@ -641,25 +725,11 @@ static bool bsd_run(struct mg_bsd_cmd *cmd) {
return true;
}
if (c->recv.len > 0) {
size_t n = cmd->op_recvfrom.len;
if (cmd->op_recvfrom.src != NULL &&
(cmd->op_recvfrom.addrlen == NULL ||
*cmd->op_recvfrom.addrlen < sizeof(struct sockaddr_in))) {
cmd->result = -1, cmd->err = EINVAL;
return true;
}
if (c->recv.len < n) n = c->recv.len;
memcpy(cmd->op_recvfrom.buf, c->recv.buf, n);
if (!(cmd->op_recvfrom.flags & MSG_PEEK)) mg_iobuf_del(&c->recv, 0, n);
if (cmd->op_recvfrom.src != NULL && cmd->op_recvfrom.addrlen != NULL) {
struct sockaddr_in *sa = (struct sockaddr_in *) cmd->op_recvfrom.src;
sa->sin_family = AF_INET;
sa->sin_port = c->rem.port;
sa->sin_addr.s_addr = c->rem.addr.ip4;
*cmd->op_recvfrom.addrlen = sizeof(*sa);
}
cmd->result = (int) n;
cmd->result = (int) bsd_recv(s, cmd->op_recvfrom.buf,
cmd->op_recvfrom.len,
cmd->op_recvfrom.flags,
cmd->op_recvfrom.src,
cmd->op_recvfrom.addrlen);
return true;
}
if (s->err != 0) {
+12
View File
@@ -64,6 +64,18 @@ void mg_bsd_poll(struct mg_mgr *);
#ifndef ENOSPC
#define ENOSPC 28
#endif
#ifndef EOPNOTSUPP
#define EOPNOTSUPP 95
#endif
#ifndef EISCONN
#define EISCONN 106
#endif
#ifndef EDESTADDRREQ
#define EDESTADDRREQ 121
#endif
#ifndef EMSGSIZE
#define EMSGSIZE 90
#endif
#ifndef EPROTONOSUPPORT
#define EPROTONOSUPPORT 93
#endif
+3 -2
View File
@@ -136,12 +136,13 @@ bool mg_dns_parse(const uint8_t *buf, size_t len, struct mg_dns_message *dm) {
dm->txnid = mg_ntohs(h->txnid);
is_response = mg_ntohs(h->flags) & 0x8000;
for (i = 0; i < mg_ntohs(h->num_questions); i++) {
for (i = 0; i < mg_ntohs(h->num_questions); i++) { // advance past queries
if ((n = mg_dns_parse_rr(buf, len, ofs, true, &rr)) == 0) return false;
// MG_INFO(("Q %lu %lu %hu/%hu", ofs, n, rr.atype, rr.aclass));
dm->addr.is_ip6 = (rr.atype == MG_DNS_RTYPE_AAAA);
mg_dns_parse_name(buf, len, ofs, dm->name, sizeof(dm->name));
ofs += n;
}
} // on unresolved responses, we got the name and query type, at least
if (!is_response) {
// For queries, there is no need to parse the answers. In this way,
+2 -3
View File
@@ -13,7 +13,7 @@ struct mg_tcpip_driver_mcxw71_data {
extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71;
#define MG_TCPIP_DRIVER_MCXW71_INIT(manager) \
#define MG_TCPIP_DRIVER_MCXW71_INIT(mgr) \
do { \
static struct mg_tcpip_driver_mcxw71_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -21,10 +21,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_mcxw71;
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_mcxw71; \
mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mcxw71, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
+2 -3
View File
@@ -12,7 +12,7 @@ struct mg_tcpip_driver_mg24_data {
extern struct mg_tcpip_driver mg_tcpip_driver_mg24;
#define MG_TCPIP_DRIVER_MG24_INIT(manager) \
#define MG_TCPIP_DRIVER_MG24_INIT(mgr) \
do { \
static struct mg_tcpip_driver_mg24_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -20,10 +20,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_mg24;
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_mg24; \
mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: mg24, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
+2 -3
View File
@@ -12,7 +12,7 @@ struct mg_tcpip_driver_nrf52_data {
extern struct mg_tcpip_driver mg_tcpip_driver_nrf52;
#define MG_TCPIP_DRIVER_NRF52_INIT(manager) \
#define MG_TCPIP_DRIVER_NRF52_INIT(mgr) \
do { \
static struct mg_tcpip_driver_nrf52_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -20,10 +20,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_nrf52;
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_nrf52; \
mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: nrf52, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
+2 -3
View File
@@ -13,7 +13,7 @@ struct mg_tcpip_driver_rw612w_data {
extern struct mg_tcpip_driver mg_tcpip_driver_rw612w;
#define MG_TCPIP_DRIVER_RW612W_INIT(manager) \
#define MG_TCPIP_DRIVER_RW612W_INIT(mgr) \
do { \
static struct mg_tcpip_driver_rw612w_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -21,10 +21,9 @@ extern struct mg_tcpip_driver mg_tcpip_driver_rw612w;
mif_.ip = MG_TCPIP_IP; \
mif_.mask = MG_TCPIP_MASK; \
mif_.gw = MG_TCPIP_GW; \
mif_.mgr = (manager); \
mif_.driver = &mg_tcpip_driver_rw612w; \
mif_.driver_data = &driver_data_; \
mg_tcpip_init((manager), &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: rw612w, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
+8 -2
View File
@@ -34,7 +34,9 @@ struct mg_tcpip_driver_stm32f_data {
#define MG_ENABLE_ETH_IRQ()
#endif
#define MG_TCPIP_DRIVER_INIT(mgr) \
extern struct mg_tcpip_driver mg_tcpip_driver_stm32f;
#define MG_TCPIP_DRIVER_STM32F_INIT(mgr) \
do { \
static struct mg_tcpip_driver_stm32f_data driver_data_; \
static struct mg_tcpip_if mif_; \
@@ -47,8 +49,12 @@ struct mg_tcpip_driver_stm32f_data {
mif_.driver_data = &driver_data_; \
MG_SET_MAC_ADDRESS(mif_.mac); \
MG_ENABLE_ETH_IRQ(); \
mg_tcpip_init(mgr, &mif_); \
mg_tcpip_init((mgr), &mif_); \
MG_INFO(("Driver: stm32f, MAC: %M", mg_print_mac, mif_.mac)); \
} while (0)
#ifndef MG_TCPIP_DRIVER_INIT
#define MG_TCPIP_DRIVER_INIT(x) MG_TCPIP_DRIVER_STM32F_INIT(x)
#endif
#endif
+8 -4
View File
@@ -752,11 +752,15 @@ static bool uri2path(const char *r, struct mg_str uri, char *buf, size_t len) {
n = mg_snprintf(buf, len, "%.*s", (int) d.len, d.buf);
if (len == 0 || n + 2 >= len) return false; // Path overflow
if (n > 0 && buf[n - 1] != '/') buf[n++] = '/', buf[n] = '\0'; // Add slash
if (mg_url_decode(uri.buf + u.len, uri.len - u.len, buf + n, len - n, 0) < 0) {
return false;
{
int dn;
size_t p = n;
dn = mg_url_decode(uri.buf + u.len, uri.len - u.len, buf + n, len - n, 0);
if (dn < 0) return false; // reject on malformed
buf[len - 1] = '\0'; // Double-check
n = strlen(buf);
if (n != p + (size_t) dn) return false; // reject on embedded NULs
}
buf[len - 1] = '\0'; // Double-check
n = strlen(buf);
if (!mg_path_is_sane(mg_str_n(buf, n))) return false;
while (n > 1 && buf[n - 1] == '/') buf[--n] = 0; // Trim trailing slashes
return true;
+29 -12
View File
@@ -1224,22 +1224,34 @@ static void proto_error(struct mg_connection *c, bool r, const char *f, ...) {
static bool rx_udp(struct mg_tcpip_if *ifp, struct pkt *pkt) {
struct mg_connection *c = getpeer(ifp->mgr, pkt, true);
struct connstate *s;
struct mg_addr rem;
uint8_t *l2addr;
if (c == NULL) return false; // No UDP listener on this port
// BSD socket has an unread datagram: drop this one to keep boundaries
if (c->is_bsd && c->recv.len > 0) return true;
if (c->is_bsd && !c->is_client && c->send.len > 0) return true;
s = (struct connstate *) (c + 1);
c->rem.port = pkt->udp->sport;
#if MG_ENABLE_IPV6
if (c->loc.is_ip6) { // matching of v4/v6 to dest is done bt getpeer()
if (!udp6csum_ok(pkt->ip6, pkt->udp)) return false;
c->rem.addr.ip6[0] = pkt->ip6->src[0],
c->rem.addr.ip6[1] = pkt->ip6->src[1], c->rem.is_ip6 = true;
if (c->is_bsd && c->is_client &&
(c->rem.port != pkt->udp->sport ||
!MG_IP6MATCH(c->rem.addr.ip6, pkt->ip6->src)))
return true;
rem.addr.ip6[0] = pkt->ip6->src[0],
rem.addr.ip6[1] = pkt->ip6->src[1], rem.is_ip6 = true;
} else
#endif
{
if (!udpcsum_ok(pkt->ip, pkt->udp)) return false;
c->rem.addr.ip4 = pkt->ip->src;
if (c->is_bsd && c->is_client &&
(c->rem.port != pkt->udp->sport || c->rem.addr.ip4 != pkt->ip->src))
return true;
rem.addr.ip4 = pkt->ip->src, rem.is_ip6 = false;
}
if ((l2addr = get_return_l2addr(ifp, &c->rem, true, pkt)) == NULL)
rem.port = pkt->udp->sport;
c->rem = rem;
if ((l2addr = get_return_l2addr(ifp, &rem, true, pkt)) == NULL)
return false; // safety net for lousy networks
memcpy(s->mac, l2addr, sizeof(s->mac));
if (c->recv.len >= MG_MAX_RECV_SIZE) {
@@ -2345,20 +2357,25 @@ void mg_connect_resolved(struct mg_connection *c) {
s->retransmit = ifp->enable_tcp_retransmit;
s->txq.align = MG_TCPIP_TXQ_ALIGN;
c->is_resolving = 0;
if (ifp->eport < MG_EPHEMERAL_PORT_BASE) ifp->eport = MG_EPHEMERAL_PORT_BASE;
c->loc.port = mg_htons(ifp->eport++);
if (c->loc.port == 0) {
if (ifp->eport < MG_EPHEMERAL_PORT_BASE)
ifp->eport = MG_EPHEMERAL_PORT_BASE;
c->loc.port = mg_htons(ifp->eport++);
} // otherwise retain an existing bound port
#if MG_ENABLE_IPV6
if (c->rem.is_ip6) {
if (c->rem.addr.ip6[0] == ifp->ip6ll[0]) { // same local LAN, use ll
if (c->loc.addr.ip6[0] == 0 && c->loc.addr.ip6[1] == 0 &&
c->rem.addr.ip6[0] == ifp->ip6ll[0]) { // same local LAN, use ll
c->loc.addr.ip6[0] = ifp->ip6ll[0], c->loc.addr.ip6[1] = ifp->ip6ll[1];
} else { // use global address
} else if (c->loc.addr.ip6[0] == 0 && c->loc.addr.ip6[1] == 0) {
// Use global address
c->loc.addr.ip6[0] = ifp->ip6[0], c->loc.addr.ip6[1] = ifp->ip6[1];
}
} // otherwise retain an existing bound address
c->loc.is_ip6 = true;
} else
#endif
{
c->loc.addr.ip4 = ifp->ip;
if (c->loc.addr.ip4 == 0) c->loc.addr.ip4 = ifp->ip;
}
MG_DEBUG(("%lu %M -> %M", c->id, mg_print_ip_port, &c->loc, mg_print_ip_port,
&c->rem));
@@ -2389,7 +2406,7 @@ void mg_connect_resolved(struct mg_connection *c) {
uint32_t rem_ip = c->rem.addr.ip4;
if (ifp->ip && MG_IPISLOCAL(ifp, rem_ip) &&
rem_ip != ifp->gw) { // skip if gw (onstatechange -> ARP)
// If we're in the same LAN, fire an ARP lookup.
// We're in the same LAN, fire an ARP lookup.
MG_DEBUG(("%lu ARP lookup...", c->id));
mg_tcpip_arp_request(ifp, rem_ip, NULL);
settmout(c, MIP_TTYPE_ARP);
+1 -1
View File
@@ -135,7 +135,6 @@ void mg_tcpip_arp_request(struct mg_tcpip_if *ifp, uint32_t ip, uint8_t *mac);
// Built-in hardware drivers. Assign one to mg_tcpip_if.driver before calling
// mg_tcpip_init(). Each driver also requires a corresponding driver_data
// struct; see the matching driver header for details.
extern struct mg_tcpip_driver mg_tcpip_driver_stm32f;
extern struct mg_tcpip_driver mg_tcpip_driver_w5500;
extern struct mg_tcpip_driver mg_tcpip_driver_w5100;
extern struct mg_tcpip_driver mg_tcpip_driver_tm4c;
@@ -159,6 +158,7 @@ extern struct mg_tcpip_driver mg_tcpip_driver_netc;
#include "drivers/mcxw71.h"
#include "drivers/nrf52.h"
#include "drivers/rw612w.h"
#include "drivers/stm32f.h"
// SPI bus abstraction for SPI-attached network chips (e.g. W5500).
// Populate and assign to the driver's driver_data field.
+2 -2
View File
@@ -297,9 +297,9 @@ static long recv_raw(struct mg_connection *c, void *buf, size_t len) {
long n = 0;
if (c->is_udp) {
union usa usa;
socklen_t slen = tousa(&c->rem, &usa);
socklen_t slen = sizeof(usa);
n = recvfrom(FD(c), (char *) buf, len, 0, &usa.sa, &slen);
if (n > 0) tomgaddr(&usa, &c->rem, slen != sizeof(usa.sin));
if (n > 0) tomgaddr(&usa, &c->rem, usa.sa.sa_family == AF_INET6);
} else {
n = recv(FD(c), (char *) buf, len, MSG_NONBLOCKING);
}
+35 -28
View File
@@ -761,8 +761,8 @@ static bool mg_tls_server_send_hello(struct mg_connection *c) {
// calculate P-256 keyshare and the shared secret
pub[0] = 0x04; // uncompressed point 0x04 || X || Y
if (!mg_p256_make_key(pub + 1, prv) ||
!mg_p256_shared_secret(tls->p256_peer, prv, tls->ecdhe_sec)) {
if (mg_p256_make_key(pub + 1, prv) == 0 ||
mg_p256_shared_secret(tls->p256_peer, prv, tls->ecdhe_sec) == 0) {
mg_bzero(prv, sizeof(prv));
mg_error(c, "bad key");
return false;
@@ -1177,7 +1177,7 @@ static bool mg_tls_send_cert_verify(struct mg_connection *c, bool is_client) {
size_t sigsz, verifysz = 0;
int adj1, adj2;
uint8_t sig[64] = {0};
if (!mg_p256_sign(tls->ec_key, hash, sizeof(hash), sig)) {
if (mg_p256_sign(tls->ec_key, hash, sizeof(hash), sig) != 1) {
mg_error(c, "P-256 sign");
return false;
}
@@ -1188,11 +1188,11 @@ static bool mg_tls_send_cert_verify(struct mg_connection *c, bool is_client) {
verify[10] = 0x02; // ASN.1 INTEGER
verify[11] = (uint8_t) (32 + adj1);
memmove(verify + (size_t) (12 + (adj1 > 0)), sig + (size_t) (adj1 < 0),
(size_t) (32 + (adj1 < 0)));
(size_t) (32 - (adj1 < 0)));
verify[12 + 32 + adj1] = 0x02; // ASN.1 INTEGER
verify[13 + 32 + adj1] = (uint8_t) (32 + adj2);
memmove(verify + (size_t) (14 + 32 + adj1 + (adj2 > 0)),
sig + (size_t) (32 + (adj2 < 0)), (size_t) (32 + (adj2 < 0)));
sig + (size_t) (32 + (adj2 < 0)), (size_t) (32 - (adj2 < 0)));
sigsz = (size_t) (70 + adj1 + adj2);
verifysz = 8U + sigsz;
verify[3] = (uint8_t) (sigsz + 4);
@@ -1309,7 +1309,7 @@ static bool mg_tls_client_send_hello(struct mg_connection *c) {
}
// calc+fill keyshare; X || Y, sent as an uncompressed point 0x04 || X || Y
if (!mg_p256_make_key(msg_client_hello + 95, tls->p256_cli)) {
if (mg_p256_make_key(msg_client_hello + 95, tls->p256_cli) == 0) {
mg_error(c, "P-256 key");
return false;
}
@@ -1399,8 +1399,8 @@ static int mg_tls_client_recv_hello(struct mg_connection *c) {
return -1;
}
if (key_exchange_len != 65 || key_exchange[0] != 0x04 ||
!mg_p256_shared_secret(key_exchange + 1, tls->p256_cli,
tls->ecdhe_sec)) { // Validates the point
mg_p256_shared_secret(key_exchange + 1, tls->p256_cli,
tls->ecdhe_sec) == 0) { // Validates the point
mg_error(c, "bad key");
return -1;
}
@@ -1677,17 +1677,20 @@ static int mg_tls_verify_cert_san(const uint8_t *der, size_t dersz,
const char *server_name,
struct mg_addr *ref_ip) {
struct mg_der_tlv root, field, name;
int r;
bool is_addr = ref_ip != NULL;
if (mg_der_parse((uint8_t *) der, dersz, &root) < 0) {
MG_ERROR(("failed to parse certificate"));
return -1;
}
if (mg_der_find_oid(&root, (uint8_t *) "\x55\x1d\x11", 3, &field) <= 0) {
if ((r = mg_der_find_oid(&root, (uint8_t *) "\x55\x1d\x11", 3, &field)) < 0) {
MG_ERROR(("failed to extract SAN"));
return -1;
} else if (r == 0) {
return 0; // No SAN
}
if (mg_der_parse(field.value, field.len, &field) < 0) {
MG_ERROR(("SAN is not a constructed object"));
if (mg_der_parse(field.value, field.len, &field) < 0 || field.type != 0x30) {
MG_ERROR(("SAN is not a constructed object")); // RFC 5280 4.2.1.6
return -1;
}
while (mg_der_next(&field, &name) > 0) {
@@ -1714,6 +1717,7 @@ static int mg_tls_verify_cert_san(const uint8_t *der, size_t dersz,
return 1; // and matches the host name
}
}
MG_ERROR(("Found SAN but does not match IP or DNS name"));
return -1;
}
@@ -1777,14 +1781,14 @@ static bool mg_tls_verify_cert_signature(const struct mg_tls_cert *cert,
}
}
static int mg_tls_verify_cert_cn(struct mg_der_tlv *subj, const char *host) {
static bool mg_tls_verify_cert_cn(struct mg_der_tlv *subj, const char *host) {
struct mg_der_tlv v;
int matched = 0;
bool matched = false;
if (mg_der_find_oid(subj, (uint8_t *) "\x55\x04\x03", 3, &v) > 0) {
struct mg_str hn, cn;
MG_VERBOSE(("using CN: %.*s <-> %s", v.len, v.value, host));
hn = mg_str(host), cn = mg_str_n((char *) v.value, v.len);
matched = (int) (countdots(hn) == countdots(cn) && mg_match(hn, cn, NULL));
matched = (countdots(hn) == countdots(cn) && mg_match(hn, cn, NULL));
}
return matched;
}
@@ -1901,12 +1905,15 @@ static int mg_tls_recv_cert(struct mg_connection *c, bool is_client) {
// and store public key for further CertVerify step
if (tls->hostname[0] != '\0') {
struct mg_addr addr; // use aton_ so localhost evals as a name
bool is_addr = mg_aton_(mg_str_s(tls->hostname), &addr);
if (mg_tls_verify_cert_san(cert, certsz, tls->hostname,
is_addr ? &addr : NULL) <= 0 &&
(!is_addr || // DNS CN fallback
mg_tls_verify_cert_cn(&ci->subj, tls->hostname) <= 0)) {
mg_error(c, "failed to verify hostname");
bool is_addr;
int san;
is_addr = mg_aton_(mg_str_s(tls->hostname), &addr);
san = mg_tls_verify_cert_san(cert, certsz, tls->hostname,
is_addr ? &addr : NULL);
if (san < 0 || // RFC 6125 6.4.4 allow legacy fallback to CN
(san == 0 &&
(is_addr || !mg_tls_verify_cert_cn(&ci->subj, tls->hostname)))) {
mg_error(c, "failed to verify host");
return -1;
}
}
@@ -2741,8 +2748,8 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
mg_error(c, "hostname too long");
return;
}
strncpy((char *) tls->hostname, opts->name.buf, sizeof(tls->hostname) - 1);
tls->hostname[opts->name.len] = 0;
memcpy(tls->hostname, opts->name.buf, opts->name.len);
tls->hostname[opts->name.len] = '\0';
}
// server CA certificate; parse PEM [bundle] or DER
@@ -2755,15 +2762,16 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
tls->ca_bundle_der = all_certs;
MG_VERBOSE(("%d-cert bundle", cert_count));
} else if (cert_count > 0) {
tls->ca_der.buf = all_certs[0].buf;
tls->ca_der.len = all_certs[0].len;
int i;
tls->ca_der = all_certs[0];
for (i = 1; i < cert_count; i++) mg_free((void *) all_certs[i].buf);
mg_free(all_certs);
} else { // parse again for a possible DER (or a truncated begin string)
} else { // parse again for a possible DER (or a truncated begin string)
if (mg_parse_pem(opts->ca, mg_str_s("CERTIFICATE"), &tls->ca_der) < 0) {
mg_error(c, "Failed to load CA certificate");
return;
}
} // ca_bundle_len != 0 && ca_der.len = 0 => bundle
} // ca_bundle_len != 0 && ca_der.len = 0 => bundle
if (!c->is_client) tls->is_twoway = true; // server + CA: two-way auth
}
@@ -2782,8 +2790,7 @@ void mg_tls_init(struct mg_connection *c, const struct mg_tls_opts *opts) {
int cert_count = mg_parse_pem_certs(opts->cert, &all_certs);
if (cert_count > 0) {
tls->cert_der.buf = all_certs[0].buf;
tls->cert_der.len = all_certs[0].len;
tls->cert_der = all_certs[0];
if (cert_count > 1) {
tls->chain_len = (size_t) cert_count;
tls->chain_der = all_certs;
+1 -1
View File
@@ -1 +1 @@
#define MG_VERSION "7.23"
#define MG_VERSION "7.24"
+1 -1
View File
@@ -98,7 +98,7 @@ mongoose.c: Makefile $(wildcard ../src/*.c) $(wildcard ../src/drivers/*.c)
cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#include "mongoose.h"' ; (for F in src/*.c src/drivers/*.c ; do echo; echo '#ifdef MG_ENABLE_LINES'; echo "#line 1 \"$$F\""; echo '#endif'; cat $$F | sed -e 's,#include ".*,,'; done))> $@
mongoose.h: $(HDRS) Makefile
cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#ifndef MONGOOSE_H'; echo '#define MONGOOSE_H'; echo; cat src/version.h ; echo; echo '#ifdef __cplusplus'; echo 'extern "C" {'; echo '#endif'; cat src/arch.h src/arch_*.h src/os_*.h src/net_ft.h src/net_lwip.h src/net_rl.h src/config.h src/profile.h src/str.h src/queue.h src/fmt.h src/printf.h src/log.h src/timer.h src/fs.h src/lfs.h src/util.h src/url.h src/iobuf.h src/base64.h src/md5.h src/sha1.h src/sha256.h src/event.h src/net.h src/http.h src/ssi.h src/tls.h src/tls_aes128.h src/tls_p256.h src/tls_p384.h src/tls_chacha20.h src/tls_rsa.h src/tls_mbed.h src/tls_openssl.h src/ws.h src/sntp.h src/mqtt.h src/dns.h src/modbus.h src/json.h src/jwt.h src/rpc.h src/dash.h src/ota.h src/health.h src/mdash.h src/flash.h src/wifi.h src/l2.h src/net_builtin.h src/l2_mesh.h src/bsd.h src/drivers/*.h | sed -e '/keep/! s,#include ".*,,' -e 's,^#pragma once,,'; echo; echo '#ifdef __cplusplus'; echo '}'; echo '#endif'; echo '#endif // MONGOOSE_H')> $@
cd .. && (export LC_ALL=C ; cat src/license.h; echo; echo '#ifndef MONGOOSE_H'; echo '#define MONGOOSE_H'; echo; cat src/version.h ; echo; cat src/ai.h; echo; echo '#ifdef __cplusplus'; echo 'extern "C" {'; echo '#endif'; cat src/arch.h src/arch_*.h src/os_*.h src/net_ft.h src/net_lwip.h src/net_rl.h src/config.h src/profile.h src/str.h src/queue.h src/fmt.h src/printf.h src/log.h src/timer.h src/fs.h src/lfs.h src/util.h src/url.h src/iobuf.h src/base64.h src/md5.h src/sha1.h src/sha256.h src/event.h src/net.h src/http.h src/ssi.h src/tls.h src/tls_aes128.h src/tls_p256.h src/tls_p384.h src/tls_chacha20.h src/tls_rsa.h src/tls_mbed.h src/tls_openssl.h src/ws.h src/sntp.h src/mqtt.h src/dns.h src/modbus.h src/json.h src/jwt.h src/rpc.h src/dash.h src/ota.h src/health.h src/mdash.h src/flash.h src/wifi.h src/l2.h src/net_builtin.h src/l2_mesh.h src/bsd.h src/drivers/*.h | sed -e '/keep/! s,#include ".*,,' -e 's,^#pragma once,,'; echo; echo '#ifdef __cplusplus'; echo '}'; echo '#endif'; echo '#endif // MONGOOSE_H')> $@
# Check that all external (exported) symbols have "mg_" prefix
mg_prefix: mongoose.c mongoose.h
+9 -6
View File
@@ -13,7 +13,7 @@ else
C_WARN ?= -Wno-deprecated
endif
.PHONY: all bsd bsd_test bsd_client bsd_nortos bsd_nortos_test shm_tap_bridge \
.PHONY: all bsd bsd_test bsd_client bsd_udp bsd_nortos bsd_nortos_test shm_tap_bridge \
shm_port_bridge bsd_s390 bsd_nortos_s390 clean
TEST_SOURCES = bsd_shm_test.c
@@ -47,11 +47,11 @@ DOCKER ?= $(DOCKER_BIN) run --platform linux/amd64 --net=host --rm $(ENV) -v $(R
CFLAGS_MONGOOSE += -DMG_ARCH=MG_ARCH_CUSTOM
all bsd: shm_tap_bridge bsd_client FreeRTOS-Kernel bsd_test
all bsd: shm_tap_bridge bsd_client bsd_udp FreeRTOS-Kernel bsd_test
ASAN_OPTIONS=$(ASAN_OPTIONS) $(RUN) ./bsd_test $(ARGS)
# also
bsd_nortos: shm_tap_bridge bsd_client bsd_nortos_test
bsd_nortos: shm_tap_bridge bsd_client bsd_udp bsd_nortos_test
ASAN_OPTIONS=$(ASAN_OPTIONS) $(RUN) ./bsd_nortos_test $(ARGS)
# requires shm_tap_bridge to be running
@@ -70,6 +70,9 @@ bsd_nortos_test:
bsd_client: bsd_client.c
$(CC) bsd_client.c -pthread -o $@
bsd_udp: bsd_udp.c
$(CC) bsd_udp.c -o $@
# bridge shm queue <--> TAP interface
shm_tap_bridge: shm_tap_bridge.c shm_queue.h
$(CC) shm_tap_bridge.c -pthread -o $@
@@ -79,7 +82,7 @@ bsd_s390: CFLAGS_MONGOOSE += -DMG_ENABLE_BSD_PROTOTYPES=0
bsd_s390: ASAN=
bsd_s390: CC = $(DOCKER) mdashnet/s390 cc
bsd_s390: RUN = $(DOCKER) --init mdashnet/s390
bsd_s390: shm_port_bridge bsd_client FreeRTOS-Kernel bsd_test
bsd_s390: shm_port_bridge bsd_client bsd_udp FreeRTOS-Kernel bsd_test
$(RUN) sh -c './shm_port_bridge & pid=$$!; sleep 1; ./bsd_test; rc=$$?; kill $$pid >/dev/null 2>&1; wait $$pid >/dev/null 2>&1; exit $$rc'
#also
@@ -87,14 +90,14 @@ bsd_nortos_s390: CFLAGS_MONGOOSE += -DMG_ENABLE_BSD_PROTOTYPES=0
bsd_nortos_s390: ASAN=
bsd_nortos_s390: CC = $(DOCKER) mdashnet/s390 cc
bsd_nortos_s390: RUN = $(DOCKER) --init mdashnet/s390
bsd_nortos_s390: shm_port_bridge bsd_client bsd_nortos_test
bsd_nortos_s390: shm_port_bridge bsd_client bsd_udp bsd_nortos_test
$(RUN) sh -c './shm_port_bridge & pid=$$!; sleep 1; ./bsd_nortos_test; rc=$$?; kill $$pid >/dev/null 2>&1; wait $$pid >/dev/null 2>&1; exit $$rc'
shm_port_bridge: shm_port_bridge.c shm_queue.h
$(CC) shm_port_bridge.c $(CFLAGS) -pthread -o $@
clean: # Cleanup. Delete built program and all build artifacts
rm -rf bsd_test bsd_client shm_port_bridge *.o *.obj FreeRTOS-Kernel
rm -rf bsd_test bsd_client bsd_udp shm_port_bridge *.o *.obj FreeRTOS-Kernel
FreeRTOS-Kernel: # FreeRTOS sources
git clone -q -c advice.detachedHead=false --depth 1 -b V11.2.0 https://github.com/FreeRTOS/FreeRTOS-Kernel $@
+60
View File
@@ -0,0 +1,60 @@
#include <arpa/inet.h>
#include <stdio.h>
#include <string.h>
#include <sys/socket.h>
#include <sys/time.h>
#include <unistd.h>
#define PORT 1235
int main(int argc, char *argv[]) {
struct sockaddr_in sa;
struct timeval timeout;
char buf[8];
ssize_t n;
int fd, rogue;
if (argc != 2) return 1;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(PORT);
if (inet_pton(AF_INET, argv[1], &sa.sin_addr) != 1) return 1;
timeout.tv_sec = 5, timeout.tv_usec = 0;
if ((fd = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ||
setsockopt(fd, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) != 0 ||
connect(fd, (struct sockaddr *) &sa, sizeof(sa)) != 0 ||
send(fd, "hello", 5, 0) != 5 || recv(fd, buf, sizeof(buf), 0) != 5 ||
memcmp(buf, "ready", 5) != 0)
goto fail;
if ((rogue = socket(AF_INET, SOCK_DGRAM, 0)) < 0 ||
setsockopt(rogue, SOL_SOCKET, SO_RCVTIMEO, &timeout, sizeof(timeout)) !=
0 ||
sendto(rogue, "rogueid", 7, 0, (struct sockaddr *) &sa, sizeof(sa)) !=
7 ||
recv(fd, buf, sizeof(buf), 0) != 7 || memcmp(buf, "peerone", 7) != 0 ||
recv(rogue, buf, sizeof(buf), 0) != 7 || memcmp(buf, "rogueok", 7) != 0 ||
send(fd, "one", 3, 0) != 3 ||
sendto(rogue, "two2", 4, 0, (struct sockaddr *) &sa, sizeof(sa)) != 4 ||
recv(fd, buf, sizeof(buf), 0) != 4 || memcmp(buf, "drop", 4) != 0 ||
send(fd, "truncate", 8, 0) != 8 ||
recv(fd, buf, sizeof(buf), 0) != 5 || memcmp(buf, "short", 5) != 0 ||
send(fd, "peek", 4, 0) != 4 ||
recv(fd, buf, sizeof(buf), 0) != 4 || memcmp(buf, "peek", 4) != 0 ||
sendto(rogue, "rogue", 5, 0, (struct sockaddr *) &sa, sizeof(sa)) != 5 ||
send(fd, "more", 4, 0) != 4 ||
recv(fd, buf, sizeof(buf), 0) != 7 || memcmp(buf, "checked", 7) != 0 ||
recv(fd, buf, sizeof(buf), 0) != 3 || memcmp(buf, "one", 3) != 0 ||
recv(fd, buf, sizeof(buf), 0) != 4 || memcmp(buf, "two2", 4) != 0 ||
send(fd, "echo", 4, 0) != 4 || recv(fd, buf, sizeof(buf), 0) != 4 ||
memcmp(buf, "echo", 4) != 0)
goto fail_close_rogue;
close(rogue);
close(fd);
return 0;
fail_close_rogue:
close(rogue);
fail:
close(fd);
return 1;
}
+253 -2
View File
@@ -33,6 +33,198 @@ static int s_abort = 0;
#define DASHBOARD(x) \
printf("HEALTH_DASHBOARD\t\"%s\": %s,\n", x, s_error ? "false" : "true")
#define UDP_PORT 1235
#if MG_ENABLE_FREERTOS
static volatile bool s_tx_held, s_tx_waits;
#endif
static int open_udp(void) {
struct sockaddr_in sa;
char buf;
int fd;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(UDP_PORT);
sa.sin_addr.s_addr = INADDR_ANY;
ASSERT((fd = socket(AF_INET, SOCK_DGRAM, 0)) >= 0);
ASSERT(bind(fd, (struct sockaddr *) &sa, sizeof(sa)) == 0);
ASSERT(send(fd, &buf, sizeof(buf), 0) < 0 && errno == EDESTADDRREQ);
ASSERT(fcntl(fd, F_SETFL, O_NONBLOCK) == 0);
return fd;
}
static void check_udp_oversize(struct mg_mgr *mgr, int fd,
const struct sockaddr *dst, socklen_t dstlen) {
static char buf[1600];
size_t len = mgr->ifp->mtu + 1;
ASSERT(len <= sizeof(buf));
if (dst == NULL) {
ASSERT(send(fd, buf, len, 0) < 0 && errno == EMSGSIZE);
} else {
ASSERT(sendto(fd, buf, len, 0, dst, dstlen) < 0 && errno == EMSGSIZE);
}
}
static void udp_exchange(struct mg_mgr *mgr, int fd,
void (*progress)(struct mg_mgr *)) {
struct sockaddr_in peer, sender;
socklen_t peerlen, senderlen;
uint64_t deadline;
struct timeval zero = {0, 0};
struct pollfd p;
fd_set r, w, e;
char buf[8];
ssize_t n;
for (;;) {
peerlen = sizeof(peer);
n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *) &peer, &peerlen);
if (n >= 0) break;
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 5 && memcmp(buf, "hello", 5) == 0);
ASSERT(sendto(fd, "ready", 5, 0, (struct sockaddr *) &peer, peerlen) ==
5);
check_udp_oversize(mgr, fd, (struct sockaddr *) &peer, peerlen);
do {
senderlen = sizeof(sender);
n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *) &sender,
&senderlen);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 7 && memcmp(buf, "rogueid", 7) == 0 &&
sender.sin_port != peer.sin_port);
#if MG_ENABLE_FREERTOS
s_tx_waits = false, s_tx_held = true;
#endif
ASSERT(sendto(fd, "peerone", 7, 0, (struct sockaddr *) &peer, peerlen) ==
7);
ASSERT(sendto(fd, "rogueok", 7, 0, (struct sockaddr *) &sender,
senderlen) < 0 && errno == EAGAIN);
#if MG_ENABLE_FREERTOS
while (!s_tx_waits) progress(mgr); // Keep peerone in the UDP slot
s_tx_held = false;
#endif
while ((n = sendto(fd, "rogueok", 7, 0, (struct sockaddr *) &sender,
senderlen)) < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 7);
deadline = mg_millis() + 100;
while (mg_millis() < deadline) progress(mgr); // Queue both; drop the second
do {
senderlen = sizeof(sender);
n = recvfrom(fd, buf, sizeof(buf), 0, (struct sockaddr *) &sender,
&senderlen);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 3 && memcmp(buf, "one", 3) == 0 &&
sender.sin_port == peer.sin_port);
ASSERT(recvfrom(fd, buf, sizeof(buf), MSG_DONTWAIT, NULL, NULL) < 0 &&
errno == EAGAIN);
ASSERT(connect(fd, (struct sockaddr *) &peer, peerlen) == 0);
senderlen = sizeof(sender);
ASSERT(getsockname(fd, (struct sockaddr *) &sender, &senderlen) == 0 &&
sender.sin_port == htons(UDP_PORT));
ASSERT(sendto(fd, "no", 2, 0, (struct sockaddr *) &peer, peerlen) < 0 &&
errno == EISCONN);
check_udp_oversize(mgr, fd, NULL, 0);
ASSERT(send(fd, "drop", 4, 0) == 4);
do {
n = recv(fd, buf, 3, 0);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 3 && memcmp(buf, "tru", 3) == 0);
ASSERT(recv(fd, buf, sizeof(buf), MSG_DONTWAIT) < 0 && errno == EAGAIN);
ASSERT(send(fd, "short", 5, 0) == 5);
do {
n = recv(fd, buf, sizeof(buf), MSG_PEEK);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 4 && memcmp(buf, "peek", 4) == 0);
ASSERT(recv(fd, buf, sizeof(buf), 0) == 4 && memcmp(buf, "peek", 4) == 0);
ASSERT(send(fd, "peek", 4, 0) == 4);
deadline = mg_millis() + 100;
while (mg_millis() < deadline) progress(mgr); // Let rogue arrive; ignore it
do {
p.fd = fd, p.events = POLLIN | POLLOUT, p.revents = 0;
ASSERT(poll(&p, 1, 0) == 1);
if (!(p.revents & POLLIN)) progress(mgr);
} while (!(p.revents & POLLIN));
ASSERT(p.revents == (POLLIN | POLLOUT));
FD_ZERO(&r);
FD_ZERO(&w);
FD_ZERO(&e);
FD_SET(fd, &r);
FD_SET(fd, &w);
FD_SET(fd, &e);
ASSERT(select(fd + 1, &r, &w, &e, &zero) == 1);
ASSERT(FD_ISSET(fd, &r) && FD_ISSET(fd, &w) && !FD_ISSET(fd, &e));
do {
n = recv(fd, buf, sizeof(buf), 0);
if (n < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
} while (n < 0);
ASSERT(n == 4 && memcmp(buf, "more", 4) == 0);
p.events = POLLIN | POLLOUT, p.revents = 0;
ASSERT(poll(&p, 1, 0) == 1 && p.revents == POLLOUT);
while ((n = send(fd, "checked", 7, 0)) < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 7);
while ((n = send(fd, "one", 3, MSG_DONTWAIT)) < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 3);
p.fd = fd, p.events = POLLOUT, p.revents = 0;
ASSERT(poll(&p, 1, 0) == 0 && p.revents == 0);
#if MG_ENABLE_FREERTOS
s_tx_waits = false, s_tx_held = true;
#endif
ASSERT(send(fd, "two2", 4, MSG_DONTWAIT) < 0 && errno == EAGAIN);
ASSERT(send(fd, "", 0, 0) == 0);
#if MG_ENABLE_FREERTOS
while (!s_tx_waits) progress(mgr); // MG_IO_WAIT keeps one datagram queued
s_tx_held = false;
#endif
while ((n = send(fd, "two2", 4, MSG_DONTWAIT)) < 0) {
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 4);
for (;;) {
n = recv(fd, buf, sizeof(buf), 0);
if (n >= 0) break;
ASSERT(errno == EAGAIN);
progress(mgr);
}
ASSERT(n == 4 && memcmp(buf, "echo", 4) == 0);
ASSERT(send(fd, "echo", 4, 0) == 4);
progress(mgr); // Drain the last queued datagram before close
ASSERT(close(fd) == 0);
}
static pid_t start_client(const char *ip, const char *connections) {
char *cmd[4];
pid_t pid;
@@ -46,6 +238,18 @@ static pid_t start_client(const char *ip, const char *connections) {
return pid;
}
static pid_t start_udp(const char *ip) {
char *cmd[3];
pid_t pid;
extern char **environ;
cmd[0] = (char *) "./bsd_udp";
cmd[1] = (char *) ip;
cmd[2] = NULL;
ASSERT(posix_spawn(&pid, cmd[0], NULL, NULL, cmd, environ) == 0);
return pid;
}
static bool client_done(pid_t pid, int *status) {
pid_t r = waitpid(pid, status, WNOHANG);
ASSERT(r >= 0);
@@ -60,12 +264,17 @@ static void check_client(int status) {
static int open_listener(int backlog, bool nonblock) {
int lfd = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in sa;
char buf;
memset(&sa, 0, sizeof(sa));
sa.sin_family = AF_INET;
sa.sin_port = htons(1234);
sa.sin_addr.s_addr = INADDR_ANY;
ASSERT(lfd >= 0);
ASSERT(sendto(lfd, &buf, sizeof(buf), 0, (struct sockaddr *) &sa,
sizeof(sa)) < 0 && errno == EOPNOTSUPP);
ASSERT(recvfrom(lfd, &buf, sizeof(buf), 0, NULL, NULL) < 0 &&
errno == EOPNOTSUPP);
ASSERT(bind(lfd, (struct sockaddr *) &sa, sizeof(sa)) == 0);
ASSERT(listen(lfd, backlog) == 0);
if (nonblock) ASSERT(fcntl(lfd, F_SETFL, O_NONBLOCK) == 0);
@@ -146,12 +355,13 @@ static volatile bool s_select_waiting, s_select_done;
static volatile bool s_poll_waiting, s_poll_done;
static volatile bool s_ready_waiting, s_ready_done;
static volatile bool s_backlog_ready, s_backlog_full, s_backlog_accept;
static volatile bool s_tx_held, s_tx_waits, s_tx_fail, s_tx_error;
static volatile bool s_tx_fail, s_tx_error;
static volatile bool s_send_waiting;
static volatile bool s_send_done, s_send_expect_error, s_send_expect_shutdown;
static volatile bool s_recv_start, s_recv_waiting, s_recv_done;
static volatile bool s_recv_expect_error;
static volatile bool s_shutdown_waiting, s_shutdown_done;
static volatile bool s_udp_ready, s_udp_done;
static size_t (*s_tx)(const void *, size_t, struct mg_tcpip_if *);
struct client_data {
@@ -170,6 +380,7 @@ static void readiness_task(void *args);
static void backlog_task(void *args);
static void tx_gate_task(void *args);
static void shutdown_task(void *args);
static void udp_task(void *args);
struct atask_args {
bool listener_nonblock;
@@ -329,6 +540,21 @@ static void tx_gate_task(void *args) {
(void) args;
}
static void udp_delay(struct mg_mgr *mgr) {
(void) mgr;
vTaskDelay(1);
}
static void udp_task(void *args) {
struct mg_mgr *mgr = (struct mg_mgr *) args;
int fd = open_udp();
s_udp_ready = true;
udp_exchange(mgr, fd, udp_delay);
s_udp_done = true;
vTaskDelete(NULL);
}
static void recv_wait_task(void *args) {
char buf;
int fd = (int) (uintptr_t) args;
@@ -599,12 +825,22 @@ static void task2(void *args) {
struct mg_mgr *mgr = (struct mg_mgr *)args; // Event manager
char *ip;
int status;
pid_t first, second;
pid_t first, second, udp;
vTaskDelay(pdMS_TO_TICKS(500)); // 500 ms
s_error = false;
s_wait = false;
ip = mg_mprintf("%M", mg_print_ip4, &mgr->ifp->ip);
s_udp_ready = s_udp_done = false;
ASSERT(xTaskCreate(udp_task, "udp", 512, mgr, configMAX_PRIORITIES - 1,
NULL) == pdPASS);
while (!s_udp_ready) vTaskDelay(1);
udp = start_udp(ip);
while (!client_done(udp, &status)) vTaskDelay(1);
check_client(status);
while (!s_udp_done) vTaskDelay(1);
DASHBOARD("udp");
s_poll_waiting = s_poll_done = false;
ASSERT(xTaskCreate(poll_task, "poll", 512, NULL,
configMAX_PRIORITIES - 1, NULL) == pdPASS);
@@ -963,6 +1199,20 @@ static void nortos_echo(struct mg_mgr *mgr, struct nortos_echo_client *clients,
nortos_wait_client(mgr, pid);
}
static void udp_poll(struct mg_mgr *mgr) {
mg_mgr_poll(mgr, 0);
}
static void nortos_udp(struct mg_mgr *mgr, const char *ip) {
pid_t pid;
int fd = open_udp();
pid = start_udp(ip);
udp_exchange(mgr, fd, udp_poll);
nortos_wait_client(mgr, pid);
DASHBOARD("nortos_udp");
}
static void nortos_test(struct mg_mgr *mgr) {
static const char bootstrap = '\0';
static const char grow[512] = {0};
@@ -1083,6 +1333,7 @@ static void nortos_test(struct mg_mgr *mgr) {
ASSERT(close(fd) == 0);
mg_mgr_poll(mgr, 0);
DASHBOARD("nortos_nonblocking_connect");
nortos_udp(mgr, ip);
mg_free(ip);
}
+1 -1
View File
@@ -1,6 +1,6 @@
PROJECTS ?= $(wildcard ../../tutorials/pico-sdk/*-picosdk-*)
SDK_PATH ?= $(realpath $(PWD))/pico-sdk
SDK_VERSION ?= 2.1.0
SDK_VERSION ?= 2.2.0
all: $(PROJECTS)
echo
+1
View File
@@ -1519,6 +1519,7 @@ static void test_http_404(void) {
ASSERT(fetch(&mgr, buf, url, "GET /a.txt HTTP/1.0\n\n") == 200);
ASSERT(cmpbody(buf, "hello\n") == 0);
ASSERT(fetch(&mgr, buf, url, "GET /a.txt%%00x HTTP/1.0\n\n") == 400);
ASSERT(fetch(&mgr, buf, url, "GET /a/a.txt HTTP/1.0\n\n") == 200);
ASSERT(cmpbody(buf, "hello\n") == 0);
ASSERT(fetch(&mgr, buf, url, "GET /unmapped HTTP/1.0\n\n") == 400);
@@ -110,6 +110,11 @@
setupAutoLogout();
document.body.style.visibility = 'visible';
refreshFiles();
// Static graph is not pushed by the device, so load it once here
Dashboard.call('get', 'graph1').then(r => {
mkGraph(graphs.graph1);
updateGraph1(r?.data);
});
});
Dashboard.login().catch(err => showLogin(true));
+2 -2
View File
@@ -32,7 +32,7 @@ dashboard.hex: build
esputil mkhex \
0x8000 build/partition_table/partition-table.bin \
0x1000 build/bootloader/bootloader.bin \
0x100000 build/mongoose-esp32-example.bin > $@
0x20000 build/mongoose-esp32-example.bin > $@
flash2: dashboard.hex
esputil -p $(PORT) -b 921600 -fp 0x220 flash dashboard.hex
@@ -41,7 +41,7 @@ flash2: dashboard.hex
ESPTOOL ?= esptool.py
flash3:
cd build && $(ESPTOOL) --chip esp32 -p $(PORT) -b 460800 --before=default_reset --after=hard_reset write_flash --flash_mode dio --flash_freq 40m --flash_size 2MB 0x8000 partition_table/partition-table.bin 0x1000 bootloader/bootloader.bin 0x100000 mongoose-esp32-example.bin
cd build && $(ESPTOOL) --chip esp32 -p $(PORT) -b 460800 --before=default_reset --after=hard_reset write_flash --flash_mode dio --flash_freq 40m --flash_size 4MB 0x8000 partition_table/partition-table.bin 0x1000 bootloader/bootloader.bin 0x20000 mongoose-esp32-example.bin
clean:
test -d build && $(DOCKER) rm -rf build sdkconfig || true
@@ -2,5 +2,5 @@
nvs, data, nvs, , 0x6000
otadata, data, ota, , 0x2000,
phy_init, data, phy, , 0x1000,
ota_0, app, ota_0, , 948K,
ota_1, app, ota_1, , 948K,
ota_0, app, ota_0, , 1536K,
ota_1, app, ota_1, , 1536K,
1 # Name, Type, SubType, Offset, Size, Flags
2 nvs, data, nvs, , 0x6000
3 otadata, data, ota, , 0x2000,
4 phy_init, data, phy, , 0x1000,
5 ota_0, app, ota_0, , 948K, ota_0, app, ota_0, , 1536K,
6 ota_1, app, ota_1, , 948K, ota_1, app, ota_1, , 1536K,
@@ -1,3 +1,5 @@
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
+1 -3
View File
@@ -17,6 +17,4 @@ flash:
cd build && esptool --chip $(ARCH) --baud 460800 --port $(PORT) write-flash @flash_args
clean:
test -d build && (rm -rf build sdkconfig || true)
.PHONY: build
test -d build && $(DOCKER) rm -rf build sdkconfig || true
@@ -1,4 +1,5 @@
#define MG_ARCH MG_ARCH_ESP32
#define MG_OTA MG_OTA_ESP32
// Crash reports and mem usage stats
// Make sure to add to sdkconfig.defaults the following:
+3 -1
View File
@@ -1,5 +1,7 @@
# Name, Type, SubType, Offset, Size, Flags
nvs, data, nvs, , 0x6000
otadata, data, ota, , 0x2000
phy_init, data, phy, , 0x1000
factory, app, factory, , 1200K
ota_0, app, ota_0, , 1536K
ota_1, app, ota_1, , 1536K
coredump, data, coredump,, 128K
1 # Name, Type, SubType, Offset, Size, Flags
2 nvs, data, nvs, , 0x6000
3 otadata, data, ota, , 0x2000
4 phy_init, data, phy, , 0x1000
5 factory, app, factory, , 1200K ota_0, app, ota_0, , 1536K
6 ota_1, app, ota_1, , 1536K
7 coredump, data, coredump,, 128K
@@ -1,3 +1,5 @@
CONFIG_ESPTOOLPY_FLASHSIZE_4MB=y
CONFIG_ESPTOOLPY_FLASHSIZE="4MB"
CONFIG_PARTITION_TABLE_CUSTOM=y
CONFIG_PARTITION_TABLE_CUSTOM_FILENAME="partitions.csv"
CONFIG_PARTITION_TABLE_FILENAME="partitions.csv"
+1 -1
View File
@@ -4,7 +4,7 @@ ROOTDIR = $(realpath $(CURDIR)/../../..)
PORT ?= /dev/ttyUSB0
DOCKER ?= docker run --rm $(DA) -v $(ROOTDIR):$(ROOTDIR) -w $(THISDIR) espressif/idf:v5.0.4
# Note that the esp32 port needs the extra .. for relative paths due to the location of its main CMakeLists.txt file
CMD ?= bash -c '$(MAKE) -C micropython/ports/esp32 submodules && $(MAKE) -C micropython/ports/esp32 USER_C_MODULES=../../../../../mongoose/micropython.cmake'
CMD ?= bash -c '$(MAKE) -C micropython/ports/esp32 submodules && $(MAKE) -C micropython/ports/esp32 USER_C_MODULES=../../../../mongoose/micropython.cmake'
all: example
@@ -0,0 +1,18 @@
# Create an INTERFACE library for our C module.
add_library(usermod_mongoose INTERFACE)
# Add our source files to the lib
target_sources(usermod_mongoose INTERFACE
${CMAKE_CURRENT_LIST_DIR}/../../mongoose/module.c
${CMAKE_CURRENT_LIST_DIR}/../../../../mongoose.c
${CMAKE_CURRENT_LIST_DIR}/main.c
)
# Add the current directory as an include directory.
target_include_directories(usermod_mongoose INTERFACE
${CMAKE_CURRENT_LIST_DIR}
${CMAKE_CURRENT_LIST_DIR}/../../../../
)
# Link our INTERFACE library to the usermod target.
target_link_libraries(usermod INTERFACE usermod_mongoose)
@@ -15,6 +15,7 @@ CFLAGS += -mcpu=cortex-m33+nodsp -mthumb -mfloat-abi=hard -mfpu=fpv5-sp-d16 $(CF
LDFLAGS ?= -Tlink.ld -nostdlib -nostartfiles --specs=nano.specs -lc -lgcc -Wl,--gc-sections
SOURCES = main.c hal.c startup.c flexspi.c flash_config.c $(MGDIR)/mongoose.c
SOURCES += $(MGDIR)/tutorials/mqtt/mqtt-client/mongoose_mqtt.c
SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_clock.c
SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_trng.c
SOURCES += cmsis_rw612/devices/RW612/drivers/fsl_reset.c
@@ -44,5 +45,8 @@ flash: firmware.bin
(echo 'loadfile firmware.elf'; echo 'reset'; echo 'exit';) | JLinkExe -device RW612 -if SWD -speed 4000 -autoconnect 1 -NoGui 1 -ExitOnError 1
# JRun --nogui --device RW612 --if SWD firmware.elf
erase:
(echo halt && echo exec EnableEraseAllFlashBanks && echo erase && echo exit) | JLinkExe -device RW612 -if SWD -speed 4000 -autoconnect 1 -NoGui 1 -ExitOnError 1
clean:
rm -rf firmware.* cmsis_* mongoose/mongoose.*
+2
View File
@@ -104,6 +104,7 @@ int main(void) {
// Start a minimal web server
struct mg_mgr mgr;
mg_mgr_init(&mgr);
mg_mqtt_init(&mgr);
mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL);
mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL);
@@ -113,6 +114,7 @@ int main(void) {
for (;;) {
mg_mgr_poll(&mgr, 0);
mg_mqtt_poll(&mgr);
blink_task();
}
@@ -9,10 +9,11 @@
#define MG_ENABLE_CUSTOM_RANDOM 1
#define MG_OTA MG_OTA_RW612
#define MG_TLS MG_TLS_BUILTIN
#define MQTT_CLIENT_ID "rw612" // For tutorials/mqtt/mqtt-client
#define MG_ENABLE_MDASH 0 // Set to 1 to enable https://mdash.net
#define MG_MDASH_KEY "..." // Edit, see https://mdash.net/docs/#mongoose-library
#define MG_FIRMWARE_VERSION "1.0.1"
#define MG_FIRMWARE_VERSION "rw612.1.0.1"
// #define MG_DRIVER_MDC_CR 51 // RMII MDC clock divider
// #define MG_DRIVER_MDC_HOLDTIME 3 // RMII MDC Holdtime (valid values [0-7])
+1 -1
View File
@@ -31,5 +31,5 @@ clean:
$(RM) build pico_sdk_import.cmake $(SDK_PATH)
$(SDK_PATH):
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.1.1 https://github.com/raspberrypi/pico-sdk $@
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.2.0 https://github.com/raspberrypi/pico-sdk $@
cd $@ && git submodule update --quiet --init
+1 -1
View File
@@ -31,5 +31,5 @@ clean:
$(RM) build pico_sdk_import.cmake $(SDK_PATH)
$(SDK_PATH):
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.1.1 https://github.com/raspberrypi/pico-sdk $@
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.2.0 https://github.com/raspberrypi/pico-sdk $@
cd $@ && git submodule update --quiet --init
+1 -1
View File
@@ -19,7 +19,7 @@ net.h: ../../mqtt/mqtt-dashboard/device/net.h
cp $< $@
pico-sdk:
git clone --depth 1 -b 2.1.0 https://github.com/raspberrypi/pico-sdk $@
git clone --depth 1 -b 2.2.0 https://github.com/raspberrypi/pico-sdk $@
cd $@ && git submodule update --init
clean:
+1 -1
View File
@@ -31,5 +31,5 @@ clean:
$(RM) build pico_sdk_import.cmake $(SDK_PATH)
$(SDK_PATH):
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.1.1 https://github.com/raspberrypi/pico-sdk $@
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.2.0 https://github.com/raspberrypi/pico-sdk $@
cd $@ && git submodule update --quiet --init
+1 -1
View File
@@ -7,7 +7,7 @@ include(pico_sdk_import.cmake)
project(firmware)
pico_sdk_init()
add_executable(firmware main.c wifi.c ../../../mongoose.c)
add_executable(firmware main.c wifi.c ../../../mongoose.c ../../mqtt/mqtt-client/mongoose_mqtt.c)
target_include_directories(firmware PRIVATE ../../.. ./)
target_link_libraries(firmware pico_stdlib hardware_spi pico_rand pico_cyw43_driver pico_cyw43_arch_none hardware_flash pico_bootrom)
+2
View File
@@ -65,11 +65,13 @@ static void run_mongoose(void) {
struct mg_mgr mgr;
mg_log_set_fn(log_fn, NULL);
mg_mgr_init(&mgr);
mg_mqtt_init(&mgr);
mg_http_listen(&mgr, "http://0.0.0.0", http_ev_handler, NULL);
mg_http_listen(&mgr, "https://0.0.0.0", http_ev_handler, NULL);
for (;;) {
mg_mgr_poll(&mgr, 1);
mg_mqtt_poll(&mgr);
blink_task();
}
}
+1
View File
@@ -5,6 +5,7 @@
#define MG_TLS MG_TLS_BUILTIN
#define MG_OTA MG_OTA_PICOSDK
#define MG_IO_SIZE 2048
#define MQTT_CLIENT_ID "rp" // For tutorials/mqtt/mqtt-client
#define MG_ENABLE_TCPIP 1
#define MG_ENABLE_DRIVER_PICO_W 1
+1 -1
View File
@@ -31,7 +31,7 @@ clean:
$(RM) build pico_sdk_import.cmake $(SDK_PATH)
$(SDK_PATH):
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.1.1 https://github.com/raspberrypi/pico-sdk $@
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.2.0 https://github.com/raspberrypi/pico-sdk $@
cd $@ && git submodule update --quiet --init
# Automated remote test. Requires env variable VCON_API_KEY set. See https://vcon.io/automated-firmware-tests/
+1 -1
View File
@@ -31,7 +31,7 @@ clean:
$(RM) build pico_sdk_import.cmake $(SDK_PATH)
$(SDK_PATH):
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.1.1 https://github.com/raspberrypi/pico-sdk $@
git clone -c advice.detachedHead=false --quiet --depth 1 -b 2.2.0 https://github.com/raspberrypi/pico-sdk $@
cd $@ && git submodule update --quiet --init
# Automated remote test. Requires env variable VCON_API_KEY set. See https://vcon.io/automated-firmware-tests/
+6 -27
View File
@@ -1,31 +1,10 @@
# Nucleo-H563ZI Mongoose Integration
# Mongoose CubeMX pack
This guide explains how to bring up a production-grade Web UI dashboard on the
STM32 Nucleo-H563ZI development board.
This pack provides an easy to use CubeMX integration.
A pre-configured, ready-to-run project zip is available for download at
https://mongoose.ws.
## Mongoose Networking Core
To integrate the Web UI dashboard into an existing CubeMX project, or to create a
new project from scratch:
This module installs Mongoose Library itself: `mogoose.c`, `mongoose.h` and
`mongoose_config.h`. To finish integration, follow this guide:
1. Configure the peripherals (described below).
2. Regenerate your project code and integrate Mongoose core by following
https://mongoose.ws/docs/guides/stm32-tcpip-stack/.
3. Add the Web UI dashboard by following
https://mongoose.ws/docs/guides/web-dashboard-guide/.
## Configure peripherals
An `.ioc` file is included in this directory for your reference. It was created
using the following steps:
- Open CubeMX. If you are starting a new project, select the STM32H563ZI
microcontroller and create a new project.
- In Pinout & Configuration / Security, enable RNG and select "Activated".
- In Clock Configuration, set the maximum clock frequency to 250 MHz.
- In the MCU pinout view, set pins PB0, PF4, and PG4 to GPIO_Output mode.
- In Pinout & Configuration / Connectivity, enable USART3 in asynchronous mode.
Configure pins PD8 and PD9 for USART.
- In Pinout & Configuration / Connectivity, enable ETH in RMII mode and set pins
PA1, PA2, PA7, PC1, PC4, PC5, PB15, PG11, and PG13 for Ethernet.
https://mongoose.ws/docs/guides/stm32-tcpip-stack/#configure-peripherals
@@ -259,6 +259,7 @@ void mg_dash_init(struct mg_mgr *mgr) {
// Read settings from flash
struct mg_dash_user u = {.level = 9}; // Super mega user
settings_fn(MG_DASH_READ, &u);
s_dash.authenticate = s_enable_login ? authenticate : NULL;
mg_mem_files = mg_packed_files;
mg_http_listen(mgr, MG_HTTP_ADDR, mg_dash_ev_handler, &s_dash);
@@ -110,6 +110,11 @@
setupAutoLogout();
document.body.style.visibility = 'visible';
refreshFiles();
// Static graph is not pushed by the device, so load it once here
Dashboard.call('get', 'graph1').then(r => {
mkGraph(graphs.graph1);
updateGraph1(r?.data);
});
});
Dashboard.login().catch(err => showLogin(true));
@@ -778,18 +783,18 @@ a, a:visited, a:link { text-decoration: none; }
</div>
<div class="note">
<p>This file manager uses /fs/ directory.
<p>This file manager uses /tmp/dashboard/ directory.
It works on any platform that supports
standard file IO: fopen, fread, fwrite, fclose.
This includes Linux/Mac/Windows.</p>
<p>
Mongoose provides a built-in LittleFS integration that
makes standard file IO work on embedded systems like STM32.
makes stadard file IO work on embedded systems like STM32.
For that, add "#define MG_ENABLE_LFS 1" to your
mongoose_config.h
</p>
<p>See
<a href="https://github.com/cesanta/mongoose/tree/master/tutorials/stm32/nucleo-h563zi/cubemx">this ready-to-build example</a>
<a href="https://github.com/cesanta/embedded-web-file-manager">this ready-to-build example</a>
which implements LittleFS on Nucleo-H563ZI internal flash. You
can upload, delete and serve files on STM32 - which is
a perfect use case for confuration files, keeping and viewing logs, etc.
@@ -6,7 +6,6 @@
#include "mongoose.h"
#include <stdio.h>
#include <stdlib.h>
struct echo_server {
@@ -43,12 +42,12 @@ int echo_init(uint16_t port) {
if (fd < 0 || !echo_nonblock(fd) ||
bind(fd, (struct sockaddr *) &sa, sizeof(sa)) < 0 || listen(fd, 3) < 0) {
printf("BSD echo init: %d\n", errno);
MG_ERROR(("BSD echo init: %d", errno));
if (fd >= 0) close(fd);
return 0;
}
s_server.sock = fd;
printf("BSD echo server on port %hu\n", port);
MG_INFO(("BSD echo server on port %hu", port));
return 1;
}
@@ -80,7 +79,7 @@ void echo_poll(void) {
if (fd >= 0) {
c = (struct echo_client *) calloc(1, sizeof(*c));
if (c == NULL || !echo_nonblock(fd)) {
printf("BSD echo accept: %d\n", c == NULL ? ENOMEM : errno);
MG_ERROR(("BSD echo accept: %d", c == NULL ? ENOMEM : errno));
close(fd);
free(c);
} else {