/** * ota_update.cpp - see ota_update.h for the command set and safety rules. * * Flow of `ota install`: * 1. gate: Wi-Fi joined, vehicle parked * 2. GET /api/v1/repos//releases/latest -> tag_name * 3. GET //releases/download//manifest.txt * 4. verify ECDSA P-256 signature over "target|version|sha256" (before download) * 5. GET //releases/download//firmware.bin -> idle OTA slot, * hashing as it streams; sha256 must equal the signed one * 6. esp_ota_end() (image self-check), gate again, switch boot slot, reboot * 7. next boot: the image is PENDING_VERIFY until tick() confirms it */ #include "modules/ota_update.h" #include "modules/serial_lock.h" #include "drivers/can_driver.h" #include "protocol/automotive_data.h" #include "config/ota_config.h" #include "modules/display_init.h" #include "modules/tunables.h" #include "display/lvgl_v8_port.h" #include #include #include #include #include #include #include #include #include #include #include // Take over Arduino's rollback hook: by default initArduino() marks a new image // valid before setup() even runs, so a crash in setup would never roll back. // Returning true leaves the image PENDING_VERIFY until Ota::tick() confirms it. extern "C" bool verifyRollbackLater() { return true; } namespace Ota { #define OTA_CONFIRM_S 30 // healthy uptime before a new image is kept #define TOSTR_(x) #x #define TOSTR(x) TOSTR_(x) static const uint32_t OTA_CONFIRM_MS = OTA_CONFIRM_S * 1000; static const uint32_t BUS_SILENT_MS = 2000; // no frames for this long = ignition off / bench static const uint32_t STALL_TIMEOUT_MS = 15000; // download aborts if no bytes arrive this long static const size_t CHUNK = 4096; // Jobs run inside the Arduino loop task (8 KB internal stack), not a task of // their own: with the display + Wi-Fi up, internal RAM has no block big enough // for another TLS-capable stack (measured 2026-09-26: 15.9 KB free, largest // block 7.6 KB), and the stack can't go to PSRAM because esp_ota_write() // disables the flash cache. The loop (screen value ticks, console) pauses // while a job runs - acceptable: parked, and an install ends in a reboot. typedef struct { char tag[32]; char target[16]; char version[32]; uint32_t size; char sha256[65]; // lowercase hex uint8_t sig[80]; // DER ECDSA signature size_t sig_len; } manifest_t; enum job_t { JOB_CHECK, JOB_INSTALL, JOB_INSTALL_FORCE }; static bool g_job_pending = false; static job_t g_job = JOB_CHECK; static bool g_pending_verify = false; // ============================================================================ // Helpers // ============================================================================ 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); SerialLock::lock(); Serial.println(buf); SerialLock::unlock(); } 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"; } } /** * The vehicle must be parked to update: installing ends in a reboot that blanks * Controller B's gauges. A silent bus (ignition off, or the bench) counts as * parked. Lever UNKNOWN is allowed so a missing gear frame can't block a bench * update; engine and output shaft are the checks that matter. */ static bool parked(char* why, size_t n) { if (!CANDriver::isActive()) return true; can_stats_t s = CANDriver::getStats(); if (millis() - s.last_receive_time > BUS_SILENT_MS) return true; driveline_t d = CANDriver::getDriveline(); if (d.engine_rpm > 0 || d.engine_run_state == ENGINE_RUN_RUNNING || d.engine_run_state == ENGINE_RUN_STARTING) { snprintf(why, n, "engine running (%u rpm) - switch the engine off", d.engine_rpm); return false; } if (d.output_shaft_raw != 0) { snprintf(why, n, "vehicle moving (output shaft turning)"); return false; } if (d.lever != GEAR_PARK && d.lever != GEAR_NEUTRAL && d.lever != GEAR_UNKNOWN) { snprintf(why, n, "lever in a drive gear - select P"); return false; } return true; } static bool gate(bool need_wifi, bool need_parked = true) { char why[96]; if (need_parked && !parked(why, sizeof(why))) { print("[ota] refused: %s", why); return false; } if (need_wifi && WiFi.status() != WL_CONNECTED) { print("[ota] refused: Wi-Fi not connected - join a network on the Settings screen first"); return false; } return true; } 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; } /** Tags end up in URLs; accept only [A-Za-z0-9._-]. */ 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; } /** HTTPS GET of a small text body (API reply, manifest). */ 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-a-ota/" FW_VERSION); code = http.GET(); bool ok = (code == HTTP_CODE_OK); if (ok) body = http.getString(); http.end(); return ok; } /** Pull "key":"value" out of a flat JSON reply without a JSON library. */ 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; } 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; } /** ECDSA P-256 over SHA-256("target|version|sha256hex"), checked before downloading. */ 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]; mbedtls_sha256((const unsigned char*)stmt, n, h, 0); 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 // ============================================================================ /** Download firmware.bin into the idle slot, hashing as it streams; true if it matches the signed manifest. */ 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-a-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); mbedtls_sha256_starts(&sc, 0); NetworkClient* stream = http.getStreamPtr(); uint32_t got = 0, last_rx = millis(); int last_decile = -1; bool ok = (buf != NULL); while (ok && got < m.size) { size_t avail = stream->available(); if (avail == 0) { // connected() can read false for a moment between TLS records, so a // drop only counts after 2 s of silence (it aborted a download at // 570 B once, 2026-09-26; the retry went through). 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)); 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(); mbedtls_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 decile = (int)((uint64_t)got * 10 / m.size); if (decile != last_decile) { print("[ota] %d%%", decile * 10); last_decile = decile; } } http.end(); free(buf); uint8_t digest[32]; char digest_hex[65]; mbedtls_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); // validates the image structure + its embedded hash if (err != ESP_OK) { print("[ota] image check failed: %s", esp_err_to_name(err)); return false; } return true; } // ---- Full-screen notice on lv_layer_top() (above every screen) ---------------- static lv_obj_t* g_notice = NULL; static lv_obj_t* g_notice_lbl = NULL; static void showNotice(const char* text) { lvgl_port_lock(-1); if (g_notice == NULL) { g_notice = lv_obj_create(lv_layer_top()); lv_obj_remove_style_all(g_notice); lv_obj_set_size(g_notice, LV_PCT(100), LV_PCT(100)); lv_obj_set_style_bg_color(g_notice, lv_color_black(), 0); lv_obj_set_style_bg_opa(g_notice, LV_OPA_COVER, 0); lv_obj_add_flag(g_notice, LV_OBJ_FLAG_CLICKABLE); // swallow touches while shown g_notice_lbl = lv_label_create(g_notice); lv_obj_set_style_text_font(g_notice_lbl, &lv_font_montserrat_30, 0); lv_obj_set_style_text_color(g_notice_lbl, lv_color_white(), 0); lv_obj_set_style_text_align(g_notice_lbl, LV_TEXT_ALIGN_CENTER, 0); lv_obj_center(g_notice_lbl); } lv_label_set_text(g_notice_lbl, text); lv_obj_clear_flag(g_notice, LV_OBJ_FLAG_HIDDEN); lvgl_port_unlock(); } static void hideNotice() { lvgl_port_lock(-1); if (g_notice) lv_obj_add_flag(g_notice, LV_OBJ_FLAG_HIDDEN); lvgl_port_unlock(); } static void install(bool force) { manifest_t m; if (!fetchManifest(m) || !verifySignature(m)) return; if (!force && strcmp(m.version, FW_VERSION) == 0) { print("[ota] already running %s - nothing to do (`ota install force` to reinstall)", FW_VERSION); return; } const esp_partition_t* part = esp_ota_get_next_update_partition(NULL); if (!part) { print("[ota] no idle OTA slot (partition table?)"); 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); return; } print("[ota] installing %s -> %s (%lu bytes)", m.version, part->label, (unsigned long)m.size); // Flash writes stall the PSRAM-fed RGB panel (flicker), so the screen is // dark while the image is written, with a notice before and after. char msg[160]; snprintf(msg, sizeof(msg), "Updating to %s\n\nThe screen goes dark for about a minute.\nDo not switch off.", m.version); showNotice(msg); delay(3000); // time to read it; LVGL renders on its own task DisplayInit::setBacklight(false); bool ok = writeImage(m, part); DisplayInit::setBacklight(true); // The download took a while - the driver may have started the engine since. if (ok && !gate(false)) { print("[ota] new image left inactive in %s; retry when parked", part->label); 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) { snprintf(msg, sizeof(msg), "Update failed\n\nStill running %s", FW_VERSION); showNotice(msg); delay(5000); hideNotice(); 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)); snprintf(msg, sizeof(msg), "Installed %s\n\nRestarting...", m.version); showNotice(msg); Tunables::flush(); delay(3000); esp_restart(); } static void check() { manifest_t m; if (!fetchManifest(m) || !verifySignature(m)) 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" : " - `ota install` to update"); } // This core's mbedtls is built with CONFIG_MBEDTLS_INTERNAL_MEM_ALLOC: every TLS // session wants ~40 KB of *internal* RAM, which the display + Wi-Fi leave no // room for. Route mbedtls to PSRAM (internal as fallback) while a job runs. // Both allocators free with heap_caps_free(), so swapping them is always safe. static void* tlsCallocPsram(size_t n, size_t size) { return heap_caps_calloc_prefer(n, size, 2, MALLOC_CAP_SPIRAM | MALLOC_CAP_8BIT, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); } static void* tlsCallocInternal(size_t n, size_t size) { return heap_caps_calloc(n, size, MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT); } static void printHeap(const char* when) { print("[ota] heap %s: internal free %u (largest block %u), PSRAM free %u", when, (unsigned)heap_caps_get_free_size(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT), (unsigned)heap_caps_get_largest_free_block(MALLOC_CAP_INTERNAL | MALLOC_CAP_8BIT), (unsigned)heap_caps_get_free_size(MALLOC_CAP_SPIRAM)); } static void runJob(job_t job) { mbedtls_platform_set_calloc_free(tlsCallocPsram, heap_caps_free); if (job == JOB_CHECK) check(); else install(job == JOB_INSTALL_FORCE); mbedtls_platform_set_calloc_free(tlsCallocInternal, heap_caps_free); print("[ota] loop stack headroom after job: %u B", (unsigned)uxTaskGetStackHighWaterMark(NULL)); } static void startJob(job_t job) { if (!gate(true, job != JOB_CHECK)) return; // checking is harmless; installing needs parked g_job = job; g_job_pending = true; // runs on the next tick(), in the loop task print("[ota] working - console and screen values pause until done"); } // ============================================================================ // Status / rollback // ============================================================================ 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 " TOSTR(OTA_CONFIRM_S) " s 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)", OTA_SERVER, OTA_REPO, OTA_TARGET); printHeap("now"); } static void rollback() { if (!gate(false)) return; if (g_pending_verify) { print("[ota] rejecting this unconfirmed image; rebooting into the previous one"); Tunables::flush(); 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); Tunables::flush(); delay(2000); esp_restart(); } static void help() { print("ota status running version, slot, rollback state"); print("ota check ask Gitea for the latest release (needs Wi-Fi)"); print("ota install [force] download + verify + flash idle slot + reboot (parked only)"); print("ota rollback boot the previous slot (parked only)"); print("Tip: `diag raw off` first so CANRAW lines don't bury the progress output."); } // ============================================================================ // Public API // ============================================================================ const char* version() { return FW_VERSION; } 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; } print("[ota] firmware %s, slot %s%s", FW_VERSION, run ? run->label : "?", g_pending_verify ? " - NEW IMAGE, unconfirmed (a reset in the next " TOSTR(OTA_CONFIRM_S) " s rolls back)" : ""); } void tick() { if (g_job_pending) { g_job_pending = false; runJob(g_job); } if (g_pending_verify && millis() > OTA_CONFIRM_MS) { esp_ota_mark_app_valid_cancel_rollback(); g_pending_verify = false; print("[ota] firmware %s confirmed - rollback cancelled", FW_VERSION); } } bool handleCommand(const char* line) { char buf[48]; strncpy(buf, line, sizeof(buf) - 1); buf[sizeof(buf) - 1] = 0; 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")) rollback(); else help(); return true; } } // namespace Ota