fix: accept form posts for manual sensor values

Accept form submissions alongside the existing JSON sensor value endpoint
for compatibility with the manual sensor use case discussed in PR #270.
Support named value and unnamed body parameters with strict numeric parsing
and bounded input lengths. Preserve authentication, unit conversion, MQTT
publication and noresponse handling.

Share payload trimming and numeric parsing between HTTP and MQTT instead
of maintaining separate parser implementations.

Refs #270
This commit is contained in:
Yurii committed 2026-11-29 05:43:51 +03:00
1 parent cc6131eac9
commit 8fba88636e
3 files changed
+148 -54

No files matched your search

+56
View File
@@ -5,11 +5,67 @@
#include <string.h> #include <string.h>
#include <time.h> #include <time.h>
#include <cerrno>
#include <cmath> #include <cmath>
#include <cstdlib>
#include <optional>
#include <string> #include <string>
#include <string_view>
#include "types.h" #include "types.h"
inline std::string_view trimPayload(std::string_view payload) {
const auto first = payload.find_first_not_of(" \t\r\n");
if (first == std::string_view::npos) {
return {};
}
return payload.substr(first, payload.find_last_not_of(" \t\r\n") - first + 1);
}
// text must be NUL-terminated; length may exclude trailing whitespace.
inline std::optional<float> parseNumber(const char* text, size_t length) {
if (text == nullptr || length == 0) {
return std::nullopt;
}
const auto payload = std::string_view(text, length);
const char first = payload.front();
// strtof also accepts leading whitespace, '+' and hexadecimal numbers.
if ((first < '0' || first > '9') && first != '-' && first != '.') {
return std::nullopt;
}
if (payload.find_first_of("xX") != std::string_view::npos) {
return std::nullopt;
}
char* end;
errno = 0;
const float parsed = std::strtof(text, &end);
if (end != text + length || !std::isfinite(parsed) || (errno == ERANGE && parsed == 0.0f)) {
return std::nullopt;
}
return parsed;
}
inline std::optional<float> parseNumber(std::string_view payload, uint8_t bufferSize = 17) {
if (payload.empty() || bufferSize < 2) {
return std::nullopt;
}
// Long input is intentionally truncated to leave room for the terminating NUL.
payload = payload.substr(0, bufferSize - 1);
char buffer[bufferSize];
memcpy(buffer, payload.data(), payload.size());
buffer[payload.size()] = '\0';
return parseNumber(buffer, payload.size());
}
inline std::string getChipId(const char* prefix = nullptr, const char* suffix = nullptr) { inline std::string getChipId(const char* prefix = nullptr, const char* suffix = nullptr) {
std::string chipId; std::string chipId;
chipId.reserve( chipId.reserve(
-42
View File
@@ -6,10 +6,8 @@
#include <algorithm> #include <algorithm>
#include <atomic> #include <atomic>
#include <bitset> #include <bitset>
#include <cerrno>
#include <cmath> #include <cmath>
#include <cstdio> #include <cstdio>
#include <cstdlib>
#include <cstring> #include <cstring>
#include <initializer_list> #include <initializer_list>
#include <list> #include <list>
@@ -308,46 +306,6 @@ static void publishState() {
publishMasterState(); publishMasterState();
} }
static std::string_view trimPayload(std::string_view payload) {
const auto first = payload.find_first_not_of(" \t\r\n");
if (first == std::string_view::npos) {
return {};
}
return payload.substr(first, payload.find_last_not_of(" \t\r\n") - first + 1);
}
static std::optional<float> parseNumber(std::string_view payload, uint8_t bufferSize = 17) {
if (payload.empty() || bufferSize < 2) {
return std::nullopt;
}
// Long input is intentionally truncated to leave room for the terminating NUL.
payload = payload.substr(0, bufferSize - 1);
// strtof also accepts leading whitespace, '+' and hexadecimal numbers.
const char first = payload.front();
if ((first < '0' || first > '9') && first != '-' && first != '.') {
return std::nullopt;
}
if (payload.find_first_of("xX") != std::string_view::npos) {
return std::nullopt;
}
char buffer[bufferSize];
memcpy(buffer, payload.data(), payload.size());
buffer[payload.size()] = '\0';
char* end;
errno = 0;
const float parsed = std::strtof(buffer, &end);
if (end != buffer + payload.size() || !std::isfinite(parsed) || (errno == ERANGE && parsed == 0.0f)) {
return std::nullopt;
}
return parsed;
}
static bool isCommandValid(const std::string& topic, std::string_view payload) { static bool isCommandValid(const std::string& topic, std::string_view payload) {
if (payload.empty()) { if (payload.empty()) {
return false; return false;
+92 -12
View File
@@ -817,57 +817,137 @@ static void restApi() {
request->send(response); request->send(response);
}).addMiddleware(&authMiddleware); }).addMiddleware(&authMiddleware);
// Set sensor value (JSON)
auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) {
if (upgrading || restartTask.scheduled() || restartTask.active()) { if (upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503); return request->send(503);
}
if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) { } else if (!requestDoc.is<JsonObjectConst>() || !requestDoc.size()) {
return request->send(400);
} else if (!request->hasParam("id") || !requestDoc[S_VALUE].is<float>()) {
return request->send(400); return request->send(400);
} }
if (!request->hasParam("id")) { // Read sensor value
return request->send(400); const auto value = requestDoc[S_VALUE].as<float>();
} requestDoc.clear();
// Parse sensor ID
const auto& id = request->getParam("id")->value(); const auto& id = request->getParam("id")->value();
const auto sensorId = Sensors::parseId(id.c_str()); const auto sensorId = Sensors::parseId(id.c_str());
if (!sensorId) { if (!sensorId) {
return request->send(404); return request->send(404);
} }
if (!requestDoc[S_VALUE].is<float>()) { // Try to set sensor value
return request->send(400);
}
const auto value = requestDoc[S_VALUE].as<float>();
requestDoc.clear();
if (!Sensors::setManualValueById(*sensorId, value, settings.system.unitSystem)) { if (!Sensors::setManualValueById(*sensorId, value, settings.system.unitSystem)) {
return request->send(400); return request->send(400);
} }
// Request MQTT publication
requestPublishMqttSensor(*sensorId); requestPublishMqttSensor(*sensorId);
// If the noresponse parameter is provided,
// simply return HTTP 201 with an empty body.
if (request->hasParam("noresponse")) { if (request->hasParam("noresponse")) {
return request->send(201); return request->send(201);
} }
// Get sensor snapshot for response
const auto sensor = Sensors::getSnapshot(*sensorId); const auto sensor = Sensors::getSnapshot(*sensorId);
if (!sensor) { if (!sensor) {
return request->send(404); return request->send(404);
} }
// Prepare response
auto *response = new AsyncJsonResponse(); auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot(); auto& responseDoc = response->getRoot();
toJson(sensor->settings, sensor->result, responseDoc); toJson(sensor->settings, sensor->result, responseDoc);
// Send response
response->setLength(); response->setLength();
response->setCode(201); response->setCode(201);
request->send(response); request->send(response);
}); });
sensorValueHandler.setMaxContentLength(1024); sensorValueHandler.setMaxContentLength(64);
sensorValueHandler.addMiddleware(&authMiddleware); sensorValueHandler.addMiddleware(&authMiddleware);
// Set sensor value (form)
webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request) {
if (upgrading || restartTask.scheduled() || restartTask.active()) {
return request->send(503);
} else if (request->contentLength() > 64) {
return request->send(413);
} else if (!request->hasParam("id")) {
return request->send(400);
}
// Parse sensor ID
const auto& id = request->getParam("id")->value();
const auto sensorId = Sensors::parseId(id.c_str());
if (!sensorId) {
return request->send(404);
}
// Read POST payload
const auto* parameter = request->getParam(S_VALUE, true);
if (parameter == nullptr) {
parameter = request->getParam("body", true);
}
if (parameter == nullptr) {
return request->send(400);
}
// Validate payload length
const auto& text = parameter->value();
const auto payload = trimPayload(std::string_view(text.c_str(), text.length()));
if (payload.size() >= 17) {
return request->send(400);
}
// Parse numeric value
const auto value = parseNumber(payload.data(), payload.size());
if (!value) {
return request->send(400);
}
// Try to set sensor value
if (!Sensors::setManualValueById(*sensorId, *value, settings.system.unitSystem)) {
return request->send(400);
}
// Request MQTT publication
requestPublishMqttSensor(*sensorId);
// If the noresponse parameter is provided,
// simply return HTTP 201 with an empty body.
if (request->hasParam("noresponse")) {
return request->send(201);
}
// Get sensor snapshot for response
const auto sensor = Sensors::getSnapshot(*sensorId);
if (!sensor) {
return request->send(404);
}
// Prepare response
auto *response = new AsyncJsonResponse();
auto& responseDoc = response->getRoot();
toJson(sensor->settings, sensor->result, responseDoc);
// Send response
response->setLength();
response->setCode(201);
request->send(response);
}).addMiddleware(&authMiddleware);
// vars // vars
webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) { webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) {
// make response // make response