diff --git a/examples/mqtt_observer/MQTTObserver.cpp b/examples/mqtt_observer/MQTTObserver.cpp index 5d3417b6..b251b585 100644 --- a/examples/mqtt_observer/MQTTObserver.cpp +++ b/examples/mqtt_observer/MQTTObserver.cpp @@ -100,7 +100,8 @@ MQTTObserver::MQTTObserver() _runtime_config{}, _work_config{}, _io_config{}, _save_record{}, _load_record{}, _config_mux(portMUX_INITIALIZER_UNLOCKED), _queue_mux(portMUX_INITIALIZER_UNLOCKED), _queue(), _raw_stager(), _brokers{}, _wifi_started(false), - _recover_requested(false), _station_request(false), _queue_disconnected_since(0), _last_ntp_request(0), + _recover_requested(false), _station_request(false), _web_ota_hold(false), + _queue_disconnected_since(0), _last_ntp_request(0), _device_id{}, _json{}, _state(STATE_OFF), _save_state(), _received(0), _published(0), _disconnected_drops(0), _queue_drops(0), _publish_drops(0) { @@ -626,9 +627,10 @@ void MQTTObserver::worker() { // release download) can request it on its own. With neither, Wi-Fi stays // down. Both cases share the join and NTP path below, so the clock is set // whenever the station is up, broker or not. + const bool requested = _station_request.load(std::memory_order_relaxed) || + _web_ota_hold.load(std::memory_order_relaxed); bool station_wanted = MQTTObserverOtaStationPolicy::stationWanted( - have_ready_broker, _station_request.load(std::memory_order_relaxed), - _work_config.wifi_ssid[0]); + have_ready_broker, requested, _work_config.wifi_ssid[0]); if (!station_wanted) { for (size_t i = 0; i < MQTT_OBSERVER_MAX_BROKERS; i++) { disconnectBroker(i); @@ -1100,8 +1102,11 @@ bool MQTTObserver::handleCommand(char* command, char* reply) { portEXIT_CRITICAL(&_config_mux); if (MQTTObserverOtaStationPolicy::wantsStation(have_credentials, WiFi.status() == WL_CONNECTED)) { - _station_request.store(true, std::memory_order_relaxed); - if (!MQTTObserverOtaStationPolicy::isOnlineFetchCommand(command)) { + if (MQTTObserverOtaStationPolicy::isOnlineFetchCommand(command)) { + _station_request.store(true, std::memory_order_relaxed); + } else { + // The uploader keeps its link until reboot, independent of online OTA. + _web_ota_hold.store(true, std::memory_order_relaxed); uint32_t started = millis(); while (WiFi.status() != WL_CONNECTED && millis() - started < MQTTObserverOtaStationPolicy::kAssociateTimeoutMs) { diff --git a/examples/mqtt_observer/MQTTObserver.h b/examples/mqtt_observer/MQTTObserver.h index f49d1364..bc09b3a0 100644 --- a/examples/mqtt_observer/MQTTObserver.h +++ b/examples/mqtt_observer/MQTTObserver.h @@ -111,7 +111,8 @@ class MQTTObserver { BrokerRuntime _brokers[MQTT_OBSERVER_MAX_BROKERS]; bool _wifi_started; std::atomic _recover_requested; // reset the Wi-Fi station and reconnect - std::atomic _station_request; // a consumer requested the station with no broker + std::atomic _station_request; // online fetch requested the station + std::atomic _web_ota_hold; // `start ota` uploader, held until reboot uint32_t _queue_disconnected_since; uint32_t _last_ntp_request; char _device_id[2 * PUB_KEY_SIZE + 1]; diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index d53b96bd..2bb4821d 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -1708,6 +1708,10 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply } else if (memcmp(command, "ota", 3) == 0 && (command[3] == ' ' || command[3] == 0)) { const char* sub = command + 3; while (*sub == ' ') sub++; +#ifdef WITH_MQTT_OBSERVER + // The frozen reply comes from otaCLI; the online job must be dropped too. + if (strcmp(sub, "abort") == 0) onlineOta.abort(); +#endif otaCLI(ota, sub, reply); } else if (memcmp(command, "clock mesh", 10) == 0 && (command[10] == 0 || command[10] == ' ')) { // before the common CLI's bare "clock" prefix match, which would swallow it diff --git a/examples/simple_repeater/OnlineOtaCore.cpp b/examples/simple_repeater/OnlineOtaCore.cpp index 1f6d0a00..d9ef5e43 100644 --- a/examples/simple_repeater/OnlineOtaCore.cpp +++ b/examples/simple_repeater/OnlineOtaCore.cpp @@ -17,6 +17,7 @@ namespace { constexpr uint32_t kStationTimeoutMs = 30000; constexpr uint32_t kClockTimeoutMs = 45000; +constexpr uint32_t kNoProgressMs = 15000; bool expired(uint32_t deadline) { return (uint32_t)(millis() - deadline) < 0x80000000u; @@ -25,7 +26,8 @@ bool expired(uint32_t deadline) { OnlineOtaCore::OnlineOtaCore() : _net(nullptr), _ota(nullptr), _slot_size(0), _phase(Phase::Idle), _err(0), - _ver_set(false), _sha_set(false), _size(0), _got(0), _deadline(0) { + _ver_set(false), _sha_set(false), _size(0), _got(0), _deadline(0), + _last_progress(0) { _env[0] = 0; _version[0] = 0; _url[0] = 0; @@ -53,6 +55,10 @@ void OnlineOtaCore::begin(OnlineOtaNet* net, OtaUpdate* ota, } bool OnlineOtaCore::setVersion(const char* version, char* reply) { + if (needsAwake()) { + snprintf(reply, CLI_REPLY_MAX, "Err - fetch already active; abort first"); + return false; + } char canonical[ONLINE_OTA_MAX_VERSION + 1]; if (!OnlineOtaPolicy::normalizeVersion(version, canonical, sizeof(canonical))) { snprintf(reply, CLI_REPLY_MAX, "Err - invalid version token"); @@ -65,6 +71,10 @@ bool OnlineOtaCore::setVersion(const char* version, char* reply) { } bool OnlineOtaCore::setSha(const char* sha, char* reply) { + if (needsAwake()) { + snprintf(reply, CLI_REPLY_MAX, "Err - fetch already active; abort first"); + return false; + } uint8_t digest[32]; if (!OnlineOtaPolicy::parseSha(sha, digest)) { snprintf(reply, CLI_REPLY_MAX, "Err - sha256 must be 64 hex chars"); @@ -82,16 +92,20 @@ bool OnlineOtaCore::start(char* reply) { snprintf(reply, CLI_REPLY_MAX, "Err - set ver and sha first"); return false; } - if (_env[0] == 0 || _net == nullptr || !_net->available() || _ota == nullptr || - _slot_size == 0) { - snprintf(reply, CLI_REPLY_MAX, "Err - unsupported board"); - return false; - } if (_ota->state() == OtaUpdate::State::Staging || _ota->state() == OtaUpdate::State::Ready) { snprintf(reply, CLI_REPLY_MAX, "Err - staging active; abort first"); return false; } + if (_phase != Phase::Idle && _phase != Phase::Error) { + snprintf(reply, CLI_REPLY_MAX, "Err - fetch already active; abort first"); + return false; + } + if (_env[0] == 0 || _net == nullptr || !_net->available() || _ota == nullptr || + _slot_size == 0) { + snprintf(reply, CLI_REPLY_MAX, "Err - unsupported board"); + return false; + } if (_ota->batterySuspended()) { snprintf(reply, CLI_REPLY_MAX, "Err - battery gate active; staging refused"); return false; @@ -112,6 +126,8 @@ bool OnlineOtaCore::start(char* reply) { } void OnlineOtaCore::fail(uint8_t err) { + // A failure path must never report err=0, which the frozen surface calls OK. + if (err == 0) err = ONLINE_ERR_HTTP; if (_net != nullptr) { _net->cancel(); _net->requestStation(false); @@ -127,7 +143,9 @@ void OnlineOtaCore::fail(uint8_t err) { } void OnlineOtaCore::loop() { - if (_phase == Phase::Idle || _phase == Phase::Ready) return; + // Error is terminal: a later battery reading must not overwrite the reason + // the operator is shown. + if (_phase == Phase::Idle || _phase == Phase::Ready || _phase == Phase::Error) return; if (_net == nullptr || !_net->available()) { fail(ONLINE_ERR_CFG); return; } if (_ota != nullptr && _ota->batterySuspended()) { fail(OTA_ERR_BATTERY); return; } @@ -145,12 +163,19 @@ void OnlineOtaCore::loop() { fail(ONLINE_ERR_HEAP); } else if (_net->clockValid()) { if (!_net->beginGet(_url, _slot_size)) fail(ONLINE_ERR_TLS); - else _phase = Phase::Asset; + else { + _phase = Phase::Asset; + _last_progress = millis(); + } } else if (expired(_deadline)) { fail(ONLINE_ERR_CLOCK); } break; case Phase::Asset: { + if (expired(_last_progress + kNoProgressMs)) { + fail(ONLINE_ERR_HTTP); + return; + } const uint8_t* chunk = nullptr; size_t len = 0; uint8_t err = 0; @@ -165,6 +190,7 @@ void OnlineOtaCore::loop() { return; } _size = size; + _last_progress = millis(); } if (step == OnlineOtaNet::Step::Busy) return; if (chunk != nullptr && len > 0) { @@ -173,6 +199,7 @@ void OnlineOtaCore::loop() { return; } _got += (uint32_t)len; + _last_progress = millis(); } if (step == OnlineOtaNet::Step::Done) { if (_size == 0 || _got != _size) { fail(ONLINE_ERR_DOWNLOAD); return; } diff --git a/examples/simple_repeater/OnlineOtaCore.h b/examples/simple_repeater/OnlineOtaCore.h index b44274b4..d31441cc 100644 --- a/examples/simple_repeater/OnlineOtaCore.h +++ b/examples/simple_repeater/OnlineOtaCore.h @@ -26,7 +26,12 @@ public: bool start(char* reply); void loop(); void abort(); - bool needsAwake() const { return _phase != Phase::Idle && _phase != Phase::Ready; } + // Only a live job holds the radio awake. Error and Ready are terminal: a + // failed update must not stop a powersaving node from sleeping. + bool needsAwake() const { + return _phase == Phase::Wifi || _phase == Phase::Clock || + _phase == Phase::Asset || _phase == Phase::Verify; + } void formatNet(char* reply, size_t cap) const; Phase phase() const { return _phase; } @@ -50,6 +55,7 @@ private: char _url[ONLINE_OTA_MAX_URL]; uint32_t _size, _got; uint32_t _deadline; + uint32_t _last_progress; }; // The online verbs, dispatched from MyMesh::handleCommand() before otaCLI(). diff --git a/examples/simple_repeater/OnlineOtaNet.cpp b/examples/simple_repeater/OnlineOtaNet.cpp index 817b3b16..fa57326c 100644 --- a/examples/simple_repeater/OnlineOtaNet.cpp +++ b/examples/simple_repeater/OnlineOtaNet.cpp @@ -41,10 +41,22 @@ bool startsWithCI(const char* s, const char* p) { } return true; } + +bool containsCI(const char* s, const char* needle) { + for (; *s; s++) { + if (startsWithCI(s, needle)) return true; + } + return false; +} } // namespace void OnlineOtaNetEsp32::begin(MQTTObserver* observer) { _observer = observer; + // The CA bundle is a framework global shared with the observer's MQTT TLS + // client. Load it once here, not on every connect or redirect. +#if !defined(ESP_IDF_VERSION_MAJOR) || ESP_IDF_VERSION_MAJOR < 5 + _client.setCACertBundle(x509_crt_bundle); +#endif } void OnlineOtaNetEsp32::requestStation(bool want) { @@ -82,6 +94,7 @@ bool OnlineOtaNetEsp32::beginGet(const char* url, uint32_t max_bytes) { if (url == nullptr || !heapOk() || !setUrl(url)) return false; _max_bytes = max_bytes; _redirects = 0; + _location[0] = 0; _phase = HttpPhase::Connect; return true; } @@ -95,22 +108,18 @@ OnlineOtaNet::Step OnlineOtaNetEsp32::step(const uint8_t** out, size_t* len, uin // DNS, TCP and TLS use the framework's socket timeout; later phases poll // available() and never wait on the link. _client.setTimeout(kSocketTimeoutSec); -#if defined(ESP_IDF_VERSION_MAJOR) && ESP_IDF_VERSION_MAJOR >= 5 - _client.attachArduinoCACertBundle(); -#else - _client.setCACertBundle(x509_crt_bundle); -#endif + // IDF5's NetworkClientSecure uses a different bundle API and is not used + // by any current observer target; the SHA gate still verifies the image. if (!_client.connect(_host, 443)) { *err = ONLINE_ERR_TLS; cancel(); return Step::Error; } - char request[512]; - const int n = snprintf(request, sizeof(request), + const int n = snprintf(_request, sizeof(_request), "GET %s HTTP/1.1\r\nHost: %s\r\nUser-Agent: MeshCore-OTA/1\r\n" "Accept: */*\r\nConnection: close\r\n\r\n", _path, _host); - if (n <= 0 || n >= (int)sizeof(request) || - _client.write((const uint8_t*)request, (size_t)n) != (size_t)n) { + if (n <= 0 || n >= (int)sizeof(_request) || + _client.write((const uint8_t*)_request, (size_t)n) != (size_t)n) { *err = ONLINE_ERR_HTTP; cancel(); return Step::Error; @@ -124,30 +133,43 @@ OnlineOtaNet::Step OnlineOtaNetEsp32::step(const uint8_t** out, size_t* len, uin if (!_client.connected()) { *err = ONLINE_ERR_HTTP; cancel(); return Step::Error; } return Step::Busy; } - char line[384]; // a GitHub redirect Location can be long - const int got = _client.readBytesUntil('\n', line, sizeof(line) - 1); + const int got = _client.readBytesUntil('\n', _line, sizeof(_line) - 1); if (got <= 0) return Step::Busy; - line[got] = 0; - size_t n = strlen(line); - while (n > 0 && (line[n - 1] == '\r' || line[n - 1] == '\n')) line[--n] = 0; + if (got >= (int)sizeof(_line) - 1) { // truncated header: fail closed + *err = ONLINE_ERR_HTTP; + cancel(); + return Step::Error; + } + _line[got] = 0; + size_t n = strlen(_line); + while (n > 0 && (_line[n - 1] == '\r' || _line[n - 1] == '\n')) _line[--n] = 0; if (n == 0) { _phase = HttpPhase::Body; return Step::Busy; } - if (startsWith(line, "HTTP/")) { - const char* sp = strchr(line, ' '); + if (startsWith(_line, "HTTP/")) { + // Each response starts with a status line: forget any Location from the + // previous response before deciding whether this one redirects. + _location[0] = 0; + const char* sp = strchr(_line, ' '); _status = sp != nullptr ? (uint16_t)strtoul(sp + 1, nullptr, 10) : 0; - } else if (startsWithCI(line, "location:")) { - const char* v = line + 9; + } else if (startsWithCI(_line, "location:")) { + const char* v = _line + 9; while (*v == ' ') v++; snprintf(_location, sizeof(_location), "%s", v); - } else if (startsWithCI(line, "content-length:")) { - const char* v = line + 15; + } else if (startsWithCI(_line, "content-length:")) { + const char* v = _line + 15; while (*v == ' ') v++; - _body_length = strtoul(v, nullptr, 10); - if (_body_length > _max_bytes) { *err = ONLINE_ERR_HTTP; cancel(); return Step::Error; } - } else if (startsWithCI(line, "transfer-encoding:")) { + char* end = nullptr; + const unsigned long declared = strtoul(v, &end, 10); + if (end == v || declared == 0 || declared > _max_bytes) { + *err = ONLINE_ERR_HTTP; + cancel(); + return Step::Error; + } + _body_length = (uint32_t)declared; + } else if (startsWithCI(_line, "transfer-encoding:")) { // Refuse a chunked body rather than mis-stage it: release assets carry - // a Content-Length. - if (strstr(line + 18, "chunked") != nullptr) { + // a Content-Length. Transfer-coding tokens are case-insensitive. + if (containsCI(_line + 18, "chunked")) { *err = ONLINE_ERR_HTTP; cancel(); return Step::Error; @@ -156,12 +178,10 @@ OnlineOtaNet::Step OnlineOtaNetEsp32::step(const uint8_t** out, size_t* len, uin if (_status >= 300 && _status < 400 && _location[0] != 0) { if (++_redirects > kMaxRedirects) { *err = ONLINE_ERR_HTTP; cancel(); return Step::Error; } - char next[sizeof(_location)]; - snprintf(next, sizeof(next), "%s", _location); const uint32_t max_bytes = _max_bytes; - cancel(); - _max_bytes = max_bytes; // closing the old socket must not drop the cap - if (!setUrl(next)) { *err = ONLINE_ERR_HTTP; return Step::Error; } + cancel(); // keeps _location, which holds the next URL + _max_bytes = max_bytes; + if (!setUrl(_location)) { *err = ONLINE_ERR_HTTP; return Step::Error; } _phase = HttpPhase::Connect; return Step::Busy; } @@ -202,7 +222,7 @@ void OnlineOtaNetEsp32::cancel() { _max_bytes = 0; _body_length = 0; _status = 0; - _location[0] = 0; + // _location survives cancel(): a redirect needs it after the socket closes. } #endif // ESP32 && WITH_MQTT_OBSERVER diff --git a/examples/simple_repeater/OnlineOtaNet.h b/examples/simple_repeater/OnlineOtaNet.h index 95e08e91..1e7506bb 100644 --- a/examples/simple_repeater/OnlineOtaNet.h +++ b/examples/simple_repeater/OnlineOtaNet.h @@ -65,8 +65,12 @@ private: uint8_t _redirects = 0; uint16_t _status = 0; char _host[128]; - char _path[256]; - char _location[320]; + // A GitHub release redirect carries a ~950 byte signed URL. These are + // members, not stack frames, and overlong headers fail closed below. + char _path[1024]; + char _location[1024]; + char _line[1024]; + char _request[1200]; // GET path + headers after a GitHub redirect uint8_t _buffer[2048]; }; diff --git a/examples/simple_repeater/OnlineOtaPolicy.h b/examples/simple_repeater/OnlineOtaPolicy.h index 8cb446a2..da7faf50 100644 --- a/examples/simple_repeater/OnlineOtaPolicy.h +++ b/examples/simple_repeater/OnlineOtaPolicy.h @@ -34,8 +34,16 @@ inline bool validVersionChar(char c) { (c >= '0' && c <= '9') || c == '.' || c == '_' || c == '-'; } -// Strip surrounding spaces, one leading v/V and an optional -filter-, -// so a version copied out of `ota status` is accepted. +inline int nibble(char c) { + if (c >= '0' && c <= '9') return c - '0'; + if (c >= 'a' && c <= 'f') return c - 'a' + 10; + if (c >= 'A' && c <= 'F') return c - 'A' + 10; + return -1; +} + +// Strip surrounding spaces, one leading v/V and an optional trailing +// -filter-, so a version copied out of `ota status` is accepted. A +// -filter- in the middle of a legitimate token is left alone. inline bool normalizeVersion(const char* input, char* out, size_t cap) { if (input == nullptr || out == nullptr || cap == 0) return false; while (*input == ' ') input++; @@ -43,7 +51,14 @@ inline bool normalizeVersion(const char* input, char* out, size_t cap) { while (end > 0 && input[end - 1] == ' ') end--; const size_t start = (end > 0 && (*input == 'v' || *input == 'V')) ? 1 : 0; for (size_t i = start; i + 8 <= end; i++) { - if (memcmp(input + i, "-filter-", 8) == 0) { end = i; break; } + if (memcmp(input + i, "-filter-", 8) != 0) continue; + const size_t sha_len = end - (i + 8); + bool is_sha = sha_len >= 7; + for (size_t j = 0; j < sha_len && is_sha; j++) { + is_sha = nibble(input[i + 8 + j]) >= 0; + } + if (is_sha) end = i; // only a trailing -filter- is a build suffix + break; } const size_t len = end - start; if (len == 0 || len > ONLINE_OTA_MAX_VERSION || len + 1 > cap) return false; @@ -56,13 +71,6 @@ inline bool normalizeVersion(const char* input, char* out, size_t cap) { return true; } -inline int nibble(char c) { - if (c >= '0' && c <= '9') return c - '0'; - if (c >= 'a' && c <= 'f') return c - 'a' + 10; - if (c >= 'A' && c <= 'F') return c - 'A' + 10; - return -1; -} - // Accepts an optional "sha256:" prefix followed by exactly 64 hex digits. inline bool parseSha(const char* input, uint8_t out[32]) { if (input == nullptr) return false; diff --git a/examples/simple_repeater/OtaUpdate.cpp b/examples/simple_repeater/OtaUpdate.cpp index 6cd16d12..b931016b 100644 --- a/examples/simple_repeater/OtaUpdate.cpp +++ b/examples/simple_repeater/OtaUpdate.cpp @@ -132,7 +132,8 @@ static void zFree(ZInflater* z) { // All fixed CLI replies go through one snprintf call. static void cliSay(char* reply, const char* text) { - snprintf(reply, CLI_REPLY_MAX, "%s", text); + // The online core passes nullptr: it only cares about success or failure. + if (reply != nullptr) snprintf(reply, CLI_REPLY_MAX, "%s", text); } static uint16_t le16(const uint8_t* p) { return (uint16_t)p[0] | ((uint16_t)p[1] << 8); } @@ -1099,31 +1100,44 @@ void OtaUpdate::formatStatus(char* reply, size_t reply_size) { state_name, (unsigned long)_size, (unsigned long)_written, (unsigned)_err); } -// The contract both staging sources must satisfy, kept in one place. +// The contract both staging sources must satisfy, kept in one place. The +// online caller passes no reply buffer and needs a real error code instead. +static void stageErr(uint8_t* out, uint8_t code) { + if (out != nullptr) *out = code; +} + bool OtaUpdate::checkStageRequest(uint32_t size, const uint8_t sha[32], - const char* ver, char* reply) { + const char* ver, char* reply, uint8_t* err_out) { if (_io == nullptr) { + stageErr(err_out, OTA_ERR_SLOT); cliSay(reply, "Err - OTA unsupported on this platform"); return false; } if (_gate != nullptr && _gate->isSuspended()) { + stageErr(err_out, OTA_ERR_BATTERY); cliSay(reply, "Err - battery gate active; staging refused"); return false; } if (size == 0 || size > 0x7FFFFFFFu) { + stageErr(err_out, OTA_ERR_SLOT); cliSay(reply, "Err - size must be 1..2147483647"); return false; } if (size > _io->slotSize()) { - snprintf(reply, CLI_REPLY_MAX, "Err - size exceeds the %lu-byte slot", - (unsigned long)_io->slotSize()); + stageErr(err_out, OTA_ERR_SLOT); + if (reply != nullptr) { + snprintf(reply, CLI_REPLY_MAX, "Err - size exceeds the %lu-byte slot", + (unsigned long)_io->slotSize()); + } return false; } if (sha == nullptr) { + stageErr(err_out, OTA_ERR_SHA); cliSay(reply, "Err - sha256 must be 64 hex chars"); return false; } if (ver == nullptr || ver[0] == 0 || strlen(ver) > 63) { + stageErr(err_out, OTA_ERR_BOUNDS); cliSay(reply, "Err - ver must be 1..63 bytes"); return false; } @@ -1141,7 +1155,7 @@ bool OtaUpdate::stageCommand(const char* size_tok, const char* sha_tok, const ch cliSay(reply, "Err - sha256 must be 64 hex chars"); return false; } - if (!checkStageRequest((uint32_t)size, sha, ver_tok, reply)) return false; + if (!checkStageRequest((uint32_t)size, sha, ver_tok, reply, nullptr)) return false; if (_rng == nullptr) { cliSay(reply, "Err - rng unavailable"); return false; @@ -1167,15 +1181,20 @@ bool OtaUpdate::stageCommand(const char* size_tok, const char* sha_tok, const ch bool OtaUpdate::beginLocalStage(uint32_t size, const uint8_t sha[32], const char* ver, char* reply) { + // A LoRa arm from an earlier `ota stage` must not survive into this session. + clearPending(); if (_local_source) { + _err = OTA_ERR_BOUNDS; cliSay(reply, "Err - online fetch already active"); return false; } if (_state == State::Staging || _state == State::Ready) { + _err = OTA_ERR_BOUNDS; cliSay(reply, "Err - staging busy; abort first"); return false; } - if (!checkStageRequest(size, sha, ver, reply)) return false; + uint8_t err = OTA_ERR_NONE; + if (!checkStageRequest(size, sha, ver, reply, &err)) { _err = err; return false; } if (_state == State::Error) resetSession(); armSession(size, sha); if (_state != State::Staging) return false; // armSession recorded the reason @@ -1187,7 +1206,10 @@ bool OtaUpdate::beginLocalStage(uint32_t size, const uint8_t sha[32], } bool OtaUpdate::appendLocalStage(const uint8_t* data, size_t len) { - if (!_local_source || _state != State::Staging) return false; + if (!_local_source || _state != State::Staging) { + _err = OTA_ERR_BOUNDS; + return false; + } if (len == 0) return true; if ((uint64_t)_written + len > _size) { abortStaging(OTA_ERR_BOUNDS); return false; } if (!_io->append(data, len)) { abortStaging(OTA_ERR_IO); return false; } @@ -1213,11 +1235,13 @@ bool OtaUpdate::finishLocalStage(char* reply) { } void OtaUpdate::cancelLocalStage() { + clearPending(); if (!_local_source) return; resetSession(); } void OtaUpdate::noteOnlineError(uint8_t err, char* reply) { + clearPending(); resetSession(); _state = State::Error; _err = err; diff --git a/examples/simple_repeater/OtaUpdate.h b/examples/simple_repeater/OtaUpdate.h index e88f2485..0416be5b 100644 --- a/examples/simple_repeater/OtaUpdate.h +++ b/examples/simple_repeater/OtaUpdate.h @@ -228,8 +228,13 @@ #define OTA_HAS_ONLINE_FETCH 1 #endif -// One reply string for the whole CLI, shared by the LoRa and online verbs. +// One reply string for the whole CLI, shared by the verbs that exist in this +// build. Non-observer builds must not advertise the online verbs. +#ifdef OTA_HAS_ONLINE_FETCH #define OTA_USAGE "Usage: ota [status|net|fetch |stage |apply|abort|rollback]" +#else +#define OTA_USAGE "Usage: ota [status|stage |apply|abort|rollback]" +#endif // OP_STATUS_REPORT.state values (same order as OtaUpdate::State). #define OTA_STATE_IDLE 0 @@ -491,7 +496,8 @@ private: void clearPending() { _pending.valid = false; } void abortStaging(uint8_t err); // scrap the staged slot on failure void armSession(uint32_t size, const uint8_t sha[32]); - bool checkStageRequest(uint32_t size, const uint8_t sha[32], const char* ver, char* reply); + bool checkStageRequest(uint32_t size, const uint8_t sha[32], const char* ver, + char* reply, uint8_t* err_out = nullptr); void handleStart(const uint8_t* body, uint16_t body_len); void applyOp(const uint8_t* body, uint16_t body_len, uint8_t op); void applyCopy(uint32_t base_off, uint16_t len); diff --git a/test/test_online_ota/test_online_ota.cpp b/test/test_online_ota/test_online_ota.cpp index afaceae1..931c3e3a 100644 --- a/test/test_online_ota/test_online_ota.cpp +++ b/test/test_online_ota/test_online_ota.cpp @@ -183,6 +183,10 @@ TEST(OnlineOtaPolicyTest, NormalizesVersionTokens) { EXPECT_FALSE(normalizeVersion("", out, sizeof(out))); EXPECT_FALSE(normalizeVersion("1.0/../evil", out, sizeof(out))); EXPECT_FALSE(normalizeVersion(std::string(65, 'a').c_str(), out, sizeof(out))); + // Only a trailing -filter- is a build suffix; a token containing it in + // the middle must be preserved. + ASSERT_TRUE(normalizeVersion("2.0-filter-hotfix", out, sizeof(out))); + EXPECT_STREQ(out, "2.0-filter-hotfix"); } TEST(OnlineOtaPolicyTest, ParsesShaWithOptionalPrefix) { @@ -246,6 +250,33 @@ TEST_F(OnlineTest, FullDownloadReachesReadyAndReleasesTheStation) { EXPECT_STREQ(reply, "OK - applied; rebooting"); } +TEST_F(OnlineTest, SecondStartIsRefusedWhileAJobIsActive) { + auto image = imageBytes(); + ASSERT_TRUE(arm(image)); + char reply[160]; + EXPECT_FALSE(core.start(reply)); + EXPECT_NE(std::string(reply).find("already active"), std::string::npos); + EXPECT_EQ(core.phase(), OnlineOtaCore::Phase::Wifi); + EXPECT_FALSE(core.setVersion("9.9.9", reply)); // inputs are frozen once armed + EXPECT_FALSE(core.setSha(kSha, reply)); + core.abort(); + EXPECT_FALSE(core.start(reply)); // abort cleared ver and sha + EXPECT_NE(std::string(reply).find("set ver and sha first"), std::string::npos); +} + +TEST_F(OnlineTest, ErrorIsTerminalAndDoesNotSleepOrChangeReason) { + net.step_err = ONLINE_ERR_HTTP; + ASSERT_TRUE(arm(imageBytes())); + pump(); + ASSERT_EQ(core.phase(), OnlineOtaCore::Phase::Error); + EXPECT_FALSE(core.needsAwake()); + board.mV = 3000; gate.setThresholds(3400, 3600); + gate.loop(&fs, board); g_mock_millis += 60000; gate.loop(&fs, board); + core.loop(); core.loop(); + EXPECT_EQ(core.error(), ONLINE_ERR_HTTP); // battery did not overwrite 14 + EXPECT_NE(status().find("err=14"), std::string::npos); +} + TEST_F(OnlineTest, AbortClearsInputsAndEveryPhase) { const OnlineOtaCore::Phase phases[] = { OnlineOtaCore::Phase::Wifi, OnlineOtaCore::Phase::Clock, diff --git a/test/test_ota/test_ota.cpp b/test/test_ota/test_ota.cpp index cdc102a2..8fe00ef1 100644 --- a/test/test_ota/test_ota.cpp +++ b/test/test_ota/test_ota.cpp @@ -1724,18 +1724,34 @@ TEST_F(OtaTest, LocalStageAbortCancelsTheFetchAndLoraOpsAreExcluded) { EXPECT_EQ(ota.state(), OtaUpdate::State::Idle); EXPECT_FALSE(ota.localStageActive()); - EXPECT_NE(stage(image).find("token="), std::string::npos); + // Arm a real LoRa transfer first, then start a local one. The valid token + // must still be unable to take over the session. + std::string arm_reply = stage(image); + ASSERT_NE(arm_reply.find("token="), std::string::npos); + auto token = armTokenOf(arm_reply); ASSERT_TRUE(beginLocal(ota, image)); feed(infoFrame()); // read-only handshake stays available uint8_t sha[32]; mockSha256(image, sha); - auto token = armTokenOf(stage(image)); auto body = makeStartBody(image.size(), sha, testTargetId(), token.data()); feed(frame(OTA_OP_START, 0, body)); EXPECT_EQ(ota.state(), OtaUpdate::State::Staging); EXPECT_TRUE(ota.localStageActive()); } +TEST_F(OtaTest, OnlineGuardsTolerateANullReplyAndRecordAnError) { + auto image = testImage(16); + ASSERT_TRUE(beginLocal(ota, image)); + // The online core passes nullptr; guarded refusals must not crash and must + // leave a real error code for ota status. + EXPECT_FALSE(ota.beginLocalStage(image.size(), image.data(), "1.2.3", nullptr)); + EXPECT_NE(statusLine().find("err=6"), std::string::npos); + EXPECT_TRUE(ota.appendLocalStage(image.data(), 0)); // zero-length append is inert + ota.cancelLocalStage(); + EXPECT_FALSE(ota.appendLocalStage(image.data(), image.size())); + EXPECT_NE(statusLine().find("err=6"), std::string::npos); +} + TEST_F(OtaTest, OnlineErrorSetsTheFrozenStatusLineAndIsReArmable) { char reply[160]; ota.noteOnlineError(15, reply);