/** * ota_update.cpp (Inst. Cluster) - see ota_update.h. * * Flow of an install: * 1. gate: parked (link data), credentials present * 2. join Wi-Fi with the credentials A handed over * 3. GET /api/v1/repos//releases/latest -> tag_name * 4. GET manifest.txt; verify ECDSA P-256 over "target|version|sha256" * 5. GET firmware.bin -> idle OTA slot, hashing as it streams * 6. esp_ota_end(), gate again, switch boot slot, reboot * 7. next boot: PENDING_VERIFY until tick() confirms after OTA_CONFIRM_MS * * Jobs run inside the Arduino loop task, like on A: the gauges freeze (parked * anyway) and STATUS frames to A are pumped from the download loop so A's * Updates screen shows the progress. * * Differences from A's module: no CAN gate (link data instead), no Tunables, * a one-line notice on the 240x240 screen instead of a full-screen panel, * mbedtls 2.28 names (IDF 4.4), and mbedtls may use internal RAM (235 KB free). */ #include "modules/ota_update.h" #include "modules/link_peer.h" #include "modules/uart_receiver.h" #include "modules/gauge_screen.h" #include "modules/gauge_outputs.h" #include "modules/espnow_receiver.h" #include "protocol/automotive_data.h" #include "config/ota_config.h" #include #include #include #include #include #include #include #include #include // Arduino marks a new image valid before setup() runs unless this says no. extern "C" bool verifyRollbackLater() { return true; } #if MBEDTLS_VERSION_MAJOR >= 3 #define SHA256_ONESHOT(in, n, out) mbedtls_sha256((in), (n), (out), 0) #define SHA256_STARTS(c) mbedtls_sha256_starts((c), 0) #define SHA256_UPDATE(c, d, n) mbedtls_sha256_update((c), (d), (n)) #define SHA256_FINISH(c, o) mbedtls_sha256_finish((c), (o)) #else #define SHA256_ONESHOT(in, n, out) mbedtls_sha256_ret((in), (n), (out), 0) #define SHA256_STARTS(c) mbedtls_sha256_starts_ret((c), 0) #define SHA256_UPDATE(c, d, n) mbedtls_sha256_update_ret((c), (d), (n)) #define SHA256_FINISH(c, o) mbedtls_sha256_finish_ret((c), (o)) #endif namespace Ota { static const uint32_t LINK_SILENT_MS = 2000; // no DATA for this long = A off / bench static const uint32_t WIFI_JOIN_MS = 25000; static const uint32_t STALL_TIMEOUT_MS = 15000; static const size_t CHUNK = 4096; typedef struct { char tag[32]; char target[16]; char version[32]; uint32_t size; char sha256[65]; uint8_t sig[80]; size_t sig_len; } manifest_t; enum job_t { JOB_NONE, JOB_CHECK, JOB_INSTALL, JOB_INSTALL_FORCE, JOB_ROLLBACK }; static job_t g_job = JOB_NONE; static bool g_pending_verify = false; static bool g_wifi_joined = false; static uint8_t g_phase = LINK_OTA_IDLE, g_progress = 0; static char g_latest[16] = "", g_message[32] = "", g_last_msg[96] = ""; static uint32_t g_last_pump_ms = 0; // ---- logging / status reported to A ---------------------------------------- static void report() { LinkPeer::setOtaStatus(g_phase, g_progress, g_latest, g_message, g_wifi_joined, g_pending_verify); } static void setPhase(uint8_t p, const char* latest = NULL, const char* msg = NULL) { g_phase = p; if (latest) strlcpy(g_latest, latest, sizeof(g_latest)); strlcpy(g_message, msg ? msg : "", sizeof(g_message)); if (p != LINK_OTA_INSTALLING) g_progress = 0; report(); } static void print(const char* fmt, ...) { char buf[220]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); Serial.println(buf); const char* m = strncmp(buf, "[ota] ", 6) == 0 ? buf + 6 : buf; strlcpy(g_last_msg, m, sizeof(g_last_msg)); } static void failPhase() { setPhase(LINK_OTA_FAILED, NULL, g_last_msg); } /** Keep A informed while the loop is blocked in a job (rate-limited to 1/s). */ static void pump(bool force = false) { if (!force && millis() - g_last_pump_ms < 1000) return; g_last_pump_ms = millis(); report(); LinkPeer::tick(); } static const char* stateName(esp_ota_img_states_t s) { switch (s) { case ESP_OTA_IMG_NEW: return "new"; case ESP_OTA_IMG_PENDING_VERIFY: return "pending-verify"; case ESP_OTA_IMG_VALID: return "valid"; case ESP_OTA_IMG_INVALID: return "invalid"; case ESP_OTA_IMG_ABORTED: return "aborted"; default: return "undefined"; } } // ---- gates ----------------------------------------------------------------- /** Parked according to the link data; a silent link (A off) counts as parked. */ static bool parked(char* why, size_t n) { if (!UARTReceiver::isConnected(LINK_SILENT_MS)) return true; automotive_data_t d = UARTReceiver::getLatestData(); if ((d.valid_flags & VALID_FLAG_RPM) && d.engine_rpm > 0) { snprintf(why, n, "engine running (%u rpm)", d.engine_rpm); return false; } if (d.valid_flags & VALID_FLAG_GEAR_POS) { if (d.gear_lever != LEVER_PARK && d.gear_lever != LEVER_NEUTRAL && d.gear_lever != LEVER_UNKNOWN) { snprintf(why, n, "lever in a drive gear"); return false; } } return true; } static bool gate(bool need_parked, char* why_out = NULL, size_t why_n = 0) { char why[96]; bool ok = true; if (need_parked && !parked(why, sizeof(why))) ok = false; else if (!LinkPeer::hasWifiCredentials()) { snprintf(why, sizeof(why), "no Wi-Fi credentials from A yet"); ok = false; } if (!ok) { print("[ota] refused: %s", why); if (why_out) snprintf(why_out, why_n, "%s", why); } return ok; } // ---- Wi-Fi for the duration of a job --------------------------------------- static bool joinWifi() { char ssid[33], pass[65]; if (!LinkPeer::getWifiCredentials(ssid, sizeof(ssid), pass, sizeof(pass))) { print("[ota] no Wi-Fi credentials"); return false; } print("[ota] joining '%s'...", ssid); WiFi.mode(WIFI_STA); WiFi.setSleep(false); WiFi.begin(ssid, pass); memset(pass, 0, sizeof(pass)); uint32_t t0 = millis(); while (WiFi.status() != WL_CONNECTED && millis() - t0 < WIFI_JOIN_MS) { delay(100); pump(); } if (WiFi.status() != WL_CONNECTED) { print("[ota] could not join '%s' (status %d)", ssid, (int)WiFi.status()); WiFi.disconnect(false); return false; } g_wifi_joined = true; print("[ota] joined, IP %s, channel %d", WiFi.localIP().toString().c_str(), WiFi.channel()); pump(true); return true; } static void leaveWifi() { if (!g_wifi_joined) return; WiFi.disconnect(false); // back to a bare STA; the ESP-NOW receiver re-locks on A's channel g_wifi_joined = false; print("[ota] left Wi-Fi; ESP-NOW receiver hops back to A"); pump(true); } // ---- helpers (as on A) ----------------------------------------------------- static void toHex(const uint8_t* in, size_t n, char* out) { static const char* d = "0123456789abcdef"; for (size_t i = 0; i < n; i++) { out[2 * i] = d[in[i] >> 4]; out[2 * i + 1] = d[in[i] & 0x0F]; } out[2 * n] = 0; } static int hexNibble(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; } static bool fromHex(const char* s, uint8_t* out, size_t cap, size_t* len) { size_t n = strlen(s); if (n == 0 || (n % 2) || n / 2 > cap) return false; for (size_t i = 0; i < n; i += 2) { int hi = hexNibble(s[i]), lo = hexNibble(s[i + 1]); if (hi < 0 || lo < 0) return false; out[i / 2] = (uint8_t)((hi << 4) | lo); } *len = n / 2; return true; } static bool safeToken(const char* s) { if (!*s) return false; for (; *s; s++) if (!isalnum((unsigned char)*s) && *s != '.' && *s != '_' && *s != '-') return false; return true; } static bool httpsGetText(const char* url, String& body, int& code) { WiFiClientSecure client; client.setCACert(OTA_CA_PEM); HTTPClient http; http.setConnectTimeout(10000); http.setTimeout(15000); if (!http.begin(client, url)) { code = -1; return false; } http.setUserAgent("patrol-b-ota/" FW_VERSION); code = http.GET(); bool ok = (code == HTTP_CODE_OK); if (ok) body = http.getString(); http.end(); return ok; } static bool jsonString(const String& s, const char* key, char* out, size_t n) { String k = String("\"") + key + "\""; int i = s.indexOf(k); if (i < 0) return false; i = s.indexOf(':', i + k.length()); if (i < 0) return false; i = s.indexOf('"', i); if (i < 0) return false; int j = s.indexOf('"', i + 1); if (j < 0 || (size_t)(j - i - 1) >= n) return false; s.substring(i + 1, j).toCharArray(out, n); return true; } static bool fetchManifest(manifest_t& m) { memset(&m, 0, sizeof(m)); String body; int code; if (!httpsGetText(OTA_LATEST_API_URL, body, code)) { if (code == 404) print("[ota] no release published yet (push a v* tag)"); else print("[ota] release lookup failed (HTTP %d)", code); return false; } if (!jsonString(body, "tag_name", m.tag, sizeof(m.tag)) || !safeToken(m.tag)) { print("[ota] could not read tag_name from the release reply"); return false; } pump(); String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/manifest.txt"; if (!httpsGetText(url.c_str(), body, code)) { print("[ota] release %s has no manifest.txt (HTTP %d)", m.tag, code); return false; } char sig_hex[2 * sizeof(m.sig) + 1] = {0}; int start = 0; while (start < (int)body.length()) { int nl = body.indexOf('\n', start); if (nl < 0) nl = body.length(); String line = body.substring(start, nl); line.trim(); start = nl + 1; int eq = line.indexOf('='); if (eq <= 0) continue; String k = line.substring(0, eq), v = line.substring(eq + 1); if (k == "target") v.toCharArray(m.target, sizeof(m.target)); else if (k == "version") v.toCharArray(m.version, sizeof(m.version)); else if (k == "size") m.size = (uint32_t)v.toInt(); else if (k == "sha256") v.toCharArray(m.sha256, sizeof(m.sha256)); else if (k == "sig" && v.length() < sizeof(sig_hex)) v.toCharArray(sig_hex, sizeof(sig_hex)); } if (strcmp(m.target, OTA_TARGET) != 0) { print("[ota] manifest is for '%s', not '%s' - refusing", m.target, OTA_TARGET); return false; } if (strcmp(m.version, m.tag) != 0 || m.size == 0 || strlen(m.sha256) != 64 || !fromHex(sig_hex, m.sig, sizeof(m.sig), &m.sig_len)) { print("[ota] manifest for %s is malformed", m.tag); return false; } for (char* c = m.sha256; *c; c++) *c = tolower(*c); return true; } static bool verifySignature(const manifest_t& m) { char stmt[160]; int n = snprintf(stmt, sizeof(stmt), "%s|%s|%s", m.target, m.version, m.sha256); uint8_t h[32]; SHA256_ONESHOT((const unsigned char*)stmt, n, h); mbedtls_pk_context pk; mbedtls_pk_init(&pk); int rc = mbedtls_pk_parse_public_key(&pk, (const unsigned char*)OTA_SIGNING_PUBKEY_PEM, sizeof(OTA_SIGNING_PUBKEY_PEM)); if (rc == 0) rc = mbedtls_pk_verify(&pk, MBEDTLS_MD_SHA256, h, sizeof(h), m.sig, m.sig_len); mbedtls_pk_free(&pk); if (rc != 0) print("[ota] SIGNATURE INVALID for %s (mbedtls -0x%04X) - refusing", m.tag, -rc); return rc == 0; } // ---- install --------------------------------------------------------------- static void notice(const char* fmt, ...) { char buf[64]; va_list ap; va_start(ap, fmt); vsnprintf(buf, sizeof(buf), fmt, ap); va_end(ap); GaugeScreen::setNotice(buf); } static bool writeImage(const manifest_t& m, const esp_partition_t* part) { String url = String(OTA_DOWNLOAD_BASE) + m.tag + "/firmware.bin"; WiFiClientSecure client; client.setCACert(OTA_CA_PEM); HTTPClient http; http.setConnectTimeout(10000); http.setTimeout(15000); if (!http.begin(client, url)) { print("[ota] bad download URL"); return false; } http.setUserAgent("patrol-b-ota/" FW_VERSION); int code = http.GET(); if (code != HTTP_CODE_OK) { print("[ota] download failed (HTTP %d)", code); http.end(); return false; } if (http.getSize() != (int)m.size) { print("[ota] server size %d != manifest size %lu", http.getSize(), (unsigned long)m.size); http.end(); return false; } esp_ota_handle_t h = 0; esp_err_t err = esp_ota_begin(part, OTA_WITH_SEQUENTIAL_WRITES, &h); if (err != ESP_OK) { print("[ota] esp_ota_begin: %s", esp_err_to_name(err)); http.end(); return false; } uint8_t* buf = (uint8_t*)malloc(CHUNK); mbedtls_sha256_context sc; mbedtls_sha256_init(&sc); SHA256_STARTS(&sc); WiFiClient* stream = http.getStreamPtr(); uint32_t got = 0, last_rx = millis(); int last_decile = -1, last_pct = -1; bool ok = (buf != NULL); while (ok && got < m.size) { size_t avail = stream->available(); if (avail == 0) { uint32_t idle = millis() - last_rx; if ((!http.connected() && idle > 2000) || idle > STALL_TIMEOUT_MS) { print("[ota] download stalled at %lu/%lu bytes", (unsigned long)got, (unsigned long)m.size); ok = false; break; } vTaskDelay(pdMS_TO_TICKS(5)); pump(); continue; } size_t want = min(min(avail, CHUNK), (size_t)(m.size - got)); int r = stream->read(buf, want); if (r <= 0) continue; last_rx = millis(); SHA256_UPDATE(&sc, buf, r); err = esp_ota_write(h, buf, r); if (err != ESP_OK) { print("[ota] flash write: %s", esp_err_to_name(err)); ok = false; break; } got += r; int pct = (int)((uint64_t)got * 100 / m.size); if (pct != last_pct) { last_pct = pct; g_progress = (uint8_t)pct; notice("Updating %s %d%%", m.version, pct); pump(); } int decile = pct / 10; if (decile != last_decile) { print("[ota] %d%%", decile * 10); last_decile = decile; } } http.end(); free(buf); uint8_t digest[32]; char digest_hex[65]; SHA256_FINISH(&sc, digest); mbedtls_sha256_free(&sc); toHex(digest, sizeof(digest), digest_hex); if (ok && strcmp(digest_hex, m.sha256) != 0) { print("[ota] SHA-256 MISMATCH - image does not match the signed manifest"); ok = false; } if (!ok) { esp_ota_abort(h); print("[ota] aborted; still running %s", FW_VERSION); return false; } err = esp_ota_end(h); if (err != ESP_OK) { print("[ota] image check failed: %s", esp_err_to_name(err)); return false; } return true; } static void install(bool force) { manifest_t m; if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; } if (!force && strcmp(m.version, FW_VERSION) == 0) { print("[ota] already running %s - nothing to do (`ota install force` to reinstall)", FW_VERSION); setPhase(LINK_OTA_UP_TO_DATE, m.version); return; } const esp_partition_t* part = esp_ota_get_next_update_partition(NULL); if (!part) { print("[ota] no idle OTA slot (partition table?)"); failPhase(); return; } if (m.size > part->size) { print("[ota] image %lu B does not fit slot %s (%lu B)", (unsigned long)m.size, part->label, (unsigned long)part->size); failPhase(); return; } print("[ota] installing %s -> %s (%lu bytes)", m.version, part->label, (unsigned long)m.size); setPhase(LINK_OTA_INSTALLING, m.version); notice("Updating %s 0%%", m.version); bool ok = writeImage(m, part); char why[64]; if (ok && !parked(why, sizeof(why))) { print("[ota] new image left inactive in %s: %s", part->label, why); ok = false; } if (ok) { esp_err_t err = esp_ota_set_boot_partition(part); if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); ok = false; } } if (!ok) { failPhase(); notice("Update failed"); pump(true); delay(3000); GaugeScreen::setNotice(NULL); return; } print("[ota] verified and installed %s. Rebooting in 3 s; it confirms itself after %lu s of uptime.", m.version, (unsigned long)(OTA_CONFIRM_MS / 1000)); notice("Installed %s - restarting", m.version); g_progress = 100; pump(true); delay(3000); esp_restart(); } static void check() { manifest_t m; if (!fetchManifest(m) || !verifySignature(m)) { failPhase(); return; } bool same = strcmp(m.version, FW_VERSION) == 0; print("[ota] running %s | latest release %s (%lu bytes, signature OK)%s", FW_VERSION, m.version, (unsigned long)m.size, same ? " - up to date" : " - install to update"); setPhase(same ? LINK_OTA_UP_TO_DATE : LINK_OTA_AVAILABLE, m.version); } static void rollback() { char why[64]; if (!parked(why, sizeof(why))) { print("[ota] refused: %s", why); return; } if (g_pending_verify) { print("[ota] rejecting this unconfirmed image; rebooting into the previous one"); delay(500); esp_ota_mark_app_invalid_rollback_and_reboot(); return; } const esp_partition_t* other = esp_ota_get_next_update_partition(NULL); esp_app_desc_t d; esp_ota_img_states_t ost = ESP_OTA_IMG_UNDEFINED; if (!other || esp_ota_get_partition_description(other, &d) != ESP_OK) { print("[ota] no previous image to roll back to"); return; } esp_ota_get_state_partition(other, &ost); if (ost == ESP_OTA_IMG_INVALID || ost == ESP_OTA_IMG_ABORTED) { print("[ota] previous image in %s is marked %s - refusing", other->label, stateName(ost)); return; } esp_err_t err = esp_ota_set_boot_partition(other); if (err != ESP_OK) { print("[ota] set boot slot: %s", esp_err_to_name(err)); return; } print("[ota] booting %s in 2 s", other->label); delay(2000); esp_restart(); } static void runJob(job_t job) { if (job == JOB_ROLLBACK) { rollback(); return; } Serial.printf("[ota] heap before job: %u free (largest block %u)\n", (unsigned)ESP.getFreeHeap(), (unsigned)ESP.getMaxAllocHeap()); // Gauges: the loop is about to block, so drive the outputs to their "no // link" state (tach off) rather than leaving them frozen mid-value. automotive_data_t none = {}; GaugeOutputs::update(none, false); if (!joinWifi()) { failPhase(); return; } if (job == JOB_CHECK) check(); else install(job == JOB_INSTALL_FORCE); leaveWifi(); GaugeScreen::setNotice(NULL); Serial.printf("[ota] heap after job: %u free | loop stack headroom %u B\n", (unsigned)ESP.getFreeHeap(), (unsigned)uxTaskGetStackHighWaterMark(NULL)); } static bool startJob(job_t job, char* why = NULL, size_t why_n = 0) { if (g_job != JOB_NONE) { if (why) snprintf(why, why_n, "busy"); return false; } if (job != JOB_ROLLBACK && !gate(job != JOB_CHECK, why, why_n)) return false; if (job == JOB_ROLLBACK) { g_job = job; return true; } setPhase(job == JOB_CHECK ? LINK_OTA_CHECKING : LINK_OTA_INSTALLING); g_job = job; print("[ota] working - the gauges pause until done"); return true; } static void status() { const esp_partition_t* run = esp_ota_get_running_partition(); const esp_partition_t* other = esp_ota_get_next_update_partition(NULL); esp_ota_img_states_t st = ESP_OTA_IMG_UNDEFINED; esp_ota_get_state_partition(run, &st); print("[ota] version %s (built %s %s), slot %s, state %s%s", FW_VERSION, __DATE__, __TIME__, run ? run->label : "?", stateName(st), g_pending_verify ? " - confirms after healthy uptime" : ""); if (other) { esp_app_desc_t d; esp_ota_img_states_t ost = ESP_OTA_IMG_UNDEFINED; esp_ota_get_state_partition(other, &ost); if (esp_ota_get_partition_description(other, &d) == ESP_OK) print("[ota] other slot %s: image built %s %s, state %s", other->label, d.date, d.time, stateName(ost)); else print("[ota] other slot %s: empty", other->label); } print("[ota] updates from %s/%s/releases (%s) | credentials %s | paired %s", OTA_SERVER, OTA_REPO, OTA_TARGET, LinkPeer::hasWifiCredentials() ? "yes" : "no", LinkPeer::isPaired() ? "yes" : "no"); } static void help() { Serial.println("ota status running version, slot, rollback state"); Serial.println("ota check join Wi-Fi, ask Gitea for the latest release"); Serial.println("ota install [force] download + verify + flash idle slot + reboot (parked only)"); Serial.println("ota rollback boot the previous slot (parked only)"); } // ---- public ---------------------------------------------------------------- const char* version() { return FW_VERSION; } bool isBusy() { return g_job != JOB_NONE || g_phase == LINK_OTA_CHECKING || g_phase == LINK_OTA_INSTALLING; } void onLinkCommand(uint8_t cmd, uint8_t flags) { char why[96]; bool ok = false; switch (cmd) { case LINK_OTA_CMD_CHECK: ok = startJob(JOB_CHECK, why, sizeof(why)); break; case LINK_OTA_CMD_INSTALL: ok = startJob((flags & LINK_OTA_FORCE) ? JOB_INSTALL_FORCE : JOB_INSTALL, why, sizeof(why)); break; case LINK_OTA_CMD_ROLLBACK: ok = startJob(JOB_ROLLBACK, why, sizeof(why)); break; default: snprintf(why, sizeof(why), "unknown command %u", cmd); break; } if (!ok) { // Tell A on the next STATUS why nothing happened setPhase(LINK_OTA_FAILED, NULL, why); } } void init() { const esp_partition_t* run = esp_ota_get_running_partition(); esp_ota_img_states_t st = ESP_OTA_IMG_UNDEFINED; if (run && esp_ota_get_state_partition(run, &st) == ESP_OK && st == ESP_OTA_IMG_PENDING_VERIFY) { g_pending_verify = true; } LinkPeer::setOtaCommandHandler(onLinkCommand); report(); print("[ota] firmware %s, slot %s%s", FW_VERSION, run ? run->label : "?", g_pending_verify ? " - NEW IMAGE, unconfirmed (a reset before healthy uptime rolls back)" : ""); } void tick() { if (g_job != JOB_NONE) { job_t j = g_job; runJob(j); g_job = JOB_NONE; } if (g_pending_verify && millis() > OTA_CONFIRM_MS) { esp_ota_mark_app_valid_cancel_rollback(); g_pending_verify = false; report(); print("[ota] firmware %s confirmed - rollback cancelled", FW_VERSION); } } bool handleCommand(const char* line) { if (strcmp(line, "help") == 0) { help(); return false; } char buf[48]; strlcpy(buf, line, sizeof(buf)); char* argv[4] = {0}; int argc = 0; for (char* t = strtok(buf, " \t"); t && argc < 4; t = strtok(NULL, " \t")) argv[argc++] = t; if (argc == 0 || strcmp(argv[0], "ota") != 0) return false; if (argc == 1 || !strcmp(argv[1], "help")) help(); else if (!strcmp(argv[1], "status")) status(); else if (!strcmp(argv[1], "check")) startJob(JOB_CHECK); else if (!strcmp(argv[1], "install")) startJob(argc > 2 && !strcmp(argv[2], "force") ? JOB_INSTALL_FORCE : JOB_INSTALL); else if (!strcmp(argv[1], "rollback")) startJob(JOB_ROLLBACK); else help(); return true; } } // namespace Ota