diff --git a/include/utils.h b/include/utils.h index d1fcf91..fa3736f 100644 --- a/include/utils.h +++ b/include/utils.h @@ -5,11 +5,67 @@ #include #include +#include #include +#include +#include #include +#include #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 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 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) { std::string chipId; chipId.reserve( diff --git a/src/mqtt.cpp b/src/mqtt.cpp index 894f15c..f8a275e 100644 --- a/src/mqtt.cpp +++ b/src/mqtt.cpp @@ -6,10 +6,8 @@ #include #include #include -#include #include #include -#include #include #include #include @@ -308,46 +306,6 @@ static void publishState() { 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 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) { if (payload.empty()) { return false; diff --git a/src/portal.cpp b/src/portal.cpp index ad1db73..1245130 100644 --- a/src/portal.cpp +++ b/src/portal.cpp @@ -817,57 +817,137 @@ static void restApi() { request->send(response); }).addMiddleware(&authMiddleware); + // Set sensor value (JSON) auto& sensorValueHandler = webServer->on(AsyncURIMatcher::exact("/api/sensor/value"), HTTP_POST, [](AsyncWebServerRequest *request, JsonVariant &requestDoc) { if (upgrading || restartTask.scheduled() || restartTask.active()) { return request->send(503); - } - if (!requestDoc.is() || !requestDoc.size()) { + } else if (!requestDoc.is() || !requestDoc.size()) { + return request->send(400); + + } else if (!request->hasParam("id") || !requestDoc[S_VALUE].is()) { return request->send(400); } - if (!request->hasParam("id")) { - return request->send(400); - } + // Read sensor value + const auto value = requestDoc[S_VALUE].as(); + requestDoc.clear(); + // Parse sensor ID const auto& id = request->getParam("id")->value(); const auto sensorId = Sensors::parseId(id.c_str()); if (!sensorId) { return request->send(404); } - if (!requestDoc[S_VALUE].is()) { - return request->send(400); - } - - const auto value = requestDoc[S_VALUE].as(); - requestDoc.clear(); + // 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); }); - sensorValueHandler.setMaxContentLength(1024); + sensorValueHandler.setMaxContentLength(64); 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 webServer->on("/api/vars", HTTP_GET, [](AsyncWebServerRequest *request) { // make response