Merge observer OTA channel switching into keymindCascade

This commit is contained in:
mikecarper committed 2026-10-04 00:26:46 -07:00
commit 63f4642252
32 files changed
+3090 -1708

No files matched your search

+1 -1
View File
@@ -179,7 +179,7 @@ public:
// Pull-based OTA: fetch the firmware build for this variant from a baked-in manifest and flash it.
// current_ver is the running firmware version string (used to skip if already up to date); when
// dry_run is true the build is only reported, not flashed. Observer (ESP32+WiFi) builds only.
virtual bool otaFromManifest(const char* current_ver, bool dry_run, char reply[]) { return false; }
virtual bool otaFromManifest(const char* manifest_base, const char* current_ver, bool dry_run, char reply[]) { return false; }
// LoRa front-end-module LNA (RX gain) control. Only FEM-equipped boards override
// these; others report they can't control it. Driven by NodePrefs.radio_fem_rxgain.
+9
View File
@@ -766,6 +766,7 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
_prefs->usb_logging_enabled = 1;
_prefs->usb_debug_enabled = 0;
_prefs->trace_when_repeat_off = 0;
_prefs->ota_channel = 0;
#ifdef WITH_RS232_BRIDGE
_prefs->bridge_uart = WITH_RS232_BRIDGE_UART;
#else
@@ -943,6 +944,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
_prefs->usb_debug_enabled = 0;
_prefs->trace_when_repeat_off = 0;
_prefs->gps_sync_interval_hours = 0;
_prefs->ota_channel = 0;
#if defined(RP2040_PLATFORM)
File file = fs->open(filename, "r");
#else
@@ -1342,6 +1344,10 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
if (file.available() >= (int)sizeof(_prefs->trace_when_repeat_off)) {
file.read((uint8_t *)&_prefs->trace_when_repeat_off,
sizeof(_prefs->trace_when_repeat_off));
if (file.available() >= (int)sizeof(_prefs->ota_channel)) {
file.read((uint8_t *)&_prefs->ota_channel,
sizeof(_prefs->ota_channel));
}
}
}
}
@@ -1500,6 +1506,7 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
_prefs->direct_retry_recent_enabled = constrain(_prefs->direct_retry_recent_enabled, 0, 1);
_prefs->flood_channel_data_enabled = constrain(_prefs->flood_channel_data_enabled, 0, 1);
_prefs->telemetry_access = constrain(_prefs->telemetry_access, 0, 1);
if (_prefs->ota_channel > 2) _prefs->ota_channel = 0;
if (_prefs->legacy_flood_channel_block_max_hops != FLOOD_CHANNEL_HOPS_ALL
&& (_prefs->legacy_flood_channel_block_max_hops < 1
|| _prefs->legacy_flood_channel_block_max_hops > 7)) {
@@ -1679,6 +1686,7 @@ static bool writeCommonPrefsImage(Writer& writer, NodePrefs* prefs) {
WRITE_COMMON_PREFS(&prefs->gps_sync_interval_hours); // published GPS sync cadence
WRITE_COMMON_PREFS(&prefs->usb_debug_enabled); // appended USB debug intent
WRITE_COMMON_PREFS(&prefs->trace_when_repeat_off); // appended repeater trace exception
WRITE_COMMON_PREFS(&prefs->ota_channel); // appended WiFi OTA channel; never shift older fields
#undef WRITE_COMMON_PREFS_BYTES
#undef WRITE_COMMON_PREFS
@@ -1841,6 +1849,7 @@ void CommonCLI::savePrefs(FILESYSTEM* fs, PrefsSaveRouting::Scope scope) {
file.write((uint8_t *)&_prefs->gps_sync_interval_hours, sizeof(_prefs->gps_sync_interval_hours)); // published GPS sync cadence
file.write((uint8_t *)&_prefs->usb_debug_enabled, sizeof(_prefs->usb_debug_enabled)); // appended
file.write((uint8_t *)&_prefs->trace_when_repeat_off, sizeof(_prefs->trace_when_repeat_off)); // appended
file.write((uint8_t *)&_prefs->ota_channel, sizeof(_prefs->ota_channel)); // appended WiFi OTA channel
_common_save_succeeded = file.commit();
if (!_common_save_succeeded) {
+2
View File
@@ -233,6 +233,7 @@ public:
uint8_t legacy_flood_channel_block_max_hops = 0;
uint8_t flood_channel_data_max_hops = 0;
uint8_t telemetry_access = 0;
uint8_t ota_channel = 0; // WiFi OTA release channel: 0=native, 1=prod, 2=beta
// NOTE: observer settings (MQTT/WiFi/timezone/SNMP/alert) were moved out of
// NodePrefs into MQTTPrefs (persisted to /mqtt_prefs) so this struct stays
@@ -421,6 +422,7 @@ protected:
def("lat", node_lat);
def("lon", node_lon);
def("disc_mod", discovery_mod_timestamp);
def("ota_ch", ota_channel); // WiFi OTA release channel selector
def("radio", radio);
def("bridge", bridge);
def("gps", gps);
+36 -2
View File
@@ -14,6 +14,7 @@
#include <Arduino.h>
#include "CommonCLI.h"
#include "CLICommandUtils.h"
#include "OtaChannel.h"
#include "TxtDataHelpers.h"
#include "AlertReporter.h" // for alertReporterBannedChannelMatch[Hex]()
#include "MQTTObserverValidation.h" // pure input validators (host-testable)
@@ -1215,7 +1216,7 @@ bool CommonCLI::handleObserverCommand(uint32_t sender_timestamp, char* command,
// costs one plain-HTTP request (no cert-bundle allocation or large JSON
// document). The later update path refetches it over verified HTTPS after
// the bridge is down. No bridge bounce is needed for this advisory check.
_board->otaFromManifest(_callbacks->getFirmwareVer(), true, reply);
_board->otaFromManifest(ota_resolve_base(_prefs->ota_channel), _callbacks->getFirmwareVer(), true, reply);
} else {
// `ota update`: cheap pre-check first (plain HTTP, bridge stays up). Only
// schedule the real update - which tears the bridge down, flashes, and
@@ -1223,7 +1224,7 @@ bool CommonCLI::handleObserverCommand(uint32_t sender_timestamp, char* command,
// returns true iff so; otherwise it leaves the explanation (up to date /
// cable flash / error) in reply, which we send without disturbing the
// bridge or misleading the user with a "Beginning update..." that no-ops.
if (_board->otaFromManifest(_callbacks->getFirmwareVer(), true, reply)) {
if (_board->otaFromManifest(ota_resolve_base(_prefs->ota_channel), _callbacks->getFirmwareVer(), true, reply)) {
// reply now holds "update available: <cur> -> <target> (N behind|new base)",
// where <target> is "vX.Y.Z.B (hash)". Pull <target> out for a friendlier
// start message. The "-> " ... trailing " (" framing is produced by
@@ -1256,6 +1257,39 @@ bool CommonCLI::handleObserverCommand(uint32_t sender_timestamp, char* command,
}
#else
strcpy(reply, "ERR: online OTA not supported on this build");
#endif
return true;
} else if (memcmp(command, "ota branch", 10) == 0 && (command[10] == 0 || command[10] == ' ')) {
// Switch (or report) the OTA release channel this device pulls from. The
// selection is persisted (NodePrefs::ota_channel) and resolved to a baked-in
// base URL by ota_resolve_base(); it changes only WHERE updates are fetched,
// never the running image's reported version. Reachable from any admin path,
// same as `ota update`.
#if defined(WITH_MQTT_BRIDGE) && defined(OTA_MANIFEST_BASE)
const char* arg = command + 10;
while (*arg == ' ') arg++;
if (*arg == 0) {
snprintf(reply, 160, "channel: %s (build: %s), base %s",
ota_channel_name(_prefs->ota_channel), ota_native_channel_name(),
ota_resolve_base(_prefs->ota_channel));
} else {
uint8_t ch;
if (!ota_parse_channel(arg, &ch)) {
strcpy(reply, "ERR: usage ota branch [prod|beta|default] (aliases: stable, dev)");
} else {
const uint8_t previous = _prefs->ota_channel;
_prefs->ota_channel = ch;
if (!saveCommonPrefs()) {
_prefs->ota_channel = previous;
strcpy(reply, "ERR: OTA channel save failed; setting unchanged");
} else {
snprintf(reply, 160, "channel set to %s, base %s; run ota update to switch",
ota_channel_name(ch), ota_resolve_base(ch));
}
}
}
#else
strcpy(reply, "ERR: online OTA not supported on this build");
#endif
return true;
} else if (memcmp(command, "start webconfig", 15) == 0 && (command[15] == 0 || command[15] == ' ')) {
+79 -12
View File
@@ -447,6 +447,8 @@ bool ESP32Board::stopOTAUpdate(char reply[]) {
#include <esp_sntp.h>
#include <strings.h>
#include <time.h>
#include "NetworkLink.h"
#include "OtaChannel.h"
// Embedded CA bundle (produced by board_build.embed_files). Weak so non-bundle
// builds still link; we check for presence at runtime.
@@ -737,6 +739,7 @@ static bool ota_streamFirmware(Client& client, size_t content_length, char reply
}
uint8_t buffer[2048];
OtaCompatScanner compat;
size_t received_total = 0;
int progress_decile = -1;
uint32_t deadline = millis() + 20000;
@@ -761,8 +764,22 @@ static bool ota_streamFirmware(Client& client, size_t content_length, char reply
if (wanted > sizeof(buffer)) wanted = sizeof(buffer);
if (wanted > (size_t)available) wanted = (size_t)available;
int received = client.read(buffer, wanted);
if (received <= 0) continue;
if (received <= 0) {
if (!client.connected()) {
strcpy(reply, "ERR: firmware download incomplete");
Update.abort();
return false;
}
if ((int32_t)(millis() - deadline) >= 0) {
strcpy(reply, "ERR: firmware download timeout");
Update.abort();
return false;
}
delay(1);
continue;
}
deadline = millis() + 20000;
compat.consume(buffer, (size_t)received);
if (Update.write(buffer, (size_t)received) != (size_t)received) {
snprintf(reply, 160, "ERR: OTA write: %s", Update.errorString());
Update.abort();
@@ -776,6 +793,25 @@ static bool ota_streamFirmware(Client& client, size_t content_length, char reply
}
}
{
OtaCompat own = {0, 0}, target = {0, 0};
const char* volatile own_tag = ota_compat_tag; // retain the tag in the linked image
const bool own_valid = ota_compat_parse(own_tag + sizeof(OTA_COMPAT_TAG) - 1, &own);
const bool tagged = compat.finish(&target);
if (!own_valid || !tagged || !ota_compat_ok(own, target)) {
// Update.end() validates the image and selects its boot slot. Refuse before
// that commit, so even a reset or power loss cannot boot an unsafe target.
Update.abort();
if (!own_valid || !tagged) {
strcpy(reply, "ERR: OTA refused: invalid or missing compatibility tag; cable flash");
} else {
snprintf(reply, 160, "ERR: OTA refused: target compat %d/%x cannot preserve node %d/%x; cable flash",
target.gen, (unsigned)target.caps, own.gen, (unsigned)own.caps);
}
return false;
}
}
if (!Update.end()) {
snprintf(reply, 160, "ERR: OTA finish: %s", Update.errorString());
return false;
@@ -861,6 +897,7 @@ static void ota_partitionSignature(char* out, size_t out_sz) {
// which stays valid because that function blocks until the worker signals done.
struct OtaTaskArgs {
ESP32Board* self;
const char* manifest_base;
const char* current_ver;
bool dry_run;
char* reply;
@@ -870,18 +907,23 @@ struct OtaTaskArgs {
static void ota_task_entry(void* param) {
OtaTaskArgs* a = static_cast<OtaTaskArgs*>(param);
a->result = a->self->otaFromManifestImpl(a->current_ver, a->dry_run, a->reply);
a->result = a->self->otaFromManifestImpl(a->manifest_base, a->current_ver, a->dry_run, a->reply);
a->done = true; // on a successful `ota update` we reboot before reaching here
vTaskDelete(nullptr);
}
bool ESP32Board::otaFromManifest(const char* current_ver, bool dry_run, char reply[]) {
bool ESP32Board::otaFromManifest(const char* manifest_base, const char* current_ver, bool dry_run, char reply[]) {
// The TLS handshake (cert-bundle verify), JSON parse, and flash stream use far more
// stack than the ~8 KB loop task offers - especially when reached via the deep
// mesh-receive call chain (it overflows the loopTask canary). Run the work in a
// dedicated 24 KB-stack task and block here until it finishes. The big stack is
// freed when the task exits; on a successful update the chip reboots inside it.
OtaTaskArgs args = { this, current_ver, dry_run, reply, false, false };
struct NetworkSwitchGuard {
NetworkLink& link;
NetworkSwitchGuard() : link(activeNetworkLink()) { link.lockSwitching(); }
~NetworkSwitchGuard() { link.unlockSwitching(); }
} network_guard;
OtaTaskArgs args = { this, manifest_base, current_ver, dry_run, reply, false, false };
TaskHandle_t handle = nullptr;
BaseType_t ok = xTaskCreatePinnedToCore(ota_task_entry, "ota", 24576, &args, 5, &handle, 1);
if (ok != pdPASS) {
@@ -894,11 +936,15 @@ bool ESP32Board::otaFromManifest(const char* current_ver, bool dry_run, char rep
return args.result;
}
bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char reply[]) {
bool ESP32Board::otaFromManifestImpl(const char* manifest_base, const char* current_ver, bool dry_run, char reply[]) {
#if !defined(OTA_MANIFEST_BASE) || !defined(OTA_VARIANT)
strcpy(reply, "ERR: OTA not configured (build via build.sh)");
return false;
#else
if (manifest_base == nullptr || *manifest_base == 0) {
strcpy(reply, "ERR: OTA manifest base missing");
return false;
}
if (WiFi.status() != WL_CONNECTED) {
strcpy(reply, "ERR: WiFi not connected");
return false;
@@ -931,10 +977,15 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
// and the handshake + the bridge both fail). This only reads version info; the
// firmware download below (ota update) is always TLS-verified. Requires the
// manifest host to serve /v over HTTP (no forced HTTPS redirect).
if (strncmp(OTA_MANIFEST_BASE, "https://", 8) == 0) {
snprintf(murl, sizeof(murl), "http://%s/%s.json", OTA_MANIFEST_BASE + 8, OTA_VARIANT);
int url_len;
if (strncmp(manifest_base, "https://", 8) == 0) {
url_len = snprintf(murl, sizeof(murl), "http://%s/%s.json", manifest_base + 8, OTA_VARIANT);
} else {
snprintf(murl, sizeof(murl), "%s/%s.json", OTA_MANIFEST_BASE, OTA_VARIANT);
url_len = snprintf(murl, sizeof(murl), "%s/%s.json", manifest_base, OTA_VARIANT);
}
if (url_len < 0 || (size_t)url_len >= sizeof(murl)) {
strcpy(reply, "ERR: manifest URL too long");
return false;
}
WiFiClient mclient;
if (!ota_fetchManifest(mclient, murl, false, doc, reply)) {
@@ -949,7 +1000,11 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
#else
mclient.setCACertBundle(rootca_crt_bundle_start);
#endif
snprintf(murl, sizeof(murl), "%s/%s.json", OTA_MANIFEST_BASE, OTA_VARIANT);
const int url_len = snprintf(murl, sizeof(murl), "%s/%s.json", manifest_base, OTA_VARIANT);
if (url_len < 0 || (size_t)url_len >= sizeof(murl)) {
strcpy(reply, "ERR: manifest URL too long");
return false;
}
mesh::usbLoggingPort().printf("OTA: downloading manifest %s\n", murl);
if (!ota_fetchManifest(mclient, murl, true, doc, reply)) {
return false;
@@ -958,7 +1013,12 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
// Copy fields out before the document is reused/cleared.
char file_url[200] = {0}, avail_version[40] = {0}, avail_base[40] = {0}, avail_hash[24] = {0};
strncpy(file_url, doc["file"] | "", sizeof(file_url) - 1);
const char* manifest_file = doc["file"] | "";
if (strlen(manifest_file) >= sizeof(file_url)) {
strcpy(reply, "ERR: firmware URL too long");
return false;
}
strncpy(file_url, manifest_file, sizeof(file_url) - 1);
strncpy(avail_version, doc["version"] | "", sizeof(avail_version) - 1);
strncpy(avail_base, doc["baseVersion"] | "", sizeof(avail_base) - 1);
strncpy(avail_hash, doc["hash"] | "", sizeof(avail_hash) - 1);
@@ -1009,10 +1069,15 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
bool same_base = (own_base[0] && avail_base[0] && strcmp(own_base, avail_base) == 0);
bool have_builds = (own_build >= 0 && avail_build >= 0);
bool diff_base = (own_base[0] && avail_base[0] && !same_base);
// Another channel's image always differs (its native base does), even from the same
// commit; build counters are per channel, so build numbers only compare natively.
bool cross_channel = (strcmp(manifest_base, OTA_MANIFEST_BASE) != 0);
int behind = 0;
bool up_to_date;
if (same_base && have_builds) {
if (cross_channel) {
up_to_date = false;
} else if (same_base && have_builds) {
behind = avail_build - own_build;
up_to_date = (behind <= 0);
} else if (diff_base) {
@@ -1037,6 +1102,8 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
if (dry_run) {
if (up_to_date) {
snprintf(reply, 160, "up to date: %s", avail_disp);
} else if (cross_channel) {
snprintf(reply, 160, "update available: %s -> %s (channel switch)%s", own_disp, avail_disp, pc_note);
} else if (same_base && have_builds) {
snprintf(reply, 160, "update available: %s -> %s (%d behind)%s", own_disp, avail_disp, behind, pc_note);
} else if (diff_base) {
@@ -1105,7 +1172,7 @@ bool ESP32Board::otaFromManifestImpl(const char* current_ver, bool dry_run, char
#endif // OTA_MANIFEST_BASE && OTA_VARIANT
}
#else
bool ESP32Board::otaFromManifest(const char* current_ver, bool dry_run, char reply[]) {
bool ESP32Board::otaFromManifest(const char* manifest_base, const char* current_ver, bool dry_run, char reply[]) {
strcpy(reply, "ERR: not supported");
return false;
}
+2 -2
View File
@@ -246,11 +246,11 @@ public:
bool startOTAUpdate(const char* id, char reply[], bool force_ap = false) override;
bool stopOTAUpdate(char reply[]) override;
bool isOTAUpdateRunning() const override { return ota_server != nullptr; }
bool otaFromManifest(const char* current_ver, bool dry_run, char reply[]) override;
bool otaFromManifest(const char* manifest_base, const char* current_ver, bool dry_run, char reply[]) override;
// Heavy body (TLS + JSON + flash streaming). Runs in a dedicated large-stack task
// spawned by otaFromManifest() - public only so that task entry point can call
// it; not meant to be invoked directly.
bool otaFromManifestImpl(const char* current_ver, bool dry_run, char reply[]);
bool otaFromManifestImpl(const char* manifest_base, const char* current_ver, bool dry_run, char reply[]);
bool isUsbDataConnected() override {
#if defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT
+217
View File
@@ -0,0 +1,217 @@
#pragma once
#include <stdint.h>
#include <string.h>
#include <limits.h>
// OTA release-channel selector, persisted in NodePrefs::ota_channel.
enum OtaChannel : uint8_t {
OTA_CH_NATIVE = 0, // follow the channel this build was made for
OTA_CH_STABLE = 1, // production
OTA_CH_DEV = 2, // beta
};
// Resolve the effective manifest base URL for a channel selector.
// build.sh injects the three bases as compile-time macros:
// OTA_MANIFEST_BASE = this build's native channel (defined on every OTA build)
// OTA_MANIFEST_BASE_STABLE = stable (production) channel
// OTA_MANIFEST_BASE_DEV = dev (beta) channel
// stable/dev fall back to the native base when their macro is undefined (legacy/local
// builds that only define OTA_MANIFEST_BASE), so this never returns nullptr on an
// OTA-capable build. On a non-OTA build it returns nullptr.
//
// Each base is stored behind an "ota-base-<channel>:" tag so CI can read a binary's
// channels back with scripts/verify_ota_channel.py. Returning a pointer
// into the tagged array keeps the tag referenced, so the linker cannot drop it.
#if defined(OTA_MANIFEST_BASE)
#define OTA_BASE_TAG_NATIVE "ota-base-native:"
#define OTA_BASE_TAG_STABLE "ota-base-stable:"
#define OTA_BASE_TAG_DEV "ota-base-dev:"
#if !defined(OTA_MANIFEST_BASE_STABLE)
#define OTA_MANIFEST_BASE_STABLE OTA_MANIFEST_BASE
#endif
#if !defined(OTA_MANIFEST_BASE_DEV)
#define OTA_MANIFEST_BASE_DEV OTA_MANIFEST_BASE
#endif
static const char ota_tagged_native[] = OTA_BASE_TAG_NATIVE OTA_MANIFEST_BASE;
static const char ota_tagged_stable[] = OTA_BASE_TAG_STABLE OTA_MANIFEST_BASE_STABLE;
static const char ota_tagged_dev[] = OTA_BASE_TAG_DEV OTA_MANIFEST_BASE_DEV;
#endif
static inline const char* ota_resolve_base(uint8_t channel) {
#if defined(OTA_MANIFEST_BASE)
switch (channel) {
case OTA_CH_STABLE: return ota_tagged_stable + sizeof(OTA_BASE_TAG_STABLE) - 1;
case OTA_CH_DEV: return ota_tagged_dev + sizeof(OTA_BASE_TAG_DEV) - 1;
case OTA_CH_NATIVE:
default: return ota_tagged_native + sizeof(OTA_BASE_TAG_NATIVE) - 1;
}
#else
(void)channel;
return nullptr;
#endif
}
// Human label for a selector (for the `ota branch` report).
static inline const char* ota_channel_name(uint8_t channel) {
switch (channel) {
case OTA_CH_STABLE: return "prod";
case OTA_CH_DEV: return "beta";
default: return "default";
}
}
// Label for the channel this build was made for, by matching its native base.
static inline const char* ota_native_channel_name() {
const char* native = ota_resolve_base(OTA_CH_NATIVE);
if (native == nullptr) return "none";
if (strcmp(native, ota_resolve_base(OTA_CH_STABLE)) == 0) return "prod";
if (strcmp(native, ota_resolve_base(OTA_CH_DEV)) == 0) return "beta";
return "custom";
}
// Parse an `ota branch` argument. Returns true and sets *out on a known keyword
// (prod|stable, beta|dev, default); returns false and leaves *out untouched otherwise.
static inline bool ota_parse_channel(const char* arg, uint8_t* out) {
if (strcmp(arg, "prod") == 0 || strcmp(arg, "stable") == 0) { *out = OTA_CH_STABLE; return true; }
if (strcmp(arg, "beta") == 0 || strcmp(arg, "dev") == 0) { *out = OTA_CH_DEV; return true; }
if (strcmp(arg, "default") == 0) { *out = OTA_CH_NATIVE; return true; }
return false;
}
// Compatibility tag, read from the download before committing a channel switch.
// A switch can land on an older build, which would boot without state it cannot read
// or without a transport this node depends on. Bump OTA_STATE_GEN when a build starts
// storing state that older builds cannot read.
// Generation numbers are only comparable within a state format family. This fork
// writes /com_prefs and versioned /mqtt_prefs; upstream's generation 2 means
// /mqtt.json and does not promise it preserves this fork's common preference tail.
// Require the explicit keymind1 capability as well as the generation, so a larger
// upstream generation cannot accidentally authorize a cross-fork state downgrade.
#ifndef OTA_STATE_GEN
#define OTA_STATE_GEN 1
#endif
#define OTA_CAP_ETH 0x01 // carries MQTT over Ethernet
#define OTA_CAP_KEYMIND_PREFS 0x02 // preserves this fork's binary common/MQTT state
#if defined(NETWORK_PREFER_ETHERNET)
#define OTA_CAPS_STR "+keymind1+eth"
#else
#define OTA_CAPS_STR "+keymind1"
#endif
#define OTA_STR_(x) #x
#define OTA_STR(x) OTA_STR_(x)
#define OTA_COMPAT_TAG "ota-compat:"
static const char ota_compat_tag[] = OTA_COMPAT_TAG OTA_STR(OTA_STATE_GEN) OTA_CAPS_STR;
struct OtaCompat {
int gen;
uint8_t caps;
};
// Parse the tag value "<gen>[+cap...]"; unknown caps are ignored.
static inline bool ota_compat_parse(const char* s, OtaCompat* out) {
if (*s < '0' || *s > '9') return false;
OtaCompat parsed = {0, 0};
while (*s >= '0' && *s <= '9') {
const int digit = *s++ - '0';
if (parsed.gen > (INT_MAX - digit) / 10) return false;
parsed.gen = parsed.gen * 10 + digit;
}
while (*s == '+') {
const char* cap = ++s;
while (*s && *s != '+') s++;
if (s == cap) return false;
if ((size_t)(s - cap) == 3 && memcmp(cap, "eth", 3) == 0) parsed.caps |= OTA_CAP_ETH;
if ((size_t)(s - cap) == 8 && memcmp(cap, "keymind1", 8) == 0) parsed.caps |= OTA_CAP_KEYMIND_PREFS;
}
if (*s != 0) return false;
*out = parsed;
return true;
}
// Find the tag in an image chunk; returns the NUL-terminated value text, or nullptr when
// the chunk holds no complete tag. Skips the bare OTA_COMPAT_TAG search literal, which
// every image also contains.
static inline const char* ota_compat_find(const uint8_t* buf, size_t len) {
const size_t tag_len = sizeof(OTA_COMPAT_TAG) - 1;
for (size_t i = 0; i + tag_len < len; i++) {
if (memcmp(buf + i, OTA_COMPAT_TAG, tag_len) != 0) continue;
if (buf[i + tag_len] < '0' || buf[i + tag_len] > '9') continue;
if (memchr(buf + i + tag_len, 0, len - i - tag_len)) return (const char*)buf + i + tag_len;
}
return nullptr;
}
// A target must read this node's state and keep every transport this node has.
static inline bool ota_compat_ok(const OtaCompat& own, const OtaCompat& target) {
return target.gen >= own.gen && (target.caps & own.caps) == own.caps;
}
// Inspect only bytes received for this download, including tags split across
// arbitrary HTTP reads. Oversized or incomplete values fail closed. A bare
// search literal or malformed candidate is not a tag.
// Duplicate tags must match exactly, including capabilities unknown to this
// firmware, matching the publish verifier's unique compatibility-tag contract.
class OtaCompatScanner {
static constexpr size_t kValueSize = 64;
size_t _prefix = 0;
size_t _length = 0;
bool _reading = false;
bool _found = false;
bool _conflicting = false;
OtaCompat _compat = {0, 0};
char _value[kValueSize] = {};
char _candidate[kValueSize] = {};
void complete() {
_candidate[_length] = 0;
OtaCompat parsed;
if (ota_compat_parse(_candidate, &parsed)) {
if (_found && strcmp(_candidate, _value) != 0) {
_conflicting = true;
} else if (!_found) {
_compat = parsed;
strcpy(_value, _candidate);
_found = true;
}
}
}
public:
void consume(const uint8_t* bytes, size_t size) {
for (size_t i = 0; i < size; ++i) {
const uint8_t byte = bytes[i];
if (_reading) {
// The search literal itself ends at the colon. Only a digit starts a
// value; a following 'o' may begin another tag, so reuse that byte below.
if (_length == 0 && (byte < '0' || byte > '9')) {
_reading = false;
} else if (byte == 0) {
complete();
_reading = false;
_length = 0;
continue;
} else {
if (_length + 1 >= sizeof(_candidate)) {
_conflicting = true;
} else {
_candidate[_length++] = (char)byte;
}
continue;
}
}
_prefix = byte == OTA_COMPAT_TAG[_prefix] ? _prefix + 1
: (byte == OTA_COMPAT_TAG[0] ? 1 : 0);
if (_prefix == sizeof(OTA_COMPAT_TAG) - 1) {
_prefix = 0;
_length = 0;
_reading = true;
}
}
}
bool finish(OtaCompat* out) const {
if (!_found || _conflicting || (_reading && _length != 0)) return false;
*out = _compat;
return true;
}
};
File diff suppressed because it is too large. Load diff