feat: browser simulator served by the controller, desktop build, browser bridge
- led-simulator: the rig runs the C++ led-driver as WebAssembly (sim-driver/), one single-threaded worker per bar, no cross-origin isolation needed. Rooms (one JSON per room) with an on-page editor, and a pattern gallery. The Python server, Pyodide boot and ring buffer are removed. - sim-controller sim_rig.c: serves /sim/ from an embedded pack, the page's WebSocket and the rooms/flash API. The desktop build embeds it too. - bridge.c: a "browser" bridge kind that carries ESP-NOW frames to the page; devices announced through it are marked sim. - UI: Simulator in the Menu, split view with resize and pop-out, swipe between controller and rig on phones; SIM/REAL badges in Devices. - Fades: preset pushes and Wi-Fi driver bodies always carry fade and beat_time, so "off" no longer inherits an earlier fade. - Also the sequences-v2 work in progress: desktop port, bridge firmware, serial bridge, Wi-Fi drivers, sequence timeline, audio and API changes. - led-driver: ESP-NOW link, beat sync, control messages, sim hooks. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
698c1463c0
commit
581b751904
506 files changed
+42336
-3599
No files matched your search
@@ -0,0 +1,129 @@
|
||||
# led-controller for the desktop: the firmware's sources built with a plain C compiler, no ESP-IDF.
|
||||
# Build from the repository root with `make desktop`, or here:
|
||||
# cmake -S desktop -B build-desktop && cmake --build build-desktop
|
||||
# Needs www_dist/www.pack (tools/build_web.sh). Third-party code is vendored: desktop/tools/vendor.sh.
|
||||
cmake_minimum_required(VERSION 3.16)
|
||||
project(led_controller_desktop VERSION 0.1.0 LANGUAGES C)
|
||||
|
||||
set(CMAKE_C_STANDARD 11)
|
||||
set(CMAKE_C_STANDARD_REQUIRED ON)
|
||||
set(CMAKE_C_EXTENSIONS ON)
|
||||
find_package(Threads REQUIRED)
|
||||
|
||||
set(ROOT ${CMAKE_CURRENT_SOURCE_DIR}/..)
|
||||
set(WWW_PACK ${ROOT}/www_dist/www.pack)
|
||||
if(NOT EXISTS ${WWW_PACK})
|
||||
message(FATAL_ERROR "www_dist/www.pack is missing: run tools/build_web.sh (make web)")
|
||||
endif()
|
||||
# The simulated rig at /sim/ (tools/build_sim_web.sh). Optional: an empty pack when it is not built.
|
||||
set(SIM_PACK ${ROOT}/www_dist/sim.pack)
|
||||
if(NOT EXISTS ${SIM_PACK})
|
||||
file(WRITE ${SIM_PACK} "WWW1")
|
||||
endif()
|
||||
|
||||
execute_process(COMMAND git -C ${ROOT} describe --tags --always --dirty
|
||||
OUTPUT_VARIABLE LED_VERSION OUTPUT_STRIP_TRAILING_WHITESPACE ERROR_QUIET)
|
||||
if(NOT LED_VERSION)
|
||||
set(LED_VERSION "desktop")
|
||||
endif()
|
||||
|
||||
# The firmware's app sources (the same list as main/CMakeLists.txt's linux branch, plus the bridge transport)
|
||||
set(MAIN_SRC
|
||||
beat.c beat_dsp.c espnow_tx.c bridge.c store.c api.c web.c envelope.c engine.c rel.c bench.c audio.c
|
||||
res_profile.c res_misc.c res_device.c res_group.c seqplay.c res_bundle.c audio_api.c patterns.c outputs.c
|
||||
ws.c ws_client.c wifi_drv.c bridge_serial.c)
|
||||
list(TRANSFORM MAIN_SRC PREPEND ${ROOT}/main/)
|
||||
|
||||
# The host stand-ins for the board's hardware (mic, OTA, littlefs, timers) and the app_main that starts it
|
||||
set(SIM_SRC sim_main.c sim_stubs.c sim_timer.c sim_rig.c)
|
||||
list(TRANSFORM SIM_SRC PREPEND ${ROOT}/sim-controller/components/sim/)
|
||||
|
||||
set(THIRD_PARTY
|
||||
third_party/esp_http_server/src/httpd_main.c
|
||||
third_party/esp_http_server/src/httpd_parse.c
|
||||
third_party/esp_http_server/src/httpd_sess.c
|
||||
third_party/esp_http_server/src/httpd_txrx.c
|
||||
third_party/esp_http_server/src/httpd_uri.c
|
||||
third_party/esp_http_server/src/httpd_ws.c
|
||||
third_party/esp_http_server/src/util/ctrl_sock.c
|
||||
third_party/http_parser/http_parser.c
|
||||
third_party/cjson/cJSON.c)
|
||||
|
||||
set(PORT
|
||||
port/src/freertos.c
|
||||
port/src/esp_glue.c
|
||||
port/src/desktop_crypto.c
|
||||
port/src/www_pack.c
|
||||
port/src/sim_pack.c
|
||||
port/src/mdns_host.c
|
||||
port/src/mic_alsa.c)
|
||||
|
||||
add_executable(led-controller desktop_main.c ${MAIN_SRC} ${SIM_SRC} ${THIRD_PARTY} ${PORT})
|
||||
# www_pack.c embeds the pack with .incbin, which CMake can't see: rebuild it when the pack changes
|
||||
set_source_files_properties(port/src/www_pack.c PROPERTIES OBJECT_DEPENDS ${WWW_PACK})
|
||||
set_source_files_properties(port/src/sim_pack.c PROPERTIES OBJECT_DEPENDS ${SIM_PACK})
|
||||
target_include_directories(led-controller PRIVATE
|
||||
port/include
|
||||
${ROOT}/main
|
||||
${ROOT}/bridge/main
|
||||
${ROOT}/sim-controller/components/sim
|
||||
${ROOT}/sim-controller/components/sim/include
|
||||
third_party/esp_http_server/include
|
||||
third_party/esp_http_server/src
|
||||
third_party/esp_http_server/src/util
|
||||
third_party/http_parser
|
||||
third_party/cjson)
|
||||
target_compile_definitions(led-controller PRIVATE
|
||||
_GNU_SOURCE
|
||||
LED_DESKTOP_MDNS
|
||||
LED_DESKTOP_ALSA
|
||||
LED_APP_VERSION="${LED_VERSION}"
|
||||
WWW_PACK="${WWW_PACK}"
|
||||
SIM_PACK="${SIM_PACK}")
|
||||
# ESP-IDF force-includes the build's sdkconfig.h into every source; the desktop port has the same file
|
||||
target_compile_options(led-controller PRIVATE -include ${CMAKE_CURRENT_SOURCE_DIR}/port/include/sdkconfig.h
|
||||
-Wall -Wno-unused-function -Wno-unused-variable -Wno-unused-parameter)
|
||||
find_library(ASOUND_LIB asound REQUIRED) # ALSA capture for the microphone (libasound2-dev at build time)
|
||||
target_link_libraries(led-controller PRIVATE Threads::Threads m rt ${ASOUND_LIB})
|
||||
install(TARGETS led-controller RUNTIME DESTINATION bin)
|
||||
|
||||
# Headless install: a .deb with the program, a systemd service and its default settings (`make deb`).
|
||||
# The service runs as a dynamic user with its store in /var/lib/led-controller.
|
||||
set(CPACK_PACKAGING_INSTALL_PREFIX /usr)
|
||||
set(CMAKE_INSTALL_PREFIX /usr)
|
||||
install(FILES packaging/led-controller.service DESTINATION lib/systemd/system)
|
||||
install(FILES packaging/led-controller.default DESTINATION /etc/default RENAME led-controller)
|
||||
install(FILES packaging/led-bridge.udev.example DESTINATION share/doc/led-controller)
|
||||
install(FILES ${ROOT}/README.md DESTINATION share/doc/led-controller RENAME README.md OPTIONAL)
|
||||
install(FILES ${ROOT}/bridge/README.md DESTINATION share/doc/led-controller RENAME bridge-README.md OPTIONAL)
|
||||
|
||||
# The command-line tool (led-tool, a PyInstaller binary) and the LED driver firmware image (led-driver, built with
|
||||
# ESP-IDF v6.1). Both are bundled into the .deb when LED_BUNDLE_TOOLS is on (`make deb` turns it on).
|
||||
option(LED_BUNDLE_TOOLS "Install led-cli and the led-driver firmware image into the package" OFF)
|
||||
set(LED_CLI_BIN ${ROOT}/led-tool/dist/led-cli)
|
||||
set(LED_DRIVER_BIN ${ROOT}/led-driver/build-v61/led_driver.bin)
|
||||
if(LED_BUNDLE_TOOLS)
|
||||
if(NOT EXISTS ${LED_CLI_BIN})
|
||||
message(FATAL_ERROR "led-tool/dist/led-cli is missing: run make led-cli")
|
||||
endif()
|
||||
if(NOT EXISTS ${LED_DRIVER_BIN})
|
||||
message(FATAL_ERROR "led-driver/build-v61/led_driver.bin is missing: build the driver with the ESP-IDF v6.1 image")
|
||||
endif()
|
||||
install(PROGRAMS ${LED_CLI_BIN} DESTINATION bin)
|
||||
install(FILES ${LED_DRIVER_BIN} DESTINATION share/led-controller/firmware)
|
||||
endif()
|
||||
|
||||
set(CPACK_PACKAGE_NAME "led-controller")
|
||||
set(CPACK_PACKAGE_VERSION "${PROJECT_VERSION}")
|
||||
set(CPACK_PACKAGE_DESCRIPTION_SUMMARY "LED rig controller: web UI, presets, sequences and ESP-NOW to the LED drivers")
|
||||
set(CPACK_PACKAGE_CONTACT "led-controller packagers <packaging@localhost>")
|
||||
set(CPACK_GENERATOR "DEB")
|
||||
set(CPACK_DEBIAN_PACKAGE_SECTION "misc")
|
||||
set(CPACK_DEBIAN_PACKAGE_PRIORITY "optional")
|
||||
set(CPACK_DEBIAN_PACKAGE_SHLIBDEPS ON)
|
||||
set(CPACK_DEBIAN_FILE_NAME DEB-DEFAULT)
|
||||
set(CPACK_DEBIAN_PACKAGE_CONTROL_EXTRA ${CMAKE_CURRENT_SOURCE_DIR}/packaging/postinst
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/packaging/prerm
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/packaging/postrm
|
||||
${CMAKE_CURRENT_SOURCE_DIR}/packaging/conffiles)
|
||||
include(CPack)
|
||||
@@ -0,0 +1,69 @@
|
||||
# led-controller on a desktop
|
||||
|
||||
The controller firmware (`main/`) built as a program for Linux: no ESP-IDF, no Docker, no board. The web
|
||||
UI and API are the same as the board's. ESP-NOW goes through a bridge: the USB bridge board (`bridge/`)
|
||||
or a UDP bridge such as `led-simulator`.
|
||||
|
||||
## Build and run
|
||||
|
||||
Needs `cmake`, a C compiler, and `www_dist/www.pack` (`make web` builds it with `node`).
|
||||
|
||||
```bash
|
||||
make desktop # builds build-desktop/led-controller
|
||||
make desktop-run # the web UI on http://localhost:8080/
|
||||
make test-desktop # starts the program and runs the API tests against it
|
||||
```
|
||||
|
||||
Or run it directly:
|
||||
|
||||
```bash
|
||||
build-desktop/led-controller --db ./data --port 8080
|
||||
```
|
||||
|
||||
| option | environment | meaning |
|
||||
| --- | --- | --- |
|
||||
| `--db DIR` | `LED_CONTROLLER_DB` | the store (default `/db`) |
|
||||
| `--port N` | `LED_CONTROLLER_HTTP_PORT` | web UI and API port (default 8080) |
|
||||
|
||||
`LED_LOG_LEVEL=error|warn|info|debug|verbose` sets how much is logged (default `info`).
|
||||
|
||||
## Install as a service (.deb)
|
||||
|
||||
```bash
|
||||
make deb # build-desktop/led-controller_0.1.0_<arch>.deb
|
||||
sudo apt install ./build-desktop/led-controller_0.1.0_*.deb
|
||||
```
|
||||
|
||||
The package installs `/usr/bin/led-controller`, the `led-cli` command-line tool (`/usr/bin/led-cli`), the LED driver
|
||||
firmware image (`/usr/share/led-controller/firmware/led_driver.bin`), a systemd unit (`led-controller.service`) that runs it as a
|
||||
dynamic user with its store in `/var/lib/led-controller`, and `/etc/default/led-controller` for the port. The service starts at install and restarts after a restart from
|
||||
the web UI. The bridges are kept in the controller's settings, so set them in the web UI under Settings > Network >
|
||||
Bridges. Change the port in `/etc/default/led-controller`, then `sudo systemctl restart led-controller`. The bridge's serial port is
|
||||
owned by `dialout`, which the service joins.
|
||||
|
||||
`packaging/led-bridge.udev.example` (installed in `/usr/share/doc/led-controller/`) gives the bridge board a
|
||||
stable name, `/dev/led-bridge`, by its serial number.
|
||||
|
||||
## How it is built
|
||||
|
||||
`desktop/CMakeLists.txt` compiles the firmware's own sources (`main/`, and the host stand-ins in
|
||||
`sim-controller/components/sim/`: mic, OTA, littlefs and the timers) with a small port of the ESP-IDF APIs
|
||||
they use:
|
||||
|
||||
- `port/src/freertos.c`: tasks, queues, semaphores, stream buffers and event groups on POSIX threads.
|
||||
- `port/src/esp_glue.c`: logging, error names, random numbers, the MAC (from the first real network
|
||||
interface), restart (an exit, for the service manager), and the app description.
|
||||
- `port/src/desktop_crypto.c`: SHA-1 and base64 for the WebSocket handshake.
|
||||
- `port/src/www_pack.c`: the web UI pack (`www_dist/www.pack`) embedded in the program.
|
||||
- `port/include/`: the headers. `sdkconfig.h` is the config the sim's build generated.
|
||||
|
||||
Third-party code is vendored in `third_party/`: the HTTP server and `http_parser` from ESP-IDF v6.1, and cJSON.
|
||||
`tools/vendor.sh` refreshes them (it runs `espressif/idf:v6.1` to copy the httpd sources). Its patch
|
||||
(`tools/patch_vendor.py`) swaps the handshake's mbedTLS and PSA calls for `desktop_crypto.c`.
|
||||
|
||||
## Limits
|
||||
|
||||
- ESP-NOW needs the bridge. Without one the program runs, and its ESP-NOW frames go nowhere.
|
||||
- The Wi-Fi drivers are not discovered automatically: their mDNS discovery is not in the desktop build yet.
|
||||
- Firmware OTA is not available (the API answers 501, as in the simulator).
|
||||
- The mic is simulated: beats come from the BPM clock, as in the simulator.
|
||||
@@ -0,0 +1,56 @@
|
||||
/*
|
||||
* led-controller as a desktop program: the firmware's app_main (sim-controller/components/sim/sim_main.c)
|
||||
* with its settings from the command line or the environment. No ESP-IDF is needed to build or run it.
|
||||
*
|
||||
* led-controller [--db DIR] [--port N]
|
||||
*
|
||||
* The bridges (the USB bridge board, /dev/ttyACM1, or host:port over UDP such as led-simulator) are kept in
|
||||
* the store's settings: set them in the web UI under Settings > Network > Bridges. The environment works
|
||||
* too: LED_CONTROLLER_DB, LED_CONTROLLER_HTTP_PORT. Without a bridge the program runs, but its ESP-NOW frames
|
||||
* go nowhere.
|
||||
*/
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
void app_main(void);
|
||||
|
||||
static void set_from_env(const char *from, const char *to)
|
||||
{
|
||||
const char *v = getenv(from);
|
||||
if (v && v[0] && !(getenv(to) && getenv(to)[0])) {
|
||||
setenv(to, v, 1);
|
||||
}
|
||||
}
|
||||
|
||||
static void usage(FILE *out)
|
||||
{
|
||||
fprintf(out,
|
||||
"usage: led-controller [--db DIR] [--port N]\n"
|
||||
" --db DIR store directory (default /db)\n"
|
||||
" --port N web UI and API port (default 8080)\n"
|
||||
" bridges are set in the web UI (Settings > Network > Bridges)\n");
|
||||
}
|
||||
|
||||
int main(int argc, char **argv)
|
||||
{
|
||||
for (int i = 1; i < argc; i++) {
|
||||
const char *a = argv[i];
|
||||
if (!strcmp(a, "-h") || !strcmp(a, "--help")) {
|
||||
usage(stdout);
|
||||
return 0;
|
||||
}
|
||||
if ((!strcmp(a, "--db") || !strcmp(a, "--port")) && i + 1 < argc) {
|
||||
const char *val = argv[++i];
|
||||
setenv(!strcmp(a, "--db") ? "LED_SIM_DB" : "LED_SIM_HTTP_PORT", val, 1);
|
||||
continue;
|
||||
}
|
||||
fprintf(stderr, "led-controller: unknown option %s\n", a);
|
||||
usage(stderr);
|
||||
return 2;
|
||||
}
|
||||
set_from_env("LED_CONTROLLER_DB", "LED_SIM_DB");
|
||||
set_from_env("LED_CONTROLLER_HTTP_PORT", "LED_SIM_HTTP_PORT");
|
||||
app_main(); // runs until the process is stopped
|
||||
return 0;
|
||||
}
|
||||
@@ -0,0 +1 @@
|
||||
/etc/default/led-controller
|
||||
@@ -0,0 +1,4 @@
|
||||
# Optional: a stable name for the USB ESP-NOW bridge board, so its bridge in the web UI can be /dev/led-bridge.
|
||||
# Replace the serial with the board's (the MAC printed by `make bridge-build`'s HELLO, or `udevadm info -q property -n /dev/ttyACM1`).
|
||||
# Copy to /etc/udev/rules.d/99-led-bridge.rules, then: sudo udevadm control --reload && sudo udevadm trigger
|
||||
SUBSYSTEM=="tty", ATTRS{idVendor}=="303a", ATTRS{idProduct}=="1001", ATTRS{serial}=="7C:4F:AD:20:AF:58", SYMLINK+="led-bridge", GROUP="dialout", MODE="0660"
|
||||
@@ -0,0 +1,8 @@
|
||||
# led-controller settings, read by /lib/systemd/system/led-controller.service. Restart the service after a change:
|
||||
# sudo systemctl restart led-controller
|
||||
|
||||
# Web UI and API port
|
||||
LED_CONTROLLER_HTTP_PORT=8080
|
||||
|
||||
# The ESP-NOW bridges (the USB bridge board, or host:port of a UDP bridge such as led-simulator) are kept in
|
||||
# the controller's settings: set them in the web UI under Settings > Network > Bridges.
|
||||
@@ -0,0 +1,27 @@
|
||||
[Unit]
|
||||
Description=led-controller: LED rig controller and web UI
|
||||
Documentation=file:///usr/share/doc/led-controller/README.md
|
||||
After=network-online.target
|
||||
Wants=network-online.target
|
||||
|
||||
[Service]
|
||||
Type=simple
|
||||
# Settings from /etc/default/led-controller: LED_CONTROLLER_HTTP_PORT (the bridges are set in the web UI)
|
||||
EnvironmentFile=-/etc/default/led-controller
|
||||
ExecStart=/usr/bin/led-controller --db /var/lib/led-controller
|
||||
# A restart from the web UI exits the program (esp_restart), so always bring it back
|
||||
Restart=always
|
||||
RestartSec=2
|
||||
# The USB bridge board is a serial port, owned by the dialout group on Debian and Ubuntu
|
||||
SupplementaryGroups=dialout
|
||||
DynamicUser=yes
|
||||
StateDirectory=led-controller
|
||||
# Port 80 without root, when LED_CONTROLLER_HTTP_PORT=80
|
||||
AmbientCapabilities=CAP_NET_BIND_SERVICE
|
||||
NoNewPrivileges=yes
|
||||
ProtectSystem=strict
|
||||
ProtectHome=yes
|
||||
PrivateTmp=yes
|
||||
|
||||
[Install]
|
||||
WantedBy=multi-user.target
|
||||
Executable
+21
@@ -0,0 +1,21 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
case "$1" in
|
||||
configure)
|
||||
if [ -d /run/systemd/system ]; then
|
||||
systemctl daemon-reload >/dev/null 2>&1 || true
|
||||
fi
|
||||
if command -v deb-systemd-helper >/dev/null 2>&1; then
|
||||
deb-systemd-helper unmask led-controller.service >/dev/null || true
|
||||
deb-systemd-helper enable led-controller.service >/dev/null || true
|
||||
fi
|
||||
if command -v deb-systemd-invoke >/dev/null 2>&1; then
|
||||
if [ -n "$2" ]; then
|
||||
deb-systemd-invoke restart led-controller.service >/dev/null || true
|
||||
else
|
||||
deb-systemd-invoke start led-controller.service >/dev/null || true
|
||||
fi
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
Executable
+14
@@ -0,0 +1,14 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
case "$1" in
|
||||
purge)
|
||||
if command -v deb-systemd-helper >/dev/null 2>&1; then
|
||||
deb-systemd-helper purge led-controller.service >/dev/null || true
|
||||
deb-systemd-helper unmask led-controller.service >/dev/null || true
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
if [ -d /run/systemd/system ]; then
|
||||
systemctl daemon-reload >/dev/null 2>&1 || true
|
||||
fi
|
||||
exit 0
|
||||
Executable
+10
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -e
|
||||
case "$1" in
|
||||
remove|deconfigure|upgrade)
|
||||
if command -v deb-systemd-invoke >/dev/null 2>&1; then
|
||||
deb-systemd-invoke stop led-controller.service >/dev/null || true
|
||||
fi
|
||||
;;
|
||||
esac
|
||||
exit 0
|
||||
@@ -0,0 +1,9 @@
|
||||
/* SHA-1 and base64 for the WebSocket handshake (desktop/port/src/desktop_crypto.c) */
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
void desktop_sha1(const uint8_t *data, size_t len, uint8_t out[20]);
|
||||
// Writes the NUL-terminated base64 of in; returns the length without the NUL, 0 if out is too small
|
||||
size_t desktop_base64_encode(char *out, size_t cap, const uint8_t *in, size_t n);
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct {
|
||||
uint32_t magic_word;
|
||||
uint32_t secure_version;
|
||||
char version[32];
|
||||
char project_name[32];
|
||||
char time[16];
|
||||
char date[16];
|
||||
char idf_ver[32];
|
||||
uint8_t app_elf_sha256[32];
|
||||
} esp_app_desc_t;
|
||||
|
||||
const esp_app_desc_t *esp_app_get_description(void);
|
||||
@@ -0,0 +1,39 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdlib.h>
|
||||
#include "esp_err.h"
|
||||
#include "esp_log.h"
|
||||
|
||||
#define ESP_RETURN_ON_ERROR(x, tag, fmt, ...) \
|
||||
do { \
|
||||
esp_err_t err_rc_ = (x); \
|
||||
if (err_rc_ != ESP_OK) { \
|
||||
ESP_LOGE(tag, "%s(%d): " fmt, __func__, (int)err_rc_, ##__VA_ARGS__); \
|
||||
return err_rc_; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define ESP_RETURN_ON_FALSE(cond, err, tag, fmt, ...) \
|
||||
do { \
|
||||
if (!(cond)) { \
|
||||
ESP_LOGE(tag, "%s(%d): " fmt, __func__, (int)(err), ##__VA_ARGS__); \
|
||||
return (err); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define ESP_ERROR_CHECK(x) \
|
||||
do { \
|
||||
esp_err_t err_rc_ = (x); \
|
||||
if (err_rc_ != ESP_OK) { \
|
||||
ESP_LOGE("check", "%s:%d: %s", __FILE__, __LINE__, esp_err_to_name(err_rc_)); \
|
||||
abort(); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define ESP_ERROR_CHECK_WITHOUT_ABORT(x) \
|
||||
do { \
|
||||
esp_err_t err_rc_ = (x); \
|
||||
if (err_rc_ != ESP_OK) { \
|
||||
ESP_LOGE("check", "%s:%d: %s", __FILE__, __LINE__, esp_err_to_name(err_rc_)); \
|
||||
} \
|
||||
} while (0)
|
||||
@@ -0,0 +1,65 @@
|
||||
/* Desktop port: the ESP-IDF error codes the firmware uses (same values as ESP-IDF). */
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdlib.h>
|
||||
#include "esp_log.h"
|
||||
|
||||
typedef int32_t esp_err_t;
|
||||
|
||||
#define ESP_OK 0
|
||||
#define ESP_FAIL -1
|
||||
#define ESP_ERR_NO_MEM 0x101
|
||||
#define ESP_ERR_INVALID_ARG 0x102
|
||||
#define ESP_ERR_INVALID_STATE 0x103
|
||||
#define ESP_ERR_INVALID_SIZE 0x104
|
||||
#define ESP_ERR_NOT_FOUND 0x105
|
||||
#define ESP_ERR_NOT_SUPPORTED 0x106
|
||||
#define ESP_ERR_TIMEOUT 0x107
|
||||
#define ESP_ERR_INVALID_RESPONSE 0x108
|
||||
#define ESP_ERR_INVALID_CRC 0x109
|
||||
#define ESP_ERR_INVALID_VERSION 0x10A
|
||||
#define ESP_ERR_INVALID_MAC 0x10B
|
||||
#define ESP_ERR_NOT_FINISHED 0x10C
|
||||
|
||||
const char *esp_err_to_name(esp_err_t code);
|
||||
|
||||
// ESP-IDF's compiler pragmas around a known false-positive warning: nothing to do on the desktop
|
||||
#define ESP_COMPILER_DIAGNOSTIC_PUSH_IGNORE(x)
|
||||
#define ESP_COMPILER_DIAGNOSTIC_POP(x)
|
||||
|
||||
// ESP-IDF keeps these in esp_err.h; esp_check.h has the same macros
|
||||
#define ESP_RETURN_ON_ERROR(x, tag, fmt, ...) \
|
||||
do { \
|
||||
esp_err_t err_rc_ = (x); \
|
||||
if (err_rc_ != ESP_OK) { \
|
||||
ESP_LOGE(tag, "%s(%d): " fmt, __func__, (int)err_rc_, ##__VA_ARGS__); \
|
||||
return err_rc_; \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define ESP_RETURN_ON_FALSE(cond, err, tag, fmt, ...) \
|
||||
do { \
|
||||
if (!(cond)) { \
|
||||
ESP_LOGE(tag, "%s(%d): " fmt, __func__, (int)(err), ##__VA_ARGS__); \
|
||||
return (err); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define ESP_ERROR_CHECK(x) \
|
||||
do { \
|
||||
esp_err_t err_rc_ = (x); \
|
||||
if (err_rc_ != ESP_OK) { \
|
||||
ESP_LOGE("check", "%s:%d: %s", __FILE__, __LINE__, esp_err_to_name(err_rc_)); \
|
||||
abort(); \
|
||||
} \
|
||||
} while (0)
|
||||
|
||||
#define ESP_ERROR_CHECK_WITHOUT_ABORT(x) \
|
||||
do { \
|
||||
esp_err_t err_rc_ = (x); \
|
||||
if (err_rc_ != ESP_OK) { \
|
||||
ESP_LOGE("check", "%s:%d: %s", __FILE__, __LINE__, esp_err_to_name(err_rc_)); \
|
||||
} \
|
||||
} while (0)
|
||||
@@ -0,0 +1,18 @@
|
||||
/* Desktop port: no Wi-Fi events on the host, so the event loop is a stub. The base macros let the vendored
|
||||
* esp_http_server declare its (unused) event base. */
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
|
||||
typedef const char *esp_event_base_t;
|
||||
typedef void (*esp_event_handler_t)(void *handler_arg, esp_event_base_t base, int32_t id, void *event_data);
|
||||
|
||||
#define ESP_EVENT_DECLARE_BASE(id) extern const esp_event_base_t id
|
||||
#define ESP_EVENT_DEFINE_BASE(id) const esp_event_base_t id = #id
|
||||
#define ESP_EVENT_ANY_ID (-1)
|
||||
#define portMAX_DELAY_EVENT 0xFFFFFFFFu
|
||||
|
||||
esp_err_t esp_event_loop_create_default(void);
|
||||
esp_err_t esp_event_post(esp_event_base_t base, int32_t id, const void *data, size_t data_size, uint32_t ticks);
|
||||
@@ -0,0 +1,3 @@
|
||||
#pragma once
|
||||
|
||||
#include "esp_event.h"
|
||||
@@ -0,0 +1,27 @@
|
||||
/* Desktop port: there is one heap, so the capability flags are accepted and ignored */
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdlib.h>
|
||||
|
||||
#define MALLOC_CAP_8BIT (1u << 2)
|
||||
#define MALLOC_CAP_SPIRAM (1u << 10)
|
||||
#define MALLOC_CAP_INTERNAL (1u << 11)
|
||||
#define MALLOC_CAP_DEFAULT (1u << 12)
|
||||
|
||||
static inline void *heap_caps_malloc(size_t size, unsigned caps)
|
||||
{
|
||||
(void)caps;
|
||||
return malloc(size);
|
||||
}
|
||||
|
||||
static inline void *heap_caps_calloc(size_t n, size_t size, unsigned caps)
|
||||
{
|
||||
(void)caps;
|
||||
return calloc(n, size);
|
||||
}
|
||||
|
||||
static inline void heap_caps_free(void *p)
|
||||
{
|
||||
free(p);
|
||||
}
|
||||
@@ -0,0 +1,32 @@
|
||||
/* Desktop port of ESP-IDF's logging: lines go to stderr with the same level letters and tags. */
|
||||
#pragma once
|
||||
|
||||
#include <stdarg.h>
|
||||
#include <stdint.h>
|
||||
|
||||
typedef enum {
|
||||
ESP_LOG_NONE,
|
||||
ESP_LOG_ERROR,
|
||||
ESP_LOG_WARN,
|
||||
ESP_LOG_INFO,
|
||||
ESP_LOG_DEBUG,
|
||||
ESP_LOG_VERBOSE
|
||||
} esp_log_level_t;
|
||||
|
||||
typedef int (*vprintf_like_t)(const char *, va_list);
|
||||
|
||||
void esp_log_write(esp_log_level_t level, const char *tag, const char *fmt, ...) __attribute__((format(printf, 3, 4)));
|
||||
void esp_log_level_set(const char *tag, esp_log_level_t level);
|
||||
vprintf_like_t esp_log_set_vprintf(vprintf_like_t fn);
|
||||
uint32_t esp_log_timestamp(void);
|
||||
|
||||
#define ESP_LOGE(tag, fmt, ...) esp_log_write(ESP_LOG_ERROR, tag, fmt, ##__VA_ARGS__)
|
||||
#define ESP_LOGW(tag, fmt, ...) esp_log_write(ESP_LOG_WARN, tag, fmt, ##__VA_ARGS__)
|
||||
#define ESP_LOGI(tag, fmt, ...) esp_log_write(ESP_LOG_INFO, tag, fmt, ##__VA_ARGS__)
|
||||
#define ESP_LOGD(tag, fmt, ...) esp_log_write(ESP_LOG_DEBUG, tag, fmt, ##__VA_ARGS__)
|
||||
#define ESP_LOGV(tag, fmt, ...) esp_log_write(ESP_LOG_VERBOSE, tag, fmt, ##__VA_ARGS__)
|
||||
#define ESP_EARLY_LOGE(tag, fmt, ...) ESP_LOGE(tag, fmt, ##__VA_ARGS__)
|
||||
#define ESP_EARLY_LOGW(tag, fmt, ...) ESP_LOGW(tag, fmt, ##__VA_ARGS__)
|
||||
#define ESP_EARLY_LOGI(tag, fmt, ...) ESP_LOGI(tag, fmt, ##__VA_ARGS__)
|
||||
#define ESP_EARLY_LOGD(tag, fmt, ...) ESP_LOGD(tag, fmt, ##__VA_ARGS__)
|
||||
#define ESP_EARLY_LOGV(tag, fmt, ...) ESP_LOGV(tag, fmt, ##__VA_ARGS__)
|
||||
@@ -0,0 +1,14 @@
|
||||
/* Desktop port: the device MAC is the first real network interface's, so it is stable across runs */
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
|
||||
typedef enum {
|
||||
ESP_MAC_WIFI_STA,
|
||||
ESP_MAC_WIFI_SOFTAP,
|
||||
ESP_MAC_BT,
|
||||
ESP_MAC_ETH,
|
||||
} esp_mac_type_t;
|
||||
|
||||
esp_err_t esp_read_mac(uint8_t mac[6], esp_mac_type_t type);
|
||||
@@ -0,0 +1,24 @@
|
||||
/* Desktop stand-in for ESP-IDF's esp_netif_ip_addr.h: the IPv4 address types the app uses. */
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct {
|
||||
uint32_t addr; /* network byte order, as the bytes sit in memory */
|
||||
} esp_ip4_addr_t;
|
||||
|
||||
typedef enum {
|
||||
ESP_IPADDR_TYPE_V4 = 0,
|
||||
ESP_IPADDR_TYPE_V6 = 6,
|
||||
ESP_IPADDR_TYPE_ANY = 46,
|
||||
} esp_ip_addr_type_t;
|
||||
|
||||
typedef struct {
|
||||
esp_ip_addr_type_t type;
|
||||
union {
|
||||
esp_ip4_addr_t ip4;
|
||||
} u_addr;
|
||||
} esp_ip_addr_t;
|
||||
|
||||
#define IPSTR "%d.%d.%d.%d"
|
||||
#define IP2STR(p) ((const uint8_t *)(p))[0], ((const uint8_t *)(p))[1], ((const uint8_t *)(p))[2], ((const uint8_t *)(p))[3]
|
||||
@@ -0,0 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
uint32_t esp_random(void);
|
||||
void esp_fill_random(void *buf, size_t len);
|
||||
@@ -0,0 +1,5 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
void esp_rom_delay_us(uint32_t us);
|
||||
@@ -0,0 +1,9 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
|
||||
// Desktop: restart means exit, and systemd (or the user's shell) starts the program again
|
||||
void esp_restart(void) __attribute__((noreturn));
|
||||
uint32_t esp_get_free_heap_size(void);
|
||||
uint32_t esp_get_minimum_free_heap_size(void);
|
||||
@@ -0,0 +1,27 @@
|
||||
/* Desktop port: esp_timer on the host clock (implemented in sim-controller/components/sim/sim_timer.c) */
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include "esp_err.h"
|
||||
|
||||
typedef void (*esp_timer_cb_t)(void *arg);
|
||||
typedef enum { ESP_TIMER_TASK } esp_timer_dispatch_t;
|
||||
|
||||
typedef struct {
|
||||
esp_timer_cb_t callback;
|
||||
void *arg;
|
||||
esp_timer_dispatch_t dispatch_method;
|
||||
const char *name;
|
||||
bool skip_unhandled_events;
|
||||
} esp_timer_create_args_t;
|
||||
|
||||
struct esp_timer;
|
||||
typedef struct esp_timer *esp_timer_handle_t;
|
||||
|
||||
int64_t esp_timer_get_time(void);
|
||||
esp_err_t esp_timer_create(const esp_timer_create_args_t *args, esp_timer_handle_t *out);
|
||||
esp_err_t esp_timer_start_once(esp_timer_handle_t t, uint64_t timeout_us);
|
||||
esp_err_t esp_timer_start_periodic(esp_timer_handle_t t, uint64_t period);
|
||||
esp_err_t esp_timer_stop(esp_timer_handle_t t);
|
||||
bool esp_timer_is_active(esp_timer_handle_t t);
|
||||
@@ -0,0 +1,22 @@
|
||||
/* Desktop port: the FreeRTOS subset the firmware uses, on POSIX threads (desktop/port/src/freertos.c). */
|
||||
#pragma once
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
#include "portmacro.h"
|
||||
|
||||
typedef int BaseType_t;
|
||||
typedef unsigned int UBaseType_t;
|
||||
typedef uint32_t TickType_t;
|
||||
|
||||
#define pdTRUE ((BaseType_t)1)
|
||||
#define pdFALSE ((BaseType_t)0)
|
||||
#define pdPASS pdTRUE
|
||||
#define pdFAIL pdFALSE
|
||||
#define portMAX_DELAY ((TickType_t)0xFFFFFFFFUL)
|
||||
#define pdMS_TO_TICKS(ms) ((TickType_t)(ms)) /* a tick is 1 ms */
|
||||
#define portTICK_PERIOD_MS ((TickType_t)1)
|
||||
#define configTICK_RATE_HZ 1000
|
||||
|
||||
#define portYIELD_FROM_ISR(x) ((void)(x))
|
||||
@@ -0,0 +1,13 @@
|
||||
#pragma once
|
||||
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
typedef struct desk_events *EventGroupHandle_t;
|
||||
typedef uint32_t EventBits_t;
|
||||
|
||||
EventGroupHandle_t xEventGroupCreate(void);
|
||||
void vEventGroupDelete(EventGroupHandle_t g);
|
||||
EventBits_t xEventGroupSetBits(EventGroupHandle_t g, EventBits_t bits);
|
||||
EventBits_t xEventGroupClearBits(EventGroupHandle_t g, EventBits_t bits);
|
||||
EventBits_t xEventGroupWaitBits(EventGroupHandle_t g, EventBits_t bits, BaseType_t clear_on_exit,
|
||||
BaseType_t wait_all, TickType_t ticks);
|
||||
@@ -0,0 +1,16 @@
|
||||
/* Desktop port: critical sections are one process-wide recursive lock (desktop/port/src/freertos.c). */
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
typedef struct {
|
||||
int unused;
|
||||
} portMUX_TYPE;
|
||||
#define portMUX_INITIALIZER_UNLOCKED {0}
|
||||
|
||||
void desk_critical_enter(void);
|
||||
void desk_critical_exit(void);
|
||||
#define portENTER_CRITICAL(mux) ((void)(mux), desk_critical_enter())
|
||||
#define portEXIT_CRITICAL(mux) ((void)(mux), desk_critical_exit())
|
||||
#define taskENTER_CRITICAL() desk_critical_enter()
|
||||
#define taskEXIT_CRITICAL() desk_critical_exit()
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
typedef struct desk_queue *QueueHandle_t;
|
||||
|
||||
QueueHandle_t xQueueCreate(UBaseType_t length, UBaseType_t item_size);
|
||||
void vQueueDelete(QueueHandle_t q);
|
||||
BaseType_t xQueueSend(QueueHandle_t q, const void *item, TickType_t ticks);
|
||||
BaseType_t xQueueSendToBack(QueueHandle_t q, const void *item, TickType_t ticks);
|
||||
BaseType_t xQueueReceive(QueueHandle_t q, void *item, TickType_t ticks);
|
||||
UBaseType_t uxQueueMessagesWaiting(QueueHandle_t q);
|
||||
@@ -0,0 +1,18 @@
|
||||
#pragma once
|
||||
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
typedef struct desk_sem *SemaphoreHandle_t;
|
||||
|
||||
SemaphoreHandle_t xSemaphoreCreateMutex(void);
|
||||
SemaphoreHandle_t xSemaphoreCreateRecursiveMutex(void);
|
||||
SemaphoreHandle_t xSemaphoreCreateBinary(void);
|
||||
SemaphoreHandle_t xSemaphoreCreateCounting(UBaseType_t max, UBaseType_t initial);
|
||||
void vSemaphoreDelete(SemaphoreHandle_t s);
|
||||
BaseType_t xSemaphoreTake(SemaphoreHandle_t s, TickType_t ticks);
|
||||
BaseType_t xSemaphoreTakeRecursive(SemaphoreHandle_t s, TickType_t ticks);
|
||||
BaseType_t xSemaphoreGive(SemaphoreHandle_t s);
|
||||
BaseType_t xSemaphoreGiveRecursive(SemaphoreHandle_t s);
|
||||
BaseType_t xSemaphoreGiveFromISR(SemaphoreHandle_t s, BaseType_t *woken);
|
||||
|
||||
#define xSemaphoreTakeFromISR(s, w) xSemaphoreTake((s), 0)
|
||||
@@ -0,0 +1,12 @@
|
||||
#pragma once
|
||||
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
typedef struct desk_stream *StreamBufferHandle_t;
|
||||
|
||||
StreamBufferHandle_t xStreamBufferCreate(size_t size, size_t trigger_level);
|
||||
void vStreamBufferDelete(StreamBufferHandle_t sb);
|
||||
size_t xStreamBufferSend(StreamBufferHandle_t sb, const void *data, size_t len, TickType_t ticks);
|
||||
size_t xStreamBufferReceive(StreamBufferHandle_t sb, void *data, size_t len, TickType_t ticks);
|
||||
BaseType_t xStreamBufferReset(StreamBufferHandle_t sb);
|
||||
size_t xStreamBufferBytesAvailable(StreamBufferHandle_t sb);
|
||||
@@ -0,0 +1,15 @@
|
||||
#pragma once
|
||||
|
||||
#include "FreeRTOS.h"
|
||||
|
||||
#define tskIDLE_PRIORITY ((UBaseType_t)0)
|
||||
#define tskNO_AFFINITY 0x7FFFFFFF
|
||||
|
||||
typedef struct desk_task *TaskHandle_t;
|
||||
typedef void (*TaskFunction_t)(void *);
|
||||
|
||||
BaseType_t xTaskCreate(TaskFunction_t fn, const char *name, uint32_t stack_words, void *arg, UBaseType_t prio,
|
||||
TaskHandle_t *handle);
|
||||
void vTaskDelete(TaskHandle_t task);
|
||||
void vTaskDelay(TickType_t ticks);
|
||||
TaskHandle_t xTaskGetCurrentTaskHandle(void);
|
||||
@@ -0,0 +1,34 @@
|
||||
/* Desktop stand-in for ESP-IDF's mdns component: the query API the controller uses (wifi_drv.c).
|
||||
* The browser is in port/src/mdns_host.c. */
|
||||
#pragma once
|
||||
|
||||
#include <stddef.h>
|
||||
#include <stdint.h>
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_netif_ip_addr.h"
|
||||
|
||||
typedef struct {
|
||||
char *key;
|
||||
char *value;
|
||||
} mdns_txt_item_t;
|
||||
|
||||
typedef struct mdns_ip_addr_s {
|
||||
esp_ip_addr_t addr;
|
||||
struct mdns_ip_addr_s *next;
|
||||
} mdns_ip_addr_t;
|
||||
|
||||
typedef struct mdns_result_s {
|
||||
struct mdns_result_s *next;
|
||||
char *instance_name;
|
||||
char *hostname; /* without the .local suffix */
|
||||
mdns_txt_item_t *txt;
|
||||
size_t txt_count;
|
||||
mdns_ip_addr_t *addr;
|
||||
} mdns_result_t;
|
||||
|
||||
/* Browse for service._proto.local (for example "_http", "_tcp") for timeout_ms. Results are IN_ADDR answers
|
||||
* with their TXT items; free them with mdns_query_results_free. ESP_ERR_NOT_FOUND when nothing answered. */
|
||||
esp_err_t mdns_query_ptr(const char *service, const char *proto, uint32_t timeout_ms, size_t max_results,
|
||||
mdns_result_t **results);
|
||||
void mdns_query_results_free(mdns_result_t *results);
|
||||
@@ -0,0 +1,37 @@
|
||||
/* Desktop port of the httpd thread wrappers (replaces ESP-IDF's src/port/esp32/osal.h) */
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/task.h"
|
||||
#include "esp_err.h"
|
||||
|
||||
#define OS_SUCCESS ESP_OK
|
||||
#define OS_FAIL ESP_FAIL
|
||||
|
||||
typedef TaskHandle_t othread_t;
|
||||
|
||||
static inline int httpd_os_thread_create(othread_t *thread, const char *name, uint16_t stacksize, int prio,
|
||||
void (*thread_routine)(void *arg), void *arg, BaseType_t core_id,
|
||||
uint32_t caps)
|
||||
{
|
||||
(void)core_id;
|
||||
(void)caps;
|
||||
return xTaskCreate(thread_routine, name, stacksize, arg, (UBaseType_t)prio, thread) == pdPASS ? OS_SUCCESS : OS_FAIL;
|
||||
}
|
||||
|
||||
// Only the calling task can delete itself
|
||||
static inline void httpd_os_thread_delete(void)
|
||||
{
|
||||
vTaskDelete(NULL);
|
||||
}
|
||||
|
||||
static inline void httpd_os_thread_sleep(int msecs)
|
||||
{
|
||||
vTaskDelay(msecs / portTICK_PERIOD_MS);
|
||||
}
|
||||
|
||||
static inline othread_t httpd_os_thread_handle(void)
|
||||
{
|
||||
return xTaskGetCurrentTaskHandle();
|
||||
}
|
||||
@@ -0,0 +1,403 @@
|
||||
/*
|
||||
* Automatically generated file. DO NOT EDIT.
|
||||
* Espressif IoT Development Framework (ESP-IDF) 6.1.0 Configuration Header
|
||||
*/
|
||||
#pragma once
|
||||
#define CONFIG_SOC_EFUSE_SUPPORTED 1
|
||||
#define CONFIG_SOC_EFUSE_KEY_PURPOSE_FIELD 1
|
||||
#define CONFIG_SOC_CPU_CORES_NUM 1
|
||||
#define CONFIG_SOC_GPIO_IN_RANGE_MAX 65535
|
||||
#define CONFIG_SOC_GPIO_OUT_RANGE_MAX 65535
|
||||
#define CONFIG_SOC_I2C_SUPPORT_SLAVE 1
|
||||
#define CONFIG_SOC_I2C_SUPPORT_10BIT_ADDR 1
|
||||
#define CONFIG_SOC_EFUSE_DIS_DOWNLOAD_ICACHE 1
|
||||
#define CONFIG_SOC_EFUSE_DIS_DOWNLOAD_DCACHE 1
|
||||
#define CONFIG_SOC_EFUSE_HARD_DIS_JTAG 1
|
||||
#define CONFIG_SOC_EFUSE_DIS_USB_JTAG 1
|
||||
#define CONFIG_SOC_EFUSE_SOFT_DIS_JTAG 1
|
||||
#define CONFIG_SOC_EFUSE_DIS_DIRECT_BOOT 1
|
||||
#define CONFIG_SOC_EFUSE_DIS_ICACHE 1
|
||||
#define CONFIG_SOC_SECURE_BOOT_V2_RSA 1
|
||||
#define CONFIG_SOC_EFUSE_SECURE_BOOT_KEY_DIGESTS 3
|
||||
#define CONFIG_SOC_EFUSE_REVOKE_BOOT_KEY_DIGESTS 1
|
||||
#define CONFIG_SOC_SUPPORT_SECURE_BOOT_REVOKE_KEY 1
|
||||
#define CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES 1
|
||||
#define CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_OPTIONS 1
|
||||
#define CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_128 1
|
||||
#define CONFIG_SOC_FLASH_ENCRYPTION_XTS_AES_256 1
|
||||
#define CONFIG_IDF_CMAKE 1
|
||||
#define CONFIG_IDF_TOOLCHAIN ""
|
||||
#define CONFIG_IDF_TARGET "linux"
|
||||
#define CONFIG_IDF_INIT_VERSION "5.5.5"
|
||||
#define CONFIG_IDF_TARGET_LINUX 1
|
||||
#define CONFIG_IDF_FIRMWARE_CHIP_ID 0xFFFF
|
||||
#define CONFIG_APP_BUILD_TYPE_RAM 1
|
||||
#define CONFIG_APP_BUILD_GENERATE_BINARIES 1
|
||||
#define CONFIG_APP_COMPILE_TIME_DATE 1
|
||||
#define CONFIG_APP_RETRIEVE_LEN_ELF_SHA 9
|
||||
#define CONFIG_ESP_ROM_USB_OTG_NUM -1
|
||||
#define CONFIG_ESP_ROM_USB_SERIAL_DEVICE_NUM -1
|
||||
#define CONFIG_ESP_ROM_HAS_ETS_PRINTF_BUG 1
|
||||
#define CONFIG_ESP_ROM_HAS_OUTPUT_PUTC_FUNC 1
|
||||
#define CONFIG_ESP_ROM_BOOTLOADER_OFFSET_FLASH 0x0
|
||||
#define CONFIG_BOOT_ROM_LOG_ALWAYS_ON 1
|
||||
#define CONFIG_W5500_SPI_HOST 1
|
||||
#define CONFIG_W5500_SPI_CLOCK_MHZ 10
|
||||
#define CONFIG_W5500_SCLK_GPIO 7
|
||||
#define CONFIG_W5500_MISO_GPIO 8
|
||||
#define CONFIG_W5500_MOSI_GPIO 9
|
||||
#define CONFIG_W5500_CS_GPIO 2
|
||||
#define CONFIG_W5500_INT_GPIO 3
|
||||
#define CONFIG_W5500_POLL_PERIOD_MS 10
|
||||
#define CONFIG_W5500_RST_GPIO 1
|
||||
#define CONFIG_MIC_SCK_GPIO 5
|
||||
#define CONFIG_MIC_WS_GPIO 6
|
||||
#define CONFIG_MIC_SD_GPIO 43
|
||||
#define CONFIG_MIC_STREAM_GAIN 16
|
||||
#define CONFIG_BEAT_LED_GPIO 21
|
||||
#define CONFIG_BEAT_LED_ACTIVE_LOW 1
|
||||
#define CONFIG_BEAT_LED_PULSE_MS 60
|
||||
#define CONFIG_BEAT_LED_DOWNBEAT_MS 200
|
||||
#define CONFIG_BEAT_GATE_DBFS -75
|
||||
#define CONFIG_BEAT_LEAD_MS 30
|
||||
#define CONFIG_AP_BUTTON_GPIO 44
|
||||
#define CONFIG_AP_HOLD_MS 1000
|
||||
#define CONFIG_ESPNOW_CHANNEL 5
|
||||
#define CONFIG_BEAT_TX_COPIES 2
|
||||
#define CONFIG_BEAT_TX_GAP_US 2000
|
||||
#define CONFIG_BEAT_TEST_GPIO -1
|
||||
#define CONFIG_BULK_HOLDOFF_US 3000
|
||||
#define CONFIG_COMPILER_OPTIMIZATION_DEBUG 1
|
||||
#define CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE 1
|
||||
#define CONFIG_COMPILER_ASSERT_NDEBUG_EVALUATE 1
|
||||
#define CONFIG_COMPILER_FLOAT_LIB_FROM_GCCLIB 1
|
||||
#define CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL 2
|
||||
#define CONFIG_COMPILER_HIDE_PATHS_MACROS 1
|
||||
#define CONFIG_COMPILER_STACK_CHECK_MODE_NONE 1
|
||||
#define CONFIG_COMPILER_DISABLE_DEFAULT_ERRORS 1
|
||||
#define CONFIG_COMPILER_RT_LIB_HOST 1
|
||||
#define CONFIG_COMPILER_RT_LIB_NAME ""
|
||||
#define CONFIG_ESP_ERR_TO_NAME_LOOKUP 1
|
||||
#define CONFIG_ESP_EVENT_POST_FROM_ISR 1
|
||||
#define CONFIG_ESP_EVENT_POST_FROM_ISR_SIZE 4
|
||||
#define CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR 1
|
||||
#define CONFIG_HTTPD_MAX_REQ_HDR_LEN 1024
|
||||
#define CONFIG_HTTPD_MAX_URI_LEN 512
|
||||
#define CONFIG_HTTPD_ERR_RESP_NO_DELAY 1
|
||||
#define CONFIG_HTTPD_PURGE_BUF_LEN 32
|
||||
#define CONFIG_HTTPD_WS_SUPPORT 1
|
||||
#define CONFIG_HTTPD_ENABLE_EVENTS 1
|
||||
#define CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT 2000
|
||||
#define CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT 1
|
||||
#define CONFIG_ESP_HW_SUPPORT_FUNC_IN_IRAM 1
|
||||
#define CONFIG_ESP_REV_MIN_FULL 0
|
||||
#define CONFIG_ESP_REV_MAX_FULL 999
|
||||
#define CONFIG_ESP_EFUSE_BLOCK_REV_MIN_FULL 0
|
||||
#define CONFIG_ESP_EFUSE_BLOCK_REV_MAX_FULL 999
|
||||
#define CONFIG_ESP_SLEEP_FLASH_LEAKAGE_WORKAROUND 1
|
||||
#define CONFIG_ESP_SLEEP_GPIO_RESET_WORKAROUND 1
|
||||
#define CONFIG_ESP_SLEEP_WAIT_FLASH_READY_EXTRA_DELAY 0
|
||||
#define CONFIG_ESP_SLEEP_GPIO_ENABLE_INTERNAL_RESISTORS 1
|
||||
#define CONFIG_RTC_CLK_FUNC_IN_IRAM 1
|
||||
#define CONFIG_RTC_TIME_FUNC_IN_IRAM 1
|
||||
#define CONFIG_ESP_PERIPH_CTRL_FUNC_IN_IRAM 1
|
||||
#define CONFIG_ESP_REGI2C_CTRL_FUNC_IN_IRAM 1
|
||||
#define CONFIG_ESP_BRINGUP_BYPASS_CPU_CLK_SETTING 1
|
||||
#define CONFIG_ESP_BRINGUP_BYPASS_RANDOM_SETTING 1
|
||||
#define CONFIG_ESP_INTR_IN_IRAM 1
|
||||
#define CONFIG_ESP_ROM_PRINT_IN_IRAM 1
|
||||
#define CONFIG_ESP_CONSOLE_UART_DEFAULT 1
|
||||
#define CONFIG_ESP_CONSOLE_UART 1
|
||||
#define CONFIG_ESP_CONSOLE_UART_NUM 0
|
||||
#define CONFIG_ESP_CONSOLE_ROM_SERIAL_PORT_NUM 0
|
||||
#define CONFIG_ESP_CONSOLE_UART_BAUDRATE 115200
|
||||
#define CONFIG_ESP_SYSTEM_IN_IRAM 1
|
||||
#define CONFIG_ESP_SYSTEM_PANIC_PRINT_REBOOT 1
|
||||
#define CONFIG_ESP_SYSTEM_PANIC_REBOOT_DELAY_SECONDS 0
|
||||
#define CONFIG_ESP_SYSTEM_SINGLE_CORE_MODE 1
|
||||
#define CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE 32
|
||||
#define CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE 2304
|
||||
#define CONFIG_ESP_MAIN_TASK_STACK_SIZE 3584
|
||||
#define CONFIG_ESP_MAIN_TASK_AFFINITY_CPU0 1
|
||||
#define CONFIG_ESP_MAIN_TASK_AFFINITY 0x0
|
||||
#define CONFIG_ESP_MINIMAL_SHARED_STACK_SIZE 2048
|
||||
#define CONFIG_ESP_DEBUG_OCDAWARE 1
|
||||
#define CONFIG_ESP_SYSTEM_CHECK_INT_LEVEL_4 1
|
||||
#define CONFIG_ESP_IPC_TASK_STACK_SIZE 1024
|
||||
#define CONFIG_ESP_TIMER_IN_IRAM 1
|
||||
#define CONFIG_ESP_TIMER_TASK_STACK_SIZE 3584
|
||||
#define CONFIG_ESP_TIMER_INTERRUPT_LEVEL 1
|
||||
#define CONFIG_ESP_TIMER_TASK_AFFINITY 0x0
|
||||
#define CONFIG_ESP_TIMER_TASK_AFFINITY_CPU0 1
|
||||
#define CONFIG_ESP_TIMER_ISR_AFFINITY_CPU0 1
|
||||
#define CONFIG_ESP_TIMER_IMPL_SYSTIMER 1
|
||||
#define CONFIG_FREERTOS_UNICORE 1
|
||||
#define CONFIG_FREERTOS_HZ 1000
|
||||
#define CONFIG_FREERTOS_OPTIMIZED_SCHEDULER 1
|
||||
#define CONFIG_FREERTOS_CHECK_STACKOVERFLOW_CANARY 1
|
||||
#define CONFIG_FREERTOS_THREAD_LOCAL_STORAGE_POINTERS 1
|
||||
#define CONFIG_FREERTOS_IDLE_TASK_STACKSIZE 1536
|
||||
#define CONFIG_FREERTOS_MAX_TASK_NAME_LEN 16
|
||||
#define CONFIG_FREERTOS_USE_TIMERS 1
|
||||
#define CONFIG_FREERTOS_TIMER_SERVICE_TASK_NAME "Tmr Svc"
|
||||
#define CONFIG_FREERTOS_TIMER_TASK_NO_AFFINITY 1
|
||||
#define CONFIG_FREERTOS_TIMER_SERVICE_TASK_CORE_AFFINITY 0x7FFFFFFF
|
||||
#define CONFIG_FREERTOS_TIMER_TASK_PRIORITY 1
|
||||
#define CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH 2053
|
||||
#define CONFIG_FREERTOS_TIMER_QUEUE_LENGTH 10
|
||||
#define CONFIG_FREERTOS_QUEUE_REGISTRY_SIZE 0
|
||||
#define CONFIG_FREERTOS_TASK_NOTIFICATION_ARRAY_ENTRIES 1
|
||||
#define CONFIG_FREERTOS_TASK_FUNCTION_WRAPPER 1
|
||||
#define CONFIG_FREERTOS_TLSP_DELETION_CALLBACKS 1
|
||||
#define CONFIG_FREERTOS_CHECK_MUTEX_GIVEN_BY_OWNER 1
|
||||
#define CONFIG_FREERTOS_ISR_STACKSIZE 1536
|
||||
#define CONFIG_FREERTOS_INTERRUPT_BACKTRACE 1
|
||||
#define CONFIG_FREERTOS_TICK_SUPPORT_SYSTIMER 1
|
||||
#define CONFIG_FREERTOS_CORETIMER_SYSTIMER_LVL1 1
|
||||
#define CONFIG_FREERTOS_SYSTICK_USES_SYSTIMER 1
|
||||
#define CONFIG_FREERTOS_IN_IRAM 1
|
||||
#define CONFIG_FREERTOS_PORT 1
|
||||
#define CONFIG_FREERTOS_NO_AFFINITY 0x7FFFFFFF
|
||||
#define CONFIG_FREERTOS_SUPPORT_STATIC_ALLOCATION 1
|
||||
#define CONFIG_FREERTOS_DEBUG_OCDAWARE 1
|
||||
#define CONFIG_FREERTOS_NUMBER_OF_CORES 1
|
||||
#define CONFIG_HAL_ASSERTION_EQUALS_SYSTEM 1
|
||||
#define CONFIG_HAL_DEFAULT_ASSERTION_LEVEL 2
|
||||
#define CONFIG_HAL_GPIO_USE_ROM_IMPL 1
|
||||
#define CONFIG_HEAP_HAS_EXEC_HEAP 1
|
||||
#define CONFIG_HEAP_POISONING_DISABLED 1
|
||||
#define CONFIG_HEAP_TRACING_OFF 1
|
||||
#define CONFIG_LOG_VERSION_1 1
|
||||
#define CONFIG_LOG_VERSION 1
|
||||
#define CONFIG_LOG_DEFAULT_LEVEL_INFO 1
|
||||
#define CONFIG_LOG_DEFAULT_LEVEL 3
|
||||
#define CONFIG_LOG_MAXIMUM_EQUALS_DEFAULT 1
|
||||
#define CONFIG_LOG_MAXIMUM_LEVEL 3
|
||||
#define CONFIG_LOG_DYNAMIC_LEVEL_CONTROL 1
|
||||
#define CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_AND_LINKED_LIST 1
|
||||
#define CONFIG_LOG_TAG_LEVEL_CACHE_BINARY_MIN_HEAP 1
|
||||
#define CONFIG_LOG_TAG_LEVEL_IMPL_CACHE_SIZE 31
|
||||
#define CONFIG_LOG_TIMESTAMP_SOURCE_RTOS 1
|
||||
#define CONFIG_LOG_MODE_TEXT_EN 1
|
||||
#define CONFIG_LOG_MODE_TEXT 1
|
||||
#define CONFIG_LOG_IN_IRAM 1
|
||||
#define CONFIG_LWIP_LOCAL_HOSTNAME "espressif"
|
||||
#define CONFIG_LWIP_TCPIP_TASK_PRIO 18
|
||||
#define CONFIG_LWIP_DNS_SUPPORT_MDNS_QUERIES 1
|
||||
#define CONFIG_LWIP_TIMERS_ONDEMAND 1
|
||||
#define CONFIG_LWIP_ND6 1
|
||||
#define CONFIG_LWIP_MAX_SOCKETS 60
|
||||
#define CONFIG_LWIP_SO_REUSE 1
|
||||
#define CONFIG_LWIP_SO_REUSE_RXTOALL 1
|
||||
#define CONFIG_LWIP_IP_DEFAULT_TTL 64
|
||||
#define CONFIG_LWIP_IP4_FRAG 1
|
||||
#define CONFIG_LWIP_IP6_FRAG 1
|
||||
#define CONFIG_LWIP_IP_REASS_MAX_PBUFS 10
|
||||
#define CONFIG_LWIP_IPV6_DUP_DETECT_ATTEMPTS 1
|
||||
#define CONFIG_LWIP_ESP_GRATUITOUS_ARP 1
|
||||
#define CONFIG_LWIP_GARP_TMR_INTERVAL 60
|
||||
#define CONFIG_LWIP_ESP_MLDV6_REPORT 1
|
||||
#define CONFIG_LWIP_MLDV6_TMR_INTERVAL 40
|
||||
#define CONFIG_LWIP_TCPIP_RECVMBOX_SIZE 32
|
||||
#define CONFIG_LWIP_DHCP_DOES_ARP_CHECK 1
|
||||
#define CONFIG_LWIP_DHCP_DISABLE_VENDOR_CLASS_ID 1
|
||||
#define CONFIG_LWIP_DHCP_OPTIONS_LEN 69
|
||||
#define CONFIG_LWIP_NUM_NETIF_CLIENT_DATA 0
|
||||
#define CONFIG_LWIP_DHCP_COARSE_TIMER_SECS 1
|
||||
#define CONFIG_LWIP_DHCPS 1
|
||||
#define CONFIG_LWIP_DHCPS_REPORT_CLIENT_HOSTNAME 1
|
||||
#define CONFIG_LWIP_DHCPS_LEASE_UNIT 60
|
||||
#define CONFIG_LWIP_DHCPS_MAX_STATION_NUM 8
|
||||
#define CONFIG_LWIP_DHCPS_MAX_HOSTNAME_LEN 64
|
||||
#define CONFIG_LWIP_DHCPS_STATIC_ENTRIES 1
|
||||
#define CONFIG_LWIP_IPV4 1
|
||||
#define CONFIG_LWIP_IPV6 1
|
||||
#define CONFIG_LWIP_IPV6_NUM_ADDRESSES 3
|
||||
#define CONFIG_LWIP_NETIF_LOOPBACK 1
|
||||
#define CONFIG_LWIP_LOOPBACK_MAX_PBUFS 8
|
||||
#define CONFIG_LWIP_MAX_ACTIVE_TCP 16
|
||||
#define CONFIG_LWIP_MAX_LISTENING_TCP 16
|
||||
#define CONFIG_LWIP_TCP_HIGH_SPEED_RETRANSMISSION 1
|
||||
#define CONFIG_LWIP_TCP_MAXRTX 12
|
||||
#define CONFIG_LWIP_TCP_SYNMAXRTX 12
|
||||
#define CONFIG_LWIP_TCP_MSS 1440
|
||||
#define CONFIG_LWIP_TCP_TMR_INTERVAL 250
|
||||
#define CONFIG_LWIP_TCP_MSL 60000
|
||||
#define CONFIG_LWIP_TCP_FIN_WAIT_TIMEOUT 20000
|
||||
#define CONFIG_LWIP_TCP_SND_BUF_DEFAULT 5760
|
||||
#define CONFIG_LWIP_TCP_WND_DEFAULT 5760
|
||||
#define CONFIG_LWIP_TCP_RECVMBOX_SIZE 6
|
||||
#define CONFIG_LWIP_TCP_ACCEPTMBOX_SIZE 6
|
||||
#define CONFIG_LWIP_TCP_QUEUE_OOSEQ 1
|
||||
#define CONFIG_LWIP_TCP_OOSEQ_TIMEOUT 6
|
||||
#define CONFIG_LWIP_TCP_OOSEQ_MAX_PBUFS 4
|
||||
#define CONFIG_LWIP_TCP_OVERSIZE_MSS 1
|
||||
#define CONFIG_LWIP_TCP_RTO_TIME 1500
|
||||
#define CONFIG_LWIP_MAX_UDP_PCBS 16
|
||||
#define CONFIG_LWIP_UDP_RECVMBOX_SIZE 6
|
||||
#define CONFIG_LWIP_CHECKSUM_CHECK_ICMP 1
|
||||
#define CONFIG_LWIP_TCPIP_TASK_STACK_SIZE 3072
|
||||
#define CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY 1
|
||||
#define CONFIG_LWIP_TCPIP_TASK_AFFINITY 0x7FFFFFFF
|
||||
#define CONFIG_LWIP_IPV6_MEMP_NUM_ND6_QUEUE 3
|
||||
#define CONFIG_LWIP_IPV6_ND6_NUM_NEIGHBORS 5
|
||||
#define CONFIG_LWIP_IPV6_ND6_NUM_PREFIXES 5
|
||||
#define CONFIG_LWIP_IPV6_ND6_NUM_ROUTERS 3
|
||||
#define CONFIG_LWIP_IPV6_ND6_NUM_DESTINATIONS 10
|
||||
#define CONFIG_LWIP_ICMP 1
|
||||
#define CONFIG_LWIP_MAX_RAW_PCBS 16
|
||||
#define CONFIG_LWIP_SNTP_MAX_SERVERS 1
|
||||
#define CONFIG_LWIP_SNTP_UPDATE_DELAY 3600000
|
||||
#define CONFIG_LWIP_SNTP_STARTUP_DELAY 1
|
||||
#define CONFIG_LWIP_SNTP_MAXIMUM_STARTUP_DELAY 5000
|
||||
#define CONFIG_LWIP_DNS_MAX_HOST_IP 1
|
||||
#define CONFIG_LWIP_DNS_MAX_SERVERS 3
|
||||
#define CONFIG_LWIP_BRIDGEIF_MAX_PORTS 7
|
||||
#define CONFIG_LWIP_ESP_LWIP_ASSERT 1
|
||||
#define CONFIG_LWIP_HOOK_TCP_ISN_DEFAULT 1
|
||||
#define CONFIG_LWIP_HOOK_IP6_ROUTE_NONE 1
|
||||
#define CONFIG_LWIP_HOOK_ND6_GET_GW_NONE 1
|
||||
#define CONFIG_LWIP_HOOK_IP6_SELECT_SRC_ADDR_NONE 1
|
||||
#define CONFIG_LWIP_HOOK_DHCP_EXTRA_OPTION_NONE 1
|
||||
#define CONFIG_LWIP_HOOK_NETCONN_EXT_RESOLVE_NONE 1
|
||||
#define CONFIG_LWIP_HOOK_DNS_EXT_RESOLVE_NONE 1
|
||||
#define CONFIG_LWIP_HOOK_IP6_INPUT_DEFAULT 1
|
||||
#define CONFIG_MBEDTLS_VER_4_X_SUPPORT 1
|
||||
#define CONFIG_MBEDTLS_COMPILER_OPTIMIZATION_SIZE 1
|
||||
#define CONFIG_MBEDTLS_FS_IO 1
|
||||
#define CONFIG_MBEDTLS_ERROR_STRINGS 1
|
||||
#define CONFIG_MBEDTLS_VERSION_C 1
|
||||
#define CONFIG_MBEDTLS_HAVE_TIME 1
|
||||
#define CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC 1
|
||||
#define CONFIG_MBEDTLS_ASYMMETRIC_CONTENT_LEN 1
|
||||
#define CONFIG_MBEDTLS_SSL_IN_CONTENT_LEN 16384
|
||||
#define CONFIG_MBEDTLS_SSL_OUT_CONTENT_LEN 4096
|
||||
#define CONFIG_MBEDTLS_SELF_TEST 1
|
||||
#define CONFIG_MBEDTLS_X509_USE_C 1
|
||||
#define CONFIG_MBEDTLS_PEM_PARSE_C 1
|
||||
#define CONFIG_MBEDTLS_PEM_WRITE_C 1
|
||||
#define CONFIG_MBEDTLS_PK_C 1
|
||||
#define CONFIG_MBEDTLS_PK_PARSE_C 1
|
||||
#define CONFIG_MBEDTLS_PK_WRITE_C 1
|
||||
#define CONFIG_MBEDTLS_X509_CRL_PARSE_C 1
|
||||
#define CONFIG_MBEDTLS_X509_CRT_PARSE_C 1
|
||||
#define CONFIG_MBEDTLS_X509_CSR_PARSE_C 1
|
||||
#define CONFIG_MBEDTLS_X509_RSASSA_PSS_SUPPORT 1
|
||||
#define CONFIG_MBEDTLS_ASN1_PARSE_C 1
|
||||
#define CONFIG_MBEDTLS_ASN1_WRITE_C 1
|
||||
#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE 1
|
||||
#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_DEFAULT_FULL 1
|
||||
#define CONFIG_MBEDTLS_CERTIFICATE_BUNDLE_MAX_CERTS 200
|
||||
#define CONFIG_MBEDTLS_TLS_ENABLED 1
|
||||
#define CONFIG_MBEDTLS_SSL_PROTO_TLS1_2 1
|
||||
#define CONFIG_MBEDTLS_TLS_SERVER 1
|
||||
#define CONFIG_MBEDTLS_TLS_CLIENT 1
|
||||
#define CONFIG_MBEDTLS_TLS_SERVER_AND_CLIENT 1
|
||||
#define CONFIG_MBEDTLS_SSL_KEEP_PEER_CERTIFICATE 1
|
||||
#define CONFIG_MBEDTLS_SSL_CACHE_C 1
|
||||
#define CONFIG_MBEDTLS_SSL_ALL_ALERT_MESSAGES 1
|
||||
#define CONFIG_MBEDTLS_KEY_EXCHANGE_RSA 1
|
||||
#define CONFIG_MBEDTLS_KEY_EXCHANGE_ELLIPTIC_CURVE 1
|
||||
#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_RSA 1
|
||||
#define CONFIG_MBEDTLS_KEY_EXCHANGE_ECDHE_ECDSA 1
|
||||
#define CONFIG_MBEDTLS_SSL_SERVER_NAME_INDICATION 1
|
||||
#define CONFIG_MBEDTLS_SSL_ALPN 1
|
||||
#define CONFIG_MBEDTLS_SSL_MAX_FRAGMENT_LENGTH 1
|
||||
#define CONFIG_MBEDTLS_SSL_RENEGOTIATION 1
|
||||
#define CONFIG_MBEDTLS_CLIENT_SSL_SESSION_TICKETS 1
|
||||
#define CONFIG_MBEDTLS_SERVER_SSL_SESSION_TICKETS 1
|
||||
#define CONFIG_MBEDTLS_AES_C 1
|
||||
#define CONFIG_MBEDTLS_CCM_C 1
|
||||
#define CONFIG_MBEDTLS_CIPHER_MODE_CBC 1
|
||||
#define CONFIG_MBEDTLS_CIPHER_MODE_CFB 1
|
||||
#define CONFIG_MBEDTLS_CIPHER_MODE_CTR 1
|
||||
#define CONFIG_MBEDTLS_CIPHER_MODE_OFB 1
|
||||
#define CONFIG_MBEDTLS_CIPHER_MODE_XTS 1
|
||||
#define CONFIG_MBEDTLS_GCM_C 1
|
||||
#define CONFIG_MBEDTLS_AES_ROM_TABLES 1
|
||||
#define CONFIG_MBEDTLS_RSA_C 1
|
||||
#define CONFIG_MBEDTLS_ECP_C 1
|
||||
#define CONFIG_MBEDTLS_ECP_DP_SECP256R1_ENABLED 1
|
||||
#define CONFIG_MBEDTLS_ECP_DP_SECP384R1_ENABLED 1
|
||||
#define CONFIG_MBEDTLS_ECP_DP_SECP521R1_ENABLED 1
|
||||
#define CONFIG_MBEDTLS_ECP_DP_SECP256K1_ENABLED 1
|
||||
#define CONFIG_MBEDTLS_ECP_DP_BP256R1_ENABLED 1
|
||||
#define CONFIG_MBEDTLS_ECP_DP_BP384R1_ENABLED 1
|
||||
#define CONFIG_MBEDTLS_ECP_DP_BP512R1_ENABLED 1
|
||||
#define CONFIG_MBEDTLS_ECP_DP_CURVE25519_ENABLED 1
|
||||
#define CONFIG_MBEDTLS_ECP_NIST_OPTIM 1
|
||||
#define CONFIG_MBEDTLS_ECDH_C 1
|
||||
#define CONFIG_MBEDTLS_ECDSA_C 1
|
||||
#define CONFIG_MBEDTLS_PK_PARSE_EC_EXTENDED 1
|
||||
#define CONFIG_MBEDTLS_PK_PARSE_EC_COMPRESSED 1
|
||||
#define CONFIG_MBEDTLS_ECDSA_DETERMINISTIC 1
|
||||
#define CONFIG_MBEDTLS_MD_C 1
|
||||
#define CONFIG_MBEDTLS_MD5_C 1
|
||||
#define CONFIG_MBEDTLS_SHA1_C 1
|
||||
#define CONFIG_MBEDTLS_SHA256_C 1
|
||||
#define CONFIG_MBEDTLS_SHA384_C 1
|
||||
#define CONFIG_MBEDTLS_SHA512_C 1
|
||||
#define CONFIG_MBEDTLS_ROM_MD5 1
|
||||
#define CONFIG_MBEDTLS_CTR_DRBG_C 1
|
||||
#define CONFIG_MBEDTLS_HMAC_DRBG_C 1
|
||||
#define CONFIG_MBEDTLS_BASE64_C 1
|
||||
#define CONFIG_MBEDTLS_PKCS5_C 1
|
||||
#define CONFIG_MBEDTLS_PKCS7_C 1
|
||||
#define CONFIG_MBEDTLS_PKCS1_V15 1
|
||||
#define CONFIG_MBEDTLS_PKCS1_V21 1
|
||||
#define CONFIG_MMU_PAGE_SIZE_64KB 1
|
||||
#define CONFIG_MMU_PAGE_MODE "64KB"
|
||||
#define CONFIG_MMU_PAGE_SIZE 0x10000
|
||||
#define CONFIG_SPI_FLASH_BROWNOUT_RESET_XMC 1
|
||||
#define CONFIG_SPI_FLASH_BROWNOUT_RESET 1
|
||||
#define CONFIG_SPI_FLASH_SUSPEND_TSUS_VAL_US 50
|
||||
#define CONFIG_SPI_FLASH_PLACE_FUNCTIONS_IN_IRAM 1
|
||||
#define CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED 1
|
||||
#define CONFIG_SPI_FLASH_YIELD_DURING_ERASE 1
|
||||
#define CONFIG_SPI_FLASH_ERASE_YIELD_DURATION_MS 20
|
||||
#define CONFIG_SPI_FLASH_ERASE_YIELD_TICKS 1
|
||||
#define CONFIG_SPI_FLASH_WRITE_CHUNK_SIZE 8192
|
||||
#define CONFIG_SPI_FLASH_ENABLE_ENCRYPTED_READ_WRITE 1
|
||||
#define CONFIG_CJSON_NESTING_LIMIT 1000
|
||||
#define CONFIG_CJSON_CIRCULAR_LIMIT 10000
|
||||
|
||||
/* List of deprecated options */
|
||||
#define CONFIG_APP_BUILD_TYPE_ELF_RAM CONFIG_APP_BUILD_TYPE_RAM
|
||||
#define CONFIG_COMPILER_OPTIMIZATION_DEFAULT CONFIG_COMPILER_OPTIMIZATION_DEBUG
|
||||
#define CONFIG_COMPILER_OPTIMIZATION_LEVEL_DEBUG CONFIG_COMPILER_OPTIMIZATION_DEBUG
|
||||
#define CONFIG_CONSOLE_UART CONFIG_ESP_CONSOLE_UART
|
||||
#define CONFIG_CONSOLE_UART_BAUDRATE CONFIG_ESP_CONSOLE_UART_BAUDRATE
|
||||
#define CONFIG_CONSOLE_UART_DEFAULT CONFIG_ESP_CONSOLE_UART_DEFAULT
|
||||
#define CONFIG_CONSOLE_UART_NUM CONFIG_ESP_CONSOLE_UART_NUM
|
||||
#define CONFIG_ESP_GRATUITOUS_ARP CONFIG_LWIP_ESP_GRATUITOUS_ARP
|
||||
#define CONFIG_GARP_TMR_INTERVAL CONFIG_LWIP_GARP_TMR_INTERVAL
|
||||
#define CONFIG_IPC_TASK_STACK_SIZE CONFIG_ESP_IPC_TASK_STACK_SIZE
|
||||
#define CONFIG_MAIN_TASK_STACK_SIZE CONFIG_ESP_MAIN_TASK_STACK_SIZE
|
||||
#define CONFIG_OPTIMIZATION_ASSERTIONS_ENABLED CONFIG_COMPILER_OPTIMIZATION_ASSERTIONS_ENABLE
|
||||
#define CONFIG_OPTIMIZATION_ASSERTION_LEVEL CONFIG_COMPILER_OPTIMIZATION_ASSERTION_LEVEL
|
||||
#define CONFIG_OPTIMIZATION_LEVEL_DEBUG CONFIG_COMPILER_OPTIMIZATION_DEBUG
|
||||
#define CONFIG_PERIPH_CTRL_FUNC_IN_IRAM CONFIG_ESP_PERIPH_CTRL_FUNC_IN_IRAM
|
||||
#define CONFIG_POST_EVENTS_FROM_IRAM_ISR CONFIG_ESP_EVENT_POST_FROM_IRAM_ISR
|
||||
#define CONFIG_POST_EVENTS_FROM_ISR CONFIG_ESP_EVENT_POST_FROM_ISR
|
||||
#define CONFIG_SPI_FLASH_WRITING_DANGEROUS_REGIONS_ALLOWED CONFIG_SPI_FLASH_DANGEROUS_WRITE_ALLOWED
|
||||
#define CONFIG_STACK_CHECK_NONE CONFIG_COMPILER_STACK_CHECK_MODE_NONE
|
||||
#define CONFIG_SYSTEM_EVENT_QUEUE_SIZE CONFIG_ESP_SYSTEM_EVENT_QUEUE_SIZE
|
||||
#define CONFIG_SYSTEM_EVENT_TASK_STACK_SIZE CONFIG_ESP_SYSTEM_EVENT_TASK_STACK_SIZE
|
||||
#define CONFIG_TCPIP_RECVMBOX_SIZE CONFIG_LWIP_TCPIP_RECVMBOX_SIZE
|
||||
#define CONFIG_TCPIP_TASK_AFFINITY CONFIG_LWIP_TCPIP_TASK_AFFINITY
|
||||
#define CONFIG_TCPIP_TASK_AFFINITY_NO_AFFINITY CONFIG_LWIP_TCPIP_TASK_AFFINITY_NO_AFFINITY
|
||||
#define CONFIG_TCPIP_TASK_STACK_SIZE CONFIG_LWIP_TCPIP_TASK_STACK_SIZE
|
||||
#define CONFIG_TCP_MAXRTX CONFIG_LWIP_TCP_MAXRTX
|
||||
#define CONFIG_TCP_MSL CONFIG_LWIP_TCP_MSL
|
||||
#define CONFIG_TCP_MSS CONFIG_LWIP_TCP_MSS
|
||||
#define CONFIG_TCP_OVERSIZE_MSS CONFIG_LWIP_TCP_OVERSIZE_MSS
|
||||
#define CONFIG_TCP_QUEUE_OOSEQ CONFIG_LWIP_TCP_QUEUE_OOSEQ
|
||||
#define CONFIG_TCP_RECVMBOX_SIZE CONFIG_LWIP_TCP_RECVMBOX_SIZE
|
||||
#define CONFIG_TCP_SND_BUF_DEFAULT CONFIG_LWIP_TCP_SND_BUF_DEFAULT
|
||||
#define CONFIG_TCP_SYNMAXRTX CONFIG_LWIP_TCP_SYNMAXRTX
|
||||
#define CONFIG_TCP_WND_DEFAULT CONFIG_LWIP_TCP_WND_DEFAULT
|
||||
#define CONFIG_TIMER_QUEUE_LENGTH CONFIG_FREERTOS_TIMER_QUEUE_LENGTH
|
||||
#define CONFIG_TIMER_TASK_PRIORITY CONFIG_FREERTOS_TIMER_TASK_PRIORITY
|
||||
#define CONFIG_TIMER_TASK_STACK_DEPTH CONFIG_FREERTOS_TIMER_TASK_STACK_DEPTH
|
||||
#define CONFIG_TIMER_TASK_STACK_SIZE CONFIG_ESP_TIMER_TASK_STACK_SIZE
|
||||
#define CONFIG_UDP_RECVMBOX_SIZE CONFIG_LWIP_UDP_RECVMBOX_SIZE
|
||||
@@ -0,0 +1,91 @@
|
||||
/* SHA-1 (FIPS 180-1) and base64 (RFC 4648) for the WebSocket handshake: no TLS library on the desktop */
|
||||
#include "desktop_crypto.h"
|
||||
|
||||
#include <string.h>
|
||||
|
||||
static uint32_t rol(uint32_t v, int n)
|
||||
{
|
||||
return (v << n) | (v >> (32 - n));
|
||||
}
|
||||
|
||||
static void sha1_block(uint32_t h[5], const uint8_t blk[64])
|
||||
{
|
||||
uint32_t w[80];
|
||||
for (int i = 0; i < 16; i++) {
|
||||
w[i] = ((uint32_t)blk[i * 4] << 24) | ((uint32_t)blk[i * 4 + 1] << 16) |
|
||||
((uint32_t)blk[i * 4 + 2] << 8) | blk[i * 4 + 3];
|
||||
}
|
||||
for (int i = 16; i < 80; i++) {
|
||||
w[i] = rol(w[i - 3] ^ w[i - 8] ^ w[i - 14] ^ w[i - 16], 1);
|
||||
}
|
||||
uint32_t a = h[0], b = h[1], c = h[2], d = h[3], e = h[4];
|
||||
for (int i = 0; i < 80; i++) {
|
||||
uint32_t f, k;
|
||||
if (i < 20) { f = (b & c) | (~b & d); k = 0x5A827999; }
|
||||
else if (i < 40) { f = b ^ c ^ d; k = 0x6ED9EBA1; }
|
||||
else if (i < 60) { f = (b & c) | (b & d) | (c & d); k = 0x8F1BBCDC; }
|
||||
else { f = b ^ c ^ d; k = 0xCA62C1D6; }
|
||||
uint32_t t = rol(a, 5) + f + e + k + w[i];
|
||||
e = d;
|
||||
d = c;
|
||||
c = rol(b, 30);
|
||||
b = a;
|
||||
a = t;
|
||||
}
|
||||
h[0] += a;
|
||||
h[1] += b;
|
||||
h[2] += c;
|
||||
h[3] += d;
|
||||
h[4] += e;
|
||||
}
|
||||
|
||||
void desktop_sha1(const uint8_t *data, size_t len, uint8_t out[20])
|
||||
{
|
||||
uint32_t h[5] = { 0x67452301, 0xEFCDAB89, 0x98BADCFE, 0x10325476, 0xC3D2E1F0 };
|
||||
size_t i = 0;
|
||||
for (; i + 64 <= len; i += 64) {
|
||||
sha1_block(h, data + i);
|
||||
}
|
||||
// the tail: the rest, a 0x80 byte, zeros, and the message length in bits, in one or two blocks
|
||||
uint8_t tail[128];
|
||||
memset(tail, 0, sizeof(tail));
|
||||
size_t rest = len - i;
|
||||
memcpy(tail, data + i, rest);
|
||||
tail[rest] = 0x80;
|
||||
size_t tail_len = rest < 56 ? 64 : 128;
|
||||
uint64_t bits = (uint64_t)len * 8;
|
||||
for (int k = 0; k < 8; k++) {
|
||||
tail[tail_len - 1 - k] = (uint8_t)(bits >> (8 * k));
|
||||
}
|
||||
sha1_block(h, tail);
|
||||
if (tail_len == 128) {
|
||||
sha1_block(h, tail + 64);
|
||||
}
|
||||
for (int k = 0; k < 5; k++) {
|
||||
out[k * 4] = (uint8_t)(h[k] >> 24);
|
||||
out[k * 4 + 1] = (uint8_t)(h[k] >> 16);
|
||||
out[k * 4 + 2] = (uint8_t)(h[k] >> 8);
|
||||
out[k * 4 + 3] = (uint8_t)h[k];
|
||||
}
|
||||
}
|
||||
|
||||
size_t desktop_base64_encode(char *out, size_t cap, const uint8_t *in, size_t n)
|
||||
{
|
||||
static const char tbl[] = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/";
|
||||
size_t need = ((n + 2) / 3) * 4;
|
||||
if (cap < need + 1) {
|
||||
return 0;
|
||||
}
|
||||
size_t o = 0;
|
||||
for (size_t i = 0; i < n; i += 3) {
|
||||
uint32_t v = (uint32_t)in[i] << 16;
|
||||
if (i + 1 < n) v |= (uint32_t)in[i + 1] << 8;
|
||||
if (i + 2 < n) v |= in[i + 2];
|
||||
out[o++] = tbl[(v >> 18) & 63];
|
||||
out[o++] = tbl[(v >> 12) & 63];
|
||||
out[o++] = (i + 1 < n) ? tbl[(v >> 6) & 63] : '=';
|
||||
out[o++] = (i + 2 < n) ? tbl[v & 63] : '=';
|
||||
}
|
||||
out[o] = '\0';
|
||||
return o;
|
||||
}
|
||||
@@ -0,0 +1,205 @@
|
||||
/* Desktop port: the ESP-IDF runtime calls the firmware makes (logging, errors, random, MAC, restart) */
|
||||
#define _GNU_SOURCE
|
||||
#include <dirent.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/random.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include "esp_app_desc.h"
|
||||
#include "esp_err.h"
|
||||
#include "esp_event.h"
|
||||
#include "esp_log.h"
|
||||
#include "esp_mac.h"
|
||||
#include "esp_random.h"
|
||||
#include "esp_rom_sys.h"
|
||||
#include "esp_system.h"
|
||||
#include "esp_timer.h"
|
||||
|
||||
#ifndef LED_APP_VERSION
|
||||
#define LED_APP_VERSION "desktop"
|
||||
#endif
|
||||
|
||||
static esp_log_level_t s_level = ESP_LOG_INFO;
|
||||
static vprintf_like_t s_vprintf;
|
||||
|
||||
// LED_LOG_LEVEL=error|warn|info|debug|verbose (default info)
|
||||
static void init_level(void)
|
||||
{
|
||||
static bool done;
|
||||
if (done) return;
|
||||
done = true;
|
||||
const char *env = getenv("LED_LOG_LEVEL");
|
||||
if (!env) return;
|
||||
if (!strcmp(env, "error")) s_level = ESP_LOG_ERROR;
|
||||
else if (!strcmp(env, "warn")) s_level = ESP_LOG_WARN;
|
||||
else if (!strcmp(env, "debug")) s_level = ESP_LOG_DEBUG;
|
||||
else if (!strcmp(env, "verbose")) s_level = ESP_LOG_VERBOSE;
|
||||
else s_level = ESP_LOG_INFO;
|
||||
}
|
||||
|
||||
void esp_log_level_set(const char *tag, esp_log_level_t level)
|
||||
{
|
||||
(void)tag;
|
||||
s_level = level;
|
||||
}
|
||||
|
||||
vprintf_like_t esp_log_set_vprintf(vprintf_like_t fn)
|
||||
{
|
||||
vprintf_like_t old = s_vprintf;
|
||||
s_vprintf = fn;
|
||||
return old;
|
||||
}
|
||||
|
||||
uint32_t esp_log_timestamp(void)
|
||||
{
|
||||
return (uint32_t)(esp_timer_get_time() / 1000);
|
||||
}
|
||||
|
||||
void esp_log_write(esp_log_level_t level, const char *tag, const char *fmt, ...)
|
||||
{
|
||||
init_level();
|
||||
if (level > s_level) return;
|
||||
static const char letters[] = " EWIDV";
|
||||
char text[512];
|
||||
va_list args;
|
||||
va_start(args, fmt);
|
||||
if (s_vprintf) {
|
||||
// a hook (the bridge firmware's LOG frames) formats the line itself
|
||||
s_vprintf(fmt, args);
|
||||
va_end(args);
|
||||
return;
|
||||
}
|
||||
vsnprintf(text, sizeof(text), fmt, args);
|
||||
va_end(args);
|
||||
fprintf(stderr, "%c (%u) %s: %s\n", letters[level], esp_log_timestamp(), tag, text);
|
||||
}
|
||||
|
||||
const char *esp_err_to_name(esp_err_t code)
|
||||
{
|
||||
switch (code) {
|
||||
case ESP_OK: return "ESP_OK";
|
||||
case ESP_FAIL: return "ESP_FAIL";
|
||||
case ESP_ERR_NO_MEM: return "ESP_ERR_NO_MEM";
|
||||
case ESP_ERR_INVALID_ARG: return "ESP_ERR_INVALID_ARG";
|
||||
case ESP_ERR_INVALID_STATE: return "ESP_ERR_INVALID_STATE";
|
||||
case ESP_ERR_INVALID_SIZE: return "ESP_ERR_INVALID_SIZE";
|
||||
case ESP_ERR_NOT_FOUND: return "ESP_ERR_NOT_FOUND";
|
||||
case ESP_ERR_NOT_SUPPORTED: return "ESP_ERR_NOT_SUPPORTED";
|
||||
case ESP_ERR_TIMEOUT: return "ESP_ERR_TIMEOUT";
|
||||
case ESP_ERR_INVALID_RESPONSE: return "ESP_ERR_INVALID_RESPONSE";
|
||||
case ESP_ERR_INVALID_CRC: return "ESP_ERR_INVALID_CRC";
|
||||
case ESP_ERR_INVALID_VERSION: return "ESP_ERR_INVALID_VERSION";
|
||||
case ESP_ERR_INVALID_MAC: return "ESP_ERR_INVALID_MAC";
|
||||
case ESP_ERR_NOT_FINISHED: return "ESP_ERR_NOT_FINISHED";
|
||||
default: return "ESP_ERR_UNKNOWN";
|
||||
}
|
||||
}
|
||||
|
||||
uint32_t esp_random(void)
|
||||
{
|
||||
uint32_t v = 0;
|
||||
esp_fill_random(&v, sizeof(v));
|
||||
return v;
|
||||
}
|
||||
|
||||
void esp_fill_random(void *buf, size_t len)
|
||||
{
|
||||
uint8_t *p = buf;
|
||||
while (len) {
|
||||
ssize_t n = getrandom(p, len, 0);
|
||||
if (n <= 0) {
|
||||
// getrandom can be interrupted: fall back to the clock rather than returning zeros
|
||||
for (size_t i = 0; i < len; i++) p[i] = (uint8_t)(esp_timer_get_time() >> (i % 8));
|
||||
return;
|
||||
}
|
||||
p += n;
|
||||
len -= (size_t)n;
|
||||
}
|
||||
}
|
||||
|
||||
void esp_rom_delay_us(uint32_t us)
|
||||
{
|
||||
usleep(us);
|
||||
}
|
||||
|
||||
// The first real network interface's MAC (not loopback), so a driver keeps its identity across runs
|
||||
esp_err_t esp_read_mac(uint8_t mac[6], esp_mac_type_t type)
|
||||
{
|
||||
(void)type;
|
||||
DIR *d = opendir("/sys/class/net");
|
||||
if (d) {
|
||||
struct dirent *e;
|
||||
char best[256] = "";
|
||||
while ((e = readdir(d))) {
|
||||
if (e->d_name[0] == '.' || !strcmp(e->d_name, "lo")) continue;
|
||||
if (!best[0] || strcmp(e->d_name, best) < 0) snprintf(best, sizeof(best), "%s", e->d_name);
|
||||
}
|
||||
closedir(d);
|
||||
if (best[0]) {
|
||||
char path[320];
|
||||
snprintf(path, sizeof(path), "/sys/class/net/%s/address", best);
|
||||
FILE *f = fopen(path, "r");
|
||||
if (f) {
|
||||
unsigned v[6];
|
||||
int n = fscanf(f, "%x:%x:%x:%x:%x:%x", &v[0], &v[1], &v[2], &v[3], &v[4], &v[5]);
|
||||
fclose(f);
|
||||
if (n == 6) {
|
||||
for (int i = 0; i < 6; i++) mac[i] = (uint8_t)v[i];
|
||||
return ESP_OK;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
const uint8_t fallback[6] = { 0x02, 0x51, 0x4d, 0x00, 0x00, 0x01 }; // locally administered
|
||||
memcpy(mac, fallback, 6);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
// On the desktop a restart is an exit: the service manager starts the program again
|
||||
void esp_restart(void)
|
||||
{
|
||||
fprintf(stderr, "restart requested: exiting for the service manager to start us again\n");
|
||||
fflush(stderr);
|
||||
_exit(0);
|
||||
}
|
||||
|
||||
uint32_t esp_get_free_heap_size(void)
|
||||
{
|
||||
return 64u * 1024u * 1024u; // the host heap is not limited the way the board's is
|
||||
}
|
||||
|
||||
uint32_t esp_get_minimum_free_heap_size(void)
|
||||
{
|
||||
return esp_get_free_heap_size();
|
||||
}
|
||||
|
||||
esp_err_t esp_event_loop_create_default(void)
|
||||
{
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t esp_event_post(esp_event_base_t base, int32_t id, const void *data, size_t data_size, uint32_t ticks)
|
||||
{
|
||||
(void)base;
|
||||
(void)id;
|
||||
(void)data;
|
||||
(void)data_size;
|
||||
(void)ticks;
|
||||
return ESP_OK; // nobody listens on the desktop
|
||||
}
|
||||
|
||||
const esp_app_desc_t *esp_app_get_description(void)
|
||||
{
|
||||
static esp_app_desc_t desc;
|
||||
static bool init;
|
||||
if (!init) {
|
||||
init = true;
|
||||
snprintf(desc.version, sizeof(desc.version), "%s", LED_APP_VERSION);
|
||||
snprintf(desc.project_name, sizeof(desc.project_name), "led_controller_desktop");
|
||||
snprintf(desc.idf_ver, sizeof(desc.idf_ver), "none");
|
||||
}
|
||||
return &desc;
|
||||
}
|
||||
@@ -0,0 +1,522 @@
|
||||
/*
|
||||
* Desktop port: the FreeRTOS calls the firmware makes, on POSIX threads.
|
||||
* task a detached pthread; the handle is kept so a task can be named, and vTaskDelete(NULL) exits it
|
||||
* queue a ring of fixed-size items, blocking send and receive with a deadline
|
||||
* semaphore counting, binary and (recursive) mutex, with the owner and depth for recursive takes
|
||||
* critical one process-wide recursive lock
|
||||
* A tick is 1 ms. Timeouts are real: a blocked task sleeps in the kernel, so the others run.
|
||||
*/
|
||||
#define _GNU_SOURCE
|
||||
#include <errno.h>
|
||||
#include <pthread.h>
|
||||
#include <sched.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include "freertos/FreeRTOS.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "freertos/queue.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "freertos/stream_buffer.h"
|
||||
#include "freertos/task.h"
|
||||
|
||||
static pthread_mutex_t s_crit = PTHREAD_RECURSIVE_MUTEX_INITIALIZER_NP;
|
||||
|
||||
void desk_critical_enter(void)
|
||||
{
|
||||
pthread_mutex_lock(&s_crit);
|
||||
}
|
||||
|
||||
void desk_critical_exit(void)
|
||||
{
|
||||
pthread_mutex_unlock(&s_crit);
|
||||
}
|
||||
|
||||
// Absolute deadline for a timeout in ticks (ms), on the realtime clock
|
||||
static void make_deadline(TickType_t ticks, struct timespec *dl)
|
||||
{
|
||||
clock_gettime(CLOCK_REALTIME, dl);
|
||||
dl->tv_sec += ticks / 1000;
|
||||
dl->tv_nsec += (long)(ticks % 1000) * 1000000L;
|
||||
if (dl->tv_nsec >= 1000000000L) {
|
||||
dl->tv_sec++;
|
||||
dl->tv_nsec -= 1000000000L;
|
||||
}
|
||||
}
|
||||
|
||||
// Wait on c (with m held) until signalled. Returns 0 when signalled, ETIMEDOUT when the deadline passed.
|
||||
// ticks == portMAX_DELAY waits without a deadline.
|
||||
static int wait_on(pthread_cond_t *c, pthread_mutex_t *m, TickType_t ticks, const struct timespec *dl)
|
||||
{
|
||||
if (ticks == portMAX_DELAY) {
|
||||
return pthread_cond_wait(c, m);
|
||||
}
|
||||
return pthread_cond_timedwait(c, m, dl);
|
||||
}
|
||||
|
||||
/* ---- tasks ------------------------------------------------------------------------------------ */
|
||||
|
||||
struct desk_task {
|
||||
pthread_t th;
|
||||
char name[16];
|
||||
TaskFunction_t fn;
|
||||
void *arg;
|
||||
};
|
||||
|
||||
static __thread struct desk_task *t_self;
|
||||
static struct desk_task t_main = { .name = "main" };
|
||||
|
||||
static void *task_entry(void *p)
|
||||
{
|
||||
struct desk_task *t = p;
|
||||
t_self = t;
|
||||
t->fn(t->arg);
|
||||
return NULL; // a FreeRTOS task must not return; here it ends its thread
|
||||
}
|
||||
|
||||
BaseType_t xTaskCreate(TaskFunction_t fn, const char *name, uint32_t stack_words, void *arg, UBaseType_t prio,
|
||||
TaskHandle_t *handle)
|
||||
{
|
||||
(void)prio; // scheduling is the host's
|
||||
struct desk_task *t = calloc(1, sizeof(*t));
|
||||
if (!t) {
|
||||
return pdFAIL;
|
||||
}
|
||||
snprintf(t->name, sizeof(t->name), "%s", name ? name : "task");
|
||||
t->fn = fn;
|
||||
t->arg = arg;
|
||||
pthread_attr_t attr;
|
||||
pthread_attr_init(&attr);
|
||||
pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
|
||||
size_t want = (size_t)stack_words * 16; // firmware stacks are in words; give the host plenty
|
||||
if (want < (size_t)512 * 1024) {
|
||||
want = (size_t)512 * 1024;
|
||||
}
|
||||
pthread_attr_setstacksize(&attr, want);
|
||||
int err = pthread_create(&t->th, &attr, task_entry, t);
|
||||
pthread_attr_destroy(&attr);
|
||||
if (err != 0) {
|
||||
free(t);
|
||||
return pdFAIL;
|
||||
}
|
||||
if (handle) {
|
||||
*handle = t;
|
||||
}
|
||||
return pdPASS;
|
||||
}
|
||||
|
||||
void vTaskDelete(TaskHandle_t task)
|
||||
{
|
||||
if (task == NULL || task == t_self) {
|
||||
pthread_exit(NULL); // self-delete: the thread ends, the handle is not reused
|
||||
}
|
||||
pthread_cancel(task->th);
|
||||
}
|
||||
|
||||
void vTaskDelay(TickType_t ticks)
|
||||
{
|
||||
if (ticks == 0) {
|
||||
sched_yield();
|
||||
return;
|
||||
}
|
||||
struct timespec ts = { .tv_sec = ticks / 1000, .tv_nsec = (long)(ticks % 1000) * 1000000L };
|
||||
while (nanosleep(&ts, &ts) != 0 && errno == EINTR) {
|
||||
}
|
||||
}
|
||||
|
||||
TaskHandle_t xTaskGetCurrentTaskHandle(void)
|
||||
{
|
||||
if (!t_self) {
|
||||
t_self = &t_main;
|
||||
}
|
||||
return t_self;
|
||||
}
|
||||
|
||||
/* ---- queues ----------------------------------------------------------------------------------- */
|
||||
|
||||
struct desk_queue {
|
||||
pthread_mutex_t m;
|
||||
pthread_cond_t not_empty;
|
||||
pthread_cond_t not_full;
|
||||
uint8_t *buf;
|
||||
UBaseType_t len;
|
||||
UBaseType_t item;
|
||||
UBaseType_t head;
|
||||
UBaseType_t count;
|
||||
};
|
||||
|
||||
QueueHandle_t xQueueCreate(UBaseType_t length, UBaseType_t item_size)
|
||||
{
|
||||
QueueHandle_t q = calloc(1, sizeof(*q));
|
||||
if (!q) {
|
||||
return NULL;
|
||||
}
|
||||
q->buf = calloc(length ? length : 1, item_size ? item_size : 1);
|
||||
if (!q->buf) {
|
||||
free(q);
|
||||
return NULL;
|
||||
}
|
||||
q->len = length;
|
||||
q->item = item_size;
|
||||
pthread_mutex_init(&q->m, NULL);
|
||||
pthread_cond_init(&q->not_empty, NULL);
|
||||
pthread_cond_init(&q->not_full, NULL);
|
||||
return q;
|
||||
}
|
||||
|
||||
void vQueueDelete(QueueHandle_t q)
|
||||
{
|
||||
if (!q) return;
|
||||
pthread_mutex_destroy(&q->m);
|
||||
pthread_cond_destroy(&q->not_empty);
|
||||
pthread_cond_destroy(&q->not_full);
|
||||
free(q->buf);
|
||||
free(q);
|
||||
}
|
||||
|
||||
static BaseType_t queue_send(QueueHandle_t q, const void *item, TickType_t ticks)
|
||||
{
|
||||
struct timespec dl;
|
||||
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
|
||||
pthread_mutex_lock(&q->m);
|
||||
while (q->count == q->len) {
|
||||
if (ticks == 0 || wait_on(&q->not_full, &q->m, ticks, &dl) != 0) {
|
||||
pthread_mutex_unlock(&q->m);
|
||||
return pdFAIL;
|
||||
}
|
||||
}
|
||||
UBaseType_t slot = (q->head + q->count) % q->len;
|
||||
memcpy(q->buf + (size_t)slot * q->item, item, q->item);
|
||||
q->count++;
|
||||
pthread_cond_signal(&q->not_empty);
|
||||
pthread_mutex_unlock(&q->m);
|
||||
return pdTRUE;
|
||||
}
|
||||
|
||||
BaseType_t xQueueSend(QueueHandle_t q, const void *item, TickType_t ticks)
|
||||
{
|
||||
return queue_send(q, item, ticks);
|
||||
}
|
||||
|
||||
BaseType_t xQueueSendToBack(QueueHandle_t q, const void *item, TickType_t ticks)
|
||||
{
|
||||
return queue_send(q, item, ticks);
|
||||
}
|
||||
|
||||
BaseType_t xQueueReceive(QueueHandle_t q, void *item, TickType_t ticks)
|
||||
{
|
||||
struct timespec dl;
|
||||
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
|
||||
pthread_mutex_lock(&q->m);
|
||||
while (q->count == 0) {
|
||||
if (ticks == 0 || wait_on(&q->not_empty, &q->m, ticks, &dl) != 0) {
|
||||
pthread_mutex_unlock(&q->m);
|
||||
return pdFAIL;
|
||||
}
|
||||
}
|
||||
memcpy(item, q->buf + (size_t)q->head * q->item, q->item);
|
||||
q->head = (q->head + 1) % q->len;
|
||||
q->count--;
|
||||
pthread_cond_signal(&q->not_full);
|
||||
pthread_mutex_unlock(&q->m);
|
||||
return pdTRUE;
|
||||
}
|
||||
|
||||
UBaseType_t uxQueueMessagesWaiting(QueueHandle_t q)
|
||||
{
|
||||
pthread_mutex_lock(&q->m);
|
||||
UBaseType_t n = q->count;
|
||||
pthread_mutex_unlock(&q->m);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ---- semaphores ------------------------------------------------------------------------------- */
|
||||
|
||||
struct desk_sem {
|
||||
pthread_mutex_t m;
|
||||
pthread_cond_t c;
|
||||
UBaseType_t count; // free "tokens"
|
||||
UBaseType_t max;
|
||||
int recursive; // the owning task may take it again
|
||||
pthread_t owner;
|
||||
UBaseType_t depth; // takes by the owner not yet given back
|
||||
};
|
||||
|
||||
static SemaphoreHandle_t sem_new(UBaseType_t init, UBaseType_t max, int recursive)
|
||||
{
|
||||
SemaphoreHandle_t s = calloc(1, sizeof(*s));
|
||||
if (!s) return NULL;
|
||||
s->count = init;
|
||||
s->max = max;
|
||||
s->recursive = recursive;
|
||||
pthread_mutex_init(&s->m, NULL);
|
||||
pthread_cond_init(&s->c, NULL);
|
||||
return s;
|
||||
}
|
||||
|
||||
SemaphoreHandle_t xSemaphoreCreateMutex(void)
|
||||
{
|
||||
return sem_new(1, 1, 0);
|
||||
}
|
||||
|
||||
SemaphoreHandle_t xSemaphoreCreateRecursiveMutex(void)
|
||||
{
|
||||
return sem_new(1, 1, 1);
|
||||
}
|
||||
|
||||
SemaphoreHandle_t xSemaphoreCreateBinary(void)
|
||||
{
|
||||
return sem_new(0, 1, 0);
|
||||
}
|
||||
|
||||
SemaphoreHandle_t xSemaphoreCreateCounting(UBaseType_t max, UBaseType_t initial)
|
||||
{
|
||||
return sem_new(initial, max, 0);
|
||||
}
|
||||
|
||||
void vSemaphoreDelete(SemaphoreHandle_t s)
|
||||
{
|
||||
if (!s) return;
|
||||
pthread_mutex_destroy(&s->m);
|
||||
pthread_cond_destroy(&s->c);
|
||||
free(s);
|
||||
}
|
||||
|
||||
static BaseType_t sem_take(SemaphoreHandle_t s, TickType_t ticks)
|
||||
{
|
||||
pthread_t me = pthread_self();
|
||||
struct timespec dl;
|
||||
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
|
||||
pthread_mutex_lock(&s->m);
|
||||
if (s->recursive && s->depth > 0 && pthread_equal(s->owner, me)) {
|
||||
s->depth++;
|
||||
pthread_mutex_unlock(&s->m);
|
||||
return pdTRUE;
|
||||
}
|
||||
while (s->count == 0) {
|
||||
if (ticks == 0 || wait_on(&s->c, &s->m, ticks, &dl) != 0) {
|
||||
pthread_mutex_unlock(&s->m);
|
||||
return pdFAIL;
|
||||
}
|
||||
}
|
||||
s->count--;
|
||||
s->owner = me;
|
||||
s->depth = 1;
|
||||
pthread_mutex_unlock(&s->m);
|
||||
return pdTRUE;
|
||||
}
|
||||
|
||||
static BaseType_t sem_give(SemaphoreHandle_t s)
|
||||
{
|
||||
pthread_mutex_lock(&s->m);
|
||||
if (s->recursive && s->depth > 1 && pthread_equal(s->owner, pthread_self())) {
|
||||
s->depth--;
|
||||
pthread_mutex_unlock(&s->m);
|
||||
return pdTRUE;
|
||||
}
|
||||
if (s->count >= s->max) {
|
||||
pthread_mutex_unlock(&s->m);
|
||||
return pdFAIL;
|
||||
}
|
||||
s->count++;
|
||||
s->depth = 0;
|
||||
pthread_cond_signal(&s->c);
|
||||
pthread_mutex_unlock(&s->m);
|
||||
return pdTRUE;
|
||||
}
|
||||
|
||||
BaseType_t xSemaphoreTake(SemaphoreHandle_t s, TickType_t ticks)
|
||||
{
|
||||
return sem_take(s, ticks);
|
||||
}
|
||||
|
||||
BaseType_t xSemaphoreTakeRecursive(SemaphoreHandle_t s, TickType_t ticks)
|
||||
{
|
||||
return sem_take(s, ticks);
|
||||
}
|
||||
|
||||
BaseType_t xSemaphoreGive(SemaphoreHandle_t s)
|
||||
{
|
||||
return sem_give(s);
|
||||
}
|
||||
|
||||
BaseType_t xSemaphoreGiveRecursive(SemaphoreHandle_t s)
|
||||
{
|
||||
return sem_give(s);
|
||||
}
|
||||
|
||||
BaseType_t xSemaphoreGiveFromISR(SemaphoreHandle_t s, BaseType_t *woken)
|
||||
{
|
||||
if (woken) *woken = pdFALSE;
|
||||
return sem_give(s);
|
||||
}
|
||||
|
||||
/* ---- stream buffers --------------------------------------------------------------------------- */
|
||||
|
||||
struct desk_stream {
|
||||
pthread_mutex_t m;
|
||||
pthread_cond_t not_empty;
|
||||
pthread_cond_t not_full;
|
||||
uint8_t *buf;
|
||||
size_t cap;
|
||||
size_t head;
|
||||
size_t count;
|
||||
};
|
||||
|
||||
StreamBufferHandle_t xStreamBufferCreate(size_t size, size_t trigger_level)
|
||||
{
|
||||
(void)trigger_level;
|
||||
StreamBufferHandle_t sb = calloc(1, sizeof(*sb));
|
||||
if (!sb) return NULL;
|
||||
sb->buf = malloc(size ? size : 1);
|
||||
if (!sb->buf) {
|
||||
free(sb);
|
||||
return NULL;
|
||||
}
|
||||
sb->cap = size;
|
||||
pthread_mutex_init(&sb->m, NULL);
|
||||
pthread_cond_init(&sb->not_empty, NULL);
|
||||
pthread_cond_init(&sb->not_full, NULL);
|
||||
return sb;
|
||||
}
|
||||
|
||||
void vStreamBufferDelete(StreamBufferHandle_t sb)
|
||||
{
|
||||
if (!sb) return;
|
||||
pthread_mutex_destroy(&sb->m);
|
||||
pthread_cond_destroy(&sb->not_empty);
|
||||
pthread_cond_destroy(&sb->not_full);
|
||||
free(sb->buf);
|
||||
free(sb);
|
||||
}
|
||||
|
||||
size_t xStreamBufferSend(StreamBufferHandle_t sb, const void *data, size_t len, TickType_t ticks)
|
||||
{
|
||||
struct timespec dl;
|
||||
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
|
||||
pthread_mutex_lock(&sb->m);
|
||||
while (sb->count == sb->cap) {
|
||||
if (ticks == 0 || wait_on(&sb->not_full, &sb->m, ticks, &dl) != 0) {
|
||||
pthread_mutex_unlock(&sb->m);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
size_t room = sb->cap - sb->count;
|
||||
size_t n = len < room ? len : room;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
sb->buf[(sb->head + sb->count + i) % sb->cap] = ((const uint8_t *)data)[i];
|
||||
}
|
||||
sb->count += n;
|
||||
pthread_cond_signal(&sb->not_empty);
|
||||
pthread_mutex_unlock(&sb->m);
|
||||
return n;
|
||||
}
|
||||
|
||||
size_t xStreamBufferReceive(StreamBufferHandle_t sb, void *data, size_t len, TickType_t ticks)
|
||||
{
|
||||
struct timespec dl;
|
||||
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
|
||||
pthread_mutex_lock(&sb->m);
|
||||
while (sb->count == 0) {
|
||||
if (ticks == 0 || wait_on(&sb->not_empty, &sb->m, ticks, &dl) != 0) {
|
||||
pthread_mutex_unlock(&sb->m);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
size_t n = len < sb->count ? len : sb->count;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
((uint8_t *)data)[i] = sb->buf[(sb->head + i) % sb->cap];
|
||||
}
|
||||
sb->head = (sb->head + n) % sb->cap;
|
||||
sb->count -= n;
|
||||
pthread_cond_signal(&sb->not_full);
|
||||
pthread_mutex_unlock(&sb->m);
|
||||
return n;
|
||||
}
|
||||
|
||||
BaseType_t xStreamBufferReset(StreamBufferHandle_t sb)
|
||||
{
|
||||
pthread_mutex_lock(&sb->m);
|
||||
sb->head = 0;
|
||||
sb->count = 0;
|
||||
pthread_cond_broadcast(&sb->not_full);
|
||||
pthread_mutex_unlock(&sb->m);
|
||||
return pdTRUE;
|
||||
}
|
||||
|
||||
size_t xStreamBufferBytesAvailable(StreamBufferHandle_t sb)
|
||||
{
|
||||
pthread_mutex_lock(&sb->m);
|
||||
size_t n = sb->count;
|
||||
pthread_mutex_unlock(&sb->m);
|
||||
return n;
|
||||
}
|
||||
|
||||
/* ---- event groups ----------------------------------------------------------------------------- */
|
||||
|
||||
struct desk_events {
|
||||
pthread_mutex_t m;
|
||||
pthread_cond_t c;
|
||||
EventBits_t bits;
|
||||
};
|
||||
|
||||
EventGroupHandle_t xEventGroupCreate(void)
|
||||
{
|
||||
EventGroupHandle_t g = calloc(1, sizeof(*g));
|
||||
if (!g) return NULL;
|
||||
pthread_mutex_init(&g->m, NULL);
|
||||
pthread_cond_init(&g->c, NULL);
|
||||
return g;
|
||||
}
|
||||
|
||||
void vEventGroupDelete(EventGroupHandle_t g)
|
||||
{
|
||||
if (!g) return;
|
||||
pthread_mutex_destroy(&g->m);
|
||||
pthread_cond_destroy(&g->c);
|
||||
free(g);
|
||||
}
|
||||
|
||||
EventBits_t xEventGroupSetBits(EventGroupHandle_t g, EventBits_t bits)
|
||||
{
|
||||
pthread_mutex_lock(&g->m);
|
||||
g->bits |= bits;
|
||||
EventBits_t now = g->bits;
|
||||
pthread_cond_broadcast(&g->c);
|
||||
pthread_mutex_unlock(&g->m);
|
||||
return now;
|
||||
}
|
||||
|
||||
EventBits_t xEventGroupClearBits(EventGroupHandle_t g, EventBits_t bits)
|
||||
{
|
||||
pthread_mutex_lock(&g->m);
|
||||
g->bits &= ~bits;
|
||||
EventBits_t now = g->bits;
|
||||
pthread_mutex_unlock(&g->m);
|
||||
return now;
|
||||
}
|
||||
|
||||
EventBits_t xEventGroupWaitBits(EventGroupHandle_t g, EventBits_t bits, BaseType_t clear_on_exit,
|
||||
BaseType_t wait_all, TickType_t ticks)
|
||||
{
|
||||
struct timespec dl;
|
||||
if (ticks != portMAX_DELAY) make_deadline(ticks, &dl);
|
||||
pthread_mutex_lock(&g->m);
|
||||
for (;;) {
|
||||
EventBits_t got = g->bits & bits;
|
||||
bool ok = wait_all ? got == bits : got != 0;
|
||||
if (ok) {
|
||||
if (clear_on_exit) {
|
||||
g->bits &= ~bits;
|
||||
}
|
||||
pthread_mutex_unlock(&g->m);
|
||||
return got;
|
||||
}
|
||||
if (ticks == 0 || wait_on(&g->c, &g->m, ticks, &dl) != 0) {
|
||||
EventBits_t now = g->bits;
|
||||
pthread_mutex_unlock(&g->m);
|
||||
return now;
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,371 @@
|
||||
/*
|
||||
* Minimal mDNS browser for the desktop build, behind the ESP-IDF mdns API used by wifi_drv.c.
|
||||
* It sends a PTR query for _service._proto.local from an ephemeral port, so responders answer unicast,
|
||||
* then reads PTR, SRV, TXT and A answers until the timeout. Only the parts of RFC 6762/1035 these need.
|
||||
*/
|
||||
#include <arpa/inet.h>
|
||||
#include <stdbool.h>
|
||||
#include <netinet/in.h>
|
||||
#include <poll.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include "esp_err.h"
|
||||
#include "esp_log.h"
|
||||
#include "mdns.h"
|
||||
|
||||
#define MDNS_PORT 5353
|
||||
#define MAX_RECS 64
|
||||
#define NAME_MAX_LEN 256
|
||||
|
||||
|
||||
|
||||
typedef struct { char name[NAME_MAX_LEN]; char target[NAME_MAX_LEN]; } srv_rec_t;
|
||||
typedef struct { char name[NAME_MAX_LEN]; char items[8][80]; int n; } txt_rec_t;
|
||||
typedef struct { char name[NAME_MAX_LEN]; uint8_t ip[4]; } a_rec_t;
|
||||
typedef struct { char name[NAME_MAX_LEN]; } ptr_rec_t;
|
||||
|
||||
typedef struct {
|
||||
ptr_rec_t ptr[MAX_RECS];
|
||||
int nptr;
|
||||
srv_rec_t srv[MAX_RECS];
|
||||
int nsrv;
|
||||
txt_rec_t txt[MAX_RECS];
|
||||
int ntxt;
|
||||
a_rec_t a[MAX_RECS];
|
||||
int na;
|
||||
} browse_t;
|
||||
|
||||
static uint16_t rd16(const uint8_t *p)
|
||||
{
|
||||
return (uint16_t)((p[0] << 8) | p[1]);
|
||||
}
|
||||
|
||||
/* Decode a (possibly compressed) name at off. Sets *next to the byte after the name in place. */
|
||||
static bool decode_name(const uint8_t *m, size_t len, size_t off, char *out, size_t cap, size_t *next)
|
||||
{
|
||||
size_t o = off, n = 0, after = 0;
|
||||
bool jumped = false;
|
||||
int hops = 0;
|
||||
out[0] = '\0';
|
||||
for (;;) {
|
||||
if (o >= len || ++hops > 64) {
|
||||
return false;
|
||||
}
|
||||
uint8_t l = m[o];
|
||||
if ((l & 0xC0) == 0xC0) {
|
||||
if (o + 1 >= len) {
|
||||
return false;
|
||||
}
|
||||
if (!jumped) {
|
||||
after = o + 2;
|
||||
}
|
||||
jumped = true;
|
||||
o = (size_t)(((l & 0x3F) << 8) | m[o + 1]);
|
||||
continue;
|
||||
}
|
||||
if (l == 0) {
|
||||
o++;
|
||||
break;
|
||||
}
|
||||
if (l > 63 || o + 1 + l > len) {
|
||||
return false;
|
||||
}
|
||||
if (n) {
|
||||
if (n + 1 >= cap) {
|
||||
return false;
|
||||
}
|
||||
out[n++] = '.';
|
||||
}
|
||||
if (n + l >= cap) {
|
||||
return false;
|
||||
}
|
||||
memcpy(out + n, m + o + 1, l);
|
||||
n += l;
|
||||
o += 1 + l;
|
||||
}
|
||||
out[n] = '\0';
|
||||
if (next) {
|
||||
*next = jumped ? after : o;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
static void add_ptr(browse_t *b, const char *name)
|
||||
{
|
||||
if (b->nptr < MAX_RECS) {
|
||||
snprintf(b->ptr[b->nptr++].name, NAME_MAX_LEN, "%s", name);
|
||||
}
|
||||
}
|
||||
|
||||
static void handle_rr(browse_t *b, const uint8_t *m, size_t len, const char *name, uint16_t type, size_t rd, uint16_t rdlen)
|
||||
{
|
||||
char tmp[NAME_MAX_LEN];
|
||||
switch (type) {
|
||||
case 12: /* PTR */
|
||||
if (decode_name(m, len, rd, tmp, sizeof(tmp), NULL)) {
|
||||
if (!strcmp(name, "_http._tcp.local") && b->nptr < MAX_RECS) {
|
||||
add_ptr(b, tmp);
|
||||
}
|
||||
}
|
||||
break;
|
||||
case 33: /* SRV: priority, weight, port, target */
|
||||
if (rdlen > 6 && b->nsrv < MAX_RECS && decode_name(m, len, rd + 6, tmp, sizeof(tmp), NULL)) {
|
||||
srv_rec_t *s = &b->srv[b->nsrv++];
|
||||
snprintf(s->name, NAME_MAX_LEN, "%s", name);
|
||||
snprintf(s->target, NAME_MAX_LEN, "%s", tmp);
|
||||
}
|
||||
break;
|
||||
case 16: { /* TXT: length-prefixed strings */
|
||||
if (b->ntxt >= MAX_RECS) {
|
||||
break;
|
||||
}
|
||||
txt_rec_t *t = &b->txt[b->ntxt];
|
||||
snprintf(t->name, NAME_MAX_LEN, "%s", name);
|
||||
t->n = 0;
|
||||
size_t p = rd, end = rd + rdlen;
|
||||
while (p < end && t->n < 8) {
|
||||
size_t l = m[p];
|
||||
if (p + 1 + l > end) {
|
||||
break;
|
||||
}
|
||||
size_t copy = l < sizeof(t->items[0]) - 1 ? l : sizeof(t->items[0]) - 1;
|
||||
memcpy(t->items[t->n], m + p + 1, copy);
|
||||
t->items[t->n][copy] = '\0';
|
||||
t->n++;
|
||||
p += 1 + l;
|
||||
}
|
||||
b->ntxt++;
|
||||
break;
|
||||
}
|
||||
case 1: /* A */
|
||||
if (rdlen == 4 && b->na < MAX_RECS) {
|
||||
a_rec_t *a = &b->a[b->na++];
|
||||
snprintf(a->name, NAME_MAX_LEN, "%s", name);
|
||||
memcpy(a->ip, m + rd, 4);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
static void parse_packet(browse_t *b, const uint8_t *m, size_t len)
|
||||
{
|
||||
if (len < 12) {
|
||||
return;
|
||||
}
|
||||
uint16_t qd = rd16(m + 4), an = rd16(m + 6), ns = rd16(m + 8), ar = rd16(m + 10);
|
||||
size_t o = 12;
|
||||
char name[NAME_MAX_LEN];
|
||||
for (int i = 0; i < qd; i++) {
|
||||
if (!decode_name(m, len, o, name, sizeof(name), &o) || o + 4 > len) {
|
||||
return;
|
||||
}
|
||||
o += 4;
|
||||
}
|
||||
int total = an + ns + ar;
|
||||
for (int i = 0; i < total; i++) {
|
||||
if (!decode_name(m, len, o, name, sizeof(name), &o) || o + 10 > len) {
|
||||
return;
|
||||
}
|
||||
uint16_t type = rd16(m + o);
|
||||
uint16_t rdlen = rd16(m + o + 8);
|
||||
size_t rd = o + 10;
|
||||
if (rd + rdlen > len) {
|
||||
return;
|
||||
}
|
||||
handle_rr(b, m, len, name, type, rd, rdlen);
|
||||
o = rd + rdlen;
|
||||
}
|
||||
}
|
||||
|
||||
/* DNS query for PTR _service._proto.local */
|
||||
static size_t build_query(uint8_t *buf, size_t cap, const char *name)
|
||||
{
|
||||
size_t o = 12;
|
||||
memset(buf, 0, 12);
|
||||
buf[5] = 1; /* one question */
|
||||
const char *p = name;
|
||||
while (*p) {
|
||||
const char *dot = strchr(p, '.');
|
||||
size_t l = dot ? (size_t)(dot - p) : strlen(p);
|
||||
if (l == 0 || l > 63 || o + 1 + l + 6 > cap) {
|
||||
return 0;
|
||||
}
|
||||
buf[o++] = (uint8_t)l;
|
||||
memcpy(buf + o, p, l);
|
||||
o += l;
|
||||
if (!dot) {
|
||||
break;
|
||||
}
|
||||
p = dot + 1;
|
||||
}
|
||||
buf[o++] = 0;
|
||||
buf[o++] = 0; /* PTR */
|
||||
buf[o++] = 12;
|
||||
buf[o++] = 0; /* IN, not unicast-response */
|
||||
buf[o++] = 1;
|
||||
return o;
|
||||
}
|
||||
|
||||
static char *mdns_dup(const char *s)
|
||||
{
|
||||
return strdup(s ? s : "");
|
||||
}
|
||||
|
||||
esp_err_t mdns_query_ptr(const char *service, const char *proto, uint32_t timeout_ms, size_t max_results,
|
||||
mdns_result_t **results)
|
||||
{
|
||||
*results = NULL;
|
||||
char qname[160];
|
||||
snprintf(qname, sizeof(qname), "%s.%s.local", service, proto); /* the caller gives "_http", "_tcp" */
|
||||
/* the query is not sent to the app's own names, so the search is only for the given service */
|
||||
uint8_t q[256];
|
||||
size_t qlen = build_query(q, sizeof(q), qname);
|
||||
if (!qlen) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
int fd = socket(AF_INET, SOCK_DGRAM, 0);
|
||||
if (fd < 0) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
struct sockaddr_in dst = { .sin_family = AF_INET, .sin_port = htons(MDNS_PORT) };
|
||||
inet_pton(AF_INET, "224.0.0.251", &dst.sin_addr);
|
||||
|
||||
browse_t *b = calloc(1, sizeof(*b));
|
||||
if (!b) {
|
||||
close(fd);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
struct timespec t0;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t0);
|
||||
int64_t start = (int64_t)t0.tv_sec * 1000 + t0.tv_nsec / 1000000;
|
||||
int64_t sent_at = -1000000;
|
||||
uint8_t pkt[2048];
|
||||
for (;;) {
|
||||
struct timespec t;
|
||||
clock_gettime(CLOCK_MONOTONIC, &t);
|
||||
int64_t now = (int64_t)t.tv_sec * 1000 + t.tv_nsec / 1000000;
|
||||
int64_t elapsed = now - start;
|
||||
if (elapsed >= (int64_t)timeout_ms) {
|
||||
break;
|
||||
}
|
||||
if (now - sent_at >= (int64_t)timeout_ms / 2 + 1 && elapsed < (int64_t)timeout_ms / 2) {
|
||||
sendto(fd, q, qlen, 0, (struct sockaddr *)&dst, sizeof(dst)); /* a second query, for lost packets */
|
||||
sent_at = now;
|
||||
} else if (sent_at < 0) {
|
||||
sendto(fd, q, qlen, 0, (struct sockaddr *)&dst, sizeof(dst));
|
||||
sent_at = now;
|
||||
}
|
||||
struct pollfd pfd = { .fd = fd, .events = POLLIN };
|
||||
int wait = (int)((int64_t)timeout_ms - elapsed);
|
||||
if (wait > 100) {
|
||||
wait = 100;
|
||||
}
|
||||
if (poll(&pfd, 1, wait) > 0 && (pfd.revents & POLLIN)) {
|
||||
ssize_t n = recv(fd, pkt, sizeof(pkt), 0);
|
||||
if (n > 0) {
|
||||
parse_packet(b, pkt, (size_t)n);
|
||||
}
|
||||
}
|
||||
}
|
||||
close(fd);
|
||||
|
||||
/* Build one result per instance that has a PTR, an SRV and an A record for its target */
|
||||
mdns_result_t *head = NULL, **tail = &head;
|
||||
size_t count = 0;
|
||||
for (int i = 0; i < b->nptr && count < max_results; i++) {
|
||||
const char *inst = b->ptr[i].name;
|
||||
const srv_rec_t *srv = NULL;
|
||||
for (int k = 0; k < b->nsrv && !srv; k++) {
|
||||
if (!strcmp(b->srv[k].name, inst)) {
|
||||
srv = &b->srv[k];
|
||||
}
|
||||
}
|
||||
if (!srv) {
|
||||
continue;
|
||||
}
|
||||
mdns_result_t *r = calloc(1, sizeof(*r));
|
||||
if (!r) {
|
||||
break;
|
||||
}
|
||||
r->instance_name = mdns_dup(inst);
|
||||
/* the SRV target is host.local: the hostname without the suffix */
|
||||
char host[NAME_MAX_LEN];
|
||||
snprintf(host, sizeof(host), "%s", srv->target);
|
||||
size_t hl = strlen(host);
|
||||
if (hl > 6 && !strcmp(host + hl - 6, ".local")) {
|
||||
host[hl - 6] = '\0';
|
||||
}
|
||||
r->hostname = mdns_dup(host);
|
||||
for (int k = 0; k < b->ntxt; k++) {
|
||||
if (!strcmp(b->txt[k].name, inst)) {
|
||||
r->txt_count = (size_t)b->txt[k].n;
|
||||
r->txt = calloc(r->txt_count ? r->txt_count : 1, sizeof(mdns_txt_item_t));
|
||||
for (size_t j = 0; r->txt && j < r->txt_count; j++) {
|
||||
char *eq = strchr(b->txt[k].items[j], '=');
|
||||
if (eq) {
|
||||
*eq = '\0';
|
||||
r->txt[j].key = mdns_dup(b->txt[k].items[j]);
|
||||
r->txt[j].value = mdns_dup(eq + 1);
|
||||
*eq = '=';
|
||||
} else {
|
||||
r->txt[j].key = mdns_dup(b->txt[k].items[j]);
|
||||
r->txt[j].value = mdns_dup("");
|
||||
}
|
||||
}
|
||||
break;
|
||||
}
|
||||
}
|
||||
mdns_ip_addr_t **at = &r->addr;
|
||||
for (int k = 0; k < b->na; k++) {
|
||||
if (!strcmp(b->a[k].name, srv->target)) {
|
||||
mdns_ip_addr_t *a = calloc(1, sizeof(*a));
|
||||
if (a) {
|
||||
a->addr.type = ESP_IPADDR_TYPE_V4;
|
||||
memcpy(&a->addr.u_addr.ip4.addr, b->a[k].ip, 4);
|
||||
*at = a;
|
||||
at = &a->next;
|
||||
}
|
||||
}
|
||||
}
|
||||
*tail = r;
|
||||
tail = &r->next;
|
||||
count++;
|
||||
}
|
||||
free(b);
|
||||
if (!head) {
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
*results = head;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void mdns_query_results_free(mdns_result_t *results)
|
||||
{
|
||||
while (results) {
|
||||
mdns_result_t *next = results->next;
|
||||
free(results->instance_name);
|
||||
free(results->hostname);
|
||||
for (size_t i = 0; i < results->txt_count && results->txt; i++) {
|
||||
free(results->txt[i].key);
|
||||
free(results->txt[i].value);
|
||||
}
|
||||
free(results->txt);
|
||||
mdns_ip_addr_t *a = results->addr;
|
||||
while (a) {
|
||||
mdns_ip_addr_t *an = a->next;
|
||||
free(a);
|
||||
a = an;
|
||||
}
|
||||
free(results);
|
||||
results = next;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,440 @@
|
||||
/*
|
||||
* Desktop microphone: captures from a Linux ALSA capture device (a USB mic such as the Blue Snowball) and feeds
|
||||
* the same level meter, beat detector and /audio.wav stream as the board's I2S mic.c. Only the devices named by
|
||||
* mic_list_devices() are selectable: plughw:CARD=... capture devices, which convert to 16 kHz mono for us.
|
||||
*/
|
||||
#include <alsa/asoundlib.h>
|
||||
#include <errno.h>
|
||||
#include <math.h>
|
||||
#include <pthread.h>
|
||||
#include <stdbool.h>
|
||||
#include <stdint.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <time.h>
|
||||
#include <unistd.h>
|
||||
#include "cJSON.h"
|
||||
#include "esp_log.h"
|
||||
#include "beat.h"
|
||||
#include "bridge.h"
|
||||
#include "mic.h"
|
||||
|
||||
#define BRIDGE_DEVICE "bridge:mic" // the microphone of a bridge board (bridge/, ESP32-S3), see bridge_serial.h
|
||||
|
||||
#define BLOCK_FRAMES (MIC_SAMPLE_RATE / 50) // 20 ms per read
|
||||
#define LEVEL_BLOCKS 5 // 100 ms per level reading
|
||||
#define RING_SAMPLES MIC_SAMPLE_RATE // 1 s of 16-bit mono for the stream
|
||||
#define DBFS_FLOOR -120.0f
|
||||
#define SPL_OFFSET 120.0f // same nominal offset as the I2S mic; not calibrated for USB mics
|
||||
#define DEVICE_NAME_MAX 128
|
||||
|
||||
static const char *TAG = "mic_alsa";
|
||||
|
||||
static pthread_mutex_t s_lock = PTHREAD_MUTEX_INITIALIZER;
|
||||
static pthread_cond_t s_cond = PTHREAD_COND_INITIALIZER;
|
||||
static bool s_open; // capture wanted (set by mic_open / mic_close)
|
||||
static uint64_t s_gen; // bumped by mic_open so the capture thread reopens the device
|
||||
static char s_device[DEVICE_NAME_MAX] = "default";
|
||||
static mic_level_t s_level = { DBFS_FLOOR, DBFS_FLOOR, DBFS_FLOOR + SPL_OFFSET };
|
||||
static char s_error[160]; // why the last open failed, "" when it works
|
||||
|
||||
static bool s_streaming;
|
||||
static int16_t s_ring[RING_SAMPLES];
|
||||
static size_t s_ring_fill; // samples waiting in the ring, oldest first from s_ring_head
|
||||
static size_t s_ring_head;
|
||||
|
||||
static float to_dbfs(float x)
|
||||
{
|
||||
return x > 0.0f ? fmaxf(20.0f * log10f(x), DBFS_FLOOR) : DBFS_FLOOR;
|
||||
}
|
||||
|
||||
// Called with s_lock held: a block of 16-bit samples for the stream listener, dropped when it is full
|
||||
static void ring_push_locked(const int16_t *pcm, size_t n)
|
||||
{
|
||||
if (!s_streaming || s_ring_fill + n > RING_SAMPLES) {
|
||||
return;
|
||||
}
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
s_ring[(s_ring_head + s_ring_fill + i) % RING_SAMPLES] = pcm[i];
|
||||
}
|
||||
s_ring_fill += n;
|
||||
pthread_cond_broadcast(&s_cond);
|
||||
}
|
||||
|
||||
static void reset_level_locked(void)
|
||||
{
|
||||
s_level.rms_dbfs = DBFS_FLOOR;
|
||||
s_level.peak_dbfs = DBFS_FLOOR;
|
||||
s_level.spl_db = DBFS_FLOOR + SPL_OFFSET;
|
||||
}
|
||||
|
||||
// Per-stream state of the level meter and high-pass filter, see process_block
|
||||
typedef struct {
|
||||
float hp_in, hp_out;
|
||||
double sum_sq;
|
||||
float peak;
|
||||
size_t frames;
|
||||
size_t blocks;
|
||||
} proc_t;
|
||||
|
||||
// One block of 16-bit mono at MIC_SAMPLE_RATE: level meter, beat detector and the stream listener's copy
|
||||
static void process_block(proc_t *p, const int16_t *raw, size_t frames)
|
||||
{
|
||||
static float filtered[BLOCK_FRAMES];
|
||||
static int16_t pcm_out[BLOCK_FRAMES];
|
||||
const float gain = CONFIG_MIC_STREAM_GAIN;
|
||||
for (size_t i = 0; i < frames; i++) {
|
||||
float x = (float)raw[i] / 32768.0f;
|
||||
float y = x - p->hp_in + 0.995f * p->hp_out; // one-pole high-pass, as in mic.c
|
||||
p->hp_in = x;
|
||||
p->hp_out = y;
|
||||
filtered[i] = y;
|
||||
p->sum_sq += (double)y * y;
|
||||
p->peak = fmaxf(p->peak, fabsf(y));
|
||||
pcm_out[i] = (int16_t)fmaxf(fminf(y * gain * 32767.0f, 32767.0f), -32768.0f);
|
||||
}
|
||||
p->frames += frames;
|
||||
beat_feed(filtered, frames);
|
||||
|
||||
pthread_mutex_lock(&s_lock);
|
||||
ring_push_locked(pcm_out, frames);
|
||||
if (++p->blocks >= LEVEL_BLOCKS) {
|
||||
s_level.rms_dbfs = to_dbfs(sqrtf((float)(p->sum_sq / p->frames)));
|
||||
s_level.peak_dbfs = to_dbfs(p->peak);
|
||||
s_level.spl_db = s_level.rms_dbfs + SPL_OFFSET;
|
||||
p->sum_sq = 0.0;
|
||||
p->peak = 0.0f;
|
||||
p->frames = p->blocks = 0;
|
||||
}
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
}
|
||||
|
||||
// Read blocks from one open device until it fails or mic_open/mic_close changes the request
|
||||
static void capture_loop(snd_pcm_t *pcm, uint64_t gen)
|
||||
{
|
||||
static int16_t raw[BLOCK_FRAMES];
|
||||
proc_t p = { 0 };
|
||||
|
||||
for (;;) {
|
||||
pthread_mutex_lock(&s_lock);
|
||||
bool keep = s_open && s_gen == gen;
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
if (!keep) {
|
||||
return;
|
||||
}
|
||||
|
||||
snd_pcm_sframes_t n = snd_pcm_readi(pcm, raw, BLOCK_FRAMES);
|
||||
if (n < 0) {
|
||||
if (snd_pcm_recover(pcm, (int)n, 1) < 0) {
|
||||
ESP_LOGW(TAG, "capture read failed: %s", snd_strerror((int)n));
|
||||
return;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
process_block(&p, raw, (size_t)n);
|
||||
}
|
||||
}
|
||||
|
||||
// Audio from a bridge board: the bridge's link task calls this while the bridge device is selected
|
||||
static proc_t s_bridge_proc;
|
||||
static void on_bridge_audio(const int16_t *pcm, size_t n)
|
||||
{
|
||||
pthread_mutex_lock(&s_lock);
|
||||
bool mine = s_open && !strcmp(s_device, BRIDGE_DEVICE);
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
if (mine) {
|
||||
process_block(&s_bridge_proc, pcm, n);
|
||||
}
|
||||
}
|
||||
|
||||
static void *capture_thread(void *arg)
|
||||
{
|
||||
(void)arg;
|
||||
for (;;) {
|
||||
pthread_mutex_lock(&s_lock);
|
||||
bool open = s_open;
|
||||
uint64_t gen = s_gen;
|
||||
char name[DEVICE_NAME_MAX];
|
||||
memcpy(name, s_device, sizeof(name));
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
|
||||
if (!open || !strcmp(name, BRIDGE_DEVICE)) {
|
||||
usleep(100 * 1000); // idle: a bridge device is fed by on_bridge_audio
|
||||
continue;
|
||||
}
|
||||
|
||||
// "pulse:<source>" is a PipeWire/PulseAudio source, opened through the pulse ALSA plugin
|
||||
const char *pcm_name = name;
|
||||
if (!strncmp(name, "pulse:", 6)) {
|
||||
setenv("PULSE_SOURCE", name + 6, 1);
|
||||
pcm_name = "pulse";
|
||||
}
|
||||
snd_pcm_t *pcm = NULL;
|
||||
int err = snd_pcm_open(&pcm, pcm_name, SND_PCM_STREAM_CAPTURE, 0);
|
||||
if (err < 0) {
|
||||
ESP_LOGW(TAG, "cannot open %s: %s", name, snd_strerror(err));
|
||||
pthread_mutex_lock(&s_lock);
|
||||
snprintf(s_error, sizeof(s_error), "Cannot open %s: %s", name, snd_strerror(err));
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
sleep(1);
|
||||
continue;
|
||||
}
|
||||
err = snd_pcm_set_params(pcm, SND_PCM_FORMAT_S16_LE, SND_PCM_ACCESS_RW_INTERLEAVED, 1,
|
||||
MIC_SAMPLE_RATE, 1, 500000);
|
||||
if (err < 0) {
|
||||
ESP_LOGW(TAG, "cannot set %s to %d Hz mono: %s", name, MIC_SAMPLE_RATE, snd_strerror(err));
|
||||
snd_pcm_close(pcm);
|
||||
sleep(1);
|
||||
continue;
|
||||
}
|
||||
ESP_LOGI(TAG, "capturing from %s", name);
|
||||
pthread_mutex_lock(&s_lock);
|
||||
s_error[0] = '\0';
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
capture_loop(pcm, gen);
|
||||
snd_pcm_drop(pcm);
|
||||
snd_pcm_close(pcm);
|
||||
|
||||
pthread_mutex_lock(&s_lock);
|
||||
if (s_gen == gen) {
|
||||
reset_level_locked();
|
||||
}
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
esp_err_t mic_start(void)
|
||||
{
|
||||
esp_err_t err = beat_start(MIC_SAMPLE_RATE);
|
||||
if (err != ESP_OK) {
|
||||
return err;
|
||||
}
|
||||
bridge_set_audio_cb(on_bridge_audio);
|
||||
pthread_t t;
|
||||
if (pthread_create(&t, NULL, capture_thread, NULL) != 0) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
pthread_detach(t);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void mic_get_level(mic_level_t *out)
|
||||
{
|
||||
pthread_mutex_lock(&s_lock);
|
||||
*out = s_level;
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
}
|
||||
|
||||
esp_err_t mic_open(const char *device)
|
||||
{
|
||||
if (!device || !device[0]) {
|
||||
device = "default";
|
||||
}
|
||||
if (strlen(device) >= DEVICE_NAME_MAX) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
bool bridge = !strcmp(device, BRIDGE_DEVICE);
|
||||
if (bridge && !bridge_has_mic()) {
|
||||
pthread_mutex_lock(&s_lock);
|
||||
snprintf(s_error, sizeof(s_error), "No bridge board with a microphone is connected");
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
if (bridge && bridge_mic(true) != ESP_OK) {
|
||||
pthread_mutex_lock(&s_lock);
|
||||
snprintf(s_error, sizeof(s_error), "The bridge microphone did not start");
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
return ESP_ERR_NOT_SUPPORTED;
|
||||
}
|
||||
pthread_mutex_lock(&s_lock);
|
||||
strcpy(s_device, device);
|
||||
s_open = true;
|
||||
s_gen++;
|
||||
s_ring_fill = 0;
|
||||
s_bridge_proc = (proc_t){ 0 };
|
||||
s_error[0] = '\0';
|
||||
reset_level_locked();
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void mic_close(void)
|
||||
{
|
||||
pthread_mutex_lock(&s_lock);
|
||||
s_open = false;
|
||||
s_gen++;
|
||||
reset_level_locked();
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
bridge_mic(false); // harmless when no bridge is attached
|
||||
}
|
||||
|
||||
void mic_error(char *out, size_t len)
|
||||
{
|
||||
pthread_mutex_lock(&s_lock);
|
||||
snprintf(out, len, "%s", s_error);
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
}
|
||||
|
||||
bool mic_is_open(void)
|
||||
{
|
||||
pthread_mutex_lock(&s_lock);
|
||||
bool open = s_open;
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
return open;
|
||||
}
|
||||
|
||||
esp_err_t mic_stream_open(void)
|
||||
{
|
||||
pthread_mutex_lock(&s_lock);
|
||||
if (s_streaming) {
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
s_streaming = true;
|
||||
s_ring_fill = 0;
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
size_t mic_stream_read(void *buf, size_t len, TickType_t timeout)
|
||||
{
|
||||
struct timespec deadline;
|
||||
clock_gettime(CLOCK_REALTIME, &deadline);
|
||||
long ms = (long)(timeout * portTICK_PERIOD_MS);
|
||||
deadline.tv_sec += ms / 1000;
|
||||
deadline.tv_nsec += (ms % 1000) * 1000000L;
|
||||
if (deadline.tv_nsec >= 1000000000L) {
|
||||
deadline.tv_sec++;
|
||||
deadline.tv_nsec -= 1000000000L;
|
||||
}
|
||||
|
||||
pthread_mutex_lock(&s_lock);
|
||||
while (s_ring_fill == 0) {
|
||||
if (pthread_cond_timedwait(&s_cond, &s_lock, &deadline) == ETIMEDOUT) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
size_t want = len / sizeof(int16_t);
|
||||
size_t n = want < s_ring_fill ? want : s_ring_fill;
|
||||
uint8_t *out = buf;
|
||||
for (size_t i = 0; i < n; i++) {
|
||||
int16_t v = s_ring[(s_ring_head + i) % RING_SAMPLES];
|
||||
out[2 * i] = (uint8_t)(v & 0xFF);
|
||||
out[2 * i + 1] = (uint8_t)((uint16_t)v >> 8);
|
||||
}
|
||||
s_ring_head = (s_ring_head + n) % RING_SAMPLES;
|
||||
s_ring_fill -= n;
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
return n * sizeof(int16_t);
|
||||
}
|
||||
|
||||
void mic_stream_close(void)
|
||||
{
|
||||
pthread_mutex_lock(&s_lock);
|
||||
s_streaming = false;
|
||||
pthread_mutex_unlock(&s_lock);
|
||||
}
|
||||
|
||||
// Input sources the desktop can record from. On a PipeWire/PulseAudio desktop the USB mic is shared through the
|
||||
// sound server, so it is listed as a pulse source (pactl). Otherwise the raw ALSA plughw:CARD=... inputs are used.
|
||||
static int list_alsa_devices(mic_device_t *out, int max);
|
||||
|
||||
static int list_pulse_sources(mic_device_t *out, int max)
|
||||
{
|
||||
FILE *p = popen("pactl -f json list sources 2>/dev/null", "r");
|
||||
if (!p) {
|
||||
return 0;
|
||||
}
|
||||
char *buf = NULL;
|
||||
size_t cap = 0, len = 0;
|
||||
for (;;) {
|
||||
if (len + 4096 > cap) {
|
||||
cap = cap ? cap * 2 : 8192;
|
||||
buf = realloc(buf, cap);
|
||||
if (!buf) {
|
||||
pclose(p);
|
||||
return 0;
|
||||
}
|
||||
}
|
||||
size_t got = fread(buf + len, 1, cap - len - 1, p);
|
||||
if (got == 0) {
|
||||
break;
|
||||
}
|
||||
len += got;
|
||||
}
|
||||
pclose(p);
|
||||
buf[len] = '\0';
|
||||
int count = 0;
|
||||
cJSON *list = cJSON_Parse(buf);
|
||||
free(buf);
|
||||
for (const cJSON *src = list ? list->child : NULL; src && count < max; src = src->next) {
|
||||
const cJSON *name = cJSON_GetObjectItem(src, "name");
|
||||
const cJSON *desc = cJSON_GetObjectItem(src, "description");
|
||||
if (!cJSON_IsString(name) || strncmp(name->valuestring, "alsa_input.", 11) != 0) {
|
||||
continue; // monitors and other sources
|
||||
}
|
||||
mic_device_t *d = &out[count];
|
||||
if (strlen(name->valuestring) + 6 >= sizeof(d->id)) {
|
||||
continue;
|
||||
}
|
||||
snprintf(d->id, sizeof(d->id), "pulse:%s", name->valuestring);
|
||||
snprintf(d->name, sizeof(d->name), "%s", cJSON_IsString(desc) ? desc->valuestring : name->valuestring);
|
||||
snprintf(d->label, sizeof(d->label), "%s", name->valuestring);
|
||||
count++;
|
||||
}
|
||||
cJSON_Delete(list);
|
||||
return count;
|
||||
}
|
||||
|
||||
int mic_list_devices(mic_device_t *out, int max)
|
||||
{
|
||||
int count = 0;
|
||||
if (bridge_has_mic() && max > 0) {
|
||||
mic_device_t *d = &out[count++];
|
||||
snprintf(d->id, sizeof(d->id), "%s", BRIDGE_DEVICE);
|
||||
snprintf(d->name, sizeof(d->name), "I2S microphone on the bridge board");
|
||||
snprintf(d->label, sizeof(d->label), "%s", BRIDGE_DEVICE);
|
||||
}
|
||||
int more = list_pulse_sources(out + count, max - count);
|
||||
if (more == 0) {
|
||||
more = list_alsa_devices(out + count, max - count);
|
||||
}
|
||||
return count + more;
|
||||
}
|
||||
|
||||
// Raw ALSA capture devices: each plughw:CARD=... input (ALSA converts to our format)
|
||||
static int list_alsa_devices(mic_device_t *out, int max)
|
||||
{
|
||||
void **hints = NULL;
|
||||
int count = 0;
|
||||
if (snd_device_name_hint(-1, "pcm", &hints) < 0) {
|
||||
return 0;
|
||||
}
|
||||
for (void **h = hints; *h && count < max; h++) {
|
||||
char *name = snd_device_name_get_hint(*h, "NAME");
|
||||
char *desc = snd_device_name_get_hint(*h, "DESC");
|
||||
char *ioid = snd_device_name_get_hint(*h, "IOID");
|
||||
bool input = !ioid || !strcmp(ioid, "Input");
|
||||
if (name && input && !strncmp(name, "plughw:CARD=", 12) && strlen(name) < sizeof(out[count].id)) {
|
||||
mic_device_t *d = &out[count];
|
||||
strcpy(d->id, name);
|
||||
strcpy(d->label, name);
|
||||
// The description runs over several lines; the first is the device's name
|
||||
const char *first = desc ? desc : name;
|
||||
size_t len = strcspn(first, "\n");
|
||||
if (len >= sizeof(d->name)) {
|
||||
len = sizeof(d->name) - 1;
|
||||
}
|
||||
memcpy(d->name, first, len);
|
||||
d->name[len] = '\0';
|
||||
count++;
|
||||
}
|
||||
free(name);
|
||||
free(desc);
|
||||
free(ioid);
|
||||
}
|
||||
snd_device_name_free_hint(hints);
|
||||
return count;
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
/* The simulated rig's page and drivers (www_dist/sim.pack, built by tools/build_sim_web.sh), embedded in the
|
||||
* program and served at /sim/ (sim-controller/components/sim/sim_rig.c). SIM_PACK is the path, set by CMake. */
|
||||
#include <stdint.h>
|
||||
|
||||
#ifndef SIM_PACK
|
||||
#error "SIM_PACK must name www_dist/sim.pack"
|
||||
#endif
|
||||
|
||||
#define STR2(x) #x
|
||||
#define STR(x) STR2(x)
|
||||
|
||||
__asm__(
|
||||
".section .rodata\n"
|
||||
".balign 16\n"
|
||||
".global _binary_sim_pack_start\n"
|
||||
"_binary_sim_pack_start:\n"
|
||||
".incbin " STR(SIM_PACK) "\n"
|
||||
".global _binary_sim_pack_end\n"
|
||||
"_binary_sim_pack_end:\n"
|
||||
".byte 0\n"
|
||||
".previous\n");
|
||||
@@ -0,0 +1,21 @@
|
||||
/* The gzipped web UI (www_dist/www.pack, built by tools/build_web.sh), embedded in the program: the same
|
||||
* symbols the firmware's web.c reads on the board. WWW_PACK is the file's path, set by CMake. */
|
||||
#include <stdint.h>
|
||||
|
||||
#ifndef WWW_PACK
|
||||
#error "WWW_PACK must name www_dist/www.pack"
|
||||
#endif
|
||||
|
||||
#define STR2(x) #x
|
||||
#define STR(x) STR2(x)
|
||||
|
||||
__asm__(
|
||||
".section .rodata\n"
|
||||
".balign 16\n"
|
||||
".global _binary_www_pack_start\n"
|
||||
"_binary_www_pack_start:\n"
|
||||
".incbin " STR(WWW_PACK) "\n"
|
||||
".global _binary_www_pack_end\n"
|
||||
"_binary_www_pack_end:\n"
|
||||
".byte 0\n"
|
||||
".previous\n");
|
||||
Vendored
+20
@@ -0,0 +1,20 @@
|
||||
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
|
||||
Vendored
+3206
File diff suppressed because it is too large.
Load diff
Vendored
+306
@@ -0,0 +1,306 @@
|
||||
/*
|
||||
Copyright (c) 2009-2017 Dave Gamble and cJSON contributors
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
of this software and associated documentation files (the "Software"), to deal
|
||||
in the Software without restriction, including without limitation the rights
|
||||
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
||||
copies of the Software, and to permit persons to whom the Software is
|
||||
furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in
|
||||
all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
||||
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
|
||||
THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#ifndef cJSON__h
|
||||
#define cJSON__h
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C"
|
||||
{
|
||||
#endif
|
||||
|
||||
#if !defined(__WINDOWS__) && (defined(WIN32) || defined(WIN64) || defined(_MSC_VER) || defined(_WIN32))
|
||||
#define __WINDOWS__
|
||||
#endif
|
||||
|
||||
#ifdef __WINDOWS__
|
||||
|
||||
/* When compiling for windows, we specify a specific calling convention to avoid issues where we are being called from a project with a different default calling convention. For windows you have 3 define options:
|
||||
|
||||
CJSON_HIDE_SYMBOLS - Define this in the case where you don't want to ever dllexport symbols
|
||||
CJSON_EXPORT_SYMBOLS - Define this on library build when you want to dllexport symbols (default)
|
||||
CJSON_IMPORT_SYMBOLS - Define this if you want to dllimport symbol
|
||||
|
||||
For *nix builds that support visibility attribute, you can define similar behavior by
|
||||
|
||||
setting default visibility to hidden by adding
|
||||
-fvisibility=hidden (for gcc)
|
||||
or
|
||||
-xldscope=hidden (for sun cc)
|
||||
to CFLAGS
|
||||
|
||||
then using the CJSON_API_VISIBILITY flag to "export" the same symbols the way CJSON_EXPORT_SYMBOLS does
|
||||
|
||||
*/
|
||||
|
||||
#define CJSON_CDECL __cdecl
|
||||
#define CJSON_STDCALL __stdcall
|
||||
|
||||
/* export symbols by default, this is necessary for copy pasting the C and header file */
|
||||
#if !defined(CJSON_HIDE_SYMBOLS) && !defined(CJSON_IMPORT_SYMBOLS) && !defined(CJSON_EXPORT_SYMBOLS)
|
||||
#define CJSON_EXPORT_SYMBOLS
|
||||
#endif
|
||||
|
||||
#if defined(CJSON_HIDE_SYMBOLS)
|
||||
#define CJSON_PUBLIC(type) type CJSON_STDCALL
|
||||
#elif defined(CJSON_EXPORT_SYMBOLS)
|
||||
#define CJSON_PUBLIC(type) __declspec(dllexport) type CJSON_STDCALL
|
||||
#elif defined(CJSON_IMPORT_SYMBOLS)
|
||||
#define CJSON_PUBLIC(type) __declspec(dllimport) type CJSON_STDCALL
|
||||
#endif
|
||||
#else /* !__WINDOWS__ */
|
||||
#define CJSON_CDECL
|
||||
#define CJSON_STDCALL
|
||||
|
||||
#if (defined(__GNUC__) || defined(__SUNPRO_CC) || defined (__SUNPRO_C)) && defined(CJSON_API_VISIBILITY)
|
||||
#define CJSON_PUBLIC(type) __attribute__((visibility("default"))) type
|
||||
#else
|
||||
#define CJSON_PUBLIC(type) type
|
||||
#endif
|
||||
#endif
|
||||
|
||||
/* project version */
|
||||
#define CJSON_VERSION_MAJOR 1
|
||||
#define CJSON_VERSION_MINOR 7
|
||||
#define CJSON_VERSION_PATCH 19
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
/* cJSON Types: */
|
||||
#define cJSON_Invalid (0)
|
||||
#define cJSON_False (1 << 0)
|
||||
#define cJSON_True (1 << 1)
|
||||
#define cJSON_NULL (1 << 2)
|
||||
#define cJSON_Number (1 << 3)
|
||||
#define cJSON_String (1 << 4)
|
||||
#define cJSON_Array (1 << 5)
|
||||
#define cJSON_Object (1 << 6)
|
||||
#define cJSON_Raw (1 << 7) /* raw json */
|
||||
|
||||
#define cJSON_IsReference 256
|
||||
#define cJSON_StringIsConst 512
|
||||
|
||||
/* The cJSON structure: */
|
||||
typedef struct cJSON
|
||||
{
|
||||
/* next/prev allow you to walk array/object chains. Alternatively, use GetArraySize/GetArrayItem/GetObjectItem */
|
||||
struct cJSON *next;
|
||||
struct cJSON *prev;
|
||||
/* An array or object item will have a child pointer pointing to a chain of the items in the array/object. */
|
||||
struct cJSON *child;
|
||||
|
||||
/* The type of the item, as above. */
|
||||
int type;
|
||||
|
||||
/* The item's string, if type==cJSON_String and type == cJSON_Raw */
|
||||
char *valuestring;
|
||||
/* writing to valueint is DEPRECATED, use cJSON_SetNumberValue instead */
|
||||
int valueint;
|
||||
/* The item's number, if type==cJSON_Number */
|
||||
double valuedouble;
|
||||
|
||||
/* The item's name string, if this item is the child of, or is in the list of subitems of an object. */
|
||||
char *string;
|
||||
} cJSON;
|
||||
|
||||
typedef struct cJSON_Hooks
|
||||
{
|
||||
/* malloc/free are CDECL on Windows regardless of the default calling convention of the compiler, so ensure the hooks allow passing those functions directly. */
|
||||
void *(CJSON_CDECL *malloc_fn)(size_t sz);
|
||||
void (CJSON_CDECL *free_fn)(void *ptr);
|
||||
} cJSON_Hooks;
|
||||
|
||||
typedef int cJSON_bool;
|
||||
|
||||
/* Limits how deeply nested arrays/objects can be before cJSON rejects to parse them.
|
||||
* This is to prevent stack overflows. */
|
||||
#ifndef CJSON_NESTING_LIMIT
|
||||
#define CJSON_NESTING_LIMIT 1000
|
||||
#endif
|
||||
|
||||
/* Limits the length of circular references can be before cJSON rejects to parse them.
|
||||
* This is to prevent stack overflows. */
|
||||
#ifndef CJSON_CIRCULAR_LIMIT
|
||||
#define CJSON_CIRCULAR_LIMIT 10000
|
||||
#endif
|
||||
|
||||
/* returns the version of cJSON as a string */
|
||||
CJSON_PUBLIC(const char*) cJSON_Version(void);
|
||||
|
||||
/* Supply malloc, realloc and free functions to cJSON */
|
||||
CJSON_PUBLIC(void) cJSON_InitHooks(cJSON_Hooks* hooks);
|
||||
|
||||
/* Memory Management: the caller is always responsible to free the results from all variants of cJSON_Parse (with cJSON_Delete) and cJSON_Print (with stdlib free, cJSON_Hooks.free_fn, or cJSON_free as appropriate). The exception is cJSON_PrintPreallocated, where the caller has full responsibility of the buffer. */
|
||||
/* Supply a block of JSON, and this returns a cJSON object you can interrogate. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_Parse(const char *value);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLength(const char *value, size_t buffer_length);
|
||||
/* ParseWithOpts allows you to require (and check) that the JSON is null terminated, and to retrieve the pointer to the final byte parsed. */
|
||||
/* If you supply a ptr in return_parse_end and parsing fails, then return_parse_end will contain a pointer to the error so will match cJSON_GetErrorPtr(). */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_ParseWithOpts(const char *value, const char **return_parse_end, cJSON_bool require_null_terminated);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_ParseWithLengthOpts(const char *value, size_t buffer_length, const char **return_parse_end, cJSON_bool require_null_terminated);
|
||||
|
||||
/* Render a cJSON entity to text for transfer/storage. */
|
||||
CJSON_PUBLIC(char *) cJSON_Print(const cJSON *item);
|
||||
/* Render a cJSON entity to text for transfer/storage without any formatting. */
|
||||
CJSON_PUBLIC(char *) cJSON_PrintUnformatted(const cJSON *item);
|
||||
/* Render a cJSON entity to text using a buffered strategy. prebuffer is a guess at the final size. guessing well reduces reallocation. fmt=0 gives unformatted, =1 gives formatted */
|
||||
CJSON_PUBLIC(char *) cJSON_PrintBuffered(const cJSON *item, int prebuffer, cJSON_bool fmt);
|
||||
/* Render a cJSON entity to text using a buffer already allocated in memory with given length. Returns 1 on success and 0 on failure. */
|
||||
/* NOTE: cJSON is not always 100% accurate in estimating how much memory it will use, so to be safe allocate 5 bytes more than you actually need */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_PrintPreallocated(cJSON *item, char *buffer, const int length, const cJSON_bool format);
|
||||
/* Delete a cJSON entity and all subentities. */
|
||||
CJSON_PUBLIC(void) cJSON_Delete(cJSON *item);
|
||||
|
||||
/* Returns the number of items in an array (or object). */
|
||||
CJSON_PUBLIC(int) cJSON_GetArraySize(const cJSON *array);
|
||||
/* Retrieve item number "index" from array "array". Returns NULL if unsuccessful. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_GetArrayItem(const cJSON *array, int index);
|
||||
/* Get item "string" from object. Case insensitive. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItem(const cJSON * const object, const char * const string);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_GetObjectItemCaseSensitive(const cJSON * const object, const char * const string);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_HasObjectItem(const cJSON *object, const char *string);
|
||||
/* For analysing failed parses. This returns a pointer to the parse error. You'll probably need to look a few chars back to make sense of it. Defined when cJSON_Parse() returns 0. 0 when cJSON_Parse() succeeds. */
|
||||
CJSON_PUBLIC(const char *) cJSON_GetErrorPtr(void);
|
||||
|
||||
/* Check item type and return its value */
|
||||
CJSON_PUBLIC(char *) cJSON_GetStringValue(const cJSON * const item);
|
||||
CJSON_PUBLIC(double) cJSON_GetNumberValue(const cJSON * const item);
|
||||
|
||||
/* These functions check the type of an item */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsInvalid(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsFalse(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsTrue(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsBool(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsNull(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsNumber(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsString(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsArray(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsObject(const cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_IsRaw(const cJSON * const item);
|
||||
|
||||
/* These calls create a cJSON item of the appropriate type. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateNull(void);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateTrue(void);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateFalse(void);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateBool(cJSON_bool boolean);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateNumber(double num);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateString(const char *string);
|
||||
/* raw json */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateRaw(const char *raw);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateArray(void);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateObject(void);
|
||||
|
||||
/* Create a string where valuestring references a string so
|
||||
* it will not be freed by cJSON_Delete */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateStringReference(const char *string);
|
||||
/* Create an object/array that only references it's elements so
|
||||
* they will not be freed by cJSON_Delete */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateObjectReference(const cJSON *child);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateArrayReference(const cJSON *child);
|
||||
|
||||
/* These utilities create an Array of count items.
|
||||
* The parameter count cannot be greater than the number of elements in the number array, otherwise array access will be out of bounds.*/
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateIntArray(const int *numbers, int count);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateFloatArray(const float *numbers, int count);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateDoubleArray(const double *numbers, int count);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_CreateStringArray(const char *const *strings, int count);
|
||||
|
||||
/* Append item to the specified array/object. */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToArray(cJSON *array, cJSON *item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObject(cJSON *object, const char *string, cJSON *item);
|
||||
/* Use this when string is definitely const (i.e. a literal, or as good as), and will definitely survive the cJSON object.
|
||||
* WARNING: When this function was used, make sure to always check that (item->type & cJSON_StringIsConst) is zero before
|
||||
* writing to `item->string` */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemToObjectCS(cJSON *object, const char *string, cJSON *item);
|
||||
/* Append reference to item to the specified array/object. Use this when you want to add an existing cJSON to a new cJSON, but don't want to corrupt your existing cJSON. */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToArray(cJSON *array, cJSON *item);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_AddItemReferenceToObject(cJSON *object, const char *string, cJSON *item);
|
||||
|
||||
/* Remove/Detach items from Arrays/Objects. */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_DetachItemViaPointer(cJSON *parent, cJSON * const item);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromArray(cJSON *array, int which);
|
||||
CJSON_PUBLIC(void) cJSON_DeleteItemFromArray(cJSON *array, int which);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObject(cJSON *object, const char *string);
|
||||
CJSON_PUBLIC(cJSON *) cJSON_DetachItemFromObjectCaseSensitive(cJSON *object, const char *string);
|
||||
CJSON_PUBLIC(void) cJSON_DeleteItemFromObject(cJSON *object, const char *string);
|
||||
CJSON_PUBLIC(void) cJSON_DeleteItemFromObjectCaseSensitive(cJSON *object, const char *string);
|
||||
|
||||
/* Update array items. */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_InsertItemInArray(cJSON *array, int which, cJSON *newitem); /* Shifts pre-existing items to the right. */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemViaPointer(cJSON * const parent, cJSON * const item, cJSON * replacement);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInArray(cJSON *array, int which, cJSON *newitem);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObject(cJSON *object,const char *string,cJSON *newitem);
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_ReplaceItemInObjectCaseSensitive(cJSON *object,const char *string,cJSON *newitem);
|
||||
|
||||
/* Duplicate a cJSON item */
|
||||
CJSON_PUBLIC(cJSON *) cJSON_Duplicate(const cJSON *item, cJSON_bool recurse);
|
||||
/* Duplicate will create a new, identical cJSON item to the one you pass, in new memory that will
|
||||
* need to be released. With recurse!=0, it will duplicate any children connected to the item.
|
||||
* The item->next and ->prev pointers are always zero on return from Duplicate. */
|
||||
/* Recursively compare two cJSON items for equality. If either a or b is NULL or invalid, they will be considered unequal.
|
||||
* case_sensitive determines if object keys are treated case sensitive (1) or case insensitive (0) */
|
||||
CJSON_PUBLIC(cJSON_bool) cJSON_Compare(const cJSON * const a, const cJSON * const b, const cJSON_bool case_sensitive);
|
||||
|
||||
/* Minify a strings, remove blank characters(such as ' ', '\t', '\r', '\n') from strings.
|
||||
* The input pointer json cannot point to a read-only address area, such as a string constant,
|
||||
* but should point to a readable and writable address area. */
|
||||
CJSON_PUBLIC(void) cJSON_Minify(char *json);
|
||||
|
||||
/* Helper functions for creating and adding items to an object at the same time.
|
||||
* They return the added item or NULL on failure. */
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddNullToObject(cJSON * const object, const char * const name);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddTrueToObject(cJSON * const object, const char * const name);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddFalseToObject(cJSON * const object, const char * const name);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddBoolToObject(cJSON * const object, const char * const name, const cJSON_bool boolean);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddNumberToObject(cJSON * const object, const char * const name, const double number);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddStringToObject(cJSON * const object, const char * const name, const char * const string);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddRawToObject(cJSON * const object, const char * const name, const char * const raw);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddObjectToObject(cJSON * const object, const char * const name);
|
||||
CJSON_PUBLIC(cJSON*) cJSON_AddArrayToObject(cJSON * const object, const char * const name);
|
||||
|
||||
/* When assigning an integer value, it needs to be propagated to valuedouble too. */
|
||||
#define cJSON_SetIntValue(object, number) ((object) ? (object)->valueint = (object)->valuedouble = (number) : (number))
|
||||
/* helper for the cJSON_SetNumberValue macro */
|
||||
CJSON_PUBLIC(double) cJSON_SetNumberHelper(cJSON *object, double number);
|
||||
#define cJSON_SetNumberValue(object, number) ((object != NULL) ? cJSON_SetNumberHelper(object, (double)number) : (number))
|
||||
/* Change the valuestring of a cJSON_String object, only takes effect when type of object is cJSON_String */
|
||||
CJSON_PUBLIC(char*) cJSON_SetValuestring(cJSON *object, const char *valuestring);
|
||||
|
||||
/* If the object is not a boolean type this does nothing and returns cJSON_Invalid else it returns the new type*/
|
||||
#define cJSON_SetBoolValue(object, boolValue) ( \
|
||||
(object != NULL && ((object)->type & (cJSON_False|cJSON_True))) ? \
|
||||
(object)->type=((object)->type &(~(cJSON_False|cJSON_True)))|((boolValue)?cJSON_True:cJSON_False) : \
|
||||
cJSON_Invalid\
|
||||
)
|
||||
|
||||
/* Macro for iterating over an array or object */
|
||||
#define cJSON_ArrayForEach(element, array) for(element = (array != NULL) ? (array)->child : NULL; element != NULL; element = element->next)
|
||||
|
||||
/* malloc/free objects using the malloc/free functions that have been set with cJSON_InitHooks */
|
||||
CJSON_PUBLIC(void *) cJSON_malloc(size_t size);
|
||||
CJSON_PUBLIC(void) cJSON_free(void *object);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,609 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
|
||||
#ifndef _HTTPD_PRIV_H_
|
||||
#define _HTTPD_PRIV_H_
|
||||
|
||||
#include <stdbool.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/param.h>
|
||||
#include <netinet/in.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_err.h>
|
||||
|
||||
#include <esp_http_server.h>
|
||||
#include "osal.h"
|
||||
#include "freertos/semphr.h"
|
||||
#include "sdkconfig.h"
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
#if CONFIG_LIBC_NEWLIB_NANO_FORMAT
|
||||
#define NEWLIB_NANO_COMPAT_FORMAT PRIu32
|
||||
#define NEWLIB_NANO_COMPAT_CAST(size_t_var) (uint32_t)size_t_var
|
||||
#else
|
||||
#define NEWLIB_NANO_COMPAT_FORMAT "zu"
|
||||
#define NEWLIB_NANO_COMPAT_CAST(size_t_var) size_t_var
|
||||
#endif
|
||||
|
||||
/* Size of request data block/chunk (not to be confused with chunked encoded data)
|
||||
* that is received and parsed in one turn of the parsing process. */
|
||||
#define PARSER_BLOCK_SIZE 128
|
||||
|
||||
/* Formats a log string to prepend context function name */
|
||||
#define LOG_FMT(x) "%s: " x, __func__
|
||||
|
||||
/**
|
||||
* @brief Control message data structure for internal use. Sent to control socket.
|
||||
*/
|
||||
struct httpd_ctrl_data {
|
||||
enum httpd_ctrl_msg {
|
||||
HTTPD_CTRL_SHUTDOWN,
|
||||
HTTPD_CTRL_WORK,
|
||||
HTTPD_CTRL_MAX,
|
||||
} hc_msg;
|
||||
httpd_work_fn_t hc_work;
|
||||
void *hc_work_arg;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Thread related data for internal use
|
||||
*/
|
||||
struct thread_data {
|
||||
othread_t handle; /*!< Handle to thread/task */
|
||||
enum {
|
||||
THREAD_IDLE = 0,
|
||||
THREAD_RUNNING,
|
||||
THREAD_STOPPING,
|
||||
THREAD_STOPPED,
|
||||
} status; /*!< State of the thread */
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief A database of all the open sockets in the system.
|
||||
*/
|
||||
struct sock_db {
|
||||
int fd; /*!< The file descriptor for this socket */
|
||||
void *ctx; /*!< A custom context for this socket */
|
||||
bool ignore_sess_ctx_changes; /*!< Flag indicating if session context changes should be ignored */
|
||||
void *transport_ctx; /*!< A custom 'transport' context for this socket, to be used by send/recv/pending */
|
||||
httpd_handle_t handle; /*!< Server handle */
|
||||
httpd_free_ctx_fn_t free_ctx; /*!< Function for freeing the context */
|
||||
httpd_free_ctx_fn_t free_transport_ctx; /*!< Function for freeing the 'transport' context */
|
||||
httpd_send_func_t send_fn; /*!< Send function for this socket */
|
||||
httpd_recv_func_t recv_fn; /*!< Receive function for this socket */
|
||||
httpd_pending_func_t pending_fn; /*!< Pending function for this socket */
|
||||
uint64_t lru_counter; /*!< LRU Counter indicating when the socket was last used */
|
||||
bool lru_socket; /*!< Flag indicating LRU socket */
|
||||
char pending_data[PARSER_BLOCK_SIZE]; /*!< Buffer for pending data to be received */
|
||||
size_t pending_len; /*!< Length of pending data to be received */
|
||||
bool for_async_req; /*!< If true, the socket will not be LRU purged */
|
||||
#ifdef CONFIG_HTTPD_WS_SUPPORT
|
||||
bool ws_handshake_done; /*!< True if it has done WebSocket handshake (if this socket is a valid WS) */
|
||||
bool ws_close; /*!< Set to true to close the socket later (when WS Close frame received) */
|
||||
esp_err_t (*ws_handler)(httpd_req_t *r); /*!< WebSocket handler, leave to null if it's not WebSocket */
|
||||
bool ws_control_frames; /*!< WebSocket flag indicating that control frames should be passed to user handlers */
|
||||
void *ws_user_ctx; /*!< Pointer to user context data which will be available to handler for websocket*/
|
||||
#endif
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Auxiliary data structure for use during reception and processing
|
||||
* of requests and temporarily keeping responses
|
||||
*/
|
||||
struct httpd_req_aux {
|
||||
struct sock_db *sd; /*!< Pointer to socket database */
|
||||
char *scratch; /*!< Temporary buffer for our operations (1 byte extra for null termination) */
|
||||
size_t scratch_size_limit; /*!< Scratch buffer size limit (By default this value is set to CONFIG_HTTPD_MAX_REQ_HDR_LEN, overwrite is possible) */
|
||||
size_t scratch_cur_size; /*!< Scratch buffer cur size (By default this value is set to CONFIG_HTTPD_MAX_URI_LEN, overwrite is possible) */
|
||||
size_t max_req_hdr_len; /*!< Header buffer size limit */
|
||||
size_t max_uri_len; /*!< URI buffer size limit */
|
||||
size_t remaining_len; /*!< Amount of data remaining to be fetched */
|
||||
char *status; /*!< HTTP response's status code */
|
||||
char *content_type; /*!< HTTP response's content type */
|
||||
bool first_chunk_sent; /*!< Used to indicate if first chunk sent */
|
||||
unsigned req_hdrs_count; /*!< Count of total headers in request packet */
|
||||
unsigned resp_hdrs_count; /*!< Count of additional headers in response packet */
|
||||
struct resp_hdr {
|
||||
const char *field;
|
||||
const char *value;
|
||||
} *resp_hdrs; /*!< Additional headers in response packet */
|
||||
struct http_parser_url url_parse_res; /*!< URL parsing result, used for retrieving URL elements */
|
||||
#ifdef CONFIG_HTTPD_WS_SUPPORT
|
||||
bool ws_handshake_detect; /*!< WebSocket handshake detection flag */
|
||||
httpd_ws_type_t ws_type; /*!< WebSocket frame type */
|
||||
bool ws_final; /*!< WebSocket FIN bit (final frame or not) */
|
||||
uint8_t mask_key[4]; /*!< WebSocket mask key for this payload */
|
||||
#endif
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Server data for each instance. This is exposed publicly as
|
||||
* httpd_handle_t but internal structure/members are kept private.
|
||||
*/
|
||||
struct httpd_data {
|
||||
httpd_config_t config; /*!< HTTPD server configuration */
|
||||
int listen_fd; /*!< Server listener FD */
|
||||
int ctrl_fd; /*!< Ctrl message receiver FD */
|
||||
SemaphoreHandle_t ctrl_sock_semaphore; /*!< Ctrl mbox slot reservation (sized to LWIP_UDP_RECVMBOX_SIZE) */
|
||||
int msg_fd; /*!< Ctrl message sender FD */
|
||||
struct thread_data hd_td; /*!< Information for the HTTPD thread */
|
||||
struct sock_db *hd_sd; /*!< The socket database */
|
||||
int hd_sd_active_count; /*!< The number of the active sockets */
|
||||
httpd_uri_t **hd_calls; /*!< Registered URI handlers */
|
||||
struct httpd_req hd_req; /*!< The current HTTPD request */
|
||||
struct httpd_req_aux hd_req_aux; /*!< Additional data about the HTTPD request kept unexposed */
|
||||
uint64_t lru_counter; /*!< LRU counter */
|
||||
esp_http_server_event_id_t http_server_state; /*!< HTTPD server state */
|
||||
|
||||
/* Array of registered error handler functions */
|
||||
httpd_err_handler_func_t *err_handler_fns;
|
||||
};
|
||||
|
||||
/**
|
||||
* @brief Options for receiving HTTP request data
|
||||
*/
|
||||
typedef enum {
|
||||
HTTPD_RECV_OPT_NONE = 0,
|
||||
HTTPD_RECV_OPT_HALT_AFTER_PENDING = 1, /*!< Halt immediately after receiving from pending buffer */
|
||||
HTTPD_RECV_OPT_BLOCKING = 2, /*!< Receive blocking (don't return partial length) */
|
||||
} httpd_recv_opt_t;
|
||||
|
||||
/******************* Group : Session Management ********************/
|
||||
/** @name Session Management
|
||||
* Functions related to HTTP session management
|
||||
* @{
|
||||
*/
|
||||
|
||||
// Enum function, which will be called for each session
|
||||
typedef int (*httpd_session_enum_function)(struct sock_db *session, void *context);
|
||||
|
||||
/**
|
||||
* @brief Enumerates all sessions
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[in] enum_function Enumeration function, which will be called for each session
|
||||
* @param[in] context Context, which will be passed to the enumeration function
|
||||
*/
|
||||
void httpd_sess_enum(struct httpd_data *hd, httpd_session_enum_function enum_function, void *context);
|
||||
|
||||
/**
|
||||
* @brief Returns next free session slot (fd<0)
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
*
|
||||
* @return
|
||||
* - +VE : Free session slot
|
||||
* - NULL: End of iteration
|
||||
*/
|
||||
struct sock_db *httpd_sess_get_free(struct httpd_data *hd);
|
||||
|
||||
/**
|
||||
* @brief Retrieve a session by its descriptor
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[in] sockfd Socket FD
|
||||
* @return pointer into the socket DB, or NULL if not found
|
||||
*/
|
||||
struct sock_db *httpd_sess_get(struct httpd_data *hd, int sockfd);
|
||||
|
||||
/**
|
||||
* @brief Delete sessions whose FDs have became invalid.
|
||||
* This is a recovery strategy e.g. after select() fails.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
*/
|
||||
void httpd_sess_delete_invalid(struct httpd_data *hd);
|
||||
|
||||
/**
|
||||
* @brief Initializes an http session by resetting the sockets database.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
*/
|
||||
void httpd_sess_init(struct httpd_data *hd);
|
||||
|
||||
/**
|
||||
* @brief Starts a new session for client requesting connection and adds
|
||||
* it's descriptor to the socket database.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[in] newfd Descriptor of the new client to be added to the session.
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK : on successfully queuing the work
|
||||
* - ESP_FAIL : in case of control socket error while sending
|
||||
*/
|
||||
esp_err_t httpd_sess_new(struct httpd_data *hd, int newfd);
|
||||
|
||||
/**
|
||||
* @brief Processes incoming HTTP requests
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[in] session Session
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK : on successfully receiving, parsing and responding to a request
|
||||
* - ESP_FAIL : in case of failure in any of the stages of processing
|
||||
*/
|
||||
esp_err_t httpd_sess_process(struct httpd_data *hd, struct sock_db *session);
|
||||
|
||||
/**
|
||||
* @brief Remove client descriptor from the session / socket database
|
||||
* and close the connection for this client.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[in] session Session
|
||||
*/
|
||||
void httpd_sess_delete(struct httpd_data *hd, struct sock_db *session);
|
||||
|
||||
/**
|
||||
* @brief Free session context
|
||||
*
|
||||
* @param[in] ctx Pointer to session context
|
||||
* @param[in] free_fn Free function to call on session context
|
||||
*/
|
||||
void httpd_sess_free_ctx(void **ctx, httpd_free_ctx_fn_t free_fn);
|
||||
|
||||
/**
|
||||
* @brief Add descriptors present in the socket database to an fdset and
|
||||
* update the value of maxfd which are needed by the select function
|
||||
* for looking through all available sockets for incoming data.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[out] fdset File descriptor set to be updated.
|
||||
* @param[out] maxfd Maximum value among all file descriptors.
|
||||
*/
|
||||
void httpd_sess_set_descriptors(struct httpd_data *hd, fd_set *fdset, int *maxfd);
|
||||
|
||||
/**
|
||||
* @brief Checks if session can accept another connection from new client.
|
||||
* If sockets database is full then this returns false.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
*
|
||||
* @return True if session can accept new clients
|
||||
*/
|
||||
bool httpd_is_sess_available(struct httpd_data *hd);
|
||||
|
||||
/**
|
||||
* @brief Checks if session has any pending data/packets
|
||||
* for processing
|
||||
*
|
||||
* This is needed as httpd_unrecv may un-receive next
|
||||
* packet in the stream. If only partial packet was
|
||||
* received then select() would mark the fd for processing
|
||||
* as remaining part of the packet would still be in socket
|
||||
* recv queue. But if a complete packet got unreceived
|
||||
* then it would not be processed until further data is
|
||||
* received on the socket. This is when this function
|
||||
* comes in use, as it checks the socket's pending data
|
||||
* buffer.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[in] session Session
|
||||
*
|
||||
* @return True if there is any pending data
|
||||
*/
|
||||
bool httpd_sess_pending(struct httpd_data *hd, struct sock_db *session);
|
||||
|
||||
/**
|
||||
* @brief Removes the least recently used client from the session
|
||||
*
|
||||
* This may be useful if new clients are requesting for connection but
|
||||
* max number of connections is reached, in which case the client which
|
||||
* is inactive for the longest will be removed from the session.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK : if session closure initiated successfully
|
||||
* - ESP_FAIL : if failed
|
||||
*/
|
||||
esp_err_t httpd_sess_close_lru(struct httpd_data *hd);
|
||||
|
||||
/**
|
||||
* @brief Closes all sessions
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
*
|
||||
*/
|
||||
void httpd_sess_close_all(struct httpd_data *hd);
|
||||
|
||||
/** End of Group : Session Management
|
||||
* @}
|
||||
*/
|
||||
|
||||
/****************** Group : URI Handling ********************/
|
||||
/** @name URI Handling
|
||||
* Methods for accessing URI handlers
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief For an HTTP request, searches through all the registered URI handlers
|
||||
* and invokes the appropriate one if found
|
||||
*
|
||||
* @param[in] hd Server instance data for which handler needs to be invoked
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK : if handler found and executed successfully
|
||||
* - ESP_FAIL : otherwise
|
||||
*/
|
||||
esp_err_t httpd_uri(struct httpd_data *hd);
|
||||
|
||||
/**
|
||||
* @brief Unregister all URI handlers
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
*/
|
||||
void httpd_unregister_all_uri_handlers(struct httpd_data *hd);
|
||||
|
||||
/**
|
||||
* @brief Validates the request to prevent users from calling APIs, that are to
|
||||
* be called only inside a URI handler, outside the handler context
|
||||
*
|
||||
* @param[in] req Pointer to HTTP request that needs to be validated
|
||||
*
|
||||
* @return
|
||||
* - true : if valid request
|
||||
* - false : otherwise
|
||||
*/
|
||||
bool httpd_validate_req_ptr(httpd_req_t *r);
|
||||
|
||||
/* httpd_validate_req_ptr() adds some overhead to frequently used APIs,
|
||||
* and is useful mostly for debugging, so it's preferable to disable
|
||||
* the check by default and enable it only if necessary */
|
||||
#ifdef CONFIG_HTTPD_VALIDATE_REQ
|
||||
#define httpd_valid_req(r) httpd_validate_req_ptr(r)
|
||||
#else
|
||||
#define httpd_valid_req(r) true
|
||||
#endif
|
||||
|
||||
/** End of Group : URI Handling
|
||||
* @}
|
||||
*/
|
||||
|
||||
/****************** Group : Processing ********************/
|
||||
/** @name Processing
|
||||
* Methods for processing HTTP requests
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Initiates the processing of HTTP request
|
||||
*
|
||||
* Receives incoming TCP packet on a socket, then parses the packet as
|
||||
* HTTP request and fills httpd_req_t data structure with the extracted
|
||||
* URI, headers are ready to be fetched from scratch buffer and calling
|
||||
* http_recv() after this reads the body of the request.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[in] sd Pointer to socket which is needed for receiving TCP packets.
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK : if request packet is valid
|
||||
* - ESP_FAIL : otherwise
|
||||
*/
|
||||
esp_err_t httpd_req_new(struct httpd_data *hd, struct sock_db *sd);
|
||||
|
||||
/**
|
||||
* @brief For an HTTP request, resets the resources allocated for it and
|
||||
* purges any data left to be received
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK : if request packet deleted and resources cleaned.
|
||||
* - ESP_FAIL : otherwise.
|
||||
*/
|
||||
esp_err_t httpd_req_delete(struct httpd_data *hd);
|
||||
|
||||
/** End of Group : Parsing
|
||||
* @}
|
||||
*/
|
||||
|
||||
/****************** Group : Send/Receive ********************/
|
||||
/** @name Send and Receive
|
||||
* Methods for transmitting and receiving HTTP requests and responses
|
||||
* @{
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief For sending out data in response to an HTTP request.
|
||||
*
|
||||
* @param[in] req Pointer to the HTTP request for which the response needs to be sent
|
||||
* @param[in] buf Pointer to the buffer from where the body of the response is taken
|
||||
* @param[in] buf_len Length of the buffer
|
||||
*
|
||||
* @return
|
||||
* - Length of data : if successful
|
||||
* - ESP_FAIL : if failed
|
||||
*/
|
||||
int httpd_send(httpd_req_t *req, const char *buf, size_t buf_len);
|
||||
|
||||
/**
|
||||
* @brief For receiving HTTP request data
|
||||
*
|
||||
* @note The exposed API httpd_recv() is simply this function with last parameter
|
||||
* set as false. This function is used internally during reception and
|
||||
* processing of a new request.
|
||||
*
|
||||
* There are 2 options available that affect the behavior of the function:
|
||||
* - HTTPD_RECV_OPT_HALT_AFTER_PENDING
|
||||
* The option to halt after receiving pending data prevents the server from
|
||||
* requesting more data than is needed for completing a packet in case when
|
||||
* all the remaining part of the packet is in the pending buffer.
|
||||
*
|
||||
* - HTTPD_RECV_OPT_BLOCKING
|
||||
* The option to not return until the `buf_len` bytes have been read.
|
||||
*
|
||||
* @param[in] req Pointer to new HTTP request which only has the socket descriptor
|
||||
* @param[out] buf Pointer to the buffer which will be filled with the received data
|
||||
* @param[in] buf_len Length of the buffer
|
||||
* @param[in] opt Receive option
|
||||
*
|
||||
* @return
|
||||
* - Length of data : if successful
|
||||
* - ESP_FAIL : if failed
|
||||
*/
|
||||
int httpd_recv_with_opt(httpd_req_t *r, char *buf, size_t buf_len, httpd_recv_opt_t opt);
|
||||
|
||||
/**
|
||||
* @brief For un-receiving HTTP request data
|
||||
*
|
||||
* This function copies data into internal buffer pending_data so that
|
||||
* when httpd_recv is called, it first fetches this pending data and
|
||||
* then only starts receiving from the socket
|
||||
*
|
||||
* @note If data is too large for the internal buffer then only
|
||||
* part of the data is unreceived, reflected in the returned
|
||||
* length. Make sure that such truncation is checked for and
|
||||
* handled properly.
|
||||
*
|
||||
* @param[in] req Pointer to new HTTP request which only has the socket descriptor
|
||||
* @param[in] buf Pointer to the buffer from where data needs to be un-received
|
||||
* @param[in] buf_len Length of the buffer
|
||||
*
|
||||
* @return Length of data copied into pending buffer
|
||||
*/
|
||||
size_t httpd_unrecv(struct httpd_req *r, const char *buf, size_t buf_len);
|
||||
|
||||
/**
|
||||
* @brief This is the low level default send function of the HTTPD. This should
|
||||
* NEVER be called directly. The semantics of this is exactly similar to
|
||||
* send() of the BSD socket API.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[in] sockfd Socket descriptor for sending data
|
||||
* @param[in] buf Pointer to the buffer from where the body of the response is taken
|
||||
* @param[in] buf_len Length of the buffer
|
||||
* @param[in] flags Flags for mode selection
|
||||
*
|
||||
* @return
|
||||
* - Length of data : if successful
|
||||
* - -1 : if failed (appropriate errno is set)
|
||||
*/
|
||||
int httpd_default_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags);
|
||||
|
||||
/**
|
||||
* @brief This is the low level default recv function of the HTTPD. This should
|
||||
* NEVER be called directly. The semantics of this is exactly similar to
|
||||
* recv() of the BSD socket API.
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
* @param[in] sockfd Socket descriptor for sending data
|
||||
* @param[out] buf Pointer to the buffer which will be filled with the received data
|
||||
* @param[in] buf_len Length of the buffer
|
||||
* @param[in] flags Flags for mode selection
|
||||
*
|
||||
* @return
|
||||
* - Length of data : if successful
|
||||
* - -1 : if failed (appropriate errno is set)
|
||||
*/
|
||||
int httpd_default_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags);
|
||||
|
||||
/** End of Group : Send and Receive
|
||||
* @}
|
||||
*/
|
||||
|
||||
/* ************** Group: WebSocket ************** */
|
||||
/** @name WebSocket
|
||||
* Functions for WebSocket header parsing
|
||||
* @{
|
||||
*/
|
||||
|
||||
|
||||
/**
|
||||
* @brief This function is for responding a WebSocket handshake
|
||||
*
|
||||
* @param[in] req Pointer to handshake request that will be handled
|
||||
* @param[in] supported_subprotocol Pointer to the subprotocol supported by this URI
|
||||
* @return
|
||||
* - ESP_OK : When handshake is successful
|
||||
* - ESP_ERR_NOT_FOUND : When some headers (Sec-WebSocket-*) are not found
|
||||
* - ESP_ERR_INVALID_VERSION : The WebSocket version is not "13"
|
||||
* - ESP_ERR_INVALID_STATE : Handshake was done beforehand
|
||||
* - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
|
||||
* - ESP_FAIL : Socket failures
|
||||
*/
|
||||
esp_err_t httpd_ws_respond_server_handshake(httpd_req_t *req, const char *supported_subprotocol);
|
||||
|
||||
/**
|
||||
* @brief This function is for getting a frame type
|
||||
* and responding a WebSocket control frame automatically
|
||||
*
|
||||
* @param[in] req Pointer to handshake request that will be handled
|
||||
* @return
|
||||
* - ESP_OK : When handshake is successful
|
||||
* - ESP_ERR_INVALID_ARG : Argument is invalid (null or non-WebSocket)
|
||||
* - ESP_ERR_INVALID_STATE : Received only some parts of a control frame
|
||||
* - ESP_FAIL : Socket failures
|
||||
*/
|
||||
esp_err_t httpd_ws_get_frame_type(httpd_req_t *req);
|
||||
|
||||
/**
|
||||
* @brief Trigger an httpd session close externally
|
||||
*
|
||||
* @note Calling this API is only required in special circumstances wherein
|
||||
* some application requires to close an httpd client session asynchronously.
|
||||
*
|
||||
* @param[in] handle Handle to server returned by httpd_start
|
||||
* @param[in] session Session to be closed
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK : On successfully initiating closure
|
||||
* - ESP_FAIL : Failure to queue work
|
||||
* - ESP_ERR_NOT_FOUND : Socket fd not found
|
||||
* - ESP_ERR_INVALID_ARG : Null arguments
|
||||
*/
|
||||
esp_err_t httpd_sess_trigger_close_(httpd_handle_t handle, struct sock_db *session);
|
||||
|
||||
/**
|
||||
* @brief Directly closes the least recently used session
|
||||
*
|
||||
* @param[in] hd Server instance data
|
||||
*
|
||||
* @return
|
||||
* - ESP_OK : if session closed successfully
|
||||
*/
|
||||
esp_err_t httpd_sess_close_lru_direct(struct httpd_data *hd);
|
||||
|
||||
/** End of WebSocket related functions
|
||||
* @}
|
||||
*/
|
||||
|
||||
#ifdef CONFIG_HTTPD_ENABLE_EVENTS
|
||||
|
||||
#if CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT == -1
|
||||
#define ESP_HTTP_SERVER_EVENT_POST_TIMEOUT portMAX_DELAY
|
||||
#else
|
||||
#define ESP_HTTP_SERVER_EVENT_POST_TIMEOUT pdMS_TO_TICKS(CONFIG_HTTPD_SERVER_EVENT_POST_TIMEOUT)
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Function to dispatch events in default event loop
|
||||
*
|
||||
*/
|
||||
void esp_http_server_dispatch_event(int32_t event_id, const void* event_data, size_t event_data_size);
|
||||
|
||||
#else // CONFIG_HTTPD_ENABLE_EVENTS
|
||||
static inline void esp_http_server_dispatch_event(int32_t event_id, const void* event_data, size_t event_data_size)
|
||||
{
|
||||
// Events disabled, do nothing
|
||||
(void) event_id;
|
||||
(void) event_data;
|
||||
(void) event_data_size;
|
||||
}
|
||||
#endif // CONFIG_HTTPD_ENABLE_EVENTS
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* ! _HTTPD_PRIV_H_ */
|
||||
@@ -0,0 +1,645 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#include <string.h>
|
||||
#include <sys/socket.h>
|
||||
#include <sys/param.h>
|
||||
#include <errno.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_err.h>
|
||||
#include <assert.h>
|
||||
#include <netinet/tcp.h>
|
||||
#include <net/if.h>
|
||||
|
||||
#include <esp_http_server.h>
|
||||
#include "esp_httpd_priv.h"
|
||||
#include "ctrl_sock.h"
|
||||
#if CONFIG_HTTPD_QUEUE_WORK_BLOCKING
|
||||
#include "freertos/semphr.h"
|
||||
#endif
|
||||
|
||||
#if defined(CONFIG_LWIP_MAX_SOCKETS)
|
||||
#define HTTPD_MAX_SOCKETS CONFIG_LWIP_MAX_SOCKETS
|
||||
#else
|
||||
/* LwIP component is not included into the build, use a default value */
|
||||
#define HTTPD_MAX_SOCKETS 15
|
||||
#endif
|
||||
|
||||
static const int DEFAULT_KEEP_ALIVE_IDLE = 5;
|
||||
static const int DEFAULT_KEEP_ALIVE_INTERVAL= 5;
|
||||
static const int DEFAULT_KEEP_ALIVE_COUNT= 3;
|
||||
|
||||
typedef struct {
|
||||
fd_set *fdset;
|
||||
struct httpd_data *hd;
|
||||
} process_session_context_t;
|
||||
|
||||
static const char *TAG = "httpd";
|
||||
|
||||
#ifdef CONFIG_HTTPD_ENABLE_EVENTS
|
||||
ESP_EVENT_DEFINE_BASE(ESP_HTTP_SERVER_EVENT);
|
||||
|
||||
void esp_http_server_dispatch_event(int32_t event_id, const void* event_data, size_t event_data_size)
|
||||
{
|
||||
esp_err_t err = esp_event_post(ESP_HTTP_SERVER_EVENT, event_id, event_data, event_data_size, ESP_HTTP_SERVER_EVENT_POST_TIMEOUT);
|
||||
if (err != ESP_OK) {
|
||||
ESP_LOGE(TAG, "Failed to post esp_http_server event: %s", esp_err_to_name(err));
|
||||
}
|
||||
}
|
||||
#endif // CONFIG_HTTPD_ENABLE_EVENTS
|
||||
|
||||
static esp_err_t httpd_accept_conn(struct httpd_data *hd)
|
||||
{
|
||||
/* If no space is available for new session, close the least recently used one */
|
||||
if (hd->config.lru_purge_enable == true) {
|
||||
if (!httpd_is_sess_available(hd)) {
|
||||
/* Queue asynchronous closure of the least recently used session */
|
||||
#if CONFIG_HTTPD_QUEUE_WORK_BLOCKING
|
||||
/* In case of blocking mode, close the least recently used session directly */
|
||||
return httpd_sess_close_lru_direct(hd);
|
||||
#else
|
||||
return httpd_sess_close_lru(hd);
|
||||
#endif /* CONFIG_HTTPD_QUEUE_WORK_BLOCKING */
|
||||
/* Returning from this allows the main server thread to process
|
||||
* the queued asynchronous control message for closing LRU session.
|
||||
* Since connection request hasn't been addressed yet using accept()
|
||||
* therefore httpd_accept_conn() will be called again, but this time
|
||||
* with space available for one session
|
||||
*/
|
||||
}
|
||||
}
|
||||
|
||||
struct sockaddr_storage addr_from;
|
||||
socklen_t addr_from_len = sizeof(addr_from);
|
||||
|
||||
int new_fd = accept(hd->listen_fd, (struct sockaddr *)&addr_from, &addr_from_len);
|
||||
if (new_fd < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in accept (%d)"), errno);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("newfd = %d"), new_fd);
|
||||
|
||||
struct timeval tv;
|
||||
/* Set recv timeout of this fd as per config */
|
||||
tv.tv_sec = hd->config.recv_wait_timeout;
|
||||
tv.tv_usec = 0;
|
||||
if (setsockopt(new_fd, SOL_SOCKET, SO_RCVTIMEO, (const char *)&tv, sizeof(tv)) < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in setsockopt SO_RCVTIMEO (%d)"), errno);
|
||||
goto exit;
|
||||
}
|
||||
|
||||
/* Set send timeout of this fd as per config */
|
||||
tv.tv_sec = hd->config.send_wait_timeout;
|
||||
tv.tv_usec = 0;
|
||||
if (setsockopt(new_fd, SOL_SOCKET, SO_SNDTIMEO, (const char *)&tv, sizeof(tv)) < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in setsockopt SO_SNDTIMEO (%d)"), errno);
|
||||
goto exit;
|
||||
}
|
||||
|
||||
if (hd->config.keep_alive_enable) {
|
||||
int keep_alive_enable = 1;
|
||||
int keep_alive_idle = hd->config.keep_alive_idle ? hd->config.keep_alive_idle : DEFAULT_KEEP_ALIVE_IDLE;
|
||||
int keep_alive_interval = hd->config.keep_alive_interval ? hd->config.keep_alive_interval : DEFAULT_KEEP_ALIVE_INTERVAL;
|
||||
int keep_alive_count = hd->config.keep_alive_count ? hd->config.keep_alive_count : DEFAULT_KEEP_ALIVE_COUNT;
|
||||
ESP_LOGD(TAG, "Enable TCP keep alive. idle: %d, interval: %d, count: %d", keep_alive_idle, keep_alive_interval, keep_alive_count);
|
||||
|
||||
if (setsockopt(new_fd, SOL_SOCKET, SO_KEEPALIVE, &keep_alive_enable, sizeof(keep_alive_enable)) < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in setsockopt SO_KEEPALIVE (%d)"), errno);
|
||||
goto exit;
|
||||
}
|
||||
#ifndef __APPLE__
|
||||
if (setsockopt(new_fd, IPPROTO_TCP, TCP_KEEPIDLE, &keep_alive_idle, sizeof(keep_alive_idle)) < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in setsockopt TCP_KEEPIDLE (%d)"), errno);
|
||||
goto exit;
|
||||
}
|
||||
if (setsockopt(new_fd, IPPROTO_TCP, TCP_KEEPINTVL, &keep_alive_interval, sizeof(keep_alive_interval)) < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in setsockopt TCP_KEEPINTVL (%d)"), errno);
|
||||
goto exit;
|
||||
}
|
||||
if (setsockopt(new_fd, IPPROTO_TCP, TCP_KEEPCNT, &keep_alive_count, sizeof(keep_alive_count)) < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in setsockopt TCP_KEEPCNT (%d)"), errno);
|
||||
goto exit;
|
||||
}
|
||||
#else // __APPLE__
|
||||
if (setsockopt(new_fd, IPPROTO_TCP, TCP_KEEPALIVE, &keep_alive_idle, sizeof(keep_alive_idle)) < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in setsockopt TCP_KEEPALIVE (%d)"), errno);
|
||||
goto exit;
|
||||
}
|
||||
#endif // __APPLE__
|
||||
}
|
||||
if (ESP_OK != httpd_sess_new(hd, new_fd)) {
|
||||
ESP_LOGE(TAG, LOG_FMT("session creation failed"));
|
||||
goto exit;
|
||||
}
|
||||
ESP_LOGD(TAG, LOG_FMT("complete"));
|
||||
hd->http_server_state = HTTP_SERVER_EVENT_ON_CONNECTED;
|
||||
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_ON_CONNECTED, &new_fd, sizeof(int));
|
||||
return ESP_OK;
|
||||
exit:
|
||||
close(new_fd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
esp_err_t httpd_queue_work(httpd_handle_t handle, httpd_work_fn_t work, void *arg)
|
||||
{
|
||||
if (handle == NULL || work == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
struct httpd_ctrl_data msg = {
|
||||
.hc_msg = HTTPD_CTRL_WORK,
|
||||
.hc_work = work,
|
||||
.hc_work_arg = arg,
|
||||
};
|
||||
|
||||
/* Reserve a slot in the control mbox before sending. In blocking mode
|
||||
* the caller waits for a slot; in the default non-blocking mode we
|
||||
* fail fast so the caller knows the work was not queued. */
|
||||
#if CONFIG_HTTPD_QUEUE_WORK_BLOCKING
|
||||
const TickType_t wait = portMAX_DELAY;
|
||||
#else
|
||||
const TickType_t wait = 0;
|
||||
#endif
|
||||
if (xSemaphoreTake(hd->ctrl_sock_semaphore, wait) != pdTRUE) {
|
||||
ESP_LOGW(TAG, LOG_FMT("ctrl socket queue full, work not queued"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
int ret = cs_send_to_ctrl_sock(hd->msg_fd, hd->config.ctrl_port, &msg, sizeof(msg));
|
||||
if (ret < 0) {
|
||||
ESP_LOGW(TAG, LOG_FMT("failed to queue work"));
|
||||
xSemaphoreGive(hd->ctrl_sock_semaphore);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_get_client_list(httpd_handle_t handle, size_t *fds, int *client_fds)
|
||||
{
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
if (hd == NULL || fds == NULL || *fds == 0 || client_fds == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
size_t max_fds = *fds;
|
||||
*fds = 0;
|
||||
for (int i = 0; i < hd->config.max_open_sockets; ++i) {
|
||||
if (hd->hd_sd[i].fd != -1) {
|
||||
if (*fds < max_fds) {
|
||||
client_fds[(*fds)++] = hd->hd_sd[i].fd;
|
||||
} else {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
}
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void *httpd_get_global_user_ctx(httpd_handle_t handle)
|
||||
{
|
||||
return ((struct httpd_data *)handle)->config.global_user_ctx;
|
||||
}
|
||||
|
||||
void *httpd_get_global_transport_ctx(httpd_handle_t handle)
|
||||
{
|
||||
return ((struct httpd_data *)handle)->config.global_transport_ctx;
|
||||
}
|
||||
|
||||
|
||||
static void httpd_process_ctrl_msg(struct httpd_data *hd)
|
||||
{
|
||||
struct httpd_ctrl_data msg;
|
||||
int ret = recv(hd->ctrl_fd, &msg, sizeof(msg), 0);
|
||||
if (ret <= 0) {
|
||||
ESP_LOGW(TAG, LOG_FMT("error in recv (%d)"), errno);
|
||||
/* No packet was actually consumed from the mbox here, so this give
|
||||
* is unbalanced. It's tolerated because the counting semaphore is
|
||||
* capped at its max — excess gives become no-ops. Spurious recv
|
||||
* errors after select() are rare in practice. */
|
||||
xSemaphoreGive(hd->ctrl_sock_semaphore);
|
||||
return;
|
||||
}
|
||||
if (ret != sizeof(msg)) {
|
||||
ESP_LOGW(TAG, LOG_FMT("incomplete msg"));
|
||||
xSemaphoreGive(hd->ctrl_sock_semaphore);
|
||||
return;
|
||||
}
|
||||
|
||||
switch (msg.hc_msg) {
|
||||
case HTTPD_CTRL_WORK:
|
||||
if (msg.hc_work) {
|
||||
ESP_LOGD(TAG, LOG_FMT("work"));
|
||||
(*msg.hc_work)(msg.hc_work_arg);
|
||||
}
|
||||
break;
|
||||
case HTTPD_CTRL_SHUTDOWN:
|
||||
ESP_LOGD(TAG, LOG_FMT("shutdown"));
|
||||
hd->hd_td.status = THREAD_STOPPING;
|
||||
break;
|
||||
default:
|
||||
break;
|
||||
}
|
||||
xSemaphoreGive(hd->ctrl_sock_semaphore);
|
||||
}
|
||||
|
||||
// Called for each session from httpd_server
|
||||
static int httpd_process_session(struct sock_db *session, void *context)
|
||||
{
|
||||
if ((!session) || (!context)) {
|
||||
return 0;
|
||||
}
|
||||
|
||||
if (session->fd < 0) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
// session is busy in an async task, do not process here.
|
||||
if (session->for_async_req) {
|
||||
return 1;
|
||||
}
|
||||
|
||||
process_session_context_t *ctx = (process_session_context_t *)context;
|
||||
int fd = session->fd;
|
||||
|
||||
if (FD_ISSET(fd, ctx->fdset) || httpd_sess_pending(ctx->hd, session)) {
|
||||
ESP_LOGD(TAG, LOG_FMT("processing socket %d"), fd);
|
||||
if (httpd_sess_process(ctx->hd, session) != ESP_OK) {
|
||||
httpd_sess_delete(ctx->hd, session); // Delete session
|
||||
}
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
/* Manage in-coming connection or data requests */
|
||||
static esp_err_t httpd_server(struct httpd_data *hd)
|
||||
{
|
||||
fd_set read_set;
|
||||
FD_ZERO(&read_set);
|
||||
if (hd->config.lru_purge_enable || httpd_is_sess_available(hd)) {
|
||||
/* Only listen for new connections if server has capacity to
|
||||
* handle more (or when LRU purge is enabled, in which case
|
||||
* older connections will be closed) */
|
||||
FD_SET(hd->listen_fd, &read_set);
|
||||
}
|
||||
FD_SET(hd->ctrl_fd, &read_set);
|
||||
|
||||
int tmp_max_fd;
|
||||
httpd_sess_set_descriptors(hd, &read_set, &tmp_max_fd);
|
||||
int maxfd = MAX(hd->listen_fd, tmp_max_fd);
|
||||
tmp_max_fd = maxfd;
|
||||
maxfd = MAX(hd->ctrl_fd, tmp_max_fd);
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("doing select maxfd+1 = %d"), maxfd + 1);
|
||||
int active_cnt = select(maxfd + 1, &read_set, NULL, NULL, NULL);
|
||||
if (active_cnt < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in select (%d)"), errno);
|
||||
httpd_sess_delete_invalid(hd);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/* Case0: Do we have a control message? */
|
||||
if (FD_ISSET(hd->ctrl_fd, &read_set)) {
|
||||
ESP_LOGD(TAG, LOG_FMT("processing ctrl message"));
|
||||
httpd_process_ctrl_msg(hd);
|
||||
if (hd->hd_td.status == THREAD_STOPPING) {
|
||||
ESP_LOGD(TAG, LOG_FMT("stopping thread"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
/* Case1: Do we have any activity on the current data
|
||||
* sessions? */
|
||||
process_session_context_t context = {
|
||||
.fdset = &read_set,
|
||||
.hd = hd
|
||||
};
|
||||
httpd_sess_enum(hd, httpd_process_session, &context);
|
||||
|
||||
/* Case2: Do we have any incoming connection requests to
|
||||
* process? */
|
||||
if (FD_ISSET(hd->listen_fd, &read_set)) {
|
||||
ESP_LOGD(TAG, LOG_FMT("processing listen socket %d"), hd->listen_fd);
|
||||
if (httpd_accept_conn(hd) != ESP_OK) {
|
||||
ESP_LOGW(TAG, LOG_FMT("error accepting new connection"));
|
||||
}
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/* The main HTTPD thread */
|
||||
static void httpd_thread(void *arg)
|
||||
{
|
||||
int ret;
|
||||
struct httpd_data *hd = (struct httpd_data *) arg;
|
||||
hd->hd_td.status = THREAD_RUNNING;
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("web server started"));
|
||||
while (1) {
|
||||
ret = httpd_server(hd);
|
||||
if (ret != ESP_OK) {
|
||||
break;
|
||||
}
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("web server exiting"));
|
||||
close(hd->msg_fd);
|
||||
cs_free_ctrl_sock(hd->ctrl_fd);
|
||||
httpd_sess_close_all(hd);
|
||||
close(hd->listen_fd);
|
||||
hd->hd_td.status = THREAD_STOPPED;
|
||||
httpd_os_thread_delete();
|
||||
}
|
||||
|
||||
static esp_err_t httpd_server_init(struct httpd_data *hd)
|
||||
{
|
||||
#if CONFIG_LWIP_IPV6
|
||||
int fd = socket(PF_INET6, SOCK_STREAM, 0);
|
||||
#else
|
||||
int fd = socket(PF_INET, SOCK_STREAM, 0);
|
||||
#endif
|
||||
if (fd < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in socket (%d)"), errno);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
#if CONFIG_LWIP_IPV6
|
||||
struct in6_addr inaddr_any = IN6ADDR_ANY_INIT;
|
||||
struct sockaddr_in6 serv_addr = {
|
||||
.sin6_family = PF_INET6,
|
||||
.sin6_addr = inaddr_any,
|
||||
.sin6_port = htons(hd->config.server_port)
|
||||
};
|
||||
#else
|
||||
struct sockaddr_in serv_addr = {
|
||||
.sin_family = PF_INET,
|
||||
.sin_addr = {
|
||||
.s_addr = htonl(INADDR_ANY)
|
||||
},
|
||||
.sin_port = htons(hd->config.server_port)
|
||||
};
|
||||
#endif
|
||||
/* Enable SO_REUSEADDR to allow binding to the same
|
||||
* address and port when restarting the server */
|
||||
int enable = 1;
|
||||
if (setsockopt(fd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(enable)) < 0) {
|
||||
/* This will fail if CONFIG_LWIP_SO_REUSE is not enabled. But
|
||||
* it does not affect the normal working of the HTTP Server */
|
||||
ESP_LOGW(TAG, LOG_FMT("error in setsockopt SO_REUSEADDR (%d)"), errno);
|
||||
}
|
||||
|
||||
/* Bind to specific network interface if configured */
|
||||
if (hd->config.if_name && hd->config.if_name->ifr_name[0] != 0) {
|
||||
ESP_LOGI(TAG, LOG_FMT("Binding server to interface: %s"), hd->config.if_name->ifr_name);
|
||||
#ifndef __APPLE__
|
||||
if (setsockopt(fd, SOL_SOCKET, SO_BINDTODEVICE, hd->config.if_name, sizeof(struct ifreq)) < 0) {
|
||||
#else
|
||||
int idx = if_nametoindex(hd->config.if_name->ifr_name);
|
||||
if (idx == 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("Invalid interface name %s"), hd->config.if_name->ifr_name);
|
||||
close(fd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
if (setsockopt(fd, IPPROTO_IP, IP_BOUND_IF, &idx, sizeof(idx)) < 0) {
|
||||
#endif
|
||||
ESP_LOGE(TAG, LOG_FMT("Failed to bind to interface %s (%d)"), hd->config.if_name->ifr_name, errno);
|
||||
close(fd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
int ret = bind(fd, (struct sockaddr *)&serv_addr, sizeof(serv_addr));
|
||||
if (ret < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in bind (%d)"), errno);
|
||||
close(fd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ret = listen(fd, hd->config.backlog_conn);
|
||||
if (ret < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in listen (%d)"), errno);
|
||||
close(fd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
int ctrl_fd = cs_create_ctrl_sock(hd->config.ctrl_port);
|
||||
if (ctrl_fd < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in creating ctrl socket (%d)"), errno);
|
||||
close(fd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
int msg_fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||
if (msg_fd < 0) {
|
||||
ESP_LOGE(TAG, LOG_FMT("error in creating msg socket (%d)"), errno);
|
||||
close(fd);
|
||||
close(ctrl_fd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
hd->listen_fd = fd;
|
||||
hd->ctrl_fd = ctrl_fd;
|
||||
hd->msg_fd = msg_fd;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static struct httpd_data *httpd_create(const httpd_config_t *config)
|
||||
{
|
||||
/* Allocate memory for httpd instance data */
|
||||
struct httpd_data *hd = calloc(1, sizeof(struct httpd_data));
|
||||
if (!hd) {
|
||||
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP server instance"));
|
||||
return NULL;
|
||||
}
|
||||
hd->hd_calls = calloc(config->max_uri_handlers, sizeof(httpd_uri_t *));
|
||||
if (!hd->hd_calls) {
|
||||
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP URI handlers"));
|
||||
free(hd);
|
||||
return NULL;
|
||||
}
|
||||
hd->hd_sd = calloc(config->max_open_sockets, sizeof(struct sock_db));
|
||||
if (!hd->hd_sd) {
|
||||
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP session data"));
|
||||
free(hd->hd_calls);
|
||||
free(hd);
|
||||
return NULL;
|
||||
}
|
||||
struct httpd_req_aux *ra = &hd->hd_req_aux;
|
||||
ra->resp_hdrs = calloc(config->max_resp_headers, sizeof(struct resp_hdr));
|
||||
if (!ra->resp_hdrs) {
|
||||
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP response headers"));
|
||||
free(hd->hd_sd);
|
||||
free(hd->hd_calls);
|
||||
free(hd);
|
||||
return NULL;
|
||||
}
|
||||
hd->err_handler_fns = calloc(HTTPD_ERR_CODE_MAX, sizeof(httpd_err_handler_func_t));
|
||||
if (!hd->err_handler_fns) {
|
||||
ESP_LOGE(TAG, LOG_FMT("Failed to allocate memory for HTTP error handlers"));
|
||||
free(ra->resp_hdrs);
|
||||
free(hd->hd_sd);
|
||||
free(hd->hd_calls);
|
||||
free(hd);
|
||||
return NULL;
|
||||
}
|
||||
/* Save the configuration for this instance */
|
||||
hd->config = *config;
|
||||
return hd;
|
||||
}
|
||||
|
||||
static void httpd_delete(struct httpd_data *hd)
|
||||
{
|
||||
struct httpd_req_aux *ra = &hd->hd_req_aux;
|
||||
/* Free memory of httpd instance data */
|
||||
free(hd->err_handler_fns);
|
||||
free(ra->resp_hdrs);
|
||||
free(hd->hd_sd);
|
||||
if (hd->ctrl_sock_semaphore) {
|
||||
vSemaphoreDelete(hd->ctrl_sock_semaphore);
|
||||
hd->ctrl_sock_semaphore = NULL;
|
||||
}
|
||||
|
||||
/* Free registered URI handlers */
|
||||
httpd_unregister_all_uri_handlers(hd);
|
||||
free(hd->hd_calls);
|
||||
free(hd);
|
||||
}
|
||||
|
||||
esp_err_t httpd_start(httpd_handle_t *handle, const httpd_config_t *config)
|
||||
{
|
||||
if (handle == NULL || config == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
/* Sanity check about whether LWIP is configured for providing the
|
||||
* maximum number of open sockets sufficient for the server. Though,
|
||||
* this check doesn't guarantee that many sockets will actually be
|
||||
* available at runtime as other processes may use up some sockets.
|
||||
* Note that server also uses 3 sockets for its internal use :
|
||||
* 1) listening for new TCP connections
|
||||
* 2) for sending control messages over UDP
|
||||
* 3) for receiving control messages over UDP
|
||||
* So the total number of required sockets is max_open_sockets + 3
|
||||
*/
|
||||
if (HTTPD_MAX_SOCKETS < config->max_open_sockets + 3) {
|
||||
ESP_LOGE(TAG, "Config option max_open_sockets is too large (max allowed %d, 3 sockets used by HTTP server internally)\n\t"
|
||||
"Either decrease this or configure LWIP_MAX_SOCKETS to a larger value",
|
||||
HTTPD_MAX_SOCKETS - 3);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_data *hd = httpd_create(config);
|
||||
if (hd == NULL) {
|
||||
/* Failed to allocate memory */
|
||||
return ESP_ERR_HTTPD_ALLOC_MEM;
|
||||
}
|
||||
/* Counting semaphore sized to the UDP control-socket recv mbox. Each
|
||||
* httpd_queue_work() take reserves one mbox slot; httpd_process_ctrl_msg()
|
||||
* gives one back per drain. This bounds the producer to the mbox capacity
|
||||
* and prevents silent lwIP-mbox overflow drops that would otherwise leak
|
||||
* the caller's async-send context. Always created so the default
|
||||
* (non-blocking) httpd_queue_work() path can also rely on it. */
|
||||
hd->ctrl_sock_semaphore = xSemaphoreCreateCounting(CONFIG_LWIP_UDP_RECVMBOX_SIZE, CONFIG_LWIP_UDP_RECVMBOX_SIZE);
|
||||
if (hd->ctrl_sock_semaphore == NULL) {
|
||||
ESP_LOGE(TAG, "Failed to create Semaphore");
|
||||
httpd_delete(hd);
|
||||
return ESP_ERR_HTTPD_ALLOC_MEM;
|
||||
}
|
||||
|
||||
if (httpd_server_init(hd) != ESP_OK) {
|
||||
httpd_delete(hd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
httpd_sess_init(hd);
|
||||
if (httpd_os_thread_create(&hd->hd_td.handle, "httpd",
|
||||
hd->config.stack_size,
|
||||
hd->config.task_priority,
|
||||
httpd_thread, hd,
|
||||
hd->config.core_id,
|
||||
hd->config.task_caps) != ESP_OK) {
|
||||
/* Close the open socket */
|
||||
close(hd->listen_fd);
|
||||
/* Close the control socket */
|
||||
cs_free_ctrl_sock(hd->ctrl_fd);
|
||||
/* Close the message socket */
|
||||
close(hd->msg_fd);
|
||||
/* Failed to launch task */
|
||||
httpd_delete(hd);
|
||||
return ESP_ERR_HTTPD_TASK;
|
||||
}
|
||||
|
||||
*handle = (httpd_handle_t)hd;
|
||||
hd->http_server_state = HTTP_SERVER_EVENT_START;
|
||||
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_START, NULL, 0);
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_stop(httpd_handle_t handle)
|
||||
{
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
if (hd == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_ctrl_data msg;
|
||||
memset(&msg, 0, sizeof(msg));
|
||||
msg.hc_msg = HTTPD_CTRL_SHUTDOWN;
|
||||
|
||||
/* Reserve a slot in the ctrl mbox before sending so we never push past
|
||||
* its capacity. Blocking is safe: the httpd task is the consumer and
|
||||
* keeps draining the mbox until it observes HTTPD_CTRL_SHUTDOWN. */
|
||||
if (xSemaphoreTake(hd->ctrl_sock_semaphore, portMAX_DELAY) != pdTRUE) {
|
||||
ESP_LOGE(TAG, "Failed to acquire ctrl socket semaphore");
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
int ret = cs_send_to_ctrl_sock(hd->msg_fd, hd->config.ctrl_port, &msg, sizeof(msg));
|
||||
if (ret < 0) {
|
||||
ESP_LOGE(TAG, "Failed to send shutdown signal err=%d", ret);
|
||||
xSemaphoreGive(hd->ctrl_sock_semaphore);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("sent control msg to stop server"));
|
||||
while (hd->hd_td.status != THREAD_STOPPED) {
|
||||
httpd_os_thread_sleep(100);
|
||||
}
|
||||
|
||||
/* Release global user context, if not NULL */
|
||||
if (hd->config.global_user_ctx) {
|
||||
if (hd->config.global_user_ctx_free_fn) {
|
||||
hd->config.global_user_ctx_free_fn(hd->config.global_user_ctx);
|
||||
} else {
|
||||
free(hd->config.global_user_ctx);
|
||||
}
|
||||
hd->config.global_user_ctx = NULL;
|
||||
}
|
||||
|
||||
/* Release global transport context, if not NULL */
|
||||
if (hd->config.global_transport_ctx) {
|
||||
if (hd->config.global_transport_ctx_free_fn) {
|
||||
hd->config.global_transport_ctx_free_fn(hd->config.global_transport_ctx);
|
||||
} else {
|
||||
free(hd->config.global_transport_ctx);
|
||||
}
|
||||
hd->config.global_transport_ctx = NULL;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("server stopped"));
|
||||
httpd_delete(hd);
|
||||
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_STOP, NULL, 0);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_http_server_event_id_t httpd_get_server_state(httpd_handle_t handle)
|
||||
{
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
if (hd == NULL) {
|
||||
return HTTP_SERVER_EVENT_ERROR;
|
||||
}
|
||||
return hd->http_server_state;
|
||||
}
|
||||
+1277
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,520 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
#include <stdlib.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_err.h>
|
||||
#include <fcntl.h>
|
||||
#include <errno.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <esp_http_server.h>
|
||||
#include "esp_httpd_priv.h"
|
||||
|
||||
static const char *TAG = "httpd_sess";
|
||||
|
||||
typedef enum {
|
||||
HTTPD_TASK_NONE = 0,
|
||||
HTTPD_TASK_INIT, // Init session
|
||||
HTTPD_TASK_GET_ACTIVE, // Get active session (fd!=-1)
|
||||
HTTPD_TASK_GET_FREE, // Get free session slot (fd<0)
|
||||
HTTPD_TASK_FIND_FD, // Find session with specific fd
|
||||
HTTPD_TASK_SET_DESCRIPTOR, // Set descriptor
|
||||
HTTPD_TASK_DELETE_INVALID, // Delete invalid session
|
||||
HTTPD_TASK_FIND_LOWEST_LRU, // Find session with lowest lru
|
||||
HTTPD_TASK_CLOSE // Close session
|
||||
} task_t;
|
||||
|
||||
typedef struct {
|
||||
task_t task;
|
||||
int fd;
|
||||
fd_set *fdset;
|
||||
int max_fd;
|
||||
struct httpd_data *hd;
|
||||
uint64_t lru_counter;
|
||||
struct sock_db *session;
|
||||
} enum_context_t;
|
||||
|
||||
void httpd_sess_enum(struct httpd_data *hd, httpd_session_enum_function enum_function, void *context)
|
||||
{
|
||||
if ((!hd) || (!hd->hd_sd) || (!hd->config.max_open_sockets)) {
|
||||
return;
|
||||
}
|
||||
|
||||
struct sock_db *current = hd->hd_sd;
|
||||
struct sock_db *end = hd->hd_sd + hd->config.max_open_sockets - 1;
|
||||
|
||||
while (current <= end) {
|
||||
if (enum_function && (!enum_function(current, context))) {
|
||||
break;
|
||||
}
|
||||
current++;
|
||||
}
|
||||
}
|
||||
|
||||
// Check if a FD is valid
|
||||
static int fd_is_valid(int fd)
|
||||
{
|
||||
return fcntl(fd, F_GETFD) != -1 || errno != EBADF;
|
||||
}
|
||||
|
||||
static int enum_function(struct sock_db *session, void *context)
|
||||
{
|
||||
if ((!session) || (!context)) {
|
||||
return 0;
|
||||
}
|
||||
enum_context_t *ctx = (enum_context_t *) context;
|
||||
int found = 0;
|
||||
switch (ctx->task) {
|
||||
// Initialize session
|
||||
case HTTPD_TASK_INIT:
|
||||
session->fd = -1;
|
||||
session->ctx = NULL;
|
||||
session->for_async_req = false;
|
||||
break;
|
||||
// Get active session
|
||||
case HTTPD_TASK_GET_ACTIVE:
|
||||
found = (session->fd != -1);
|
||||
break;
|
||||
// Get free slot
|
||||
case HTTPD_TASK_GET_FREE:
|
||||
found = (session->fd < 0);
|
||||
break;
|
||||
// Find fd
|
||||
case HTTPD_TASK_FIND_FD:
|
||||
found = (session->fd == ctx->fd);
|
||||
break;
|
||||
// Set descriptor
|
||||
case HTTPD_TASK_SET_DESCRIPTOR:
|
||||
if (session->fd != -1 && !session->for_async_req) {
|
||||
FD_SET(session->fd, ctx->fdset);
|
||||
if (session->fd > ctx->max_fd) {
|
||||
ctx->max_fd = session->fd;
|
||||
}
|
||||
}
|
||||
break;
|
||||
// Delete invalid session
|
||||
case HTTPD_TASK_DELETE_INVALID:
|
||||
if (!fd_is_valid(session->fd)) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Closing invalid socket %d"), session->fd);
|
||||
httpd_sess_delete(ctx->hd, session);
|
||||
}
|
||||
break;
|
||||
// Find lowest lru
|
||||
case HTTPD_TASK_FIND_LOWEST_LRU:
|
||||
// Found free slot - no need to check other sessions
|
||||
if (session->fd == -1) {
|
||||
return 0;
|
||||
}
|
||||
// Only close sockets that are not in use
|
||||
if (session->for_async_req == false) {
|
||||
// Check/update lowest lru
|
||||
if (session->lru_counter < ctx->lru_counter) {
|
||||
ctx->lru_counter = session->lru_counter;
|
||||
ctx->session = session;
|
||||
}
|
||||
}
|
||||
break;
|
||||
case HTTPD_TASK_CLOSE:
|
||||
if (session->fd != -1) {
|
||||
ESP_LOGD(TAG, LOG_FMT("cleaning up socket %d"), session->fd);
|
||||
httpd_sess_delete(ctx->hd, session);
|
||||
}
|
||||
break;
|
||||
default:
|
||||
return 0;
|
||||
}
|
||||
if (found) {
|
||||
ctx->session = session;
|
||||
return 0;
|
||||
}
|
||||
return 1;
|
||||
}
|
||||
|
||||
static void httpd_sess_close(void *arg)
|
||||
{
|
||||
struct sock_db *sock_db = (struct sock_db *) arg;
|
||||
if (!sock_db) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (!sock_db->lru_counter && !sock_db->lru_socket) {
|
||||
ESP_LOGD(TAG, "Skipping session close for %d as it seems to be a race condition", sock_db->fd);
|
||||
return;
|
||||
}
|
||||
sock_db->lru_socket = false;
|
||||
struct httpd_data *hd = (struct httpd_data *) sock_db->handle;
|
||||
hd->http_server_state = HTTP_SERVER_EVENT_DISCONNECTED;
|
||||
httpd_sess_delete(hd, sock_db);
|
||||
}
|
||||
|
||||
struct sock_db *httpd_sess_get_free(struct httpd_data *hd)
|
||||
{
|
||||
if ((!hd) || (hd->hd_sd_active_count == hd->config.max_open_sockets)) {
|
||||
return NULL;
|
||||
}
|
||||
enum_context_t context = {
|
||||
.task = HTTPD_TASK_GET_FREE
|
||||
};
|
||||
httpd_sess_enum(hd, enum_function, &context);
|
||||
return context.session;
|
||||
}
|
||||
|
||||
bool httpd_is_sess_available(struct httpd_data *hd)
|
||||
{
|
||||
return httpd_sess_get_free(hd) ? true : false;
|
||||
}
|
||||
|
||||
struct sock_db *httpd_sess_get(struct httpd_data *hd, int sockfd)
|
||||
{
|
||||
if ((!hd) || (!hd->hd_sd) || (!hd->config.max_open_sockets)) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Check if called inside a request handler, and the session sockfd in use is same as the parameter
|
||||
// => Just return the pointer to the sock_db corresponding to the request
|
||||
if ((hd->hd_req_aux.sd) && (hd->hd_req_aux.sd->fd == sockfd)) {
|
||||
return hd->hd_req_aux.sd;
|
||||
}
|
||||
|
||||
enum_context_t context = {
|
||||
.task = HTTPD_TASK_FIND_FD,
|
||||
.fd = sockfd
|
||||
};
|
||||
httpd_sess_enum(hd, enum_function, &context);
|
||||
return context.session;
|
||||
}
|
||||
|
||||
esp_err_t httpd_sess_new(struct httpd_data *hd, int newfd)
|
||||
{
|
||||
ESP_LOGD(TAG, LOG_FMT("fd = %d"), newfd);
|
||||
|
||||
if (httpd_sess_get(hd, newfd)) {
|
||||
ESP_LOGE(TAG, LOG_FMT("session already exists with fd = %d"), newfd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
struct sock_db *session = httpd_sess_get_free(hd);
|
||||
if (!session) {
|
||||
ESP_LOGD(TAG, LOG_FMT("unable to launch session for fd = %d"), newfd);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
// Clear session data
|
||||
memset(session, 0, sizeof (struct sock_db));
|
||||
session->fd = newfd;
|
||||
session->handle = (httpd_handle_t) hd;
|
||||
session->send_fn = httpd_default_send;
|
||||
session->recv_fn = httpd_default_recv;
|
||||
session->lru_counter = hd->lru_counter;
|
||||
|
||||
// increment number of sessions
|
||||
hd->hd_sd_active_count++;
|
||||
|
||||
// Call user-defined session opening function
|
||||
if (hd->config.open_fn) {
|
||||
esp_err_t ret = hd->config.open_fn(hd, session->fd);
|
||||
if (ret != ESP_OK) {
|
||||
httpd_sess_delete(hd, session);
|
||||
ESP_LOGD(TAG, LOG_FMT("open_fn failed for fd = %d"), newfd);
|
||||
return ret;
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("active sockets: %d"), hd->hd_sd_active_count);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
void httpd_sess_free_ctx(void **ctx, httpd_free_ctx_fn_t free_fn)
|
||||
{
|
||||
if ((!ctx) || (!*ctx)) {
|
||||
return;
|
||||
}
|
||||
if (free_fn) {
|
||||
free_fn(*ctx);
|
||||
} else {
|
||||
free(*ctx);
|
||||
}
|
||||
*ctx = NULL;
|
||||
}
|
||||
|
||||
void httpd_sess_clear_ctx(struct sock_db *session)
|
||||
{
|
||||
if ((!session) || ((!session->ctx) && (!session->transport_ctx))) {
|
||||
return;
|
||||
}
|
||||
|
||||
// free user ctx
|
||||
if (session->ctx) {
|
||||
httpd_sess_free_ctx(&session->ctx, session->free_ctx);
|
||||
session->free_ctx = NULL;
|
||||
}
|
||||
|
||||
// Free 'transport' context
|
||||
if (session->transport_ctx) {
|
||||
httpd_sess_free_ctx(&session->transport_ctx, session->free_transport_ctx);
|
||||
session->free_transport_ctx = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
void *httpd_sess_get_ctx(httpd_handle_t handle, int sockfd)
|
||||
{
|
||||
struct sock_db *session = httpd_sess_get(handle, sockfd);
|
||||
if (!session) {
|
||||
return NULL;
|
||||
}
|
||||
|
||||
// Check if the function has been called from inside a
|
||||
// request handler, in which case fetch the context from
|
||||
// the httpd_req_t structure
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
if (hd->hd_req_aux.sd == session) {
|
||||
return hd->hd_req.sess_ctx;
|
||||
}
|
||||
return session->ctx;
|
||||
}
|
||||
|
||||
void httpd_sess_set_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn)
|
||||
{
|
||||
struct sock_db *session = httpd_sess_get(handle, sockfd);
|
||||
if (!session) {
|
||||
return;
|
||||
}
|
||||
|
||||
// Check if the function has been called from inside a
|
||||
// request handler, in which case set the context inside
|
||||
// the httpd_req_t structure
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
if (hd->hd_req_aux.sd == session) {
|
||||
if (hd->hd_req.sess_ctx != ctx) {
|
||||
// Don't free previous context if it is in sockdb
|
||||
// as it will be freed inside httpd_req_cleanup()
|
||||
if (session->ctx != hd->hd_req.sess_ctx) {
|
||||
httpd_sess_free_ctx(&hd->hd_req.sess_ctx, hd->hd_req.free_ctx); // Free previous context
|
||||
}
|
||||
hd->hd_req.sess_ctx = ctx;
|
||||
}
|
||||
hd->hd_req.free_ctx = free_fn;
|
||||
return;
|
||||
}
|
||||
|
||||
// Else set the context inside the sock_db structure
|
||||
if (session->ctx != ctx) {
|
||||
// Free previous context
|
||||
httpd_sess_free_ctx(&session->ctx, session->free_ctx);
|
||||
session->ctx = ctx;
|
||||
}
|
||||
session->free_ctx = free_fn;
|
||||
}
|
||||
|
||||
void *httpd_sess_get_transport_ctx(httpd_handle_t handle, int sockfd)
|
||||
{
|
||||
struct sock_db *session = httpd_sess_get(handle, sockfd);
|
||||
return session ? session->transport_ctx : NULL;
|
||||
}
|
||||
|
||||
void httpd_sess_set_transport_ctx(httpd_handle_t handle, int sockfd, void *ctx, httpd_free_ctx_fn_t free_fn)
|
||||
{
|
||||
struct sock_db *session = httpd_sess_get(handle, sockfd);
|
||||
if (!session) {
|
||||
return;
|
||||
}
|
||||
|
||||
if (session->transport_ctx != ctx) {
|
||||
// Free previous transport context
|
||||
httpd_sess_free_ctx(&session->transport_ctx, session->free_transport_ctx);
|
||||
session->transport_ctx = ctx;
|
||||
}
|
||||
session->free_transport_ctx = free_fn;
|
||||
}
|
||||
|
||||
void httpd_sess_set_descriptors(struct httpd_data *hd, fd_set *fdset, int *maxfd)
|
||||
{
|
||||
enum_context_t context = {
|
||||
.task = HTTPD_TASK_SET_DESCRIPTOR,
|
||||
.max_fd = -1,
|
||||
.fdset = fdset
|
||||
};
|
||||
httpd_sess_enum(hd, enum_function, &context);
|
||||
if (maxfd) {
|
||||
*maxfd = context.max_fd;
|
||||
}
|
||||
}
|
||||
|
||||
void httpd_sess_delete_invalid(struct httpd_data *hd)
|
||||
{
|
||||
enum_context_t context = {
|
||||
.task = HTTPD_TASK_DELETE_INVALID,
|
||||
.hd = hd
|
||||
};
|
||||
httpd_sess_enum(hd, enum_function, &context);
|
||||
}
|
||||
|
||||
void httpd_sess_delete(struct httpd_data *hd, struct sock_db *session)
|
||||
{
|
||||
if ((!hd) || (!session) || (session->fd < 0)) {
|
||||
return;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("fd = %d"), session->fd);
|
||||
if (hd->config.enable_so_linger) {
|
||||
struct linger so_linger = {
|
||||
.l_onoff = true,
|
||||
.l_linger = hd->config.linger_timeout,
|
||||
};
|
||||
if (setsockopt(session->fd, SOL_SOCKET, SO_LINGER, &so_linger, sizeof(struct linger)) < 0) {
|
||||
ESP_LOGW(TAG, LOG_FMT("error enabling SO_LINGER (%d)"), errno);
|
||||
}
|
||||
}
|
||||
|
||||
// Call close function if defined
|
||||
if (hd->config.close_fn) {
|
||||
hd->config.close_fn(hd, session->fd);
|
||||
} else {
|
||||
close(session->fd);
|
||||
}
|
||||
hd->http_server_state = HTTP_SERVER_EVENT_DISCONNECTED;
|
||||
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_DISCONNECTED, &session->fd, sizeof(int));
|
||||
|
||||
// clear all contexts
|
||||
httpd_sess_clear_ctx(session);
|
||||
|
||||
// mark session slot as available
|
||||
session->fd = -1;
|
||||
|
||||
// decrement number of sessions
|
||||
hd->hd_sd_active_count--;
|
||||
ESP_LOGD(TAG, LOG_FMT("active sockets: %d"), hd->hd_sd_active_count);
|
||||
if (!hd->hd_sd_active_count) {
|
||||
hd->lru_counter = 0;
|
||||
}
|
||||
}
|
||||
|
||||
void httpd_sess_init(struct httpd_data *hd)
|
||||
{
|
||||
enum_context_t context = {
|
||||
.task = HTTPD_TASK_INIT
|
||||
};
|
||||
httpd_sess_enum(hd, enum_function, &context);
|
||||
}
|
||||
|
||||
bool httpd_sess_pending(struct httpd_data *hd, struct sock_db *session)
|
||||
{
|
||||
if (!session) {
|
||||
return false;
|
||||
}
|
||||
if (session->pending_fn) {
|
||||
// test if there's any data to be read (besides read() function, which is handled by select() in the main httpd loop)
|
||||
// this should check e.g. for the SSL data buffer
|
||||
if (session->pending_fn(hd, session->fd) > 0) {
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return (session->pending_len != 0);
|
||||
}
|
||||
|
||||
/* This MUST return ESP_OK on successful execution. If any other
|
||||
* value is returned, everything related to this socket will be
|
||||
* cleaned up and the socket will be closed.
|
||||
*/
|
||||
esp_err_t httpd_sess_process(struct httpd_data *hd, struct sock_db *session)
|
||||
{
|
||||
if ((!hd) || (!session)) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("httpd_req_new"));
|
||||
if (httpd_req_new(hd, session) != ESP_OK) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
ESP_LOGD(TAG, LOG_FMT("httpd_req_delete"));
|
||||
if (httpd_req_delete(hd) != ESP_OK) {
|
||||
return ESP_FAIL;
|
||||
}
|
||||
ESP_LOGD(TAG, LOG_FMT("success"));
|
||||
session->lru_counter = ++hd->lru_counter;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_sess_update_lru_counter(httpd_handle_t handle, int sockfd)
|
||||
{
|
||||
if (handle == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
|
||||
enum_context_t context = {
|
||||
.task = HTTPD_TASK_FIND_FD,
|
||||
.fd = sockfd
|
||||
};
|
||||
httpd_sess_enum(hd, enum_function, &context);
|
||||
if (context.session) {
|
||||
context.session->lru_counter = ++hd->lru_counter;
|
||||
return ESP_OK;
|
||||
}
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
|
||||
esp_err_t httpd_sess_close_lru(struct httpd_data *hd)
|
||||
{
|
||||
enum_context_t context = {
|
||||
.task = HTTPD_TASK_FIND_LOWEST_LRU,
|
||||
.lru_counter = UINT64_MAX,
|
||||
.fd = -1
|
||||
};
|
||||
httpd_sess_enum(hd, enum_function, &context);
|
||||
if (!context.session) {
|
||||
return ESP_OK;
|
||||
}
|
||||
ESP_LOGD(TAG, LOG_FMT("Closing session with fd %d"), context.session->fd);
|
||||
context.session->lru_socket = true;
|
||||
return httpd_sess_trigger_close_(hd, context.session);
|
||||
}
|
||||
|
||||
esp_err_t httpd_sess_trigger_close_(httpd_handle_t handle, struct sock_db *session)
|
||||
{
|
||||
if (!session) {
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
return httpd_queue_work(handle, httpd_sess_close, session);
|
||||
}
|
||||
|
||||
esp_err_t httpd_sess_trigger_close(httpd_handle_t handle, int sockfd)
|
||||
{
|
||||
struct sock_db *session = httpd_sess_get(handle, sockfd);
|
||||
if (!session) {
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
return httpd_sess_trigger_close_(handle, session);
|
||||
}
|
||||
|
||||
void httpd_sess_close_all(struct httpd_data *hd)
|
||||
{
|
||||
enum_context_t context = {
|
||||
.task = HTTPD_TASK_CLOSE,
|
||||
.hd = hd
|
||||
};
|
||||
httpd_sess_enum(hd, enum_function, &context);
|
||||
}
|
||||
|
||||
esp_err_t httpd_sess_close_lru_direct(struct httpd_data *hd)
|
||||
{
|
||||
enum_context_t context = {
|
||||
.task = HTTPD_TASK_FIND_LOWEST_LRU,
|
||||
.lru_counter = UINT64_MAX,
|
||||
.fd = -1
|
||||
};
|
||||
httpd_sess_enum(hd, enum_function, &context);
|
||||
if (!context.session) {
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("Directly closing session with fd %d"), context.session->fd);
|
||||
// Call httpd_sess_delete directly instead of going through work queue
|
||||
httpd_sess_delete(hd, context.session);
|
||||
return ESP_OK;
|
||||
}
|
||||
@@ -0,0 +1,848 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
|
||||
#include <errno.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_err.h>
|
||||
|
||||
#include <esp_http_server.h>
|
||||
#include "esp_httpd_priv.h"
|
||||
#include <netinet/tcp.h>
|
||||
#include "ctrl_sock.h"
|
||||
|
||||
static const char *TAG = "httpd_txrx";
|
||||
|
||||
esp_err_t httpd_sess_set_send_override(httpd_handle_t hd, int sockfd, httpd_send_func_t send_func)
|
||||
{
|
||||
struct sock_db *sess = httpd_sess_get(hd, sockfd);
|
||||
if (!sess) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
sess->send_fn = send_func;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_sess_set_recv_override(httpd_handle_t hd, int sockfd, httpd_recv_func_t recv_func)
|
||||
{
|
||||
struct sock_db *sess = httpd_sess_get(hd, sockfd);
|
||||
if (!sess) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
sess->recv_fn = recv_func;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_sess_set_pending_override(httpd_handle_t hd, int sockfd, httpd_pending_func_t pending_func)
|
||||
{
|
||||
struct sock_db *sess = httpd_sess_get(hd, sockfd);
|
||||
if (!sess) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
sess->pending_fn = pending_func;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
int httpd_send(httpd_req_t *r, const char *buf, size_t buf_len)
|
||||
{
|
||||
if (r == NULL || buf == NULL) {
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
|
||||
if (!httpd_valid_req(r)) {
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
int ret = ra->sd->send_fn(ra->sd->handle, ra->sd->fd, buf, buf_len, 0);
|
||||
if (ret < 0) {
|
||||
ESP_LOGD(TAG, LOG_FMT("error in send_fn"));
|
||||
return ret;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
static esp_err_t httpd_send_all(httpd_req_t *r, const char *buf, size_t buf_len)
|
||||
{
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
int ret;
|
||||
|
||||
while (buf_len > 0) {
|
||||
ret = ra->sd->send_fn(ra->sd->handle, ra->sd->fd, buf, buf_len, 0);
|
||||
if (ret < 0) {
|
||||
ESP_LOGD(TAG, LOG_FMT("error in send_fn"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
ESP_LOGD(TAG, LOG_FMT("sent = %d"), ret);
|
||||
buf += ret;
|
||||
buf_len -= ret;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static size_t httpd_recv_pending(httpd_req_t *r, char *buf, size_t buf_len)
|
||||
{
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
size_t offset = sizeof(ra->sd->pending_data) - ra->sd->pending_len;
|
||||
|
||||
/* buf_len must not be greater than remaining_len */
|
||||
buf_len = MIN(ra->sd->pending_len, buf_len);
|
||||
memcpy(buf, ra->sd->pending_data + offset, buf_len);
|
||||
|
||||
ra->sd->pending_len -= buf_len;
|
||||
return buf_len;
|
||||
}
|
||||
|
||||
int httpd_recv_with_opt(httpd_req_t *r, char *buf, size_t buf_len, httpd_recv_opt_t opt)
|
||||
{
|
||||
ESP_LOGD(TAG, LOG_FMT("requested length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(buf_len));
|
||||
|
||||
size_t pending_len = 0;
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
|
||||
/* First fetch pending data from local buffer */
|
||||
if (ra->sd->pending_len > 0) {
|
||||
ESP_LOGD(TAG, LOG_FMT("pending length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(ra->sd->pending_len));
|
||||
pending_len = httpd_recv_pending(r, buf, buf_len);
|
||||
buf += pending_len;
|
||||
buf_len -= pending_len;
|
||||
|
||||
/* If buffer filled then no need to recv.
|
||||
* If asked to halt after receiving pending data then
|
||||
* return with received length */
|
||||
if (!buf_len || opt == HTTPD_RECV_OPT_HALT_AFTER_PENDING) {
|
||||
return pending_len;
|
||||
}
|
||||
}
|
||||
|
||||
/* Receive data of remaining length */
|
||||
size_t recv_len = pending_len;
|
||||
do {
|
||||
int ret = ra->sd->recv_fn(ra->sd->handle, ra->sd->fd, buf, buf_len, 0);
|
||||
if (ret <= 0) {
|
||||
ESP_LOGD(TAG, LOG_FMT("error in recv_fn"));
|
||||
if ((ret == HTTPD_SOCK_ERR_TIMEOUT) && (pending_len != 0)) {
|
||||
/* If recv() timeout occurred, but pending data is
|
||||
* present, return length of pending data.
|
||||
* This behavior is similar to that of socket recv()
|
||||
* function, which, in case has only partially read the
|
||||
* requested length, due to timeout, returns with read
|
||||
* length, rather than error */
|
||||
return pending_len;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
recv_len += ret;
|
||||
buf += ret;
|
||||
buf_len -= ret;
|
||||
} while (buf_len > 0 && opt == HTTPD_RECV_OPT_BLOCKING);
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("received length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(recv_len));
|
||||
return recv_len;
|
||||
}
|
||||
|
||||
int httpd_recv(httpd_req_t *r, char *buf, size_t buf_len)
|
||||
{
|
||||
return httpd_recv_with_opt(r, buf, buf_len, HTTPD_RECV_OPT_NONE);
|
||||
}
|
||||
|
||||
size_t httpd_unrecv(struct httpd_req *r, const char *buf, size_t buf_len)
|
||||
{
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
/* Truncate if external buf_len is greater than pending_data buffer size */
|
||||
ra->sd->pending_len = MIN(sizeof(ra->sd->pending_data), buf_len);
|
||||
|
||||
/* Copy data into internal pending_data buffer with the exact offset
|
||||
* such that it is right aligned inside the buffer */
|
||||
size_t offset = sizeof(ra->sd->pending_data) - ra->sd->pending_len;
|
||||
memcpy(ra->sd->pending_data + offset, buf, ra->sd->pending_len);
|
||||
ESP_LOGD(TAG, LOG_FMT("length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(ra->sd->pending_len));
|
||||
return ra->sd->pending_len;
|
||||
}
|
||||
|
||||
/**
|
||||
* This API appends an additional header field-value pair in the HTTP response.
|
||||
* But the header isn't sent out until any of the send APIs is executed.
|
||||
*/
|
||||
esp_err_t httpd_resp_set_hdr(httpd_req_t *r, const char *field, const char *value)
|
||||
{
|
||||
if (r == NULL || field == NULL || value == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
if (!httpd_valid_req(r)) {
|
||||
return ESP_ERR_HTTPD_INVALID_REQ;
|
||||
}
|
||||
|
||||
/* Reject CRLF in header field or value */
|
||||
if (strpbrk(field, "\r\n") || strpbrk(value, "\r\n")) {
|
||||
ESP_LOGW(TAG, LOG_FMT("rejecting header with CRLF: %.32s"), field);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
struct httpd_data *hd = (struct httpd_data *) r->handle;
|
||||
|
||||
/* Number of additional headers is limited */
|
||||
if (ra->resp_hdrs_count >= hd->config.max_resp_headers) {
|
||||
return ESP_ERR_HTTPD_RESP_HDR;
|
||||
}
|
||||
|
||||
/* Assign header field-value pair */
|
||||
ra->resp_hdrs[ra->resp_hdrs_count].field = field;
|
||||
ra->resp_hdrs[ra->resp_hdrs_count].value = value;
|
||||
ra->resp_hdrs_count++;
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("new header = %s: %s"), field, value);
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* This API sets the status of the HTTP response to the value specified.
|
||||
* But the status isn't sent out until any of the send APIs is executed.
|
||||
*/
|
||||
esp_err_t httpd_resp_set_status(httpd_req_t *r, const char *status)
|
||||
{
|
||||
if (r == NULL || status == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
if (!httpd_valid_req(r)) {
|
||||
return ESP_ERR_HTTPD_INVALID_REQ;
|
||||
}
|
||||
|
||||
/* Reject CRLF in status */
|
||||
if (strpbrk(status, "\r\n")) {
|
||||
ESP_LOGW(TAG, LOG_FMT("rejecting status with CRLF: %.32s"), status);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
ra->status = (char *)status;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
/**
|
||||
* This API sets the method/type of the HTTP response to the value specified.
|
||||
* But the method isn't sent out until any of the send APIs is executed.
|
||||
*/
|
||||
esp_err_t httpd_resp_set_type(httpd_req_t *r, const char *type)
|
||||
{
|
||||
if (r == NULL || type == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
if (!httpd_valid_req(r)) {
|
||||
return ESP_ERR_HTTPD_INVALID_REQ;
|
||||
}
|
||||
|
||||
/* Reject CRLF in content type */
|
||||
if (strpbrk(type, "\r\n")) {
|
||||
ESP_LOGW(TAG, LOG_FMT("rejecting content type with CRLF: %.32s"), type);
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
ra->content_type = (char *)type;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_resp_send(httpd_req_t *r, const char *buf, ssize_t buf_len)
|
||||
{
|
||||
if (r == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
if (!httpd_valid_req(r)) {
|
||||
return ESP_ERR_HTTPD_INVALID_REQ;
|
||||
}
|
||||
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
const char *httpd_hdr_str = "HTTP/1.1 %s\r\nContent-Type: %s\r\nContent-Length: %d\r\n";
|
||||
const char *colon_separator = ": ";
|
||||
const char *cr_lf_seperator = "\r\n";
|
||||
|
||||
if (buf_len == HTTPD_RESP_USE_STRLEN) {
|
||||
buf_len = strlen(buf);
|
||||
}
|
||||
|
||||
/* Request headers are no longer available */
|
||||
ra->req_hdrs_count = 0;
|
||||
|
||||
/* Calculate the size of the headers. +1 for the null terminator */
|
||||
size_t required_size = snprintf(NULL, 0, httpd_hdr_str, ra->status, ra->content_type, buf_len) + 1;
|
||||
if (required_size > ra->max_req_hdr_len) {
|
||||
return ESP_ERR_HTTPD_RESP_HDR;
|
||||
}
|
||||
char *res_buf = malloc(required_size); /* Temporary buffer to store the headers */
|
||||
if (res_buf == NULL) {
|
||||
ESP_LOGE(TAG, "Unable to allocate httpd send buffer");
|
||||
return ESP_ERR_HTTPD_ALLOC_MEM;
|
||||
}
|
||||
|
||||
esp_err_t ret = snprintf(res_buf, required_size, httpd_hdr_str, ra->status, ra->content_type, buf_len);
|
||||
if (ret < 0 || ret >= required_size) {
|
||||
free(res_buf);
|
||||
return ESP_ERR_HTTPD_RESP_HDR;
|
||||
}
|
||||
ESP_LOGD(TAG, "httpd send buffer size = %d", strlen(res_buf));
|
||||
ret = httpd_send_all(r, res_buf, strlen(res_buf));
|
||||
free(res_buf);
|
||||
if (ret != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
|
||||
/* Sending additional headers based on set_header */
|
||||
for (unsigned i = 0; i < ra->resp_hdrs_count; i++) {
|
||||
/* Send header field */
|
||||
if (httpd_send_all(r, ra->resp_hdrs[i].field, strlen(ra->resp_hdrs[i].field)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
/* Send ': ' */
|
||||
if (httpd_send_all(r, colon_separator, strlen(colon_separator)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
/* Send header value */
|
||||
if (httpd_send_all(r, ra->resp_hdrs[i].value, strlen(ra->resp_hdrs[i].value)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
/* Send CR + LF */
|
||||
if (httpd_send_all(r, cr_lf_seperator, strlen(cr_lf_seperator)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
}
|
||||
|
||||
/* End header section */
|
||||
if (httpd_send_all(r, cr_lf_seperator, strlen(cr_lf_seperator)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
struct httpd_data *hd = (struct httpd_data *) r->handle;
|
||||
hd->http_server_state = HTTP_SERVER_EVENT_HEADERS_SENT;
|
||||
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_HEADERS_SENT, &(ra->sd->fd), sizeof(int));
|
||||
|
||||
/* Sending content */
|
||||
if (buf && buf_len) {
|
||||
if (httpd_send_all(r, buf, buf_len) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
}
|
||||
esp_http_server_event_data evt_data = {
|
||||
.fd = ra->sd->fd,
|
||||
.data_len = buf_len,
|
||||
};
|
||||
hd->http_server_state = HTTP_SERVER_EVENT_SENT_DATA;
|
||||
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_SENT_DATA, &evt_data, sizeof(esp_http_server_event_data));
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_resp_send_chunk(httpd_req_t *r, const char *buf, ssize_t buf_len)
|
||||
{
|
||||
if (r == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
if (!httpd_valid_req(r)) {
|
||||
return ESP_ERR_HTTPD_INVALID_REQ;
|
||||
}
|
||||
|
||||
if (buf_len == HTTPD_RESP_USE_STRLEN) {
|
||||
buf_len = strlen(buf);
|
||||
}
|
||||
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
struct httpd_data *hd = (struct httpd_data *) r->handle;
|
||||
const char *httpd_chunked_hdr_str = "HTTP/1.1 %s\r\nContent-Type: %s\r\nTransfer-Encoding: chunked\r\n";
|
||||
const char *colon_separator = ": ";
|
||||
const char *cr_lf_seperator = "\r\n";
|
||||
|
||||
/* Request headers are no longer available */
|
||||
ra->req_hdrs_count = 0;
|
||||
|
||||
if (!ra->first_chunk_sent) {
|
||||
/* Calculate the size of the headers. +1 for the null terminator */
|
||||
size_t required_size = snprintf(NULL, 0, httpd_chunked_hdr_str, ra->status, ra->content_type) + 1;
|
||||
if (required_size > ra->max_req_hdr_len) {
|
||||
return ESP_ERR_HTTPD_RESP_HDR;
|
||||
}
|
||||
char *res_buf = malloc(required_size); /* Temporary buffer to store the headers */
|
||||
if (res_buf == NULL) {
|
||||
ESP_LOGE(TAG, "Unable to allocate httpd send chunk buffer");
|
||||
return ESP_ERR_HTTPD_ALLOC_MEM;
|
||||
}
|
||||
esp_err_t ret = snprintf(res_buf, required_size, httpd_chunked_hdr_str, ra->status, ra->content_type);
|
||||
if (ret < 0 || ret >= required_size) {
|
||||
free(res_buf);
|
||||
return ESP_ERR_HTTPD_RESP_HDR;
|
||||
}
|
||||
ESP_LOGD(TAG, "httpd send chunk buffer size = %d", strlen(res_buf));
|
||||
/* Size of essential headers is limited by scratch buffer size */
|
||||
ret = httpd_send_all(r, res_buf, strlen(res_buf));
|
||||
free(res_buf);
|
||||
if (ret != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
|
||||
/* Sending additional headers based on set_header */
|
||||
for (unsigned i = 0; i < ra->resp_hdrs_count; i++) {
|
||||
/* Send header field */
|
||||
if (httpd_send_all(r, ra->resp_hdrs[i].field, strlen(ra->resp_hdrs[i].field)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
/* Send ': ' */
|
||||
if (httpd_send_all(r, colon_separator, strlen(colon_separator)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
/* Send header value */
|
||||
if (httpd_send_all(r, ra->resp_hdrs[i].value, strlen(ra->resp_hdrs[i].value)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
/* Send CR + LF */
|
||||
if (httpd_send_all(r, cr_lf_seperator, strlen(cr_lf_seperator)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
}
|
||||
|
||||
/* End header section */
|
||||
if (httpd_send_all(r, cr_lf_seperator, strlen(cr_lf_seperator)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
ra->first_chunk_sent = true;
|
||||
}
|
||||
|
||||
/* Sending chunked content */
|
||||
char len_str[10];
|
||||
snprintf(len_str, sizeof(len_str), "%lx\r\n", (long)buf_len);
|
||||
if (httpd_send_all(r, len_str, strlen(len_str)) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
|
||||
if (buf) {
|
||||
if (httpd_send_all(r, buf, (size_t) buf_len) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
}
|
||||
|
||||
/* Indicate end of chunk */
|
||||
if (httpd_send_all(r, "\r\n", strlen("\r\n")) != ESP_OK) {
|
||||
return ESP_ERR_HTTPD_RESP_SEND;
|
||||
}
|
||||
esp_http_server_event_data evt_data = {
|
||||
.fd = ra->sd->fd,
|
||||
.data_len = buf_len,
|
||||
};
|
||||
hd->http_server_state = HTTP_SERVER_EVENT_SENT_DATA;
|
||||
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_SENT_DATA, &evt_data, sizeof(esp_http_server_event_data));
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_resp_send_err(httpd_req_t *req, httpd_err_code_t error, const char *usr_msg)
|
||||
{
|
||||
esp_err_t ret;
|
||||
const char *msg;
|
||||
const char *status;
|
||||
|
||||
switch (error) {
|
||||
case HTTPD_501_METHOD_NOT_IMPLEMENTED:
|
||||
status = "501 Method Not Implemented";
|
||||
msg = "Server does not support this method";
|
||||
break;
|
||||
case HTTPD_505_VERSION_NOT_SUPPORTED:
|
||||
status = "505 Version Not Supported";
|
||||
msg = "HTTP version not supported by server";
|
||||
break;
|
||||
case HTTPD_400_BAD_REQUEST:
|
||||
status = "400 Bad Request";
|
||||
msg = "Bad request syntax";
|
||||
break;
|
||||
case HTTPD_401_UNAUTHORIZED:
|
||||
status = "401 Unauthorized";
|
||||
msg = "No permission -- see authorization schemes";
|
||||
break;
|
||||
case HTTPD_403_FORBIDDEN:
|
||||
status = "403 Forbidden";
|
||||
msg = "Request forbidden -- authorization will not help";
|
||||
break;
|
||||
case HTTPD_404_NOT_FOUND:
|
||||
status = "404 Not Found";
|
||||
msg = "Nothing matches the given URI";
|
||||
break;
|
||||
case HTTPD_405_METHOD_NOT_ALLOWED:
|
||||
status = "405 Method Not Allowed";
|
||||
msg = "Specified method is invalid for this resource";
|
||||
break;
|
||||
case HTTPD_408_REQ_TIMEOUT:
|
||||
status = "408 Request Timeout";
|
||||
msg = "Server closed this connection";
|
||||
break;
|
||||
case HTTPD_414_URI_TOO_LONG:
|
||||
status = "414 URI Too Long";
|
||||
msg = "URI is too long";
|
||||
break;
|
||||
case HTTPD_411_LENGTH_REQUIRED:
|
||||
status = "411 Length Required";
|
||||
msg = "Client must specify Content-Length";
|
||||
break;
|
||||
case HTTPD_413_CONTENT_TOO_LARGE:
|
||||
status = "413 Content Too Large";
|
||||
msg = "Content is too large";
|
||||
break;
|
||||
case HTTPD_431_REQ_HDR_FIELDS_TOO_LARGE:
|
||||
status = "431 Request Header Fields Too Large";
|
||||
msg = "Header fields are too long";
|
||||
break;
|
||||
case HTTPD_500_INTERNAL_SERVER_ERROR:
|
||||
default:
|
||||
status = "500 Internal Server Error";
|
||||
msg = "Server has encountered an unexpected error";
|
||||
}
|
||||
|
||||
/* If user has provided custom message, override default message */
|
||||
msg = usr_msg ? usr_msg : msg;
|
||||
ESP_LOGW(TAG, LOG_FMT("%s - %s"), status, msg);
|
||||
|
||||
/* Set error code in HTTP response */
|
||||
httpd_resp_set_status(req, status);
|
||||
httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
|
||||
|
||||
#ifdef CONFIG_HTTPD_ERR_RESP_NO_DELAY
|
||||
/* Use TCP_NODELAY option to force socket to send data in buffer
|
||||
* This ensures that the error message is sent before the socket
|
||||
* is closed */
|
||||
struct httpd_req_aux *ra = req->aux;
|
||||
int nodelay = 1;
|
||||
if (setsockopt(ra->sd->fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) {
|
||||
/* If failed to turn on TCP_NODELAY, throw warning and continue */
|
||||
ESP_LOGW(TAG, LOG_FMT("error calling setsockopt : %d"), errno);
|
||||
nodelay = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Send HTTP error message */
|
||||
ret = httpd_resp_send(req, msg, HTTPD_RESP_USE_STRLEN);
|
||||
|
||||
#ifdef CONFIG_HTTPD_ERR_RESP_NO_DELAY
|
||||
/* If TCP_NODELAY was set successfully above, time to disable it */
|
||||
if (nodelay == 1) {
|
||||
nodelay = 0;
|
||||
if (setsockopt(ra->sd->fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) {
|
||||
/* If failed to turn off TCP_NODELAY, throw error and
|
||||
* return failure to signal for socket closure */
|
||||
ESP_LOGE(TAG, LOG_FMT("error calling setsockopt : %d"), errno);
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_ERROR, &error, sizeof(httpd_err_code_t));
|
||||
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t httpd_resp_send_custom_err(httpd_req_t *req, const char *status, const char *msg)
|
||||
{
|
||||
ESP_LOGW(TAG, LOG_FMT("%s - %s"), status, msg);
|
||||
|
||||
/* Set error code in HTTP response */
|
||||
httpd_resp_set_status(req, status);
|
||||
httpd_resp_set_type(req, HTTPD_TYPE_TEXT);
|
||||
|
||||
#ifdef CONFIG_HTTPD_ERR_RESP_NO_DELAY
|
||||
/* Use TCP_NODELAY option to force socket to send data in buffer
|
||||
* This ensures that the error message is sent before the socket
|
||||
* is closed */
|
||||
struct httpd_req_aux *ra = req->aux;
|
||||
int nodelay = 1;
|
||||
if (setsockopt(ra->sd->fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) {
|
||||
/* If failed to turn on TCP_NODELAY, throw warning and continue */
|
||||
ESP_LOGW(TAG, LOG_FMT("error calling setsockopt : %d"), errno);
|
||||
nodelay = 0;
|
||||
}
|
||||
#endif
|
||||
|
||||
/* Send HTTP error message */
|
||||
esp_err_t ret = httpd_resp_send(req, msg, HTTPD_RESP_USE_STRLEN);
|
||||
|
||||
#ifdef CONFIG_HTTPD_ERR_RESP_NO_DELAY
|
||||
/* If TCP_NODELAY was set successfully above, time to disable it */
|
||||
if (nodelay == 1) {
|
||||
nodelay = 0;
|
||||
if (setsockopt(ra->sd->fd, IPPROTO_TCP, TCP_NODELAY, &nodelay, sizeof(nodelay)) < 0) {
|
||||
/* If failed to turn off TCP_NODELAY, throw error and
|
||||
* return failure to signal for socket closure */
|
||||
ESP_LOGE(TAG, LOG_FMT("error calling setsockopt : %d"), errno);
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
}
|
||||
#endif
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t httpd_register_err_handler(httpd_handle_t handle,
|
||||
httpd_err_code_t error,
|
||||
httpd_err_handler_func_t err_handler_fn)
|
||||
{
|
||||
if (handle == NULL || error >= HTTPD_ERR_CODE_MAX) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
hd->err_handler_fns[error] = err_handler_fn;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_req_handle_err(httpd_req_t *req, httpd_err_code_t error)
|
||||
{
|
||||
struct httpd_data *hd = (struct httpd_data *) req->handle;
|
||||
esp_err_t ret;
|
||||
|
||||
/* Invoke custom error handler if configured */
|
||||
if (hd->err_handler_fns[error]) {
|
||||
ret = hd->err_handler_fns[error](req, error);
|
||||
|
||||
/* If error code is 500, force return failure
|
||||
* irrespective of the handler's return value */
|
||||
ret = (error == HTTPD_500_INTERNAL_SERVER_ERROR ? ESP_FAIL : ret);
|
||||
} else {
|
||||
/* If no handler is registered for this error default
|
||||
* behavior is to send the HTTP error response and
|
||||
* return failure for closure of underlying socket */
|
||||
httpd_resp_send_err(req, error, NULL);
|
||||
ret = ESP_FAIL;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
int httpd_req_recv(httpd_req_t *r, char *buf, size_t buf_len)
|
||||
{
|
||||
if (r == NULL || buf == NULL) {
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
|
||||
if (!httpd_valid_req(r)) {
|
||||
ESP_LOGW(TAG, LOG_FMT("invalid request"));
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
ESP_LOGD(TAG, LOG_FMT("remaining length = %"NEWLIB_NANO_COMPAT_FORMAT), NEWLIB_NANO_COMPAT_CAST(ra->remaining_len));
|
||||
|
||||
if (buf_len > ra->remaining_len) {
|
||||
buf_len = ra->remaining_len;
|
||||
}
|
||||
if (buf_len == 0) {
|
||||
return buf_len;
|
||||
}
|
||||
|
||||
int ret = httpd_recv(r, buf, buf_len);
|
||||
if (ret < 0) {
|
||||
ESP_LOGD(TAG, LOG_FMT("error in httpd_recv"));
|
||||
return ret;
|
||||
}
|
||||
ra->remaining_len -= ret;
|
||||
ESP_LOGD(TAG, LOG_FMT("received length = %d"), ret);
|
||||
struct httpd_data *hd = (struct httpd_data *) r->handle;
|
||||
hd->http_server_state = HTTP_SERVER_EVENT_ON_DATA;
|
||||
esp_http_server_event_data evt_data = {
|
||||
.fd = ra->sd->fd,
|
||||
.data_len = ret,
|
||||
};
|
||||
esp_http_server_dispatch_event(HTTP_SERVER_EVENT_ON_DATA, &evt_data, sizeof(esp_http_server_event_data));
|
||||
return ret;
|
||||
}
|
||||
|
||||
esp_err_t httpd_req_async_handler_begin(httpd_req_t *r, httpd_req_t **out)
|
||||
{
|
||||
if (r == NULL || out == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
// alloc async req
|
||||
httpd_req_t *async = malloc(sizeof(httpd_req_t));
|
||||
if (async == NULL) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
memcpy(async, r, sizeof(httpd_req_t));
|
||||
|
||||
// alloc async aux
|
||||
async->aux = malloc(sizeof(struct httpd_req_aux));
|
||||
if (async->aux == NULL) {
|
||||
free(async);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
memcpy(async->aux, r->aux, sizeof(struct httpd_req_aux));
|
||||
|
||||
// Copy response header block
|
||||
struct httpd_data *hd = (struct httpd_data *) r->handle;
|
||||
struct httpd_req_aux *async_aux = (struct httpd_req_aux *) async->aux;
|
||||
struct httpd_req_aux *r_aux = (struct httpd_req_aux *) r->aux;
|
||||
|
||||
if (r_aux->scratch) {
|
||||
async_aux->scratch = malloc(r_aux->scratch_cur_size);
|
||||
if (async_aux->scratch == NULL) {
|
||||
free(async_aux);
|
||||
free(async);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
memcpy(async_aux->scratch, r_aux->scratch, r_aux->scratch_cur_size);
|
||||
} else {
|
||||
async_aux->scratch = NULL;
|
||||
}
|
||||
|
||||
async_aux->resp_hdrs = calloc(hd->config.max_resp_headers, sizeof(struct resp_hdr));
|
||||
if (async_aux->resp_hdrs == NULL) {
|
||||
free(async_aux->scratch);
|
||||
free(async_aux);
|
||||
free(async);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
memcpy(async_aux->resp_hdrs, r_aux->resp_hdrs, hd->config.max_resp_headers * sizeof(struct resp_hdr));
|
||||
|
||||
// Prevent the main thread from reading the rest of the request after the handler returns.
|
||||
r_aux->remaining_len = 0;
|
||||
|
||||
// mark socket as "in use"
|
||||
r_aux->sd->for_async_req = true;
|
||||
|
||||
*out = async;
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_req_async_handler_complete(httpd_req_t *r)
|
||||
{
|
||||
if (r == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
// Get server handle and control socket info before freeing the request
|
||||
struct httpd_data *hd = (struct httpd_data *) r->handle;
|
||||
int msg_fd = hd->msg_fd;
|
||||
int port = hd->config.ctrl_port;
|
||||
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
ra->sd->for_async_req = false;
|
||||
free(ra->scratch);
|
||||
ra->scratch = NULL;
|
||||
ra->scratch_cur_size = 0;
|
||||
ra->scratch_size_limit = 0;
|
||||
free(ra->resp_hdrs);
|
||||
free(r->aux);
|
||||
free(r);
|
||||
|
||||
// Send a dummy control message(httpd_ctrl_data) to unblock the main HTTP server task from the select() call.
|
||||
// Since the current connection FD was marked as inactive for async requests, the main task
|
||||
// will now re-add this FD to its select() descriptor list. This ensures that subsequent requests
|
||||
// on the same FD are processed correctly
|
||||
struct httpd_ctrl_data msg = {.hc_msg = HTTPD_CTRL_MAX};
|
||||
|
||||
/* Reserve an mbox slot so we don't overrun ctrl_sock_semaphore's
|
||||
* accounting and starve concurrent httpd_queue_work() producers. The
|
||||
* httpd main task is the consumer and will drain the mbox shortly. */
|
||||
if (xSemaphoreTake(hd->ctrl_sock_semaphore, portMAX_DELAY) != pdTRUE) {
|
||||
ESP_LOGW(TAG, LOG_FMT("failed to acquire ctrl socket semaphore"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
int ret = cs_send_to_ctrl_sock(msg_fd, port, &msg, sizeof(msg));
|
||||
if (ret < 0) {
|
||||
ESP_LOGW(TAG, LOG_FMT("failed to send socket notification"));
|
||||
xSemaphoreGive(hd->ctrl_sock_semaphore);
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("socket notification sent"));
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
int httpd_req_to_sockfd(httpd_req_t *r)
|
||||
{
|
||||
if (r == NULL) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
if (!httpd_valid_req(r)) {
|
||||
ESP_LOGW(TAG, LOG_FMT("invalid request"));
|
||||
return -1;
|
||||
}
|
||||
|
||||
struct httpd_req_aux *ra = r->aux;
|
||||
return ra->sd->fd;
|
||||
}
|
||||
|
||||
static int httpd_sock_err(const char *ctx, int sockfd)
|
||||
{
|
||||
int errval;
|
||||
ESP_LOGW(TAG, LOG_FMT("error in %s : %d"), ctx, errno);
|
||||
|
||||
switch (errno) {
|
||||
case EAGAIN:
|
||||
case EINTR:
|
||||
errval = HTTPD_SOCK_ERR_TIMEOUT;
|
||||
break;
|
||||
case EINVAL:
|
||||
case EBADF:
|
||||
case EFAULT:
|
||||
case ENOTSOCK:
|
||||
errval = HTTPD_SOCK_ERR_INVALID;
|
||||
break;
|
||||
default:
|
||||
errval = HTTPD_SOCK_ERR_FAIL;
|
||||
}
|
||||
return errval;
|
||||
}
|
||||
|
||||
int httpd_default_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags)
|
||||
{
|
||||
(void)hd;
|
||||
if (buf == NULL) {
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
|
||||
int ret = send(sockfd, buf, buf_len, flags);
|
||||
if (ret < 0) {
|
||||
return httpd_sock_err("send", sockfd);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
int httpd_default_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags)
|
||||
{
|
||||
(void)hd;
|
||||
if (buf == NULL) {
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
|
||||
int ret = recv(sockfd, buf, buf_len, flags);
|
||||
if (ret < 0) {
|
||||
return httpd_sock_err("recv", sockfd);
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
int httpd_socket_send(httpd_handle_t hd, int sockfd, const char *buf, size_t buf_len, int flags)
|
||||
{
|
||||
struct sock_db *sess = httpd_sess_get(hd, sockfd);
|
||||
if (!sess) {
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
if (!sess->send_fn) {
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
return sess->send_fn(hd, sockfd, buf, buf_len, flags);
|
||||
}
|
||||
|
||||
int httpd_socket_recv(httpd_handle_t hd, int sockfd, char *buf, size_t buf_len, int flags)
|
||||
{
|
||||
struct sock_db *sess = httpd_sess_get(hd, sockfd);
|
||||
if (!sess) {
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
if (!sess->recv_fn) {
|
||||
return HTTPD_SOCK_ERR_INVALID;
|
||||
}
|
||||
return sess->recv_fn(hd, sockfd, buf, buf_len, flags);
|
||||
}
|
||||
+375
@@ -0,0 +1,375 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2018-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
|
||||
#include <errno.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_err.h>
|
||||
#include <http_parser.h>
|
||||
|
||||
#include <esp_http_server.h>
|
||||
#include "esp_httpd_priv.h"
|
||||
|
||||
static const char *TAG = "httpd_uri";
|
||||
|
||||
static bool httpd_uri_match_simple(const char *uri1, const char *uri2, size_t len2)
|
||||
{
|
||||
return strlen(uri1) == len2 && // First match lengths
|
||||
(strncmp(uri1, uri2, len2) == 0); // Then match actual URIs
|
||||
}
|
||||
|
||||
bool httpd_uri_match_wildcard(const char *template, const char *uri, size_t len)
|
||||
{
|
||||
const size_t tpl_len = strlen(template);
|
||||
size_t exact_match_chars = tpl_len;
|
||||
|
||||
/* Check for trailing question mark and asterisk */
|
||||
const char last = (const char) (tpl_len > 0 ? template[tpl_len - 1] : 0);
|
||||
const char prevlast = (const char) (tpl_len > 1 ? template[tpl_len - 2] : 0);
|
||||
const bool asterisk = last == '*' || (prevlast == '*' && last == '?');
|
||||
const bool quest = last == '?' || (prevlast == '?' && last == '*');
|
||||
|
||||
/* Minimum template string length must be:
|
||||
* 0 : if neither of '*' and '?' are present
|
||||
* 1 : if only '*' is present
|
||||
* 2 : if only '?' is present
|
||||
* 3 : if both are present
|
||||
*
|
||||
* The expression (asterisk + quest*2) serves as a
|
||||
* case wise generator of these length values
|
||||
*/
|
||||
|
||||
/* abort in cases such as "?" with no preceding character (invalid template) */
|
||||
if (exact_match_chars < asterisk + quest*2) {
|
||||
return false;
|
||||
}
|
||||
|
||||
/* account for special characters and the optional character if "?" is used */
|
||||
exact_match_chars -= asterisk + quest*2;
|
||||
|
||||
if (len < exact_match_chars) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (!quest) {
|
||||
if (!asterisk && len != exact_match_chars) {
|
||||
/* no special characters and different length - strncmp would return false */
|
||||
return false;
|
||||
}
|
||||
/* asterisk allows arbitrary trailing characters, we ignore these using
|
||||
* exact_match_chars as the length limit */
|
||||
return (strncmp(template, uri, exact_match_chars) == 0);
|
||||
} else {
|
||||
/* question mark present */
|
||||
if (len > exact_match_chars && template[exact_match_chars] != uri[exact_match_chars]) {
|
||||
/* the optional character is present, but different */
|
||||
return false;
|
||||
}
|
||||
if (strncmp(template, uri, exact_match_chars) != 0) {
|
||||
/* the mandatory part differs */
|
||||
return false;
|
||||
}
|
||||
/* Now we know the URI is longer than the required part of template,
|
||||
* the mandatory part matches, and if the optional character is present, it is correct.
|
||||
* Match is OK if we have asterisk, i.e. any trailing characters are OK, or if
|
||||
* there are no characters beyond the optional character. */
|
||||
return asterisk || len <= exact_match_chars + 1;
|
||||
}
|
||||
}
|
||||
|
||||
/* Find handler with matching URI and method, and set
|
||||
* appropriate error code if URI or method not found */
|
||||
static httpd_uri_t* httpd_find_uri_handler(struct httpd_data *hd,
|
||||
const char *uri, size_t uri_len,
|
||||
httpd_method_t method,
|
||||
httpd_err_code_t *err)
|
||||
{
|
||||
if (err) {
|
||||
*err = HTTPD_404_NOT_FOUND;
|
||||
}
|
||||
|
||||
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
|
||||
if (!hd->hd_calls[i]) {
|
||||
break;
|
||||
}
|
||||
ESP_LOGD(TAG, LOG_FMT("[%d] = %s"), i, hd->hd_calls[i]->uri);
|
||||
|
||||
/* Check if custom URI matching function is set,
|
||||
* else use simple string compare */
|
||||
if (hd->config.uri_match_fn ?
|
||||
hd->config.uri_match_fn(hd->hd_calls[i]->uri, uri, uri_len) :
|
||||
httpd_uri_match_simple(hd->hd_calls[i]->uri, uri, uri_len)) {
|
||||
/* URIs match. Now check if method is supported */
|
||||
if (hd->hd_calls[i]->method == method || hd->hd_calls[i]->method == HTTP_ANY) {
|
||||
/* Match found! */
|
||||
if (err) {
|
||||
/* Unset any error that may
|
||||
* have been set earlier */
|
||||
*err = 0;
|
||||
}
|
||||
return hd->hd_calls[i];
|
||||
}
|
||||
/* URI found but method not allowed.
|
||||
* If URI is found later then this
|
||||
* error must be set to 0 */
|
||||
if (err) {
|
||||
*err = HTTPD_405_METHOD_NOT_ALLOWED;
|
||||
}
|
||||
}
|
||||
}
|
||||
return NULL;
|
||||
}
|
||||
|
||||
esp_err_t httpd_register_uri_handler(httpd_handle_t handle,
|
||||
const httpd_uri_t *uri_handler)
|
||||
{
|
||||
if (handle == NULL || uri_handler == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
|
||||
/* Make sure another handler with matching URI and method
|
||||
* is not already registered. This will also catch cases
|
||||
* when a registered URI wildcard pattern already accounts
|
||||
* for the new URI being registered */
|
||||
if (httpd_find_uri_handler(handle, uri_handler->uri,
|
||||
strlen(uri_handler->uri),
|
||||
uri_handler->method, NULL) != NULL) {
|
||||
ESP_LOGW(TAG, LOG_FMT("handler %s with method %d already registered"),
|
||||
uri_handler->uri, uri_handler->method);
|
||||
return ESP_ERR_HTTPD_HANDLER_EXISTS;
|
||||
}
|
||||
|
||||
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
|
||||
if (hd->hd_calls[i] == NULL) {
|
||||
ESP_COMPILER_DIAGNOSTIC_PUSH_IGNORE("-Wanalyzer-malloc-leak") // False-positive detection. TODO GCC-366
|
||||
hd->hd_calls[i] = malloc(sizeof(httpd_uri_t));
|
||||
if (hd->hd_calls[i] == NULL) {
|
||||
/* Failed to allocate memory */
|
||||
return ESP_ERR_HTTPD_ALLOC_MEM;
|
||||
}
|
||||
ESP_COMPILER_DIAGNOSTIC_POP("-Wanalyzer-malloc-leak")
|
||||
|
||||
/* Copy URI string */
|
||||
hd->hd_calls[i]->uri = strdup(uri_handler->uri);
|
||||
if (hd->hd_calls[i]->uri == NULL) {
|
||||
/* Failed to allocate memory */
|
||||
free(hd->hd_calls[i]);
|
||||
hd->hd_calls[i] = NULL;
|
||||
return ESP_ERR_HTTPD_ALLOC_MEM;
|
||||
}
|
||||
|
||||
/* Copy remaining members */
|
||||
hd->hd_calls[i]->method = uri_handler->method;
|
||||
hd->hd_calls[i]->handler = uri_handler->handler;
|
||||
hd->hd_calls[i]->user_ctx = uri_handler->user_ctx;
|
||||
#ifdef CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT
|
||||
hd->hd_calls[i]->ws_pre_handshake_cb = uri_handler->ws_pre_handshake_cb;
|
||||
#endif
|
||||
#ifdef CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT
|
||||
hd->hd_calls[i]->ws_post_handshake_cb = uri_handler->ws_post_handshake_cb;
|
||||
#endif
|
||||
#ifdef CONFIG_HTTPD_WS_SUPPORT
|
||||
hd->hd_calls[i]->is_websocket = uri_handler->is_websocket;
|
||||
hd->hd_calls[i]->handle_ws_control_frames = uri_handler->handle_ws_control_frames;
|
||||
if (uri_handler->supported_subprotocol) {
|
||||
hd->hd_calls[i]->supported_subprotocol = strdup(uri_handler->supported_subprotocol);
|
||||
if (hd->hd_calls[i]->supported_subprotocol == NULL) {
|
||||
/* Failed to allocate memory */
|
||||
free((void *)hd->hd_calls[i]->uri);
|
||||
free(hd->hd_calls[i]);
|
||||
hd->hd_calls[i] = NULL;
|
||||
return ESP_ERR_HTTPD_ALLOC_MEM;
|
||||
}
|
||||
} else {
|
||||
hd->hd_calls[i]->supported_subprotocol = NULL;
|
||||
}
|
||||
#endif
|
||||
ESP_LOGD(TAG, LOG_FMT("[%d] installed %s"), i, uri_handler->uri);
|
||||
return ESP_OK;
|
||||
}
|
||||
ESP_LOGD(TAG, LOG_FMT("[%d] exists %s"), i, hd->hd_calls[i]->uri);
|
||||
}
|
||||
ESP_LOGW(TAG, LOG_FMT("no slots left for registering handler"));
|
||||
return ESP_ERR_HTTPD_HANDLERS_FULL;
|
||||
}
|
||||
|
||||
esp_err_t httpd_unregister_uri_handler(httpd_handle_t handle,
|
||||
const char *uri, httpd_method_t method)
|
||||
{
|
||||
if (handle == NULL || uri == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
for (int i = 0; i < hd->config.max_uri_handlers; i++) {
|
||||
if (!hd->hd_calls[i]) {
|
||||
break;
|
||||
}
|
||||
if ((hd->hd_calls[i]->method == method) && // First match methods
|
||||
(strcmp(hd->hd_calls[i]->uri, uri) == 0)) { // Then match URI string
|
||||
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
|
||||
|
||||
free((char*)hd->hd_calls[i]->uri);
|
||||
#ifdef CONFIG_HTTPD_WS_SUPPORT
|
||||
free((char*)hd->hd_calls[i]->supported_subprotocol);
|
||||
#endif // CONFIG_HTTPD_WS_SUPPORT
|
||||
free(hd->hd_calls[i]);
|
||||
hd->hd_calls[i] = NULL;
|
||||
|
||||
/* Shift the remaining non null handlers in the array
|
||||
* forward by 1 so that order of insertion is maintained */
|
||||
for (i += 1; i < hd->config.max_uri_handlers; i++) {
|
||||
if (!hd->hd_calls[i]) {
|
||||
break;
|
||||
}
|
||||
hd->hd_calls[i-1] = hd->hd_calls[i];
|
||||
}
|
||||
/* Nullify the following non null entry */
|
||||
hd->hd_calls[i-1] = NULL;
|
||||
return ESP_OK;
|
||||
}
|
||||
}
|
||||
ESP_LOGW(TAG, LOG_FMT("handler %s with method %d not found"), uri, method);
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
|
||||
esp_err_t httpd_unregister_uri(httpd_handle_t handle, const char *uri)
|
||||
{
|
||||
if (handle == NULL || uri == NULL) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct httpd_data *hd = (struct httpd_data *) handle;
|
||||
bool found = false;
|
||||
|
||||
int i = 0, j = 0; // For keeping count of removed entries
|
||||
for (; i < hd->config.max_uri_handlers; i++) {
|
||||
if (!hd->hd_calls[i]) {
|
||||
break;
|
||||
}
|
||||
if (strcmp(hd->hd_calls[i]->uri, uri) == 0) { // Match URI strings
|
||||
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, uri);
|
||||
|
||||
free((char*)hd->hd_calls[i]->uri);
|
||||
#ifdef CONFIG_HTTPD_WS_SUPPORT
|
||||
free((char*)hd->hd_calls[i]->supported_subprotocol);
|
||||
#endif // CONFIG_HTTPD_WS_SUPPORT
|
||||
free(hd->hd_calls[i]);
|
||||
hd->hd_calls[i] = NULL;
|
||||
found = true;
|
||||
|
||||
j++; // Update count of removed entries
|
||||
} else {
|
||||
/* Shift the remaining non null handlers in the array
|
||||
* forward by j so that order of insertion is maintained */
|
||||
hd->hd_calls[i-j] = hd->hd_calls[i];
|
||||
}
|
||||
}
|
||||
/* Nullify the following non null entries */
|
||||
for (int k = (i - j); k < i; k++) {
|
||||
hd->hd_calls[k] = NULL;
|
||||
}
|
||||
|
||||
if (!found) {
|
||||
ESP_LOGW(TAG, LOG_FMT("no handler found for URI %s"), uri);
|
||||
}
|
||||
return (found ? ESP_OK : ESP_ERR_NOT_FOUND);
|
||||
}
|
||||
|
||||
void httpd_unregister_all_uri_handlers(struct httpd_data *hd)
|
||||
{
|
||||
for (unsigned i = 0; i < hd->config.max_uri_handlers; i++) {
|
||||
if (!hd->hd_calls[i]) {
|
||||
break;
|
||||
}
|
||||
ESP_LOGD(TAG, LOG_FMT("[%d] removing %s"), i, hd->hd_calls[i]->uri);
|
||||
|
||||
free((char*)hd->hd_calls[i]->uri);
|
||||
#ifdef CONFIG_HTTPD_WS_SUPPORT
|
||||
free((char*)hd->hd_calls[i]->supported_subprotocol);
|
||||
#endif // CONFIG_HTTPD_WS_SUPPORT
|
||||
free(hd->hd_calls[i]);
|
||||
hd->hd_calls[i] = NULL;
|
||||
}
|
||||
}
|
||||
|
||||
esp_err_t httpd_uri(struct httpd_data *hd)
|
||||
{
|
||||
httpd_uri_t *uri = NULL;
|
||||
httpd_req_t *req = &hd->hd_req;
|
||||
struct http_parser_url *res = &hd->hd_req_aux.url_parse_res;
|
||||
|
||||
/* For conveying URI not found/method not allowed */
|
||||
httpd_err_code_t err = 0;
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("request for %s with type %d"), req->uri, req->method);
|
||||
|
||||
/* URL parser result contains offset and length of path string */
|
||||
if (res->field_set & (1 << UF_PATH)) {
|
||||
uri = httpd_find_uri_handler(hd, req->uri + res->field_data[UF_PATH].off,
|
||||
res->field_data[UF_PATH].len, req->method, &err);
|
||||
}
|
||||
|
||||
/* If URI with method not found, respond with error code */
|
||||
if (uri == NULL) {
|
||||
switch (err) {
|
||||
case HTTPD_404_NOT_FOUND:
|
||||
ESP_LOGW(TAG, LOG_FMT("URI '%s' not found"), req->uri);
|
||||
return httpd_req_handle_err(req, HTTPD_404_NOT_FOUND);
|
||||
case HTTPD_405_METHOD_NOT_ALLOWED:
|
||||
ESP_LOGW(TAG, LOG_FMT("Method '%d' not allowed for URI '%s'"),
|
||||
req->method, req->uri);
|
||||
return httpd_req_handle_err(req, HTTPD_405_METHOD_NOT_ALLOWED);
|
||||
default:
|
||||
return ESP_FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
/* Attach user context data (passed during URI registration) into request */
|
||||
req->user_ctx = uri->user_ctx;
|
||||
|
||||
/* Final step for a WebSocket handshake verification */
|
||||
#ifdef CONFIG_HTTPD_WS_SUPPORT
|
||||
struct httpd_req_aux *aux = req->aux;
|
||||
if (uri->is_websocket && aux->ws_handshake_detect && uri->method == HTTP_GET) {
|
||||
#ifdef CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT
|
||||
if (uri->ws_pre_handshake_cb && uri->ws_pre_handshake_cb(req) != ESP_OK) {
|
||||
ESP_LOGW(TAG, LOG_FMT("ws_pre_handshake_cb failed"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
#endif /* CONFIG_HTTPD_WS_PRE_HANDSHAKE_CB_SUPPORT */
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("Responding WS handshake to sock %d"), aux->sd->fd);
|
||||
esp_err_t ret = httpd_ws_respond_server_handshake(&hd->hd_req, uri->supported_subprotocol);
|
||||
if (ret != ESP_OK) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
aux->sd->ws_handshake_done = true;
|
||||
aux->sd->ws_handler = uri->handler;
|
||||
aux->sd->ws_control_frames = uri->handle_ws_control_frames;
|
||||
aux->sd->ws_user_ctx = uri->user_ctx;
|
||||
|
||||
#ifdef CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT
|
||||
if (uri->ws_post_handshake_cb && uri->ws_post_handshake_cb(req) != ESP_OK) {
|
||||
ESP_LOGW(TAG, LOG_FMT("ws_post_handshake_cb failed"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
#endif /* CONFIG_HTTPD_WS_POST_HANDSHAKE_CB_SUPPORT */
|
||||
/* If the request is websocket handshake, then do not call the uri->handler */
|
||||
return ESP_OK;
|
||||
}
|
||||
#endif /* CONFIG_HTTPD_WS_SUPPORT */
|
||||
/* Invoke handler */
|
||||
if (uri->handler(req) != ESP_OK) {
|
||||
/* Handler returns error, this socket should be closed */
|
||||
ESP_LOGW(TAG, LOG_FMT("uri handler execution failed"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
+624
@@ -0,0 +1,624 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2020-2026 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <sys/random.h>
|
||||
#include <esp_log.h>
|
||||
#include <esp_err.h>
|
||||
#include "desktop_crypto.h"
|
||||
|
||||
#include <esp_http_server.h>
|
||||
#include "esp_httpd_priv.h"
|
||||
#include "freertos/event_groups.h"
|
||||
#include "sdkconfig.h"
|
||||
|
||||
#ifdef CONFIG_HTTPD_WS_SUPPORT
|
||||
|
||||
#define WS_SEND_OK (1 << 0)
|
||||
#define WS_SEND_FAILED (1 << 1)
|
||||
|
||||
typedef struct {
|
||||
httpd_ws_frame_t frame;
|
||||
httpd_handle_t handle;
|
||||
int socket;
|
||||
transfer_complete_cb callback;
|
||||
void *arg;
|
||||
bool blocking;
|
||||
EventGroupHandle_t transfer_done;
|
||||
} async_transfer_t;
|
||||
|
||||
static const char *TAG="httpd_ws";
|
||||
|
||||
/*
|
||||
* Bit masks for WebSocket frames.
|
||||
* Please refer to RFC6455 Section 5.2 for more details.
|
||||
*/
|
||||
#define HTTPD_WS_CONTINUE 0x00U
|
||||
#define HTTPD_WS_FIN_BIT 0x80U
|
||||
#define HTTPD_WS_OPCODE_BITS 0x0fU
|
||||
#define HTTPD_WS_MASK_BIT 0x80U
|
||||
#define HTTPD_WS_LENGTH_BITS 0x7fU
|
||||
|
||||
/*
|
||||
* The magic GUID string used for handshake
|
||||
* Please refer to RFC6455 Section 1.3 for more details.
|
||||
*/
|
||||
static const char ws_magic_uuid[] = "258EAFA5-E914-47DA-95CA-C5AB0DC85B11";
|
||||
|
||||
/* Checks if any subprotocols from the comma separated list matches the supported one
|
||||
*
|
||||
* Returns true if the response should contain a protocol field
|
||||
*/
|
||||
|
||||
/**
|
||||
* @brief Checks if any subprotocols from the comma separated list matches the supported one
|
||||
*
|
||||
* @param supported_subprotocol[in] The subprotocol supported by the URI
|
||||
* @param subprotocol[in], [in]: A comma separate list of subprotocols requested
|
||||
* @param buf_len Length of the buffer
|
||||
* @return true: found a matching subprotocol
|
||||
* @return false
|
||||
*/
|
||||
static bool httpd_ws_get_response_subprotocol(const char *supported_subprotocol, char *subprotocol, size_t buf_len)
|
||||
{
|
||||
/* Request didn't contain any subprotocols */
|
||||
if (strnlen(subprotocol, buf_len) == 0) {
|
||||
return false;
|
||||
}
|
||||
|
||||
if (supported_subprotocol == NULL) {
|
||||
ESP_LOGW(TAG, "Sec-WebSocket-Protocol %s not supported, URI do not support any subprotocols", subprotocol);
|
||||
return false;
|
||||
}
|
||||
|
||||
/* Get first subprotocol from comma separated list */
|
||||
char *rest = NULL;
|
||||
char *s = strtok_r(subprotocol, ", ", &rest);
|
||||
int supported_subprotocol_len = strlen(supported_subprotocol);
|
||||
while (s != NULL) {
|
||||
if (strlen(s) == supported_subprotocol_len &&
|
||||
strncmp(s, supported_subprotocol, supported_subprotocol_len) == 0) {
|
||||
ESP_LOGD(TAG, "Requested subprotocol supported: %s", s);
|
||||
return true;
|
||||
}
|
||||
s = strtok_r(NULL, ", ", &rest);
|
||||
}
|
||||
|
||||
ESP_LOGW(TAG, "Sec-WebSocket-Protocol %s not supported, supported subprotocol is %s", subprotocol, supported_subprotocol);
|
||||
|
||||
/* No matches */
|
||||
return false;
|
||||
|
||||
}
|
||||
|
||||
esp_err_t httpd_ws_respond_server_handshake(httpd_req_t *req, const char *supported_subprotocol)
|
||||
{
|
||||
/* Probe if input parameters are valid or not */
|
||||
if (!req || !req->aux) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Argument is invalid"));
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
/* Detect handshake - reject if handshake was ALREADY performed */
|
||||
struct httpd_req_aux *req_aux = req->aux;
|
||||
if (req_aux->sd->ws_handshake_done) {
|
||||
ESP_LOGW(TAG, LOG_FMT("State is invalid - Handshake has been performed"));
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
|
||||
/* Detect WS version existence */
|
||||
char version_val[3] = { '\0' };
|
||||
if (httpd_req_get_hdr_value_str(req, "Sec-WebSocket-Version", version_val, sizeof(version_val)) != ESP_OK) {
|
||||
ESP_LOGW(TAG, LOG_FMT("\"Sec-WebSocket-Version\" is not found"));
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
|
||||
/* Detect if WS version is "13" or not.
|
||||
* WS version must be 13 for now. Please refer to RFC6455 Section 4.1, Page 18 for more details. */
|
||||
if (strcasecmp(version_val, "13") != 0) {
|
||||
ESP_LOGW(TAG, LOG_FMT("\"Sec-WebSocket-Version\" is not \"13\", it is: %s"), version_val);
|
||||
return ESP_ERR_INVALID_VERSION;
|
||||
}
|
||||
|
||||
/* Grab Sec-WebSocket-Key (client key) from the header */
|
||||
/* Size of base64 coded string is equal '((input_size * 4) / 3) + (input_size / 96) + 6' including Z-term */
|
||||
char sec_key_encoded[28] = { '\0' };
|
||||
if (httpd_req_get_hdr_value_str(req, "Sec-WebSocket-Key", sec_key_encoded, sizeof(sec_key_encoded)) != ESP_OK) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Cannot find client key"));
|
||||
return ESP_ERR_NOT_FOUND;
|
||||
}
|
||||
|
||||
/* Prepare server key (Sec-WebSocket-Accept), concat the string */
|
||||
char server_key_encoded[33] = { '\0' };
|
||||
uint8_t server_key_hash[20] = { 0 };
|
||||
char server_raw_text[sizeof(sec_key_encoded) + sizeof(ws_magic_uuid) + 1] = { '\0' };
|
||||
|
||||
strcpy(server_raw_text, sec_key_encoded);
|
||||
strcat(server_raw_text, ws_magic_uuid);
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("Server key before encoding: %s"), server_raw_text);
|
||||
|
||||
/* Generate SHA-1 hash, then base64 (desktop build: desktop_crypto.c) */
|
||||
desktop_sha1((const uint8_t *)server_raw_text, strlen(server_raw_text), server_key_hash);
|
||||
size_t encoded_len = desktop_base64_encode(server_key_encoded, sizeof(server_key_encoded),
|
||||
server_key_hash, sizeof(server_key_hash));
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("Generated server key: %s"), server_key_encoded);
|
||||
|
||||
char subprotocol[50] = { '\0' };
|
||||
if (httpd_req_get_hdr_value_str(req, "Sec-WebSocket-Protocol", subprotocol, sizeof(subprotocol) - 1) == ESP_ERR_HTTPD_RESULT_TRUNC) {
|
||||
ESP_LOGW(TAG, "Sec-WebSocket-Protocol length exceeded buffer size of %"NEWLIB_NANO_COMPAT_FORMAT", was truncated", NEWLIB_NANO_COMPAT_CAST(sizeof(subprotocol)));
|
||||
}
|
||||
|
||||
|
||||
/* Prepare the Switching Protocol response */
|
||||
char tx_buf[192] = { '\0' };
|
||||
int fmt_len = snprintf(tx_buf, sizeof(tx_buf),
|
||||
"HTTP/1.1 101 Switching Protocols\r\n"
|
||||
"Upgrade: websocket\r\n"
|
||||
"Connection: Upgrade\r\n"
|
||||
"Sec-WebSocket-Accept: %s\r\n", server_key_encoded);
|
||||
|
||||
if (fmt_len < 0 || fmt_len > sizeof(tx_buf)) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to prepare Tx buffer"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
if ( httpd_ws_get_response_subprotocol(supported_subprotocol, subprotocol, sizeof(subprotocol))) {
|
||||
ESP_LOGD(TAG, "subprotocol: %s", subprotocol);
|
||||
int r = snprintf(tx_buf + fmt_len, sizeof(tx_buf) - fmt_len, "Sec-WebSocket-Protocol: %s\r\n", supported_subprotocol);
|
||||
if (r <= 0) {
|
||||
ESP_LOGE(TAG, "Error in response generation"
|
||||
"(snprintf of subprotocol returned %d, buffer size: %"NEWLIB_NANO_COMPAT_FORMAT, r, NEWLIB_NANO_COMPAT_CAST(sizeof(tx_buf)));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
fmt_len += r;
|
||||
|
||||
if (fmt_len >= sizeof(tx_buf)) {
|
||||
ESP_LOGE(TAG, "Error in response generation"
|
||||
"(snprintf of subprotocol returned %d, desired response len: %d, buffer size: %"NEWLIB_NANO_COMPAT_FORMAT, r, fmt_len, NEWLIB_NANO_COMPAT_CAST(sizeof(tx_buf)));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
int r = snprintf(tx_buf + fmt_len, sizeof(tx_buf) - fmt_len, "\r\n");
|
||||
if (r <= 0) {
|
||||
ESP_LOGE(TAG, "Error in response generation"
|
||||
"(snprintf of subprotocol returned %d, buffer size: %"NEWLIB_NANO_COMPAT_FORMAT, r, NEWLIB_NANO_COMPAT_CAST(sizeof(tx_buf)));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
fmt_len += r;
|
||||
if (fmt_len >= sizeof(tx_buf)) {
|
||||
ESP_LOGE(TAG, "Error in response generation"
|
||||
"(snprintf of header terminal returned %d, desired response len: %d, buffer size: %"NEWLIB_NANO_COMPAT_FORMAT, r, fmt_len, NEWLIB_NANO_COMPAT_CAST(sizeof(tx_buf)));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
/* Send off the response */
|
||||
if (httpd_send(req, tx_buf, fmt_len) < 0) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to send the response"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t httpd_ws_check_req(httpd_req_t *req)
|
||||
{
|
||||
/* Probe if input parameters are valid or not */
|
||||
if (!req || !req->aux) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Argument is null"));
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
/* Detect handshake - reject if handshake was NOT YET performed */
|
||||
struct httpd_req_aux *req_aux = req->aux;
|
||||
if (!req_aux->sd->ws_handshake_done) {
|
||||
ESP_LOGW(TAG, LOG_FMT("State is invalid - No handshake performed"));
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t httpd_ws_unmask_payload(uint8_t *payload, size_t len, const uint8_t *mask_key, size_t mask_offset)
|
||||
{
|
||||
if (len < 1 || !payload) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Invalid payload provided"));
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
for (size_t idx = 0; idx < len; idx++) {
|
||||
payload[idx] = (payload[idx] ^ mask_key[(idx + mask_offset) % 4]);
|
||||
}
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
static esp_err_t httpd_ws_recv_frame_internal(httpd_req_t *req, httpd_ws_frame_t *frame, size_t max_len, bool partial)
|
||||
{
|
||||
esp_err_t ret = httpd_ws_check_req(req);
|
||||
if (ret != ESP_OK) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
struct httpd_req_aux *aux = req->aux;
|
||||
if (aux == NULL) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Invalid Aux pointer"));
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
if (!frame) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Frame pointer is invalid"));
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
/* If frame len is 0, will get frame len from req. Otherwise regard frame len already achieved by calling httpd_ws_recv_frame before */
|
||||
if (frame->len == 0) {
|
||||
/* Assign the frame info from the previous reading */
|
||||
frame->type = aux->ws_type;
|
||||
frame->final = aux->ws_final;
|
||||
|
||||
/* Grab the second byte */
|
||||
uint8_t second_byte = 0;
|
||||
int recv_ret = httpd_recv_with_opt(req, (char *)&second_byte, sizeof(second_byte), HTTPD_RECV_OPT_BLOCKING);
|
||||
if (recv_ret != (int)sizeof(second_byte)) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to receive the second byte"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
/* Parse the second byte */
|
||||
/* Please refer to RFC6455 Section 5.2 for more details */
|
||||
bool masked = (second_byte & HTTPD_WS_MASK_BIT) != 0;
|
||||
|
||||
/* Interpret length */
|
||||
uint8_t init_len = second_byte & HTTPD_WS_LENGTH_BITS;
|
||||
if (init_len < 126) {
|
||||
/* Case 1: If length is 0-125, then this length bit is 7 bits */
|
||||
frame->len = init_len;
|
||||
} else if (init_len == 126) {
|
||||
/* Case 2: If length byte is 126, then this frame's length bit is 16 bits */
|
||||
uint8_t length_bytes[2] = { 0 };
|
||||
recv_ret = httpd_recv_with_opt(req, (char *)length_bytes, sizeof(length_bytes), HTTPD_RECV_OPT_BLOCKING);
|
||||
if (recv_ret != (int)sizeof(length_bytes)) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to receive 2 bytes length"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
frame->len = ((uint32_t)(length_bytes[0] << 8U) | (length_bytes[1]));
|
||||
} else if (init_len == 127) {
|
||||
/* Case 3: If length is byte 127, then this frame's length bit is 64 bits */
|
||||
uint8_t length_bytes[8] = { 0 };
|
||||
recv_ret = httpd_recv_with_opt(req, (char *)length_bytes, sizeof(length_bytes), HTTPD_RECV_OPT_BLOCKING);
|
||||
if (recv_ret != (int)sizeof(length_bytes)) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to receive 8 bytes length"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
frame->len = (((uint64_t)length_bytes[0] << 56U) |
|
||||
((uint64_t)length_bytes[1] << 48U) |
|
||||
((uint64_t)length_bytes[2] << 40U) |
|
||||
((uint64_t)length_bytes[3] << 32U) |
|
||||
((uint64_t)length_bytes[4] << 24U) |
|
||||
((uint64_t)length_bytes[5] << 16U) |
|
||||
((uint64_t)length_bytes[6] << 8U) |
|
||||
((uint64_t)length_bytes[7]));
|
||||
}
|
||||
frame->left_len = frame->len;
|
||||
|
||||
/* If this frame is masked, dump the mask as well */
|
||||
if (masked) {
|
||||
recv_ret = httpd_recv_with_opt(req, (char *)aux->mask_key, sizeof(aux->mask_key), HTTPD_RECV_OPT_BLOCKING);
|
||||
if (recv_ret != (int)sizeof(aux->mask_key)) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to receive mask key"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
} else {
|
||||
/* If the WS frame from client to server is not masked, it should be rejected.
|
||||
* Please refer to RFC6455 Section 5.2 for more details. */
|
||||
ESP_LOGW(TAG, LOG_FMT("WS frame is not properly masked."));
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
}
|
||||
/* If max_len is 0, regard it OK for userspace to get frame len */
|
||||
if (max_len == 0) {
|
||||
ESP_LOGD(TAG, "regard max_len == 0 is OK for user to get frame len");
|
||||
return ESP_OK;
|
||||
}
|
||||
if (frame->len > max_len) {
|
||||
/* When reading entire packet at once, we only accept the incoming packet length that is smaller than the max_len (or it will overflow the buffer!) */
|
||||
if (!partial) {
|
||||
ESP_LOGW(TAG, LOG_FMT("WS Message too long"));
|
||||
return ESP_ERR_INVALID_SIZE;
|
||||
}
|
||||
ESP_LOGD(TAG, LOG_FMT("WS Message too long. User will have to call read again"));
|
||||
}
|
||||
|
||||
/* Receive buffer */
|
||||
/* If there's nothing to receive, return and stop here. */
|
||||
if (frame->left_len == 0) {
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
if (frame->payload == NULL) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Payload buffer is null"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
size_t left_len = (max_len < frame->left_len) ? max_len : frame->left_len;
|
||||
size_t offset = 0;
|
||||
|
||||
while (left_len > 0) {
|
||||
int read_len = httpd_recv_with_opt(req, (char *)frame->payload + offset, left_len, HTTPD_RECV_OPT_NONE);
|
||||
if (read_len <= 0) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to receive payload"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
offset += read_len;
|
||||
left_len -= read_len;
|
||||
|
||||
ESP_LOGD(TAG, "Frame length: %"NEWLIB_NANO_COMPAT_FORMAT", Bytes Read: %"NEWLIB_NANO_COMPAT_FORMAT, NEWLIB_NANO_COMPAT_CAST(frame->len), NEWLIB_NANO_COMPAT_CAST(offset));
|
||||
}
|
||||
|
||||
size_t mask_offset = frame->len - frame->left_len;
|
||||
frame->left_len -= offset;
|
||||
|
||||
/* Unmask payload */
|
||||
httpd_ws_unmask_payload(frame->payload, offset, aux->mask_key, mask_offset);
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_ws_recv_frame(httpd_req_t *req, httpd_ws_frame_t *frame, size_t max_len) {
|
||||
return httpd_ws_recv_frame_internal(req, frame, max_len, false);
|
||||
}
|
||||
|
||||
esp_err_t httpd_ws_recv_frame_part(httpd_req_t *req, httpd_ws_frame_t *frame, size_t max_len) {
|
||||
return httpd_ws_recv_frame_internal(req, frame, max_len, true);
|
||||
}
|
||||
|
||||
esp_err_t httpd_ws_send_frame(httpd_req_t *req, httpd_ws_frame_t *frame)
|
||||
{
|
||||
esp_err_t ret = httpd_ws_check_req(req);
|
||||
if (ret != ESP_OK) {
|
||||
return ret;
|
||||
}
|
||||
return httpd_ws_send_frame_async(req->handle, httpd_req_to_sockfd(req), frame);
|
||||
}
|
||||
|
||||
esp_err_t httpd_ws_send_frame_async(httpd_handle_t hd, int fd, httpd_ws_frame_t *frame)
|
||||
{
|
||||
if (!frame) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Argument is invalid"));
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
/* Prepare Tx buffer - maximum length is 14, which includes 2 bytes header, 8 bytes length, 4 bytes mask key */
|
||||
uint8_t tx_len = 0;
|
||||
uint8_t header_buf[10] = {0 };
|
||||
/* Set the `FIN` bit by default if message is not fragmented. Else, set it as per the `final` field */
|
||||
header_buf[0] |= (!frame->fragmented) ? HTTPD_WS_FIN_BIT : (frame->final? HTTPD_WS_FIN_BIT: HTTPD_WS_CONTINUE);
|
||||
header_buf[0] |= frame->type; /* Type (opcode): 4 bits */
|
||||
|
||||
if (frame->len <= 125) {
|
||||
header_buf[1] = frame->len & 0x7fU; /* Length for 7 bits */
|
||||
tx_len = 2;
|
||||
} else if (frame->len > 125 && frame->len < UINT16_MAX) {
|
||||
header_buf[1] = 126; /* Length for 16 bits */
|
||||
header_buf[2] = (frame->len >> 8U) & 0xffU;
|
||||
header_buf[3] = frame->len & 0xffU;
|
||||
tx_len = 4;
|
||||
} else {
|
||||
header_buf[1] = 127; /* Length for 64 bits */
|
||||
uint8_t shift_idx = sizeof(uint64_t) - 1; /* Shift index starts at 7 */
|
||||
uint64_t len64 = frame->len; /* Raise variable size to make sure we won't shift by more bits
|
||||
* than the length has (to avoid undefined behaviour) */
|
||||
for (int8_t idx = 2; idx <= 9; idx++) {
|
||||
/* Now do shifting (be careful of endianness, i.e. when buffer index is 2, frame length shift index is 7) */
|
||||
header_buf[idx] = (len64 >> (shift_idx * 8)) & 0xffU;
|
||||
shift_idx--;
|
||||
}
|
||||
tx_len = 10;
|
||||
}
|
||||
|
||||
/* WebSocket server does not required to mask response payload, so leave the MASK bit as 0. */
|
||||
header_buf[1] &= (~HTTPD_WS_MASK_BIT);
|
||||
|
||||
struct sock_db *sess = httpd_sess_get(hd, fd);
|
||||
if (!sess) {
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
/* Send off header */
|
||||
if (sess->send_fn(hd, fd, (const char *)header_buf, tx_len, 0) < 0) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to send WS header"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
|
||||
/* Send off payload */
|
||||
if(frame->len > 0 && frame->payload != NULL) {
|
||||
if (sess->send_fn(hd, fd, (const char *)frame->payload, frame->len, 0) < 0) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to send WS payload"));
|
||||
return ESP_FAIL;
|
||||
}
|
||||
}
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
esp_err_t httpd_ws_get_frame_type(httpd_req_t *req)
|
||||
{
|
||||
esp_err_t ret = httpd_ws_check_req(req);
|
||||
if (ret != ESP_OK) {
|
||||
return ret;
|
||||
}
|
||||
|
||||
struct httpd_req_aux *aux = req->aux;
|
||||
if (aux == NULL) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Invalid Aux pointer"));
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
struct sock_db *sd = aux->sd;
|
||||
if (sd == NULL) {
|
||||
ESP_LOGW(TAG, LOG_FMT("Invalid sd pointer"));
|
||||
return ESP_ERR_INVALID_ARG;
|
||||
}
|
||||
|
||||
/* Read the first byte from the frame to get the FIN flag and Opcode */
|
||||
/* Please refer to RFC6455 Section 5.2 for more details */
|
||||
uint8_t first_byte = 0;
|
||||
int recv_ret = httpd_recv_with_opt(req, (char *)&first_byte, sizeof(first_byte), HTTPD_RECV_OPT_BLOCKING);
|
||||
if (recv_ret != (int)sizeof(first_byte)) {
|
||||
/* If we fail to read exactly one byte, this socket FD is invalid or the frame header is incomplete. */
|
||||
/* Here we mark it as a Close message and close it later. */
|
||||
ESP_LOGW(TAG, LOG_FMT("Failed to read header byte (socket FD invalid), closing socket now"));
|
||||
aux->ws_final = true;
|
||||
aux->ws_type = HTTPD_WS_TYPE_CLOSE;
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
ESP_LOGD(TAG, LOG_FMT("First byte received: 0x%02X"), first_byte);
|
||||
|
||||
/* Decode the FIN flag and Opcode from the byte */
|
||||
aux->ws_final = (first_byte & HTTPD_WS_FIN_BIT) != 0;
|
||||
aux->ws_type = (first_byte & HTTPD_WS_OPCODE_BITS);
|
||||
|
||||
/* If userspace requests control frames, do not deal with the control frames */
|
||||
if (!sd->ws_control_frames) {
|
||||
ESP_LOGD(TAG, LOG_FMT("Handler not requests control frames"));
|
||||
|
||||
/* Reply to PING. For PONG and CLOSE, it will be handled elsewhere. */
|
||||
if (aux->ws_type == HTTPD_WS_TYPE_PING) {
|
||||
ESP_LOGD(TAG, LOG_FMT("Got a WS PING frame, Replying PONG..."));
|
||||
|
||||
/* Read the rest of the PING frame, for PONG to reply back. */
|
||||
/* Please refer to RFC6455 Section 5.5.2 for more details */
|
||||
httpd_ws_frame_t frame;
|
||||
uint8_t frame_buf[128] = { 0 };
|
||||
memset(&frame, 0, sizeof(httpd_ws_frame_t));
|
||||
frame.payload = frame_buf;
|
||||
|
||||
if (httpd_ws_recv_frame(req, &frame, 126) != ESP_OK) {
|
||||
ESP_LOGD(TAG, LOG_FMT("Cannot receive the full PING frame"));
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
|
||||
/* Now turn the frame to PONG */
|
||||
frame.type = HTTPD_WS_TYPE_PONG;
|
||||
return httpd_ws_send_frame(req, &frame);
|
||||
} else if (aux->ws_type == HTTPD_WS_TYPE_CLOSE) {
|
||||
ESP_LOGD(TAG, LOG_FMT("Got a WS CLOSE frame, Replying CLOSE..."));
|
||||
|
||||
/* Read the rest of the CLOSE frame and response */
|
||||
/* Please refer to RFC6455 Section 5.5.1 for more details */
|
||||
httpd_ws_frame_t frame;
|
||||
uint8_t frame_buf[128] = { 0 };
|
||||
memset(&frame, 0, sizeof(httpd_ws_frame_t));
|
||||
frame.payload = frame_buf;
|
||||
|
||||
if (httpd_ws_recv_frame(req, &frame, 126) != ESP_OK) {
|
||||
ESP_LOGD(TAG, LOG_FMT("Cannot receive the full CLOSE frame"));
|
||||
return ESP_ERR_INVALID_STATE;
|
||||
}
|
||||
|
||||
frame.len = 0;
|
||||
frame.type = HTTPD_WS_TYPE_CLOSE;
|
||||
frame.payload = NULL;
|
||||
return httpd_ws_send_frame(req, &frame);
|
||||
}
|
||||
}
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
httpd_ws_client_info_t httpd_ws_get_fd_info(httpd_handle_t hd, int fd)
|
||||
{
|
||||
struct sock_db *sess = httpd_sess_get(hd, fd);
|
||||
|
||||
if (sess == NULL) {
|
||||
return HTTPD_WS_CLIENT_INVALID;
|
||||
}
|
||||
bool is_active_ws = sess->ws_handshake_done && (!sess->ws_close);
|
||||
return is_active_ws ? HTTPD_WS_CLIENT_WEBSOCKET : HTTPD_WS_CLIENT_HTTP;
|
||||
}
|
||||
|
||||
static void httpd_ws_send_cb(void *arg)
|
||||
{
|
||||
async_transfer_t *trans = arg;
|
||||
|
||||
esp_err_t err = httpd_ws_send_frame_async(trans->handle, trans->socket, &trans->frame);
|
||||
|
||||
if (trans->blocking) {
|
||||
xEventGroupSetBits(trans->transfer_done, err ? WS_SEND_FAILED : WS_SEND_OK);
|
||||
} else if (trans->callback) {
|
||||
trans->callback(err, trans->socket, trans->arg);
|
||||
}
|
||||
|
||||
free(trans);
|
||||
}
|
||||
|
||||
esp_err_t httpd_ws_send_data(httpd_handle_t handle, int socket, httpd_ws_frame_t *frame)
|
||||
{
|
||||
async_transfer_t *transfer = calloc(1, sizeof(async_transfer_t));
|
||||
if (transfer == NULL) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
EventGroupHandle_t transfer_done = xEventGroupCreate();
|
||||
if (!transfer_done) {
|
||||
free(transfer);
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
transfer->blocking = true;
|
||||
transfer->handle = handle;
|
||||
transfer->socket = socket;
|
||||
transfer->transfer_done = transfer_done;
|
||||
memcpy(&transfer->frame, frame, sizeof(httpd_ws_frame_t));
|
||||
|
||||
esp_err_t err = httpd_queue_work(handle, httpd_ws_send_cb, transfer);
|
||||
if (err != ESP_OK) {
|
||||
vEventGroupDelete(transfer_done);
|
||||
free(transfer);
|
||||
return err;
|
||||
}
|
||||
|
||||
EventBits_t status = xEventGroupWaitBits(transfer_done, WS_SEND_OK | WS_SEND_FAILED,
|
||||
pdTRUE, pdFALSE, portMAX_DELAY);
|
||||
|
||||
vEventGroupDelete(transfer_done);
|
||||
|
||||
return (status & WS_SEND_OK) ? ESP_OK : ESP_FAIL;
|
||||
}
|
||||
|
||||
esp_err_t httpd_ws_send_data_async(httpd_handle_t handle, int socket, httpd_ws_frame_t *frame,
|
||||
transfer_complete_cb callback, void *arg)
|
||||
{
|
||||
async_transfer_t *transfer = calloc(1, sizeof(async_transfer_t));
|
||||
if (transfer == NULL) {
|
||||
return ESP_ERR_NO_MEM;
|
||||
}
|
||||
|
||||
transfer->arg = arg;
|
||||
transfer->callback = callback;
|
||||
transfer->handle = handle;
|
||||
transfer->socket = socket;
|
||||
memcpy(&transfer->frame, frame, sizeof(httpd_ws_frame_t));
|
||||
|
||||
esp_err_t err = httpd_queue_work(handle, httpd_ws_send_cb, transfer);
|
||||
|
||||
if (err) {
|
||||
free(transfer);
|
||||
return err;
|
||||
}
|
||||
|
||||
return ESP_OK;
|
||||
}
|
||||
|
||||
#endif /* CONFIG_HTTPD_WS_SUPPORT */
|
||||
@@ -0,0 +1,106 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2018-2025 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
#include <string.h>
|
||||
#include <unistd.h>
|
||||
|
||||
#include <sys/socket.h>
|
||||
#include <netinet/in.h>
|
||||
#include <arpa/inet.h>
|
||||
#include "sdkconfig.h"
|
||||
#include "esp_log.h"
|
||||
#include "ctrl_sock.h"
|
||||
|
||||
#if CONFIG_IDF_TARGET_LINUX
|
||||
#define IPV4_ENABLED 1
|
||||
#define IPV6_ENABLED 1
|
||||
#define LOOPBACK_ENABLED 1
|
||||
#else // CONFIG_IDF_TARGET_LINUX
|
||||
#define IPV4_ENABLED CONFIG_LWIP_IPV4
|
||||
#define IPV6_ENABLED CONFIG_LWIP_IPV6
|
||||
#define LOOPBACK_ENABLED CONFIG_LWIP_NETIF_LOOPBACK
|
||||
#endif // !CONFIG_IDF_TARGET_LINUX
|
||||
|
||||
/* Control socket, because in some network stacks select can't be woken up any
|
||||
* other way
|
||||
*/
|
||||
int cs_create_ctrl_sock(int port)
|
||||
{
|
||||
#if !LOOPBACK_ENABLED
|
||||
ESP_LOGE("esp_http_server", "Please enable LWIP_NETIF_LOOPBACK for %s API", __func__);
|
||||
return -1;
|
||||
#endif
|
||||
|
||||
int fd = socket(AF_INET, SOCK_DGRAM, IPPROTO_UDP);
|
||||
if (fd < 0) {
|
||||
return -1;
|
||||
}
|
||||
|
||||
int ret;
|
||||
struct sockaddr_storage addr = {};
|
||||
socklen_t addr_len = 0;
|
||||
#if IPV4_ENABLED
|
||||
struct sockaddr_in *addr4 = (struct sockaddr_in *)&addr;
|
||||
addr4->sin_family = AF_INET;
|
||||
addr4->sin_port = htons(port);
|
||||
inet_aton("127.0.0.1", &addr4->sin_addr);
|
||||
addr_len = sizeof(struct sockaddr_in);
|
||||
#else
|
||||
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&addr;
|
||||
addr6->sin6_family = AF_INET6;
|
||||
addr6->sin6_port = htons(port);
|
||||
inet6_aton("::1", &addr6->sin6_addr);
|
||||
addr_len = sizeof(struct sockaddr_in6);
|
||||
#endif
|
||||
ret = bind(fd, (struct sockaddr *)&addr, addr_len);
|
||||
if (ret < 0) {
|
||||
close(fd);
|
||||
return -1;
|
||||
}
|
||||
return fd;
|
||||
}
|
||||
|
||||
void cs_free_ctrl_sock(int fd)
|
||||
{
|
||||
close(fd);
|
||||
}
|
||||
|
||||
int cs_send_to_ctrl_sock(int send_fd, int port, void *data, unsigned int data_len)
|
||||
{
|
||||
int ret;
|
||||
struct sockaddr_storage to_addr = {};
|
||||
socklen_t addr_len = 0;
|
||||
#if IPV4_ENABLED
|
||||
struct sockaddr_in *addr4 = (struct sockaddr_in *)&to_addr;
|
||||
addr4->sin_family = AF_INET;
|
||||
addr4->sin_port = htons(port);
|
||||
inet_aton("127.0.0.1", &addr4->sin_addr);
|
||||
addr_len = sizeof(struct sockaddr_in);
|
||||
#else
|
||||
struct sockaddr_in6 *addr6 = (struct sockaddr_in6 *)&to_addr;
|
||||
addr6->sin6_family = AF_INET6;
|
||||
addr6->sin6_port = htons(port);
|
||||
inet6_aton("::1", &addr6->sin6_addr);
|
||||
addr_len = sizeof(struct sockaddr_in6);
|
||||
#endif
|
||||
ret = sendto(send_fd, data, data_len, 0, (struct sockaddr *)&to_addr, addr_len);
|
||||
|
||||
if (ret < 0) {
|
||||
return -1;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
int cs_recv_from_ctrl_sock(int fd, void *data, unsigned int data_len)
|
||||
{
|
||||
int ret;
|
||||
ret = recvfrom(fd, data, data_len, 0, NULL, NULL);
|
||||
|
||||
if (ret < 0) {
|
||||
return -1;
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
/*
|
||||
* SPDX-FileCopyrightText: 2018-2021 Espressif Systems (Shanghai) CO LTD
|
||||
*
|
||||
* SPDX-License-Identifier: Apache-2.0
|
||||
*/
|
||||
|
||||
/**
|
||||
* \file ctrl_sock.h
|
||||
* \brief Control Socket for select() wakeup
|
||||
*
|
||||
* LWIP doesn't allow an easy mechanism to on-demand wakeup a thread
|
||||
* sleeping on select. This is a common requirement for sending
|
||||
* control commands to a network server. This control socket API
|
||||
* facilitates the same.
|
||||
*/
|
||||
#ifndef _CTRL_SOCK_H_
|
||||
#define _CTRL_SOCK_H_
|
||||
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/**
|
||||
* @brief Create a control socket
|
||||
*
|
||||
* LWIP doesn't allow an easy mechanism to on-demand wakeup a thread
|
||||
* sleeping on select. This is a common requirement for sending
|
||||
* control commands to a network server. This control socket API
|
||||
* facilitates the same.
|
||||
*
|
||||
* This API will create a UDP control socket on the specified port. It
|
||||
* will return a socket descriptor that can then be added to your
|
||||
* fd_set in select()
|
||||
*
|
||||
* @param[in] port the local port on which the control socket will listen
|
||||
*
|
||||
* @return - the socket descriptor that can be added to the fd_set in select.
|
||||
* - an error code if less than zero
|
||||
*/
|
||||
int cs_create_ctrl_sock(int port);
|
||||
|
||||
/**
|
||||
* @brief Free the control socket
|
||||
*
|
||||
* This frees up the control socket that was earlier created using
|
||||
* cs_create_ctrl_sock()
|
||||
*
|
||||
* @param[in] fd the socket descriptor associated with this control socket
|
||||
*/
|
||||
void cs_free_ctrl_sock(int fd);
|
||||
|
||||
/**
|
||||
* @brief Send data to control socket
|
||||
*
|
||||
* This API sends data to the control socket. If a server is blocked
|
||||
* on select() with the control socket, this call will wake up that
|
||||
* server.
|
||||
*
|
||||
* @param[in] send_fd the socket for sending ctrl messages
|
||||
* @param[in] port the port on which the control socket was created
|
||||
* @param[in] data pointer to a buffer that contains data to send on the socket
|
||||
* @param[in] data_len the length of the data contained in the buffer pointed to be data
|
||||
*
|
||||
* @return - the number of bytes sent to the control socket
|
||||
* - an error code if less than zero
|
||||
*/
|
||||
int cs_send_to_ctrl_sock(int send_fd, int port, void *data, unsigned int data_len);
|
||||
|
||||
/**
|
||||
* @brief Receive data from control socket
|
||||
*
|
||||
* This API receives any data that was sent to the control
|
||||
* socket. This will be typically called from the server thread to
|
||||
* process any commands on this socket.
|
||||
*
|
||||
* @param[in] fd the socket descriptor of the control socket
|
||||
* @param[in] data pointer to a buffer that will be used to store
|
||||
* received from the control socket
|
||||
* @param[in] data_len the maximum length of the data that can be
|
||||
* stored in the buffer pointed by data
|
||||
*
|
||||
* @return - the number of bytes received from the control socket
|
||||
* - an error code if less than zero
|
||||
*/
|
||||
int cs_recv_from_ctrl_sock(int fd, void *data, unsigned int data_len);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
|
||||
#endif /* ! _CTRL_SOCK_H_ */
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
/* Based on src/http/ngx_http_parse.c from NGINX copyright Igor Sysoev
|
||||
*
|
||||
* Additional changes are licensed under the same terms as NGINX and
|
||||
* copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to
|
||||
* deal in the Software without restriction, including without limitation the
|
||||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
* sell copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
+2494
File diff suppressed because it is too large.
Load diff
+362
@@ -0,0 +1,362 @@
|
||||
/* Copyright Joyent, Inc. and other Node contributors. All rights reserved.
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy
|
||||
* of this software and associated documentation files (the "Software"), to
|
||||
* deal in the Software without restriction, including without limitation the
|
||||
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
|
||||
* sell copies of the Software, and to permit persons to whom the Software is
|
||||
* furnished to do so, subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in
|
||||
* all copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
||||
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
||||
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
||||
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
|
||||
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
|
||||
* IN THE SOFTWARE.
|
||||
*/
|
||||
#ifndef http_parser_h
|
||||
#define http_parser_h
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
/* Also update SONAME in the Makefile whenever you change these. */
|
||||
#define HTTP_PARSER_VERSION_MAJOR 2
|
||||
#define HTTP_PARSER_VERSION_MINOR 7
|
||||
#define HTTP_PARSER_VERSION_PATCH 0
|
||||
|
||||
#include <sys/types.h>
|
||||
#if defined(_WIN32) && !defined(__MINGW32__) && \
|
||||
(!defined(_MSC_VER) || _MSC_VER<1600) && !defined(__WINE__)
|
||||
#include <BaseTsd.h>
|
||||
#include <stddef.h>
|
||||
typedef __int8 int8_t;
|
||||
typedef unsigned __int8 uint8_t;
|
||||
typedef __int16 int16_t;
|
||||
typedef unsigned __int16 uint16_t;
|
||||
typedef __int32 int32_t;
|
||||
typedef unsigned __int32 uint32_t;
|
||||
typedef __int64 int64_t;
|
||||
typedef unsigned __int64 uint64_t;
|
||||
#else
|
||||
#include <stdint.h>
|
||||
#endif
|
||||
|
||||
/* Compile with -DHTTP_PARSER_STRICT=0 to make less checks, but run
|
||||
* faster
|
||||
*/
|
||||
#ifndef HTTP_PARSER_STRICT
|
||||
# define HTTP_PARSER_STRICT 1
|
||||
#endif
|
||||
|
||||
/* Maximium header size allowed. If the macro is not defined
|
||||
* before including this header then the default is used. To
|
||||
* change the maximum header size, define the macro in the build
|
||||
* environment (e.g. -DHTTP_MAX_HEADER_SIZE=<value>). To remove
|
||||
* the effective limit on the size of the header, define the macro
|
||||
* to a very large number (e.g. -DHTTP_MAX_HEADER_SIZE=0x7fffffff)
|
||||
*/
|
||||
#ifndef HTTP_MAX_HEADER_SIZE
|
||||
# define HTTP_MAX_HEADER_SIZE (80*1024)
|
||||
#endif
|
||||
|
||||
typedef struct http_parser http_parser;
|
||||
typedef struct http_parser_settings http_parser_settings;
|
||||
|
||||
|
||||
/* Callbacks should return non-zero to indicate an error. The parser will
|
||||
* then halt execution.
|
||||
*
|
||||
* The one exception is on_headers_complete. In a HTTP_RESPONSE parser
|
||||
* returning '1' from on_headers_complete will tell the parser that it
|
||||
* should not expect a body. This is used when receiving a response to a
|
||||
* HEAD request which may contain 'Content-Length' or 'Transfer-Encoding:
|
||||
* chunked' headers that indicate the presence of a body.
|
||||
*
|
||||
* Returning `2` from on_headers_complete will tell parser that it should not
|
||||
* expect neither a body nor any futher responses on this connection. This is
|
||||
* useful for handling responses to a CONNECT request which may not contain
|
||||
* `Upgrade` or `Connection: upgrade` headers.
|
||||
*
|
||||
* http_data_cb does not return data chunks. It will be called arbitrarily
|
||||
* many times for each string. E.G. you might get 10 callbacks for "on_url"
|
||||
* each providing just a few characters more data.
|
||||
*/
|
||||
typedef int (*http_data_cb) (http_parser*, const char *at, size_t length);
|
||||
typedef int (*http_cb) (http_parser*);
|
||||
|
||||
|
||||
/* Request Methods */
|
||||
#define HTTP_METHOD_MAP(XX) \
|
||||
XX(0, DELETE, DELETE) \
|
||||
XX(1, GET, GET) \
|
||||
XX(2, HEAD, HEAD) \
|
||||
XX(3, POST, POST) \
|
||||
XX(4, PUT, PUT) \
|
||||
/* pathological */ \
|
||||
XX(5, CONNECT, CONNECT) \
|
||||
XX(6, OPTIONS, OPTIONS) \
|
||||
XX(7, TRACE, TRACE) \
|
||||
/* WebDAV */ \
|
||||
XX(8, COPY, COPY) \
|
||||
XX(9, LOCK, LOCK) \
|
||||
XX(10, MKCOL, MKCOL) \
|
||||
XX(11, MOVE, MOVE) \
|
||||
XX(12, PROPFIND, PROPFIND) \
|
||||
XX(13, PROPPATCH, PROPPATCH) \
|
||||
XX(14, SEARCH, SEARCH) \
|
||||
XX(15, UNLOCK, UNLOCK) \
|
||||
XX(16, BIND, BIND) \
|
||||
XX(17, REBIND, REBIND) \
|
||||
XX(18, UNBIND, UNBIND) \
|
||||
XX(19, ACL, ACL) \
|
||||
/* subversion */ \
|
||||
XX(20, REPORT, REPORT) \
|
||||
XX(21, MKACTIVITY, MKACTIVITY) \
|
||||
XX(22, CHECKOUT, CHECKOUT) \
|
||||
XX(23, MERGE, MERGE) \
|
||||
/* upnp */ \
|
||||
XX(24, MSEARCH, M-SEARCH) \
|
||||
XX(25, NOTIFY, NOTIFY) \
|
||||
XX(26, SUBSCRIBE, SUBSCRIBE) \
|
||||
XX(27, UNSUBSCRIBE, UNSUBSCRIBE) \
|
||||
/* RFC-5789 */ \
|
||||
XX(28, PATCH, PATCH) \
|
||||
XX(29, PURGE, PURGE) \
|
||||
/* CalDAV */ \
|
||||
XX(30, MKCALENDAR, MKCALENDAR) \
|
||||
/* RFC-2068, section 19.6.1.2 */ \
|
||||
XX(31, LINK, LINK) \
|
||||
XX(32, UNLINK, UNLINK) \
|
||||
|
||||
enum http_method
|
||||
{
|
||||
#define XX(num, name, string) HTTP_##name = num,
|
||||
HTTP_METHOD_MAP(XX)
|
||||
#undef XX
|
||||
};
|
||||
|
||||
|
||||
enum http_parser_type { HTTP_REQUEST, HTTP_RESPONSE, HTTP_BOTH };
|
||||
|
||||
|
||||
/* Flag values for http_parser.flags field */
|
||||
enum flags
|
||||
{ F_CHUNKED = 1 << 0
|
||||
, F_CONNECTION_KEEP_ALIVE = 1 << 1
|
||||
, F_CONNECTION_CLOSE = 1 << 2
|
||||
, F_CONNECTION_UPGRADE = 1 << 3
|
||||
, F_TRAILING = 1 << 4
|
||||
, F_UPGRADE = 1 << 5
|
||||
, F_SKIPBODY = 1 << 6
|
||||
, F_CONTENTLENGTH = 1 << 7
|
||||
};
|
||||
|
||||
|
||||
/* Map for errno-related constants
|
||||
*
|
||||
* The provided argument should be a macro that takes 2 arguments.
|
||||
*/
|
||||
#define HTTP_ERRNO_MAP(XX) \
|
||||
/* No error */ \
|
||||
XX(OK, "success") \
|
||||
\
|
||||
/* Callback-related errors */ \
|
||||
XX(CB_message_begin, "the on_message_begin callback failed") \
|
||||
XX(CB_url, "the on_url callback failed") \
|
||||
XX(CB_header_field, "the on_header_field callback failed") \
|
||||
XX(CB_header_value, "the on_header_value callback failed") \
|
||||
XX(CB_headers_complete, "the on_headers_complete callback failed") \
|
||||
XX(CB_body, "the on_body callback failed") \
|
||||
XX(CB_message_complete, "the on_message_complete callback failed") \
|
||||
XX(CB_status, "the on_status callback failed") \
|
||||
XX(CB_chunk_header, "the on_chunk_header callback failed") \
|
||||
XX(CB_chunk_complete, "the on_chunk_complete callback failed") \
|
||||
\
|
||||
/* Parsing-related errors */ \
|
||||
XX(INVALID_EOF_STATE, "stream ended at an unexpected time") \
|
||||
XX(HEADER_OVERFLOW, \
|
||||
"too many header bytes seen; overflow detected") \
|
||||
XX(CLOSED_CONNECTION, \
|
||||
"data received after completed connection: close message") \
|
||||
XX(INVALID_VERSION, "invalid HTTP version") \
|
||||
XX(INVALID_STATUS, "invalid HTTP status code") \
|
||||
XX(INVALID_METHOD, "invalid HTTP method") \
|
||||
XX(INVALID_URL, "invalid URL") \
|
||||
XX(INVALID_HOST, "invalid host") \
|
||||
XX(INVALID_PORT, "invalid port") \
|
||||
XX(INVALID_PATH, "invalid path") \
|
||||
XX(INVALID_QUERY_STRING, "invalid query string") \
|
||||
XX(INVALID_FRAGMENT, "invalid fragment") \
|
||||
XX(LF_EXPECTED, "LF character expected") \
|
||||
XX(INVALID_HEADER_TOKEN, "invalid character in header") \
|
||||
XX(INVALID_CONTENT_LENGTH, \
|
||||
"invalid character in content-length header") \
|
||||
XX(UNEXPECTED_CONTENT_LENGTH, \
|
||||
"unexpected content-length header") \
|
||||
XX(INVALID_CHUNK_SIZE, \
|
||||
"invalid character in chunk size header") \
|
||||
XX(INVALID_CONSTANT, "invalid constant string") \
|
||||
XX(INVALID_INTERNAL_STATE, "encountered unexpected internal state")\
|
||||
XX(STRICT, "strict mode assertion failed") \
|
||||
XX(PAUSED, "parser is paused") \
|
||||
XX(UNKNOWN, "an unknown error occurred")
|
||||
|
||||
|
||||
/* Define HPE_* values for each errno value above */
|
||||
#define HTTP_ERRNO_GEN(n, s) HPE_##n,
|
||||
enum http_errno {
|
||||
HTTP_ERRNO_MAP(HTTP_ERRNO_GEN)
|
||||
};
|
||||
#undef HTTP_ERRNO_GEN
|
||||
|
||||
|
||||
/* Get an http_errno value from an http_parser */
|
||||
#define HTTP_PARSER_ERRNO(p) ((enum http_errno) (p)->http_errno)
|
||||
|
||||
|
||||
struct http_parser {
|
||||
/** PRIVATE **/
|
||||
unsigned int type : 2; /* enum http_parser_type */
|
||||
unsigned int flags : 8; /* F_* values from 'flags' enum; semi-public */
|
||||
unsigned int state : 7; /* enum state from http_parser.c */
|
||||
unsigned int header_state : 7; /* enum header_state from http_parser.c */
|
||||
unsigned int index : 7; /* index into current matcher */
|
||||
unsigned int lenient_http_headers : 1;
|
||||
|
||||
uint32_t nread; /* # bytes read in various scenarios */
|
||||
uint64_t content_length; /* # bytes in body (0 if no Content-Length header) */
|
||||
|
||||
/** READ-ONLY **/
|
||||
unsigned short http_major;
|
||||
unsigned short http_minor;
|
||||
unsigned int status_code : 16; /* responses only */
|
||||
unsigned int method : 8; /* requests only */
|
||||
unsigned int http_errno : 7;
|
||||
|
||||
/* 1 = Upgrade header was present and the parser has exited because of that.
|
||||
* 0 = No upgrade header present.
|
||||
* Should be checked when http_parser_execute() returns in addition to
|
||||
* error checking.
|
||||
*/
|
||||
unsigned int upgrade : 1;
|
||||
|
||||
/** PUBLIC **/
|
||||
void *data; /* A pointer to get hook to the "connection" or "socket" object */
|
||||
};
|
||||
|
||||
|
||||
struct http_parser_settings {
|
||||
http_cb on_message_begin;
|
||||
http_data_cb on_url;
|
||||
http_data_cb on_status;
|
||||
http_data_cb on_header_field;
|
||||
http_data_cb on_header_value;
|
||||
http_cb on_headers_complete;
|
||||
http_data_cb on_body;
|
||||
http_cb on_message_complete;
|
||||
/* When on_chunk_header is called, the current chunk length is stored
|
||||
* in parser->content_length.
|
||||
*/
|
||||
http_cb on_chunk_header;
|
||||
http_cb on_chunk_complete;
|
||||
};
|
||||
|
||||
|
||||
enum http_parser_url_fields
|
||||
{ UF_SCHEMA = 0
|
||||
, UF_HOST = 1
|
||||
, UF_PORT = 2
|
||||
, UF_PATH = 3
|
||||
, UF_QUERY = 4
|
||||
, UF_FRAGMENT = 5
|
||||
, UF_USERINFO = 6
|
||||
, UF_MAX = 7
|
||||
};
|
||||
|
||||
|
||||
/* Result structure for http_parser_parse_url().
|
||||
*
|
||||
* Callers should index into field_data[] with UF_* values iff field_set
|
||||
* has the relevant (1 << UF_*) bit set. As a courtesy to clients (and
|
||||
* because we probably have padding left over), we convert any port to
|
||||
* a uint16_t.
|
||||
*/
|
||||
struct http_parser_url {
|
||||
uint16_t field_set; /* Bitmask of (1 << UF_*) values */
|
||||
uint16_t port; /* Converted UF_PORT string */
|
||||
|
||||
struct {
|
||||
uint16_t off; /* Offset into buffer in which field starts */
|
||||
uint16_t len; /* Length of run in buffer */
|
||||
} field_data[UF_MAX];
|
||||
};
|
||||
|
||||
|
||||
/* Returns the library version. Bits 16-23 contain the major version number,
|
||||
* bits 8-15 the minor version number and bits 0-7 the patch level.
|
||||
* Usage example:
|
||||
*
|
||||
* unsigned long version = http_parser_version();
|
||||
* unsigned major = (version >> 16) & 255;
|
||||
* unsigned minor = (version >> 8) & 255;
|
||||
* unsigned patch = version & 255;
|
||||
* printf("http_parser v%u.%u.%u\n", major, minor, patch);
|
||||
*/
|
||||
unsigned long http_parser_version(void);
|
||||
|
||||
void http_parser_init(http_parser *parser, enum http_parser_type type);
|
||||
|
||||
|
||||
/* Initialize http_parser_settings members to 0
|
||||
*/
|
||||
void http_parser_settings_init(http_parser_settings *settings);
|
||||
|
||||
|
||||
/* Executes the parser. Returns number of parsed bytes. Sets
|
||||
* `parser->http_errno` on error. */
|
||||
size_t http_parser_execute(http_parser *parser,
|
||||
const http_parser_settings *settings,
|
||||
const char *data,
|
||||
size_t len);
|
||||
|
||||
|
||||
/* If http_should_keep_alive() in the on_headers_complete or
|
||||
* on_message_complete callback returns 0, then this should be
|
||||
* the last message on the connection.
|
||||
* If you are the server, respond with the "Connection: close" header.
|
||||
* If you are the client, close the connection.
|
||||
*/
|
||||
int http_should_keep_alive(const http_parser *parser);
|
||||
|
||||
/* Returns a string version of the HTTP method. */
|
||||
const char *http_method_str(enum http_method m);
|
||||
|
||||
/* Return a string name of the given error */
|
||||
const char *http_errno_name(enum http_errno err);
|
||||
|
||||
/* Return a string description of the given error */
|
||||
const char *http_errno_description(enum http_errno err);
|
||||
|
||||
/* Initialize all http_parser_url members to 0 */
|
||||
void http_parser_url_init(struct http_parser_url *u);
|
||||
|
||||
/* Parse a URL; return nonzero on failure */
|
||||
int http_parser_parse_url(const char *buf, size_t buflen,
|
||||
int is_connect,
|
||||
struct http_parser_url *u);
|
||||
|
||||
/* Pause or un-pause the parser; a nonzero value pauses */
|
||||
void http_parser_pause(http_parser *parser, int paused);
|
||||
|
||||
/* Checks if this is the final chunk of the body. */
|
||||
int http_body_is_final(const http_parser *parser);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
@@ -0,0 +1,45 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Patch the vendored ESP-IDF httpd so it needs no mbedTLS or PSA.
|
||||
|
||||
The WebSocket handshake hashes the client key with SHA-1 and base64-encodes it. The desktop build uses its
|
||||
own SHA-1 and base64 (desktop/port/src/desktop_crypto.c), so only that block changes. Idempotent.
|
||||
"""
|
||||
import re
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
root = Path(sys.argv[1])
|
||||
|
||||
# esp_http_server.h uses the heap capability flags without including their header (ESP-IDF gets them
|
||||
# from its own include order), so include it here
|
||||
hdr = root / "esp_http_server" / "include" / "esp_http_server.h"
|
||||
h = hdr.read_text()
|
||||
if '#include "esp_heap_caps.h"' not in h:
|
||||
h = h.replace("#include ", '#include "esp_heap_caps.h"\n#include ', 1)
|
||||
hdr.write_text(h)
|
||||
print("patched", hdr)
|
||||
|
||||
ws = root / "esp_http_server" / "src" / "httpd_ws.c"
|
||||
s = ws.read_text()
|
||||
|
||||
if "desktop_crypto.h" not in s:
|
||||
s = s.replace("#include <psa/crypto.h>\n", "")
|
||||
s = s.replace("#include <mbedtls/base64.h>\n", '#include "desktop_crypto.h"\n')
|
||||
s = s.replace("#include <mbedtls/error.h>\n", "")
|
||||
start = s.index(" /* Generate SHA-1 hash */")
|
||||
end_marker = "server_key_hash, sizeof(server_key_hash));\n"
|
||||
end = s.index(end_marker, start) + len(end_marker)
|
||||
s = s[:start] + (
|
||||
" /* Generate SHA-1 hash, then base64 (desktop build: desktop_crypto.c) */\n"
|
||||
" desktop_sha1((const uint8_t *)server_raw_text, strlen(server_raw_text), server_key_hash);\n"
|
||||
" size_t encoded_len = desktop_base64_encode(server_key_encoded, sizeof(server_key_encoded),\n"
|
||||
" server_key_hash, sizeof(server_key_hash));\n"
|
||||
) + s[end:]
|
||||
ws.write_text(s)
|
||||
print("patched", ws)
|
||||
else:
|
||||
print("already patched", ws)
|
||||
|
||||
if "mbedtls" in s or "psa_" in s:
|
||||
print("WARNING: mbedTLS/PSA still referenced in", ws, file=sys.stderr)
|
||||
sys.exit(1)
|
||||
Executable
+28
@@ -0,0 +1,28 @@
|
||||
#!/usr/bin/env bash
|
||||
# Vendor the third-party sources the desktop build needs, from ESP-IDF (espressif/idf:v6.1) and the cJSON
|
||||
# managed component, then patch the two spots that use mbedTLS/PSA (see patch_vendor.py).
|
||||
# Run from the repository root after changing the IDF version: desktop/tools/vendor.sh
|
||||
set -euo pipefail
|
||||
cd "$(dirname "$0")/../.."
|
||||
IDF_IMAGE=${IDF_IMAGE:-espressif/idf:v6.1}
|
||||
OUT=desktop/third_party
|
||||
rm -rf "$OUT/esp_http_server" "$OUT/http_parser" "$OUT/cjson"
|
||||
mkdir -p "$OUT/esp_http_server/src/util" "$OUT/esp_http_server/include" "$OUT/http_parser" "$OUT/cjson"
|
||||
docker run --rm -v "$PWD/$OUT:/out" "$IDF_IMAGE" bash -c '
|
||||
set -e; S=/opt/esp/idf/components
|
||||
cp $S/esp_http_server/src/*.c $S/esp_http_server/src/esp_httpd_priv.h /out/esp_http_server/src/
|
||||
cp $S/esp_http_server/src/util/* /out/esp_http_server/src/util/
|
||||
cp $S/esp_http_server/include/esp_http_server.h /out/esp_http_server/include/
|
||||
cp $S/http_parser/http_parser.c $S/http_parser/http_parser.h $S/http_parser/LICENSE.txt /out/http_parser/
|
||||
cp $S/esp_http_server/LICENSE /out/esp_http_server/ 2>/dev/null || true
|
||||
chown -R 0:0 /out
|
||||
'
|
||||
# cJSON: the managed component the board and the sim already use (version pinned in dependencies.lock)
|
||||
CJSON=sim-controller/managed_components/espressif__cjson/cJSON
|
||||
cp "$CJSON/cJSON.c" "$CJSON/cJSON.h" "$CJSON/LICENSE" "$OUT/cjson/"
|
||||
python3 desktop/tools/patch_vendor.py "$OUT"
|
||||
# sdkconfig.h: the config the sim's ESP-IDF linux build generated (the same CONFIG_* values the firmware reads)
|
||||
if [ -f sim-controller/build/config/sdkconfig.h ]; then
|
||||
cp sim-controller/build/config/sdkconfig.h desktop/port/include/sdkconfig.h
|
||||
fi
|
||||
echo "vendored into $OUT"
|
||||
Reference in new issue
Block a user