Merge PR 2864 LoRa OTA into Keymind
This commit is contained in:
commit
4c0dbe707d
94 files changed
+12959
-123
No files matched your search
+180
@@ -1,5 +1,26 @@
|
||||
#include "Mesh.h"
|
||||
//#include <Arduino.h>
|
||||
#if defined(ENABLE_OTA)
|
||||
#include "helpers/ota/OtaContext.h" // OTA mesh-integration is centralized here so every role gets it
|
||||
#include "helpers/ota/OtaProtocol.h" // decode_adv -> the `ota neighbors` discovery table
|
||||
#include "helpers/ota/OtaSelf.h" // ota_self_firmware -> auto-advertise our own image
|
||||
#ifndef OTA_ANNOUNCE_BOOT_MS
|
||||
#define OTA_ANNOUNCE_BOOT_MS 8000UL // first self-advert ~8 s after boot (settled, but quick to discover)
|
||||
#endif
|
||||
#ifndef OTA_ANNOUNCE_BURST
|
||||
#define OTA_ANNOUNCE_BURST 4 // a few closely-spaced boot adverts so co-booting peers catch one
|
||||
#endif
|
||||
#ifndef OTA_ANNOUNCE_BURST_MS
|
||||
#define OTA_ANNOUNCE_BURST_MS 20000UL // spacing during the boot burst (~1 min total), then ...
|
||||
#endif
|
||||
// ... then re-announce at a FIXED cadence so a long-running node stays discoverable (a fresh `ota ls`
|
||||
// neighbour eventually sees it, not at boot only). The cadence is OtaManager::advert_mins() minutes (default
|
||||
// 24h, runtime-tunable via `ota config advert` + persisted; 0 = disabled = boot burst only). The beacon is
|
||||
// tiny + lowest-priority + duty-gated, so even a frequent cadence is cheap.
|
||||
#ifndef OTA_ANNOUNCE_DISABLED_POLL_MS
|
||||
#define OTA_ANNOUNCE_DISABLED_POLL_MS 600000UL // when periodic advert is off, re-check config every 10 min
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
|
||||
@@ -104,6 +125,19 @@ void Mesh::configureDirectRetryPacket(Packet* retry, const Packet* original, uin
|
||||
|
||||
retry->tx_cr = getDirectRetryCodingRateForAttempt(default_cr, retry_attempt);
|
||||
}
|
||||
#if defined(ENABLE_OTA)
|
||||
// Adapter so the portable OtaManager can emit packets through the mesh (lowest priority, hop-capped).
|
||||
void Mesh::otaSendAdapter(void* ctx, const uint8_t* msg, uint16_t len, bool /*flood*/) {
|
||||
Mesh* m = (Mesh*)ctx;
|
||||
if (!m->isTempRadioActive()) return;
|
||||
Packet* p = m->createOtaPacket(msg, len);
|
||||
if (p) m->sendOtaFlood(p);
|
||||
}
|
||||
|
||||
// Runtime OTA flood reach (`ota config hops`, persisted in NodePrefs): accept packets up to N hops away and
|
||||
// relay those still under N hops. 0 = direct only. Overridable per-role by subclassing.
|
||||
uint8_t Mesh::getOtaHopLimit() const { return ota::ota_ctx().manager.max_hops(); }
|
||||
#endif
|
||||
|
||||
void Mesh::begin() {
|
||||
for (int i = 0; i < MAX_DIRECT_RETRY_SLOTS; i++) {
|
||||
@@ -138,6 +172,18 @@ void Mesh::begin() {
|
||||
_flood_retries[i].active = false;
|
||||
}
|
||||
Dispatcher::begin();
|
||||
#if defined(ENABLE_OTA)
|
||||
uint32_t my_tid = 0;
|
||||
#ifdef MOTA_TARGET_ID
|
||||
my_tid = (uint32_t)(MOTA_TARGET_ID); // sha2-256:4(env name), injected by build.sh
|
||||
#endif
|
||||
const char* my_hw = "";
|
||||
#ifdef MOTA_HW_ID
|
||||
my_hw = MOTA_HW_ID; // human-readable hardware tag (per-variant), for the apply hw gate
|
||||
#endif
|
||||
ota::ota_ctx().begin(my_tid, Mesh::otaSendAdapter, this, my_hw); // also sets the platform apply codec
|
||||
ota::ota_ctx().manager.set_seeder_id(self_id.pub_key); // node id (pubkey[0:4]) for advert seeder count
|
||||
#endif
|
||||
}
|
||||
|
||||
void Mesh::loop() {
|
||||
@@ -209,6 +255,82 @@ void Mesh::loop() {
|
||||
clearFloodRetrySlot(i);
|
||||
}
|
||||
}
|
||||
#if defined(ENABLE_OTA)
|
||||
// Deferred apply-reboot: a verified `ota applydelta` approves the update but does NOT reboot inline,
|
||||
// so its "verified; applying" reply can be delivered first (over LoRa that reply is the operator's
|
||||
// only confirmation the apply started). Reboot once that reply has actually been transmitted (the
|
||||
// outbound queue drains) after a short grace to let it be queued, with a hard cap for a busy node
|
||||
// whose queue never idles.
|
||||
{
|
||||
ota::OtaContext& oc = ota::ota_ctx();
|
||||
if (oc.apply_pending) {
|
||||
if (oc.apply_at == 0) {
|
||||
oc.apply_at = futureMillis(1500);
|
||||
oc.apply_hard = futureMillis(15000);
|
||||
} else if (millisHasNowPassed(oc.apply_at) &&
|
||||
(_mgr->getOutboundTotal() == 0 || millisHasNowPassed(oc.apply_hard))) {
|
||||
ota::ota_reboot_to_apply(); // does not return
|
||||
}
|
||||
}
|
||||
}
|
||||
const bool ota_active = isTempRadioActive();
|
||||
if (!ota_active) {
|
||||
_ota_temp_was_active = false;
|
||||
return;
|
||||
}
|
||||
if (!_ota_temp_was_active) {
|
||||
_ota_temp_was_active = true;
|
||||
_next_ota_tick = 0;
|
||||
_next_ota_announce = 0;
|
||||
_ota_announce_count = 0;
|
||||
}
|
||||
if (millisHasNowPassed(_next_ota_tick)) {
|
||||
// one-shot on first tick: resume an interrupted fetch left staged in flash before a reboot. Only adopt
|
||||
// a PARTIAL container (continue fetching the holes); a COMPLETE one is left for manual/auto-install,
|
||||
// not re-adopted at boot. requestMissing() (inside resumeStaged) drives the rest via REQ/DATA.
|
||||
if (!_ota_resumed) {
|
||||
_ota_resumed = true;
|
||||
ota::OtaContext& oc = ota::ota_ctx();
|
||||
if (oc.manager.fetchState() == ota::OtaManager::IDLE && oc.manager.resumeStaged(nullptr)
|
||||
&& oc.manager.fetchState() == ota::OtaManager::COMPLETE) {
|
||||
oc.manager.reset_session(); // don't auto-adopt a complete staged container on boot
|
||||
}
|
||||
}
|
||||
ota::ota_ctx().manager.set_clock(_ms->getMillis()); // for discovery jitter/ages + the pending-query timer
|
||||
ota::ota_ctx().manager.loop(); // re-request still-missing OTA blocks + fire scheduled queries
|
||||
_next_ota_tick = futureMillis(3000);
|
||||
}
|
||||
if (millisHasNowPassed(_next_ota_announce)) { // auto-advertise so peers discover us (tiny beacon)
|
||||
ota::OtaContext& oc = ota::ota_ctx();
|
||||
bool in_burst = _ota_announce_count < OTA_ANNOUNCE_BURST;
|
||||
uint32_t mins = oc.manager.advert_mins(); // periodic cadence in minutes; 0 = disabled (boot burst only)
|
||||
if (in_burst || mins != 0) {
|
||||
// To be discoverable as a source of our OWN firmware, set up flash-backed self-serve once; then the
|
||||
// beacon (announce) advertises our served set and peers can QUERY + fetch it.
|
||||
if (!oc.serving) oc.serving = ota::ota_serve_self(oc, 0);
|
||||
oc.manager.announce();
|
||||
if (_ota_announce_count < 250) _ota_announce_count++;
|
||||
}
|
||||
// Re-arm: tight spacing during the boot burst; afterwards the fixed cadence (default 24h). When periodic
|
||||
// advert is disabled (0), re-check on a slow timer so a later `ota config advert <mins>` takes effect live.
|
||||
uint32_t gap = in_burst ? OTA_ANNOUNCE_BURST_MS
|
||||
: (mins != 0) ? mins * 60000UL
|
||||
: OTA_ANNOUNCE_DISABLED_POLL_MS;
|
||||
_next_ota_announce = futureMillis(gap);
|
||||
}
|
||||
{ // auto-install (once per COMPLETE fetch): only signed images, and apply_fetched enforces trust
|
||||
ota::OtaContext& oc = ota::ota_ctx();
|
||||
if (oc.manager.fetchState() != ota::OtaManager::COMPLETE) {
|
||||
_ota_autoinstall_tried = false;
|
||||
} else if (!_ota_autoinstall_tried && !oc.apply_pending
|
||||
&& oc.autoinstall == ota::OtaContext::AUTOINSTALL_TRUSTED
|
||||
&& oc.manager.fetched_is_signed()) {
|
||||
_ota_autoinstall_tried = true;
|
||||
char msg[100];
|
||||
oc.apply_fetched(msg); // arms + sets apply_pending only if signed & allowlisted; refused otherwise
|
||||
}
|
||||
}
|
||||
#endif
|
||||
}
|
||||
|
||||
bool Mesh::allowPacketForward(const mesh::Packet* packet) {
|
||||
@@ -618,6 +740,41 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
|
||||
}
|
||||
break;
|
||||
|
||||
#if defined(ENABLE_OTA)
|
||||
case PAYLOAD_TYPE_OTA: {
|
||||
// OTA is invisible outside an actually-running temporary-radio window. In particular, do not add it
|
||||
// to the seen table: a copy heard on the normal channel must not suppress one received after temp radio starts.
|
||||
if (!isTempRadioActive()) break;
|
||||
uint8_t n = pkt->getPathHashCount(); // hops travelled to reach us (flood path-hash count)
|
||||
// Accept-gate (duty-cycle horizon): ignore OTA from further than our hop limit — neither process nor
|
||||
// relay it. 0 = only directly-received OTA. Runtime-tunable via `ota config hops`.
|
||||
if (n > getOtaHopLimit()) break;
|
||||
// ALWAYS process every accepted copy: OTA handlers are idempotent, and "eventually reliable" retries
|
||||
// deliberately re-send IDENTICAL requests — if we gated processing on hasSeen(), the dedup would
|
||||
// suppress those retries and the transfer could never recover from a lost reply. hasSeen() is used
|
||||
// ONLY to avoid re-flooding the same packet more than once.
|
||||
bool seen = _tables->wasSeen(pkt);
|
||||
if (!seen) _tables->markSeen(pkt);
|
||||
ota::ota_ctx().manager.set_clock(_ms->getMillis()); // discovery jitter/ages
|
||||
ota::ota_ctx().manager.on_message(pkt->payload, pkt->payload_len); // central OTA receive (beacon/query/
|
||||
// have/manifest/data/proof; all roles)
|
||||
ota::ota_ctx().track_session(ota::ota_ctx().manager.fetchState(), _ms->getMillis());
|
||||
onOtaRecv(pkt); // optional per-example hook
|
||||
// Re-flood at the LOWEST priority and only while still under the hop limit, so OTA never competes with
|
||||
// mesh traffic. The free-pool guard keeps heavy OTA from monopolising the shared packet pool — dropping
|
||||
// a relay is safe (OTA is best-effort; the source retries).
|
||||
if (!seen && pkt->isRouteFlood() && !pkt->isMarkedDoNotRetransmit()
|
||||
&& n < getOtaHopLimit()
|
||||
&& (n + 1) * pkt->getPathHashSize() <= MAX_PATH_SIZE
|
||||
&& _mgr->getFreeCount() > OTA_FWD_MIN_FREE
|
||||
&& allowPacketForward(pkt)) {
|
||||
self_id.copyHashTo(&pkt->path[n * pkt->getPathHashSize()], pkt->getPathHashSize());
|
||||
pkt->setPathHashCount(n + 1);
|
||||
action = ACTION_RETRANSMIT_DELAYED(OTA_TX_PRIORITY, getRetransmitDelay(pkt));
|
||||
}
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
default:
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::onRecvPacket(): unknown payload type, header: %d", getLogDateTime(), (int) pkt->header);
|
||||
// Don't flood route unknown packet types! action = routeRecvPacket(pkt);
|
||||
@@ -1570,6 +1727,29 @@ Packet* Mesh::createControlData(const uint8_t* data, size_t len) {
|
||||
return packet;
|
||||
}
|
||||
|
||||
#if defined(ENABLE_OTA)
|
||||
Packet* Mesh::createOtaPacket(const uint8_t* data, size_t len) {
|
||||
if (len > sizeof(Packet::payload)) return NULL;
|
||||
Packet* packet = obtainNewPacket();
|
||||
if (packet == NULL) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::createOtaPacket(): error, packet pool empty", getLogDateTime());
|
||||
return NULL;
|
||||
}
|
||||
packet->header = (PAYLOAD_TYPE_OTA << PH_TYPE_SHIFT); // ROUTE_TYPE_* set by sendOtaFlood
|
||||
memcpy(packet->payload, data, len);
|
||||
packet->payload_len = len;
|
||||
return packet;
|
||||
}
|
||||
|
||||
void Mesh::sendOtaFlood(Packet* packet, uint32_t delay_millis) {
|
||||
packet->header &= ~PH_ROUTE_MASK;
|
||||
packet->header |= ROUTE_TYPE_FLOOD;
|
||||
packet->setPathHashSizeAndCount(1, 0);
|
||||
_tables->markSeen(packet); // mark as sent, in case it floods back to us
|
||||
sendPacket(packet, OTA_TX_PRIORITY, delay_millis);
|
||||
}
|
||||
#endif
|
||||
|
||||
void Mesh::sendFlood(Packet* packet, uint32_t delay_millis, uint8_t path_hash_size) {
|
||||
if (packet->getPayloadType() == PAYLOAD_TYPE_TRACE) {
|
||||
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
|
||||
|
||||
+44
@@ -2,6 +2,19 @@
|
||||
|
||||
#include <Dispatcher.h>
|
||||
|
||||
#if defined(ENABLE_OTA)
|
||||
// OTA-over-LoRa: lowest TX priority (selected only after all real traffic). The hop limit is runtime-
|
||||
// tunable (OtaManager::max_hops(), `ota config hops`); the default lives in OtaManager.h.
|
||||
#ifndef OTA_TX_PRIORITY
|
||||
#define OTA_TX_PRIORITY 250
|
||||
#endif
|
||||
// An OTA flood is relayed only while this many pool slots stay free, so heavy OTA (best-effort, low-
|
||||
// priority) can never monopolise the shared packet pool and starve real traffic.
|
||||
#ifndef OTA_FWD_MIN_FREE
|
||||
#define OTA_FWD_MIN_FREE 4
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
|
||||
#ifndef MAX_DIRECT_RETRY_SLOTS
|
||||
@@ -311,6 +324,30 @@ protected:
|
||||
*/
|
||||
virtual void onRawDataRecv(Packet* packet) { }
|
||||
|
||||
#if defined(ENABLE_OTA)
|
||||
/** OTA transport is dormant unless the role has actually switched into a temporary-radio window. */
|
||||
virtual bool isTempRadioActive() const { return false; }
|
||||
|
||||
/**
|
||||
* \brief An OTA-over-LoRa packet (PAYLOAD_TYPE_OTA) has been received. Subclasses forward the
|
||||
* payload bytes to their OtaManager. See docs/ota_protocol.md.
|
||||
*/
|
||||
virtual void onOtaRecv(Packet* packet) { }
|
||||
|
||||
/** \returns max OTA flood reach in hops — accept up to N, relay while < N (0=direct). `ota config hops`. */
|
||||
virtual uint8_t getOtaHopLimit() const;
|
||||
|
||||
// OTA mesh-integration is centralized in Mesh::begin()/loop()/dispatch, so every role (repeater,
|
||||
// companion, room, sensor, ...) gets fetch/serve/apply without per-example wiring.
|
||||
static void otaSendAdapter(void* ctx, const uint8_t* msg, uint16_t len, bool flood);
|
||||
unsigned long _next_ota_tick = 0;
|
||||
unsigned long _next_ota_announce = 0; // advertisements are scheduled only while temp radio is active
|
||||
uint8_t _ota_announce_count = 0; // adverts sent so far (boot burst before settling to daily)
|
||||
bool _ota_resumed = false; // one-shot: resumed an interrupted fetch staged in flash on boot
|
||||
bool _ota_autoinstall_tried = false; // attempted auto-install for the current COMPLETE fetch
|
||||
bool _ota_temp_was_active = false; // detects entry into a temporary-radio window
|
||||
#endif
|
||||
|
||||
/**
|
||||
* \brief Perform search of local DB of matching GroupChannels.
|
||||
* \param channels OUT - store matching channels in this array, up to max_matches
|
||||
@@ -359,6 +396,13 @@ public:
|
||||
Packet* createPathReturn(const uint8_t* dest_hash, const uint8_t* secret, const uint8_t* path, uint8_t path_len, uint8_t extra_type, const uint8_t*extra, size_t extra_len);
|
||||
Packet* createPathReturn(const Identity& dest, const uint8_t* secret, const uint8_t* path, uint8_t path_len, uint8_t extra_type, const uint8_t*extra, size_t extra_len);
|
||||
Packet* createRawData(const uint8_t* data, size_t len);
|
||||
|
||||
#if defined(ENABLE_OTA)
|
||||
// Build a PAYLOAD_TYPE_OTA packet from raw OTA message bytes (route set by sendOtaFlood).
|
||||
Packet* createOtaPacket(const uint8_t* data, size_t len);
|
||||
// Flood-send at the lowest priority (so OTA never competes with mesh traffic).
|
||||
void sendOtaFlood(Packet* packet, uint32_t delay_millis = 0);
|
||||
#endif
|
||||
Packet* createTrace(uint32_t tag, uint32_t auth_code, uint8_t flags = 0);
|
||||
Packet* createControlData(const uint8_t* data, size_t len);
|
||||
|
||||
|
||||
@@ -75,6 +75,27 @@ public:
|
||||
virtual bool setLoRaFemLnaEnabled(bool enable) { return false; }
|
||||
virtual bool canControlLoRaFemLna() const { return false; }
|
||||
virtual bool isLoRaFemLnaEnabled() const { return false; }
|
||||
#if defined(ENABLE_OTA)
|
||||
// 4-byte build-target discriminator for OTA-over-LoRa (docs/ota_protocol.md §9). Default is the
|
||||
// MOTA_TARGET_ID build flag injected by build.sh; 0 when unset (e.g. a bare IDE build).
|
||||
virtual uint32_t getOtaTargetId() const {
|
||||
#ifdef MOTA_TARGET_ID
|
||||
return (uint32_t)(MOTA_TARGET_ID);
|
||||
#else
|
||||
return 0;
|
||||
#endif
|
||||
}
|
||||
// Human-readable hardware tag (<=32 ASCII chars, e.g. "RAK4631") naming the hardware this firmware can
|
||||
// boot on. Same tag == bootable-compatible; the OTA applier refuses a `.mota` whose hw_id differs (brick-
|
||||
// safety). Defined per-variant via the MOTA_HW_ID build flag; "" when unset (then the check is skipped).
|
||||
virtual const char* getOtaHwId() const {
|
||||
#ifdef MOTA_HW_ID
|
||||
return MOTA_HW_ID;
|
||||
#else
|
||||
return "";
|
||||
#endif
|
||||
}
|
||||
#endif
|
||||
|
||||
// Power management interface (boards with power management override these)
|
||||
virtual bool isExternalPowered() { return false; }
|
||||
|
||||
@@ -28,6 +28,7 @@ namespace mesh {
|
||||
#define PAYLOAD_TYPE_TRACE 0x09 // trace a path, collecting SNR for each hop
|
||||
#define PAYLOAD_TYPE_MULTIPART 0x0A // packet is one of a set of packets
|
||||
#define PAYLOAD_TYPE_CONTROL 0x0B // a control/discovery packet
|
||||
#define PAYLOAD_TYPE_OTA 0x0C // OTA-over-LoRa firmware distribution (see docs/ota_protocol.md)
|
||||
//...
|
||||
#define PAYLOAD_TYPE_RAW_CUSTOM 0x0F // custom packet as raw bytes, for applications with custom encryption, payloads, etc
|
||||
|
||||
|
||||
@@ -31,6 +31,10 @@ static void resetToUf2Bootloader() {
|
||||
|
||||
#define STR_HELPER(x) #x
|
||||
#define STR(x) STR_HELPER(x)
|
||||
#if defined(ENABLE_OTA)
|
||||
#include "ota/OtaCli.h"
|
||||
#include "ota/OtaContext.h" // persist/sync OTA policy + signer allowlist with NodePrefs
|
||||
#endif
|
||||
|
||||
#ifndef BRIDGE_MAX_BAUD
|
||||
#define BRIDGE_MAX_BAUD 115200
|
||||
@@ -637,11 +641,13 @@ static void formatSnrDbX4Short(char* dest, size_t dest_len, int16_t snr_x4) {
|
||||
void CommonCLI::loadPrefs(FILESYSTEM* fs) {
|
||||
bool is_fresh_install = false;
|
||||
bool is_upgrade = false;
|
||||
|
||||
bool loaded = false;
|
||||
|
||||
if (fs->exists("/com_prefs")) {
|
||||
loadPrefsInt(fs, "/com_prefs"); // new filename
|
||||
loadPrefsInt(fs, "/com_prefs"); loaded = true; // new filename
|
||||
} else if (fs->exists("/node_prefs")) {
|
||||
loadPrefsInt(fs, "/node_prefs");
|
||||
loaded = true;
|
||||
is_upgrade = true; // Migrating from old filename
|
||||
savePrefs(fs); // save to new filename
|
||||
fs->remove("/node_prefs"); // remove old
|
||||
@@ -676,8 +682,26 @@ void CommonCLI::loadPrefs(FILESYSTEM* fs) {
|
||||
savePrefs(fs);
|
||||
_com_prefs_needs_upgrade = false;
|
||||
}
|
||||
#if defined(ENABLE_OTA)
|
||||
if (loaded) syncOtaConfigFromPrefs(); // persisted OTA policy/keys -> OtaContext (else keep safe defaults)
|
||||
#endif
|
||||
}
|
||||
|
||||
#if defined(ENABLE_OTA)
|
||||
// Push the persisted OTA policy + signer allowlist into the running OtaContext (called after load).
|
||||
void CommonCLI::syncOtaConfigFromPrefs() {
|
||||
mesh::ota::OtaContext& c = mesh::ota::ota_ctx();
|
||||
c.manager.set_autofetch(_prefs->ota_autofetch);
|
||||
c.manager.set_checkpoint_blocks(_prefs->ota_checkpoint_blocks);
|
||||
c.manager.set_advert_mins(_prefs->ota_advert_interval);
|
||||
c.manager.set_max_hops(_prefs->ota_max_hops);
|
||||
c.autoinstall = _prefs->ota_autoinstall;
|
||||
c.allow.clear();
|
||||
for (uint8_t i = 0; i < _prefs->ota_signer_count && i < MAX_OTA_SIGNERS; i++)
|
||||
c.allow.add(_prefs->ota_signers[i]);
|
||||
}
|
||||
#endif
|
||||
|
||||
void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
|
||||
#if defined(RP2040_PLATFORM)
|
||||
File file = fs->open(filename, "r");
|
||||
@@ -739,6 +763,17 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
|
||||
// (upstream defaults: FEM RX gain on, CAD off) — overwritten below if present.
|
||||
_prefs->radio_fem_rxgain = 1;
|
||||
_prefs->cad_enabled = 0;
|
||||
#if defined(ENABLE_OTA)
|
||||
// OTA settings were appended after Keymind's retry/flood tail. Initialize them
|
||||
// before reading so older and legacy preference files remain conservative.
|
||||
_prefs->ota_autofetch = 0;
|
||||
_prefs->ota_autoinstall = 0;
|
||||
_prefs->ota_signer_count = 0;
|
||||
memset(_prefs->ota_signers, 0, sizeof(_prefs->ota_signers));
|
||||
_prefs->ota_checkpoint_blocks = 4;
|
||||
_prefs->ota_advert_interval = 0;
|
||||
_prefs->ota_max_hops = 3;
|
||||
#endif
|
||||
// A remainder larger than the smallest legacy MQTT gap (864) means an old fork
|
||||
// file with the zero-filled gap; detect and recover it below. Anything smaller
|
||||
// (upstream/flex 5-byte tails, or the ~384-byte keymind retry tail) takes the
|
||||
@@ -923,7 +958,31 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
|
||||
file.read((uint8_t *)&_prefs->flood_channel_data_max_hops, sizeof(_prefs->flood_channel_data_max_hops));
|
||||
}
|
||||
}
|
||||
// next: 674
|
||||
#if defined(ENABLE_OTA)
|
||||
// OTA config starts at 674. Guard every appended field so older files keep defaults.
|
||||
if (file.available() >= (int)sizeof(_prefs->ota_autofetch)) {
|
||||
file.read((uint8_t *)&_prefs->ota_autofetch, sizeof(_prefs->ota_autofetch));
|
||||
}
|
||||
if (file.available() >= (int)sizeof(_prefs->ota_autoinstall)) {
|
||||
file.read((uint8_t *)&_prefs->ota_autoinstall, sizeof(_prefs->ota_autoinstall));
|
||||
}
|
||||
if (file.available() >= (int)sizeof(_prefs->ota_signer_count)) {
|
||||
file.read((uint8_t *)&_prefs->ota_signer_count, sizeof(_prefs->ota_signer_count));
|
||||
}
|
||||
if (file.available() >= (int)sizeof(_prefs->ota_signers)) {
|
||||
file.read((uint8_t *)_prefs->ota_signers, sizeof(_prefs->ota_signers));
|
||||
}
|
||||
if (file.available() >= (int)sizeof(_prefs->ota_checkpoint_blocks)) {
|
||||
file.read((uint8_t *)&_prefs->ota_checkpoint_blocks, sizeof(_prefs->ota_checkpoint_blocks));
|
||||
}
|
||||
if (file.available() >= (int)sizeof(_prefs->ota_advert_interval)) {
|
||||
file.read((uint8_t *)&_prefs->ota_advert_interval, sizeof(_prefs->ota_advert_interval));
|
||||
}
|
||||
if (file.available() >= (int)sizeof(_prefs->ota_max_hops)) {
|
||||
file.read((uint8_t *)&_prefs->ota_max_hops, sizeof(_prefs->ota_max_hops));
|
||||
}
|
||||
// next: 810
|
||||
#endif
|
||||
}
|
||||
|
||||
// sanitise bad pref values
|
||||
@@ -999,6 +1058,14 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
|
||||
_prefs->battery_alert_low_percent = BATTERY_ALERT_LOW_PERCENT_DEFAULT;
|
||||
_prefs->battery_alert_critical_percent = BATTERY_ALERT_CRITICAL_PERCENT_DEFAULT;
|
||||
}
|
||||
#if defined(ENABLE_OTA)
|
||||
_prefs->ota_autofetch = constrain(_prefs->ota_autofetch, 0, 2);
|
||||
_prefs->ota_autoinstall = constrain(_prefs->ota_autoinstall, 0, 1);
|
||||
if (_prefs->ota_checkpoint_blocks > 4096) _prefs->ota_checkpoint_blocks = 4; // 0=never; cap absurd
|
||||
if (_prefs->ota_advert_interval > 10080) _prefs->ota_advert_interval = 1440; // 0=off; cap at 7 days
|
||||
if (_prefs->ota_max_hops > 8) _prefs->ota_max_hops = 3; // 0=direct only; cap absurd reach
|
||||
if (_prefs->ota_signer_count > 4) _prefs->ota_signer_count = 0; // corrupt count -> drop keys
|
||||
#endif
|
||||
|
||||
file.close();
|
||||
}
|
||||
@@ -1096,7 +1163,16 @@ void CommonCLI::savePrefs(FILESYSTEM* fs) {
|
||||
file.write((uint8_t *)&_prefs->flood_channel_data_enabled, sizeof(_prefs->flood_channel_data_enabled));
|
||||
file.write((uint8_t *)&_prefs->flood_channel_block_max_hops, sizeof(_prefs->flood_channel_block_max_hops));
|
||||
file.write((uint8_t *)&_prefs->flood_channel_data_max_hops, sizeof(_prefs->flood_channel_data_max_hops));
|
||||
// next: 674
|
||||
#if defined(ENABLE_OTA)
|
||||
file.write((uint8_t *)&_prefs->ota_autofetch, sizeof(_prefs->ota_autofetch)); // 674
|
||||
file.write((uint8_t *)&_prefs->ota_autoinstall, sizeof(_prefs->ota_autoinstall)); // 675
|
||||
file.write((uint8_t *)&_prefs->ota_signer_count, sizeof(_prefs->ota_signer_count)); // 676
|
||||
file.write((uint8_t *)_prefs->ota_signers, sizeof(_prefs->ota_signers)); // 677
|
||||
file.write((uint8_t *)&_prefs->ota_checkpoint_blocks, sizeof(_prefs->ota_checkpoint_blocks)); // 805
|
||||
file.write((uint8_t *)&_prefs->ota_advert_interval, sizeof(_prefs->ota_advert_interval)); // 807
|
||||
file.write((uint8_t *)&_prefs->ota_max_hops, sizeof(_prefs->ota_max_hops)); // 809
|
||||
// next: 810
|
||||
#endif
|
||||
|
||||
file.close();
|
||||
}
|
||||
@@ -1536,6 +1612,23 @@ void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* re
|
||||
sprintf(reply, "%s (Build: %s)", _callbacks->getFirmwareVer(), _callbacks->getBuildDate());
|
||||
} else if (memcmp(command, "board", 5) == 0) {
|
||||
sprintf(reply, "%s", _board->getManufacturerName());
|
||||
#if defined(ENABLE_OTA)
|
||||
} else if (memcmp(command, "ota", 3) == 0 && (command[3] == 0 || command[3] == ' ')) {
|
||||
mesh::ota::handle_ota_command(command, reply, *_board);
|
||||
if (mesh::ota::ota_ctx().config_dirty) { // a policy/key changed via the CLI -> persist it
|
||||
mesh::ota::OtaContext& c = mesh::ota::ota_ctx();
|
||||
_prefs->ota_autofetch = c.manager.autofetch();
|
||||
_prefs->ota_checkpoint_blocks = c.manager.checkpoint_blocks();
|
||||
_prefs->ota_advert_interval = c.manager.advert_mins();
|
||||
_prefs->ota_max_hops = c.manager.max_hops();
|
||||
_prefs->ota_autoinstall = c.autoinstall;
|
||||
_prefs->ota_signer_count = c.allow.count();
|
||||
for (uint8_t i = 0; i < c.allow.count() && i < MAX_OTA_SIGNERS; i++)
|
||||
memcpy(_prefs->ota_signers[i], c.allow.get(i), 32);
|
||||
_callbacks->savePrefs();
|
||||
c.config_dirty = false;
|
||||
}
|
||||
#endif
|
||||
} else if (memcmp(command, "sensor get ", 11) == 0) {
|
||||
const char* key = command + 11;
|
||||
const char* val = _sensors->getSettingByKey(key);
|
||||
|
||||
@@ -181,6 +181,17 @@ struct NodePrefs { // persisted to file
|
||||
// NodePrefs into MQTTPrefs (persisted to /mqtt_prefs) so this struct stays
|
||||
// aligned with upstream (plus the keymind retry/flood tail above). See
|
||||
// struct MQTTPrefs below.
|
||||
|
||||
#if defined(ENABLE_OTA)
|
||||
// OTA config (persisted; synced to OtaContext on load, written on change). 0 = conservative defaults.
|
||||
uint8_t ota_autofetch; // OtaManager AUTOFETCH_* (0=off, 1=any-compatible, 2=signed-only)
|
||||
uint8_t ota_autoinstall; // OtaContext AUTOINSTALL_* (0=off, 1=trusted-only)
|
||||
uint8_t ota_signer_count; // # of allowlisted signer pubkeys below
|
||||
uint8_t ota_signers[4][32]; // trusted Ed25519 signer pubkeys (== MAX_OTA_SIGNERS)
|
||||
uint16_t ota_checkpoint_blocks; // resume checkpoint cadence (blocks); 0=never. Default 4 (runtime-tunable)
|
||||
uint16_t ota_advert_interval; // OTA beacon re-advertise cadence (mins); 0=off. Default 1440 (24h, tunable)
|
||||
uint8_t ota_max_hops; // OTA flood reach in hops; 0=direct only. Default 3 (runtime-tunable)
|
||||
#endif
|
||||
};
|
||||
|
||||
#ifdef WITH_MQTT_BRIDGE
|
||||
@@ -554,6 +565,9 @@ class CommonCLI {
|
||||
void loadMQTTPrefs(FILESYSTEM* fs);
|
||||
void saveMQTTPrefs(FILESYSTEM* fs);
|
||||
#endif
|
||||
#if defined(ENABLE_OTA)
|
||||
void syncOtaConfigFromPrefs(); // persisted OTA policy + signer allowlist -> running OtaContext
|
||||
#endif
|
||||
|
||||
void handleRegionCmd(char* command, char* reply);
|
||||
void handleGetCmd(uint32_t sender_timestamp, char* command, char* reply);
|
||||
|
||||
@@ -0,0 +1,52 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
// Block-availability helpers (docs/ota_protocol.md §7).
|
||||
//
|
||||
// Availability is *derived* from the staged manifest's leaves[]: block i is present iff its 4-byte
|
||||
// leaf slot is non-erased (!= FF FF FF FF). No separate persistent structure. A compact bitmap
|
||||
// (1 bit/block) is used on the wire (OTA_HAVE) and as an in-RAM cache. All ops are caller-buffer
|
||||
// based; no allocation.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
inline bool leaf_present(const uint8_t* leaves, uint32_t i) {
|
||||
const uint8_t* p = leaves + (size_t)i * 4;
|
||||
return !(p[0] == 0xFF && p[1] == 0xFF && p[2] == 0xFF && p[3] == 0xFF);
|
||||
}
|
||||
|
||||
inline uint32_t bitmap_bytes(uint32_t block_count) { return (block_count + 7) / 8; }
|
||||
|
||||
inline bool bitmap_get(const uint8_t* bm, uint32_t i) {
|
||||
return (bm[i >> 3] >> (i & 7)) & 1;
|
||||
}
|
||||
|
||||
inline void bitmap_set(uint8_t* bm, uint32_t i, bool v) {
|
||||
uint8_t mask = (uint8_t)(1u << (i & 7));
|
||||
if (v) bm[i >> 3] |= mask; else bm[i >> 3] &= (uint8_t)~mask;
|
||||
}
|
||||
|
||||
// Build a bitmap (caller buffer >= bitmap_bytes(count)) from leaves[].
|
||||
inline void leaves_to_bitmap(const uint8_t* leaves, uint32_t count, uint8_t* bm_out) {
|
||||
memset(bm_out, 0, bitmap_bytes(count));
|
||||
for (uint32_t i = 0; i < count; i++)
|
||||
if (leaf_present(leaves, i)) bitmap_set(bm_out, i, true);
|
||||
}
|
||||
|
||||
inline uint32_t count_present(const uint8_t* leaves, uint32_t count) {
|
||||
uint32_t n = 0;
|
||||
for (uint32_t i = 0; i < count; i++) if (leaf_present(leaves, i)) n++;
|
||||
return n;
|
||||
}
|
||||
|
||||
inline bool all_present(const uint8_t* leaves, uint32_t count) {
|
||||
for (uint32_t i = 0; i < count; i++) if (!leaf_present(leaves, i)) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,42 @@
|
||||
#include "FirmwareInfo.h"
|
||||
#include "Multihash.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
bool find_self_firmware(const uint8_t* region, uint32_t region_len,
|
||||
SelfFwInfo& out, bool verify_body) {
|
||||
out = SelfFwInfo();
|
||||
if (!region || region_len < ENDF_LEN) return false;
|
||||
|
||||
for (uint32_t off = 0; off + ENDF_LEN <= region_len; off++) {
|
||||
if (region[off] != ENDF_MAGIC[0]) continue; // cheap pre-filter ('E')
|
||||
if (memcmp(region + off, ENDF_MAGIC, 4) != 0) continue;
|
||||
uint32_t body_len = rd_u32le(region + off + 4);
|
||||
if (body_len != off) continue; // trailer must sit right after the body
|
||||
|
||||
if (verify_body) {
|
||||
uint8_t h[8];
|
||||
mh8(h, region, body_len);
|
||||
if (memcmp(h, region + off + 8, 8) != 0) continue; // coincidental marker — keep scanning
|
||||
}
|
||||
out.valid = true;
|
||||
out.endf_offset = off;
|
||||
out.body_len = body_len;
|
||||
out.image_len = off + ENDF_LEN;
|
||||
memcpy(out.body_hash, region + off + 8, 8);
|
||||
// Fixed 56-byte trailer: the self-describing identity follows body_hash at constant offsets
|
||||
// (fw_version@16, target_id@20, hw_id@24..56). Zero/"" means "unknown".
|
||||
out.fw_version = rd_u32le(region + off + 16);
|
||||
out.target_id = rd_u32le(region + off + 20);
|
||||
memcpy(out.hw_id, region + off + 24, 32);
|
||||
out.hw_id[32] = 0;
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "OtaFormat.h"
|
||||
|
||||
// Locate the EndF trailer in a firmware image to learn the running firmware's size + identity
|
||||
// (docs/ota_protocol.md §2). Portable: operates on a contiguous, readable region — on nRF52/ESP32
|
||||
// the application flash is memory-mapped, so the region pointer is just (const uint8_t*)APP_BASE.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
struct SelfFwInfo {
|
||||
bool valid = false;
|
||||
uint32_t body_len = 0; // firmware body length (excludes the EndF trailer)
|
||||
uint32_t image_len = 0; // body_len + ENDF_LEN (what a delta base / full image hashes over)
|
||||
uint32_t endf_offset = 0; // offset of the "EndF" marker within the region (== body_len)
|
||||
uint8_t body_hash[8] = {0}; // sha2-256:8 of the body (read from EndF; == a delta's base_hash)
|
||||
// Self-describing identity — always present in the fixed 56-byte trailer (zero/"" means "unknown",
|
||||
// e.g. a dev build with no dotted version).
|
||||
uint32_t fw_version = 0; // packed MAJOR<<24|MINOR<<16|PATCH<<8|pre
|
||||
uint32_t target_id = 0; // sha2-256:4(env) as uint32 — hw+role+partition (fetch routing)
|
||||
char hw_id[33] = {0}; // readable hardware tag (NUL-terminated), e.g. "RAK4631"
|
||||
};
|
||||
|
||||
// Scan `region[0..region_len)` for the firmware's EndF trailer. The body starts at offset 0, so the
|
||||
// trailer's offset must equal its stored body_len — this uniquely identifies the running firmware's
|
||||
// EndF even if a staged `.mota` (which contains its own embedded EndF) sits higher in the region.
|
||||
// If `verify_body` is true the body hash is recomputed and must match (rules out coincidental markers).
|
||||
bool find_self_firmware(const uint8_t* region, uint32_t region_len,
|
||||
SelfFwInfo& out, bool verify_body = false);
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,113 @@
|
||||
#include "FolderMotaStore.h"
|
||||
#include "MotaSeederProto.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
bool FolderMotaStore::readByteT(uint8_t& b) const {
|
||||
uint32_t t0 = millis();
|
||||
while ((millis() - t0) < _to) {
|
||||
int c = _io.read();
|
||||
if (c >= 0) { b = (uint8_t)c; return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool FolderMotaStore::readExact(uint8_t* b, uint16_t n) const {
|
||||
for (uint16_t i = 0; i < n; i++) if (!readByteT(b[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Resync-safe request/response (same framing as SerialMotaSource): drain stale input, frame op+args with an
|
||||
// XOR checksum, scan for the response magic, validate op+status+checksum, deliver payload.
|
||||
bool FolderMotaStore::txn(uint8_t op, const uint8_t* args, uint16_t arglen,
|
||||
uint8_t* payload, uint16_t payload_len) const {
|
||||
while (_io.read() >= 0) {} // drop any stale/partial bytes before a fresh request
|
||||
uint8_t xs = op;
|
||||
for (uint16_t i = 0; i < arglen; i++) xs ^= args[i];
|
||||
_io.write(MOTA_SEEDER_REQ_MAGIC0); _io.write(MOTA_SEEDER_REQ_MAGIC1);
|
||||
_io.write(op);
|
||||
if (arglen) _io.write(args, arglen);
|
||||
_io.write(xs);
|
||||
_io.flush();
|
||||
|
||||
uint32_t t0 = millis(); bool got = false; uint8_t prev = 0;
|
||||
while ((millis() - t0) < _to) { // scan for response magic 'm' 's' (tolerate noise)
|
||||
int c = _io.read();
|
||||
if (c < 0) continue;
|
||||
if (prev == MOTA_SEEDER_RSP_MAGIC0 && (uint8_t)c == MOTA_SEEDER_RSP_MAGIC1) { got = true; break; }
|
||||
prev = (uint8_t)c;
|
||||
}
|
||||
if (!got) return false;
|
||||
|
||||
uint8_t hdr[2];
|
||||
if (!readExact(hdr, 2)) return false; // op, status
|
||||
if (hdr[0] != op) return false;
|
||||
uint8_t rxs = (uint8_t)(MOTA_SEEDER_RSP_MAGIC0 ^ MOTA_SEEDER_RSP_MAGIC1) ^ hdr[0] ^ hdr[1];
|
||||
bool ok = (hdr[1] == MS_STATUS_OK);
|
||||
if (ok && payload_len) {
|
||||
if (!readExact(payload, payload_len)) return false;
|
||||
for (uint16_t i = 0; i < payload_len; i++) rxs ^= payload[i];
|
||||
}
|
||||
uint8_t xsum;
|
||||
if (!readByteT(xsum)) return false;
|
||||
if (xsum != rxs) return false; // corrupt frame -> caller retries
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool FolderMotaStore::begin(uint32_t total_size) {
|
||||
uint8_t args[8];
|
||||
memcpy(args, _mid, 4);
|
||||
wr_u32le(args + 4, total_size);
|
||||
if (!txn(MS_OP_BEGIN, args, 8, nullptr, 0)) return false;
|
||||
_total = total_size;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FolderMotaStore::write(uint32_t off, const uint8_t* data, uint32_t len) {
|
||||
uint8_t req[10 + MOTA_SEEDER_WRITE_MAX];
|
||||
memcpy(req, _mid, 4);
|
||||
uint32_t done = 0;
|
||||
while (done < len) {
|
||||
uint16_t chunk = (len - done > MOTA_SEEDER_WRITE_MAX) ? MOTA_SEEDER_WRITE_MAX : (uint16_t)(len - done);
|
||||
wr_u32le(req + 4, off + done);
|
||||
req[8] = (uint8_t)(chunk & 0xFF); req[9] = (uint8_t)(chunk >> 8);
|
||||
memcpy(req + 10, data + done, chunk);
|
||||
if (!txn(MS_OP_WRITE, req, (uint16_t)(10 + chunk), nullptr, 0)) return false;
|
||||
done += chunk;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool FolderMotaStore::read(uint32_t off, uint8_t* buf, uint32_t len) const {
|
||||
uint8_t args[10];
|
||||
memcpy(args, _mid, 4);
|
||||
uint32_t done = 0;
|
||||
while (done < len) {
|
||||
uint16_t chunk = (len - done > MOTA_SEEDER_WRITE_MAX) ? MOTA_SEEDER_WRITE_MAX : (uint16_t)(len - done);
|
||||
wr_u32le(args + 4, off + done);
|
||||
args[8] = (uint8_t)(chunk & 0xFF); args[9] = (uint8_t)(chunk >> 8);
|
||||
if (!txn(MS_OP_SREAD, args, 10, buf + done, chunk)) return false;
|
||||
done += chunk;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void FolderMotaStore::finalize() {
|
||||
txn(MS_OP_FIN, _mid, 4, nullptr, 0); // publish <midhex>.mota.part as <midhex>.mota (best-effort)
|
||||
}
|
||||
|
||||
bool FolderMotaStore::reopen() {
|
||||
uint8_t pl[5];
|
||||
if (!txn(MS_OP_STAT, _mid, 4, pl, 5)) return false;
|
||||
if (pl[0] == 0) return false; // host has no partial/complete file -> start fresh
|
||||
uint32_t total = rd_u32le(pl + 1);
|
||||
if (total < 13) return false; // implausible container
|
||||
_total = total;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,57 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "OtaStore.h"
|
||||
|
||||
// An OtaStore that captures an in-transit `.mota` onto a HOST folder over the mota-seeder link (the WRITE
|
||||
// half of MotaSeederProto: OP_STAT/BEGIN/WRITE/SREAD/FIN). This is the destination for `ota pull <#> folder`:
|
||||
// blocks stream straight to the host `<mid>.mota` — the device holds NO RAM/flash staging for it.
|
||||
//
|
||||
// begin(total) -> OP_BEGIN (host creates a 0xFF-filled <midhex>.mota.part)
|
||||
// write(off,data) -> OP_WRITE (split into <= MOTA_SEEDER_WRITE_MAX chunks)
|
||||
// read(off,buf) -> OP_SREAD (read back; unwritten regions are 0xFF)
|
||||
// reopen() -> OP_STAT (adopt an existing partial/complete file for resume)
|
||||
// finalize() -> OP_FIN (publish <midhex>.mota.part as <midhex>.mota)
|
||||
//
|
||||
// If the link drops, every op returns false: the OtaManager PAUSES and keeps its progress (it does NOT fall
|
||||
// back to RAM/flash). On reconnect the host still has the partial, and the manager re-reopen()s so only the
|
||||
// missing blocks are refetched. All ops are keyed by `mid` (set via set_mid() before the fetch begins).
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
class FolderMotaStore : public OtaStore {
|
||||
public:
|
||||
explicit FolderMotaStore(Stream& io, uint32_t timeout_ms = 3000) : _io(io), _to(timeout_ms) {}
|
||||
|
||||
// The container being pulled — set from the chosen `ota pull` mid before begin()/reopen().
|
||||
void set_mid(const uint8_t mid[4]) { memcpy(_mid, mid, 4); }
|
||||
|
||||
bool begin(uint32_t total_size) override;
|
||||
bool write(uint32_t off, const uint8_t* data, uint32_t len) override;
|
||||
bool read(uint32_t off, uint8_t* buf, uint32_t len) const override;
|
||||
uint32_t capacity() const override { return 0xF0000000u; } // host disk — effectively unbounded
|
||||
uint32_t staged_size() const override { return _total; }
|
||||
void clear() override { _total = 0; }
|
||||
void finalize() override;
|
||||
bool reopen() override; // OP_STAT: adopt an existing file for resume
|
||||
|
||||
// A host-backed store is fully random-access, so it needs no pinned-meta RAM page and no layout planning.
|
||||
bool set_meta_size(uint32_t) override { return true; }
|
||||
bool plan_layout(bool, uint32_t, uint32_t, uint32_t) override { return true; }
|
||||
|
||||
private:
|
||||
// One request/response transaction over the seeder link (mirrors SerialMotaSource). `arglen` is uint16 so
|
||||
// OP_WRITE can carry its data inline. Returns true iff a well-formed OK response for `op` arrived in time.
|
||||
bool txn(uint8_t op, const uint8_t* args, uint16_t arglen, uint8_t* payload, uint16_t payload_len) const;
|
||||
bool readByteT(uint8_t& b) const;
|
||||
bool readExact(uint8_t* b, uint16_t n) const;
|
||||
|
||||
Stream& _io;
|
||||
uint32_t _to;
|
||||
uint8_t _mid[4] = {0, 0, 0, 0};
|
||||
uint32_t _total = 0;
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,110 @@
|
||||
#include "MerkleTree.h"
|
||||
#include "Multihash.h"
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
void merkle_leaf(uint8_t out[4], const uint8_t* block, uint32_t block_len) {
|
||||
mh4(out, block, block_len);
|
||||
}
|
||||
|
||||
void merkle_combine(uint8_t out[4], const uint8_t* left, const uint8_t* right) {
|
||||
sha256_trunc2(out, 4, left, 4, right, 4);
|
||||
}
|
||||
|
||||
// Root via binary-counter / Merkle-Mountain-Range with right-to-left bagging.
|
||||
// Equivalent to the level-by-level "pair adjacent, promote lone last (left||right)" reduction
|
||||
// (verified against the reference implementation across many counts in the native tests).
|
||||
void merkle_root(uint8_t out[4], const uint8_t* leaves, uint32_t count) {
|
||||
if (count == 0) { memset(out, 0, 4); return; }
|
||||
if (count == 1) { memcpy(out, leaves, 4); return; }
|
||||
|
||||
uint8_t peaks[32][4];
|
||||
bool valid[32] = { false };
|
||||
|
||||
for (uint32_t i = 0; i < count; i++) {
|
||||
uint8_t cur[4];
|
||||
memcpy(cur, leaves + (size_t)i * 4, 4);
|
||||
uint32_t level = 0;
|
||||
while (valid[level]) { // carry: combine with the pending peak at this level
|
||||
merkle_combine(cur, peaks[level], cur); // peak is earlier (left), cur is right
|
||||
valid[level] = false;
|
||||
level++;
|
||||
}
|
||||
memcpy(peaks[level], cur, 4);
|
||||
valid[level] = true;
|
||||
}
|
||||
|
||||
// bag peaks right-to-left: acc starts at the lowest set level (rightmost peak)
|
||||
int level = 0;
|
||||
while (level < 32 && !valid[level]) level++;
|
||||
uint8_t acc[4];
|
||||
memcpy(acc, peaks[level], 4);
|
||||
for (int l = level + 1; l < 32; l++) {
|
||||
if (valid[l]) merkle_combine(acc, peaks[l], acc); // higher peak is left, acc is right
|
||||
}
|
||||
memcpy(out, acc, 4);
|
||||
}
|
||||
|
||||
bool merkle_verify(const uint8_t* block, uint32_t block_len, uint32_t index,
|
||||
const uint8_t* siblings, uint8_t n_siblings,
|
||||
const uint8_t root[4], uint32_t count) {
|
||||
uint8_t leaf[4];
|
||||
merkle_leaf(leaf, block, block_len);
|
||||
return merkle_verify_from_leaf(leaf, index, siblings, n_siblings, root, count);
|
||||
}
|
||||
|
||||
bool merkle_verify_from_leaf(const uint8_t leaf[4], uint32_t index,
|
||||
const uint8_t* siblings, uint8_t n_siblings,
|
||||
const uint8_t root[4], uint32_t count) {
|
||||
if (count == 0 || index >= count) return false;
|
||||
uint8_t h[4];
|
||||
memcpy(h, leaf, 4);
|
||||
|
||||
uint32_t idx = index;
|
||||
uint32_t n = count;
|
||||
uint8_t p = 0;
|
||||
while (n > 1) {
|
||||
bool is_last_odd = (n & 1u) && (idx == n - 1);
|
||||
if (!is_last_odd) {
|
||||
if (p >= n_siblings) return false;
|
||||
const uint8_t* sib = siblings + (size_t)p * 4;
|
||||
p++;
|
||||
if (idx & 1u) merkle_combine(h, sib, h); // odd index -> sibling on the left
|
||||
else merkle_combine(h, h, sib); // even index -> sibling on the right
|
||||
}
|
||||
idx >>= 1;
|
||||
n = (n + 1) >> 1;
|
||||
}
|
||||
return (p == n_siblings) && (memcmp(h, root, 4) == 0);
|
||||
}
|
||||
|
||||
uint8_t merkle_gen_proof(const uint8_t* leaves, uint32_t count, uint32_t index,
|
||||
uint8_t* scratch, uint8_t* out_siblings) {
|
||||
if (count == 0 || index >= count) return 0;
|
||||
memcpy(scratch, leaves, (size_t)count * 4);
|
||||
uint32_t n = count, idx = index;
|
||||
uint8_t p = 0;
|
||||
while (n > 1) {
|
||||
bool is_last_odd = (n & 1u) && (idx == n - 1);
|
||||
if (!is_last_odd) {
|
||||
uint32_t s = (idx & 1u) ? idx - 1 : idx + 1;
|
||||
memcpy(out_siblings + (size_t)p * 4, scratch + (size_t)s * 4, 4);
|
||||
p++;
|
||||
}
|
||||
// reduce one level in place (parent m written from children 2m,2m+1; m <= i so it's safe)
|
||||
uint32_t m = 0;
|
||||
for (uint32_t i = 0; i < n; i += 2) {
|
||||
if (i + 1 < n) merkle_combine(scratch + (size_t)m * 4, scratch + (size_t)i * 4, scratch + (size_t)(i + 1) * 4);
|
||||
else memmove(scratch + (size_t)m * 4, scratch + (size_t)i * 4, 4);
|
||||
m++;
|
||||
}
|
||||
idx >>= 1;
|
||||
n = (n + 1) >> 1;
|
||||
}
|
||||
return p;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,46 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
// Merkle tree over PAYLOAD blocks, sha2-256:4 (4-byte) leaves/nodes. See docs/ota_protocol.md §6.
|
||||
//
|
||||
// Scheme: leaf = H(block); node = H(left || right); on an odd level the last node is promoted
|
||||
// unchanged (no duplication). Root = single remaining node.
|
||||
//
|
||||
// No dynamic allocation: the root is computed with an O(log count) "binary counter" of partial
|
||||
// peaks (<= 32 levels => 128 bytes of stack). Proofs carry only sibling digests; the left/right
|
||||
// direction is derived from the block index + total count (no direction bits on the wire).
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// leaf digest of one payload block
|
||||
void merkle_leaf(uint8_t out[4], const uint8_t* block, uint32_t block_len);
|
||||
|
||||
// parent of two 4-byte children
|
||||
void merkle_combine(uint8_t out[4], const uint8_t* left, const uint8_t* right);
|
||||
|
||||
// root over `count` contiguous 4-byte leaf digests (leaves[count*4]). count >= 1.
|
||||
void merkle_root(uint8_t out[4], const uint8_t* leaves, uint32_t count);
|
||||
|
||||
// Verify that `block` is block `index` of a `count`-block payload whose tree has the given `root`.
|
||||
// `siblings` is n_siblings contiguous 4-byte digests, ordered leaf->root (promoted levels omitted;
|
||||
// left/right direction derived from index + count).
|
||||
bool merkle_verify(const uint8_t* block, uint32_t block_len, uint32_t index,
|
||||
const uint8_t* siblings, uint8_t n_siblings,
|
||||
const uint8_t root[4], uint32_t count);
|
||||
|
||||
// Same, but starting from a precomputed 4-byte leaf digest (skips the H(block) step).
|
||||
bool merkle_verify_from_leaf(const uint8_t leaf[4], uint32_t index,
|
||||
const uint8_t* siblings, uint8_t n_siblings,
|
||||
const uint8_t root[4], uint32_t count);
|
||||
|
||||
// Generate the proof (ordered sibling digests) for block `index`, for a server holding leaves[].
|
||||
// `scratch` must be >= count*4 bytes (working buffer); `out_siblings` >= 32*4 bytes.
|
||||
// Returns the number of 4-byte siblings written. Output matches the wire form merkle_verify expects.
|
||||
uint8_t merkle_gen_proof(const uint8_t* leaves, uint32_t count, uint32_t index,
|
||||
uint8_t* scratch, uint8_t* out_siblings);
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,83 @@
|
||||
#include "MotaContainer.h"
|
||||
#include "MerkleTree.h"
|
||||
#include "Multihash.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
bool MotaManifest::is_approved() const {
|
||||
return approval && memcmp(approval, APPROVAL_YES, 4) == 0;
|
||||
}
|
||||
|
||||
// Fixed-layout parse (docs/ota_protocol.md §4): every field sits at a constant offset — base_hash(8),
|
||||
// signer_pubkey(32) and signature(64) are ALWAYS present (zero-filled when not applicable), so there are
|
||||
// no conditionals. Only leaves[]/payload (after `approval`) is variable, read by the caller. The signature
|
||||
// always covers manifest[0, MOTA_SIGNED_LEN). Returns false on any over-read or bad format_ver.
|
||||
static bool parse_manifest_fields(ByteReader& r, MotaManifest& out) {
|
||||
out.format_ver = r.u8();
|
||||
if (out.format_ver != MOTA_FORMAT_VER) return false;
|
||||
out.flags = r.u8();
|
||||
out.hash_algo = r.u8();
|
||||
out.target_id = r.u32();
|
||||
out.fw_version = r.u32();
|
||||
out.image_size = r.u32();
|
||||
out.payload_size = r.u32();
|
||||
out.block_size_log2 = r.u8();
|
||||
out.merkle_root = r.take(4);
|
||||
out.image_hash = r.take(32);
|
||||
out.codec_id = r.u8();
|
||||
out.hw_id = r.take(32); // 32-byte NUL-padded hardware tag (signed)
|
||||
out.base_hash = r.take(8); // always present (zero for a full image)
|
||||
out.signer_pubkey = r.take(32); // always present (zero when unsigned)
|
||||
out.signed_len = MOTA_SIGNED_LEN; // signature always covers manifest[0, 129)
|
||||
out.signature = r.take(64); // always present (zero when unsigned)
|
||||
out.approval = r.take(4);
|
||||
if (!r.ok) return false;
|
||||
if (out.block_size_log2 == 0 || out.block_size_log2 > 24 || out.payload_size == 0) return false;
|
||||
out.block_count = (out.payload_size + out.block_size() - 1) / out.block_size();
|
||||
// block_idx is uint16 on the wire; capping here also keeps block_count*4 (leaves length) from overflowing.
|
||||
return out.block_count != 0 && out.block_count <= 0xFFFFu;
|
||||
}
|
||||
|
||||
bool mota_parse(const uint8_t* buf, uint32_t len, MotaManifest& out) {
|
||||
out = MotaManifest();
|
||||
if (len < 4 + 4 + 5) return false;
|
||||
if (memcmp(buf, MOTA_MAGIC, 4) != 0) return false;
|
||||
if (memcmp(buf + len - 5, MOTA_TRAILER, 5) != 0) return false;
|
||||
if (rd_u32le(buf + 4) != len) return false; // MOTA_TOTAL_SIZE must equal the actual length
|
||||
|
||||
ByteReader r(buf, len - 5); // everything up to (not incl.) the trailer
|
||||
r.skip(4 + 4); // MAGIC + MOTA_TOTAL_SIZE (already validated)
|
||||
out.manifest_start = buf + 8;
|
||||
if (!parse_manifest_fields(r, out)) return false;
|
||||
out.leaves = r.take(out.block_count * 4);
|
||||
out.payload = r.take(out.payload_size);
|
||||
if (!r.ok) return false;
|
||||
return r.pos() == len - 5; // payload must end exactly at the trailer
|
||||
}
|
||||
|
||||
bool mota_parse_manifest(const uint8_t* mf, uint32_t len, MotaManifest& out) {
|
||||
out = MotaManifest();
|
||||
out.manifest_start = mf;
|
||||
ByteReader r(mf, len); // a standalone manifest = container bytes [8, leaves)
|
||||
return parse_manifest_fields(r, out);
|
||||
}
|
||||
|
||||
bool mota_check_root(const MotaManifest& m) {
|
||||
if (!m.leaves || m.block_count == 0) return false;
|
||||
uint8_t root[4];
|
||||
merkle_root(root, m.leaves, m.block_count);
|
||||
return memcmp(root, m.merkle_root, 4) == 0;
|
||||
}
|
||||
|
||||
bool mota_check_image_hash_full(const MotaManifest& m) {
|
||||
if (!m.is_full() || !m.payload || !m.image_hash) return false;
|
||||
uint8_t h[32];
|
||||
mh32(h, m.payload, m.payload_size);
|
||||
return memcmp(h, m.image_hash, 32) == 0;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,64 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "OtaFormat.h"
|
||||
|
||||
// Parse/validate a `.mota` container that is fully present in a RAM buffer (docs/ota_protocol.md
|
||||
// §3-§4). Variable-length parts are referenced by pointer into the caller's buffer — no copies, no
|
||||
// allocation. (Device flash-backed staging gets a streaming variant in a later milestone; the field
|
||||
// layout here is the single source of truth.)
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
struct MotaManifest {
|
||||
uint8_t format_ver = 0;
|
||||
uint8_t flags = 0;
|
||||
uint8_t hash_algo = 0;
|
||||
uint32_t target_id = 0;
|
||||
uint32_t fw_version = 0;
|
||||
uint32_t image_size = 0;
|
||||
uint32_t payload_size = 0;
|
||||
uint8_t block_size_log2 = 0;
|
||||
uint8_t codec_id = 0;
|
||||
uint32_t block_count = 0;
|
||||
|
||||
// Fixed layout (docs/ota_protocol.md §4): every field below sits at a constant offset and is ALWAYS
|
||||
// present; base_hash/signer_pubkey/signature are zero-filled when not applicable (full / unsigned).
|
||||
const uint8_t* merkle_root = nullptr; // 4 @20
|
||||
const uint8_t* image_hash = nullptr; // 32 @24
|
||||
const uint8_t* hw_id = nullptr; // 32 @57 (NUL-padded ASCII hardware tag; signed)
|
||||
const uint8_t* base_hash = nullptr; // 8 @89 (zero for a full image)
|
||||
const uint8_t* signer_pubkey = nullptr; // 32 @97 (zero when unsigned)
|
||||
const uint8_t* signature = nullptr; // 64 @129 (zero when unsigned)
|
||||
const uint8_t* approval = nullptr; // 4 @193
|
||||
const uint8_t* leaves = nullptr; // 4 * block_count (the only variable-length field)
|
||||
const uint8_t* payload = nullptr; // payload_size
|
||||
const uint8_t* manifest_start = nullptr;// first manifest byte (== start of the signed region)
|
||||
uint32_t signed_len = 0; // = MOTA_SIGNED_LEN (129): bytes the signature covers
|
||||
|
||||
bool is_full() const { return flags & MFLAG_FULL; }
|
||||
bool is_signed() const { return flags & MFLAG_SIGNED; }
|
||||
uint32_t block_size() const { return 1u << block_size_log2; }
|
||||
bool is_approved() const;
|
||||
};
|
||||
|
||||
// Parse a whole container in `buf[len]`. Returns true on success and fills `out` with pointers into
|
||||
// `buf`. Validates MAGIC, TRAILER, MOTA_TOTAL_SIZE, format_ver, and internal length consistency.
|
||||
bool mota_parse(const uint8_t* buf, uint32_t len, MotaManifest& out);
|
||||
|
||||
// Parse a standalone manifest (the bytes [manifest_start, leaves) of a container, i.e. without the
|
||||
// MAGIC/TOTAL_SIZE framing, leaves[] or payload). Used by the apply path, which receives the manifest
|
||||
// separately from the image. Sets the fixed fields + signer/signature + signed_len; leaves/payload
|
||||
// are left null.
|
||||
bool mota_parse_manifest(const uint8_t* mf, uint32_t len, MotaManifest& out);
|
||||
|
||||
// Recompute the merkle root from the manifest's leaves[] and compare to the merkle_root field.
|
||||
bool mota_check_root(const MotaManifest& m);
|
||||
|
||||
// For FULL images only: check sha2-256:32(payload) == image_hash.
|
||||
bool mota_check_image_hash_full(const MotaManifest& m);
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,62 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
// Wire contract for the "mota-seeder" link: a device (CLIENT) pulls `.mota` bytes on demand from a host
|
||||
// daemon (SERVER) that owns a folder of `.mota` files. This is the FIRST concrete MotaSource transport
|
||||
// (docs/ota_protocol.md §9) — the device speaks it over a dedicated Stream (a spare UART / USB-UART), so
|
||||
// it never contends with the line-based text CLI on the main console.
|
||||
//
|
||||
// The device always initiates; every request gets exactly one response. Framing is resync-safe: the
|
||||
// reader scans for the 2-byte magic, so line noise / a half-read frame just times out and is retried
|
||||
// (OTA is lowest priority — eventually-upgradable). All multi-byte fields are little-endian.
|
||||
//
|
||||
// request (device -> host): 'M' 'S' op(1) args... xsum(1 = XOR of op+args)
|
||||
// response (host -> device): 'm' 's' op(1) status(1) payload... xsum(1 = XOR of all prior)
|
||||
//
|
||||
// OP_COUNT 0x01 args: - resp payload: count(1)
|
||||
// OP_DESCRIBE 0x02 args: idx(1) resp payload: MotaDesc wire (38 B, see below) [status OK]
|
||||
// OP_READ 0x03 args: idx(1) off(4) len(2) resp payload: len bytes [status OK]
|
||||
//
|
||||
// MotaDesc wire (38 B): mid[4] target_id(4) fw_version(4) codec(1) flags(1) total_size(4)
|
||||
// leaves_off(4) block_count(4) payload_off(4) payload_size(4)
|
||||
//
|
||||
// --- STORAGE ops (device -> host WRITE): "pull to folder". The device is fetching a `.mota` off the mesh
|
||||
// (e.g. a neighbour's self-served firmware it has no local copy of) and streams it into the host folder as
|
||||
// `<mid>.mota`, so the exact image can be captured for later delta-building. The device still initiates.
|
||||
// Resume needs NO host bookkeeping: OP_BEGIN 0xFF-fills the file and, on reconnect, the device OP_SREADs the
|
||||
// merkle leaves and re-requests only the missing blocks (identical to flash-resume). All keyed by mid[4].
|
||||
// OP_STAT 0x04 args: mid(4) resp payload: present(1) total_size(4)
|
||||
// OP_BEGIN 0x05 args: mid(4) total_size(4) resp: status OK (create/truncate, 0xFF-filled)
|
||||
// OP_WRITE 0x06 args: mid(4) off(4) len(2) data(len) resp: status OK
|
||||
// OP_SREAD 0x07 args: mid(4) off(4) len(2) resp payload: len bytes (0xFF = never written)
|
||||
// OP_FIN 0x08 args: mid(4) resp: status OK (validate + make servable)
|
||||
//
|
||||
// status: 0 = OK, non-zero = error (idx out of range, read past EOF, no such stored file, ...). On error the
|
||||
// response carries no payload (just magic+op+status+xsum).
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
static const uint8_t MOTA_SEEDER_REQ_MAGIC0 = 'M';
|
||||
static const uint8_t MOTA_SEEDER_REQ_MAGIC1 = 'S';
|
||||
static const uint8_t MOTA_SEEDER_RSP_MAGIC0 = 'm';
|
||||
static const uint8_t MOTA_SEEDER_RSP_MAGIC1 = 's';
|
||||
|
||||
static const uint8_t MS_OP_COUNT = 0x01;
|
||||
static const uint8_t MS_OP_DESCRIBE = 0x02;
|
||||
static const uint8_t MS_OP_READ = 0x03;
|
||||
static const uint8_t MS_OP_STAT = 0x04; // storage: does <mid>.mota exist on the host? + its size
|
||||
static const uint8_t MS_OP_BEGIN = 0x05; // storage: create/truncate <mid>.mota (0xFF-filled)
|
||||
static const uint8_t MS_OP_WRITE = 0x06; // storage: write bytes at offset
|
||||
static const uint8_t MS_OP_SREAD = 0x07; // storage: read bytes back (resume: recompute missing blocks)
|
||||
static const uint8_t MS_OP_FIN = 0x08; // storage: transfer complete — validate + make servable
|
||||
|
||||
static const uint8_t MS_STATUS_OK = 0x00;
|
||||
static const uint8_t MS_STATUS_ERR = 0x01;
|
||||
|
||||
static const uint16_t MOTA_DESC_WIRE = 38; // bytes of a MotaDesc on the wire (see layout above)
|
||||
static const uint16_t MOTA_SEEDER_WRITE_MAX = 512; // max data bytes per OP_WRITE/OP_SREAD (bounds frames)
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,96 @@
|
||||
#include "MotaSourceSerial.h"
|
||||
#include "MotaSeederProto.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
bool SerialMotaSource::readByteT(uint8_t& b) {
|
||||
uint32_t t0 = millis();
|
||||
while ((millis() - t0) < _to) {
|
||||
int c = _io.read();
|
||||
if (c >= 0) { b = (uint8_t)c; return true; }
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool SerialMotaSource::readExact(uint8_t* b, uint32_t n) {
|
||||
for (uint32_t i = 0; i < n; i++) if (!readByteT(b[i])) return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// One request/response transaction. Resync-safe: drains stale input, frames the request with an XOR
|
||||
// checksum, then scans for the response magic and validates op+status+checksum before delivering payload.
|
||||
bool SerialMotaSource::txn(uint8_t op, const uint8_t* args, uint8_t arglen,
|
||||
uint8_t* payload, uint32_t payload_len) {
|
||||
while (_io.read() >= 0) {} // drop any stale/partial bytes before a fresh request
|
||||
uint8_t xs = op;
|
||||
for (uint8_t i = 0; i < arglen; i++) xs ^= args[i];
|
||||
_io.write(MOTA_SEEDER_REQ_MAGIC0); _io.write(MOTA_SEEDER_REQ_MAGIC1);
|
||||
_io.write(op);
|
||||
if (arglen) _io.write(args, arglen);
|
||||
_io.write(xs);
|
||||
_io.flush();
|
||||
|
||||
// scan for response magic 'm' 's' (tolerate leading noise)
|
||||
uint32_t t0 = millis(); bool got = false;
|
||||
uint8_t prev = 0;
|
||||
while ((millis() - t0) < _to) {
|
||||
int c = _io.read();
|
||||
if (c < 0) continue;
|
||||
if (prev == MOTA_SEEDER_RSP_MAGIC0 && (uint8_t)c == MOTA_SEEDER_RSP_MAGIC1) { got = true; break; }
|
||||
prev = (uint8_t)c;
|
||||
}
|
||||
if (!got) return false;
|
||||
|
||||
uint8_t hdr[2];
|
||||
if (!readExact(hdr, 2)) return false; // op, status
|
||||
if (hdr[0] != op) return false;
|
||||
uint8_t rxs = (uint8_t)(MOTA_SEEDER_RSP_MAGIC0 ^ MOTA_SEEDER_RSP_MAGIC1) ^ hdr[0] ^ hdr[1];
|
||||
bool ok = (hdr[1] == MS_STATUS_OK);
|
||||
if (ok && payload_len) {
|
||||
if (!readExact(payload, payload_len)) return false;
|
||||
for (uint32_t i = 0; i < payload_len; i++) rxs ^= payload[i];
|
||||
}
|
||||
uint8_t xsum;
|
||||
if (!readByteT(xsum)) return false;
|
||||
if (xsum != rxs) return false; // corrupt frame -> caller retries
|
||||
return ok;
|
||||
}
|
||||
|
||||
uint8_t SerialMotaSource::count() {
|
||||
uint8_t n = 0;
|
||||
if (!txn(MS_OP_COUNT, nullptr, 0, &n, 1)) return 0;
|
||||
return n;
|
||||
}
|
||||
|
||||
bool SerialMotaSource::describe(uint8_t idx, MotaDesc& out) {
|
||||
uint8_t args[1] = { idx };
|
||||
uint8_t w[MOTA_DESC_WIRE];
|
||||
if (!txn(MS_OP_DESCRIBE, args, 1, w, MOTA_DESC_WIRE)) return false;
|
||||
memcpy(out.mid, w, 4);
|
||||
out.target_id = rd_u32le(w + 4);
|
||||
out.fw_version = rd_u32le(w + 8);
|
||||
out.codec_id = w[12];
|
||||
out.flags = w[13];
|
||||
out.total_size = rd_u32le(w + 14);
|
||||
out.leaves_off = rd_u32le(w + 18);
|
||||
out.block_count = rd_u32le(w + 22);
|
||||
out.payload_off = rd_u32le(w + 26);
|
||||
out.payload_size = rd_u32le(w + 30);
|
||||
// bytes [34,38) reserved (zero) — kept for forward compat without changing MOTA_DESC_WIRE
|
||||
return true;
|
||||
}
|
||||
|
||||
bool SerialMotaSource::read(uint8_t idx, uint32_t off, uint8_t* buf, uint32_t len) {
|
||||
if (len > 0xFFFF) return false; // single transaction caps at 64 KB (a block is <=1 KB)
|
||||
uint8_t args[7];
|
||||
args[0] = idx;
|
||||
wr_u32le(args + 1, off);
|
||||
args[5] = (uint8_t)(len & 0xFF); args[6] = (uint8_t)(len >> 8);
|
||||
return txn(MS_OP_READ, args, 7, buf, len);
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,35 @@
|
||||
#pragma once
|
||||
|
||||
#include <Arduino.h>
|
||||
#include "OtaSource.h"
|
||||
|
||||
// A MotaSource backed by a host "mota-seeder" daemon over a dedicated Stream (a spare UART / USB-UART).
|
||||
// The device pulls catalog + bytes on demand (MotaSeederProto.h); the folder image is never held on the
|
||||
// device — it streams through. Use a stream that is NOT the text-CLI console so the binary framing never
|
||||
// collides with command/log text. Reads block on the Stream up to `timeout_ms` (OTA is lowest priority,
|
||||
// so a serial round-trip's latency is acceptable; keep the daemon on a fast link).
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
class SerialMotaSource : public MotaSource {
|
||||
public:
|
||||
explicit SerialMotaSource(Stream& io, uint32_t timeout_ms = 400) : _io(io), _to(timeout_ms) {}
|
||||
|
||||
uint8_t count() override;
|
||||
bool describe(uint8_t idx, MotaDesc& out) override;
|
||||
bool read(uint8_t idx, uint32_t off, uint8_t* buf, uint32_t len) override;
|
||||
|
||||
private:
|
||||
// Send a request (op+args) and read its response header; on OK, `payload` (if non-null) receives
|
||||
// `payload_len` bytes. Returns true iff a well-formed OK response for `op` arrived in time.
|
||||
bool txn(uint8_t op, const uint8_t* args, uint8_t arglen, uint8_t* payload, uint32_t payload_len);
|
||||
bool readByteT(uint8_t& b); // one byte within the timeout
|
||||
bool readExact(uint8_t* b, uint32_t n);
|
||||
|
||||
Stream& _io;
|
||||
uint32_t _to;
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "Utils.h" // mesh::Utils::sha256 (real on device; real host SHA-256 via test/mocks)
|
||||
#include "OtaFormat.h"
|
||||
|
||||
// Thin multihash helpers: SHA-256 truncated to N bytes. No state, no allocation.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
inline void sha256_trunc(uint8_t* out, size_t out_len, const uint8_t* data, size_t len) {
|
||||
mesh::Utils::sha256(out, out_len, data, (int)len);
|
||||
}
|
||||
|
||||
inline void sha256_trunc2(uint8_t* out, size_t out_len,
|
||||
const uint8_t* a, size_t a_len,
|
||||
const uint8_t* b, size_t b_len) {
|
||||
mesh::Utils::sha256(out, out_len, a, (int)a_len, b, (int)b_len);
|
||||
}
|
||||
|
||||
inline void mh4(uint8_t out[4], const uint8_t* data, size_t len) { sha256_trunc(out, 4, data, len); }
|
||||
inline void mh8(uint8_t out[8], const uint8_t* data, size_t len) { sha256_trunc(out, 8, data, len); }
|
||||
inline void mh32(uint8_t out[32], const uint8_t* data, size_t len){ sha256_trunc(out, 32, data, len); }
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,509 @@
|
||||
#include "OtaApply.h"
|
||||
#include "OtaFormat.h"
|
||||
#include "MotaContainer.h"
|
||||
#include "Identity.h"
|
||||
#include <string.h>
|
||||
|
||||
#if defined(ESP32_PLATFORM)
|
||||
#include <SHA256.h> // rweather streaming SHA-256 (for hashing the slot in chunks)
|
||||
#include "esp_ota_ops.h"
|
||||
#include "esp_partition.h"
|
||||
#include "esp_system.h"
|
||||
extern "C" {
|
||||
#include "detools/detools.h" // vendored detools 0.53.0 embeddable decoder (CRLE-only build)
|
||||
}
|
||||
#if defined(OTA_FLASH_STORE)
|
||||
#include "OtaStoreFlashEsp32.h" // flash-staged container (delta patch / full image in the slot)
|
||||
#include "OtaSelf.h" // SelfFwInfo / ota_self_firmware (running-image base_hash gate)
|
||||
#endif
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
#include "OtaVerify.h"
|
||||
#include "OtaSelf.h"
|
||||
#include "OtaFlashLayout_nrf52.h"
|
||||
#include "OtaBlInfo.h" // read the bootloader capability marker before arming an apply
|
||||
#include "flash/flash_nrf5x.h" // Adafruit core internal-flash driver (has its own extern "C")
|
||||
#include "nrf.h"
|
||||
#include "nrf_soc.h"
|
||||
#include "nrf_sdm.h"
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
#if defined(ESP32_PLATFORM)
|
||||
|
||||
bool ota_apply_slot_info(uint32_t* addr, uint32_t* size) {
|
||||
const esp_partition_t* p = esp_ota_get_next_update_partition(nullptr);
|
||||
if (!p) return false;
|
||||
if (addr) *addr = p->address;
|
||||
if (size) *size = p->size;
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ota_apply_set_manifest(const uint8_t* mf, uint32_t len, const SignerAllowlist& allow, ApplyState& st) {
|
||||
st = ApplyState();
|
||||
ota_apply_slot_info(&st.slot_addr, &st.slot_size);
|
||||
MotaManifest m;
|
||||
if (!mota_parse_manifest(mf, len, m)) return false;
|
||||
if (!m.is_full()) return false; // A/B apply takes a full image (delta would need decode)
|
||||
st.image_size = m.image_size;
|
||||
memcpy(st.image_hash, m.image_hash, 32);
|
||||
st.manifest_ok = true;
|
||||
if (m.is_signed()) {
|
||||
mesh::Identity signer(m.signer_pubkey);
|
||||
st.sig_ok = signer.verify(m.signature, m.manifest_start, (int)m.signed_len);
|
||||
st.trusted = st.sig_ok && allow.contains(m.signer_pubkey);
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool ota_apply_verify_slot(ApplyState& st) {
|
||||
st.slot_ok = false;
|
||||
if (!st.manifest_ok || st.image_size == 0 || st.image_size > st.slot_size) return false;
|
||||
const esp_partition_t* p = esp_ota_get_next_update_partition(nullptr);
|
||||
if (!p) return false;
|
||||
SHA256 sha;
|
||||
uint8_t buf[512];
|
||||
uint32_t off = 0;
|
||||
while (off < st.image_size) {
|
||||
uint32_t n = st.image_size - off; if (n > sizeof(buf)) n = sizeof(buf);
|
||||
if (esp_partition_read(p, off, buf, n) != ESP_OK) return false;
|
||||
sha.update(buf, n);
|
||||
off += n;
|
||||
}
|
||||
uint8_t h[32];
|
||||
sha.finalize(h, 32);
|
||||
st.slot_ok = (memcmp(h, st.image_hash, 32) == 0);
|
||||
return st.slot_ok;
|
||||
}
|
||||
|
||||
bool ota_apply_commit() {
|
||||
const esp_partition_t* p = esp_ota_get_next_update_partition(nullptr);
|
||||
if (!p) return false;
|
||||
if (esp_ota_set_boot_partition(p) != ESP_OK) return false;
|
||||
esp_restart(); // does not return
|
||||
return true;
|
||||
}
|
||||
|
||||
// --- detools callback context -----------------------------------------------------------------
|
||||
// The delta base is the running OTA slot; the reconstructed image is streamed into the inactive slot
|
||||
// via esp_ota_write (sequential, append-only -- matches detools' sequential output ordering) and
|
||||
// hashed on the fly so we can check it against the signed manifest image_hash before arming.
|
||||
struct DetoolsCtx {
|
||||
const esp_partition_t* base; // delta base (running image), read at absolute `from_pos`
|
||||
long from_pos; // absolute byte offset into `base`
|
||||
#if defined(OTA_FLASH_STORE)
|
||||
OtaStoreFlashEsp32* store; // staged container; patch = payload region [patch_base, +patch_len)
|
||||
uint32_t patch_base; // container offset where the payload (patch) begins
|
||||
#else
|
||||
const uint8_t* patch; // .mota payload held wholly in RAM (RAM store; bring-up/host)
|
||||
#endif
|
||||
uint32_t patch_len;
|
||||
uint32_t patch_pos;
|
||||
esp_ota_handle_t out; // inactive slot write handle
|
||||
SHA256* sha; // running hash of the reconstructed output
|
||||
uint32_t out_pos; // #bytes written to the output slot
|
||||
bool io_ok;
|
||||
};
|
||||
|
||||
static int dt_from_read(void* arg, uint8_t* buf, size_t size) {
|
||||
DetoolsCtx* c = (DetoolsCtx*)arg;
|
||||
if (c->from_pos < 0 || (uint32_t)(c->from_pos) + size > c->base->size) return -DETOOLS_IO_FAILED;
|
||||
if (esp_partition_read(c->base, (size_t)c->from_pos, buf, size) != ESP_OK) { c->io_ok = false; return -DETOOLS_IO_FAILED; }
|
||||
c->from_pos += (long)size;
|
||||
return DETOOLS_OK;
|
||||
}
|
||||
static int dt_from_seek(void* arg, int offset) { // detools uses relative seeks
|
||||
DetoolsCtx* c = (DetoolsCtx*)arg;
|
||||
c->from_pos += offset;
|
||||
if (c->from_pos < 0 || (uint32_t)c->from_pos > c->base->size) return -DETOOLS_IO_FAILED;
|
||||
return DETOOLS_OK;
|
||||
}
|
||||
static int dt_patch_read(void* arg, uint8_t* buf, size_t size) {
|
||||
DetoolsCtx* c = (DetoolsCtx*)arg;
|
||||
if (c->patch_pos + size > c->patch_len) return -DETOOLS_IO_FAILED;
|
||||
#if defined(OTA_FLASH_STORE)
|
||||
if (!c->store->read(c->patch_base + c->patch_pos, buf, size)) { c->io_ok = false; return -DETOOLS_IO_FAILED; }
|
||||
#else
|
||||
memcpy(buf, c->patch + c->patch_pos, size);
|
||||
#endif
|
||||
c->patch_pos += (uint32_t)size;
|
||||
return DETOOLS_OK;
|
||||
}
|
||||
static int dt_to_write(void* arg, const uint8_t* buf, size_t size) {
|
||||
DetoolsCtx* c = (DetoolsCtx*)arg;
|
||||
if (esp_ota_write(c->out, buf, size) != ESP_OK) { c->io_ok = false; return -DETOOLS_IO_FAILED; }
|
||||
c->sha->update(buf, size);
|
||||
c->out_pos += (uint32_t)size;
|
||||
return DETOOLS_OK;
|
||||
}
|
||||
|
||||
#if defined(OTA_FLASH_STORE)
|
||||
// --- in-place delta on ESP32 (codec 2) ----------------------------------------------------------
|
||||
// A single in-place `.mota` can target BOTH nRF52 (bootloader applies it) and ESP32. On ESP32 the
|
||||
// inactive slot is used as the in-place working memory: we copy the running image (the base) into the
|
||||
// slot's bottom-staged-container-FREE region [0, write_start), then run detools' in-place decoder over
|
||||
// that region (it reads the base, erases segments, writes the target back), reading the patch from the
|
||||
// staged container's payload (which lives at/below write_start, disjoint from the working region). The
|
||||
// decoded image is hashed against the signed image_hash BEFORE arming, so a bad decode never boots; the
|
||||
// callbacks are bounded to [0, write_start) so they fail gracefully instead of touching the patch.
|
||||
// (Sequential is still preferred on ESP32 — it streams straight to the slot with no base-copy; in-place
|
||||
// exists only for single-artifact distribution. Requires the patch built with --inplace-segment 4096.)
|
||||
struct InPlaceCtx {
|
||||
const esp_partition_t* slot; // in-place working memory = slot[0, mem_max)
|
||||
uint32_t mem_max; // = container write_start; accesses beyond this are refused
|
||||
OtaStoreFlashEsp32* store; // staged container; patch = payload region [patch_base, +patch_len)
|
||||
uint32_t patch_base, patch_len, patch_pos;
|
||||
int step; // detools resume cursor (RAM; no cross-reboot resume of the apply)
|
||||
bool io_ok;
|
||||
const char* fail; // first failure point (diagnostic), nullptr until set
|
||||
uint32_t fa, fn; int frc; // failing addr / len / esp_err
|
||||
};
|
||||
static inline int ip_fail(InPlaceCtx* c, const char* w, uint32_t a, size_t n, int rc) {
|
||||
if (!c->fail) { c->fail = w; c->fa = a; c->fn = (uint32_t)n; c->frc = rc; }
|
||||
c->io_ok = false; return -DETOOLS_IO_FAILED;
|
||||
}
|
||||
static int ip_mem_read(void* a, void* dst, uintptr_t src, size_t n) {
|
||||
InPlaceCtx* c = (InPlaceCtx*)a;
|
||||
if ((uint32_t)src + n > c->mem_max) return ip_fail(c, "rd>max", (uint32_t)src, n, 0);
|
||||
int rc = esp_partition_read(c->slot, (size_t)src, dst, n);
|
||||
if (rc != ESP_OK) return ip_fail(c, "rd", (uint32_t)src, n, rc);
|
||||
return DETOOLS_OK;
|
||||
}
|
||||
static int ip_mem_write(void* a, uintptr_t dst, void* src, size_t n) {
|
||||
InPlaceCtx* c = (InPlaceCtx*)a;
|
||||
if ((uint32_t)dst + n > c->mem_max) return ip_fail(c, "wr>max", (uint32_t)dst, n, 0);
|
||||
int rc = esp_partition_write(c->slot, (size_t)dst, src, n);
|
||||
if (rc != ESP_OK) return ip_fail(c, "wr", (uint32_t)dst, n, rc);
|
||||
return DETOOLS_OK;
|
||||
}
|
||||
static int ip_mem_erase(void* a, uintptr_t addr, size_t n) {
|
||||
InPlaceCtx* c = (InPlaceCtx*)a;
|
||||
// esp_partition_erase_range requires a SECTOR-aligned size; detools' final in-place segment is partial
|
||||
// (the image tail past the last full sector). addr is sector-aligned (== --inplace-segment), so round
|
||||
// the length UP to a full sector. The over-erased bytes are scratch beyond image_size (never hashed),
|
||||
// and — since detools processes high→low and erases-before-writing — they are never live patch data.
|
||||
const uint32_t SEC = 4096;
|
||||
if ((uint32_t)addr % SEC != 0) return ip_fail(c, "er!align", (uint32_t)addr, n, 0);
|
||||
uint32_t len = ((uint32_t)n + SEC - 1) & ~(SEC - 1);
|
||||
if ((uint32_t)addr + len > c->mem_max) return ip_fail(c, "er>max", (uint32_t)addr, len, 0);
|
||||
int rc = esp_partition_erase_range(c->slot, (size_t)addr, len);
|
||||
if (rc != ESP_OK) return ip_fail(c, "er", (uint32_t)addr, len, rc);
|
||||
return DETOOLS_OK;
|
||||
}
|
||||
static int ip_step_set(void* a, int s) { ((InPlaceCtx*)a)->step = s; return DETOOLS_OK; }
|
||||
static int ip_step_get(void* a, int* s) { *s = ((InPlaceCtx*)a)->step; return DETOOLS_OK; }
|
||||
static int ip_patch_read(void* a, uint8_t* b, size_t n) {
|
||||
InPlaceCtx* c = (InPlaceCtx*)a;
|
||||
if (c->patch_pos + n > c->patch_len) return ip_fail(c, "patch>len", c->patch_pos, n, 0);
|
||||
if (!c->store->read(c->patch_base + c->patch_pos, b, n)) return ip_fail(c, "patch_rd", c->patch_pos, n, 0);
|
||||
c->patch_pos += (uint32_t)n;
|
||||
return DETOOLS_OK;
|
||||
}
|
||||
|
||||
static bool esp32_inplace_apply(OtaStoreFlashEsp32& store, const MotaManifest& m, ApplyState& st, char* msg) {
|
||||
const esp_partition_t* slot = store.partition();
|
||||
const esp_partition_t* base = esp_ota_get_running_partition();
|
||||
if (!slot || !base) { strcpy(msg, "no slot/base partition"); return false; }
|
||||
SelfFwInfo fi;
|
||||
if (!ota_self_firmware(fi) || !fi.valid) { strcpy(msg, "cannot read running firmware (no EndF)"); return false; }
|
||||
if (!m.base_hash || memcmp(m.base_hash, fi.body_hash, 8) != 0) { strcpy(msg, "not built for the running firmware (base mismatch)"); return false; }
|
||||
uint32_t mem_max = store.write_start(); // working region [0, mem_max); the patch sits at/above it
|
||||
if (mem_max == 0) { strcpy(msg, "in-place needs a bottom-staged container"); return false; }
|
||||
if (fi.image_len > mem_max || m.image_size > mem_max) { strcpy(msg, "in-place region too small for base/image"); return false; }
|
||||
|
||||
// load the base (running image) into the working region [0, base_len), sector by sector (erase + copy)
|
||||
uint8_t buf[512];
|
||||
for (uint32_t off = 0; off < fi.image_len; ) {
|
||||
uint32_t sec = off & ~(4096u - 1);
|
||||
if (esp_partition_erase_range(slot, sec, 4096) != ESP_OK) { strcpy(msg, "base erase failed"); return false; }
|
||||
uint32_t secend = sec + 4096; if (secend > fi.image_len) secend = fi.image_len;
|
||||
for (uint32_t p = (off > sec ? off : sec); p < secend; ) {
|
||||
uint32_t n = secend - p; if (n > sizeof(buf)) n = sizeof(buf);
|
||||
if (esp_partition_read(base, p, buf, n) != ESP_OK || esp_partition_write(slot, p, buf, n) != ESP_OK) {
|
||||
strcpy(msg, "base copy failed"); return false; }
|
||||
p += n;
|
||||
}
|
||||
off = secend;
|
||||
}
|
||||
|
||||
// patch in place over the working region; patch streamed from the staged container payload
|
||||
InPlaceCtx c;
|
||||
c.slot = slot; c.mem_max = mem_max; c.store = &store;
|
||||
c.patch_base = store.meta_bytes(); c.patch_len = m.payload_size; c.patch_pos = 0; c.step = 0; c.io_ok = true;
|
||||
c.fail = nullptr; c.fa = c.fn = 0; c.frc = 0;
|
||||
int r = detools_apply_patch_in_place_callbacks(ip_mem_read, ip_mem_write, ip_mem_erase,
|
||||
ip_step_set, ip_step_get, ip_patch_read,
|
||||
(size_t)m.payload_size, &c);
|
||||
if (r < 0 || !c.io_ok) {
|
||||
if (c.fail) sprintf(msg, "in-place decode err %d @%s a=%u n=%u rc=%d max=%u", r, c.fail,
|
||||
(unsigned)c.fa, (unsigned)c.fn, c.frc, (unsigned)mem_max);
|
||||
else sprintf(msg, "in-place decode err %d", r);
|
||||
return false;
|
||||
}
|
||||
if ((uint32_t)r != m.image_size) { sprintf(msg, "in-place size %u!=%u", (unsigned)r, (unsigned)m.image_size); return false; }
|
||||
|
||||
// verify the decoded slot image against the signed image_hash BEFORE arming (mismatch -> never boots)
|
||||
SHA256 sha;
|
||||
for (uint32_t off = 0; off < m.image_size; ) {
|
||||
uint32_t n = m.image_size - off; if (n > sizeof(buf)) n = sizeof(buf);
|
||||
if (esp_partition_read(slot, off, buf, n) != ESP_OK) { strcpy(msg, "slot read failed"); return false; }
|
||||
sha.update(buf, n); off += n;
|
||||
}
|
||||
uint8_t hh[32]; sha.finalize(hh, 32);
|
||||
st.slot_ok = (memcmp(hh, m.image_hash, 32) == 0);
|
||||
if (!st.slot_ok) { strcpy(msg, "image_hash MISMATCH after in-place decode"); return false; }
|
||||
if (esp_ota_set_boot_partition(slot) != ESP_OK) { strcpy(msg, "set_boot failed"); return false; }
|
||||
sprintf(msg, "verified%s; in-place decoded %u B, image hash OK — armed, rebooting to apply",
|
||||
m.is_signed() ? " (signer trusted)" : " (unsigned)", (unsigned)m.image_size);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Apply the `.mota` staged in the inactive slot by OtaStoreFlashEsp32 (no contiguous RAM copy).
|
||||
// FULL: the payload was streamed straight to slot offset 0 during the fetch -> hash the slot image
|
||||
// and compare to the signed image_hash, then arm. No decode, no copy.
|
||||
// DELTA (sequential): base = the running slot; the patch is read from the staged payload region (the
|
||||
// slot's bottom); the reconstructed image is written to the inactive slot via esp_ota_write and
|
||||
// hashed vs image_hash. esp_ota_begin only erases [0, image_size], which the fetch-time fit
|
||||
// check kept below the bottom-staged container, so the patch survives while we decode over it.
|
||||
// DELTA (in-place): copy the running image into the slot's working region then patch in place
|
||||
// (esp32_inplace_apply); image_hash-gated before arming. Lets one in-place .mota target both
|
||||
// ESP32 and nRF52. Sequential is still preferred on ESP32 (no base-copy).
|
||||
// The result is verified (signature/trust up front, image_hash after) and the slot armed; the caller
|
||||
// reboots once the confirmation reply has gone out.
|
||||
bool ota_apply_detools_mota(OtaStoreFlashEsp32& store, const SignerAllowlist& allow, ApplyState& st, char* msg) {
|
||||
st = ApplyState();
|
||||
const esp_partition_t* slot = store.partition();
|
||||
if (!slot || store.staged_size() < 16) { strcpy(msg, "no staged update"); return false; }
|
||||
st.slot_addr = slot->address; st.slot_size = slot->size;
|
||||
|
||||
// read + parse the manifest out of the staged container (header = MAGIC(4) + total(4))
|
||||
uint8_t hdr[8];
|
||||
if (!store.read(0, hdr, 8) || memcmp(hdr, MOTA_MAGIC, 4) != 0) { strcpy(msg, "bad container"); return false; }
|
||||
uint8_t mfbuf[256];
|
||||
uint32_t mflen = store.meta_bytes() > 8 ? store.meta_bytes() - 8 : 0; // manifest+leaves; cap to mfbuf
|
||||
if (mflen > sizeof(mfbuf)) mflen = sizeof(mfbuf);
|
||||
MotaManifest m;
|
||||
if (mflen < 57 || !store.read(8, mfbuf, mflen) || !mota_parse_manifest(mfbuf, mflen, m)) {
|
||||
strcpy(msg, "manifest parse failed"); return false; }
|
||||
st.image_size = m.image_size; memcpy(st.image_hash, m.image_hash, 32); st.manifest_ok = true;
|
||||
if (m.image_size == 0 || m.image_size > slot->size) { strcpy(msg, "image > slot"); return false; }
|
||||
|
||||
// signature / trust BEFORE arming an untrusted image (image_hash below is the target-firmware gate)
|
||||
if (m.is_signed()) {
|
||||
mesh::Identity signer(m.signer_pubkey);
|
||||
st.sig_ok = signer.verify(m.signature, m.manifest_start, (int)m.signed_len);
|
||||
st.trusted = st.sig_ok && allow.contains(m.signer_pubkey);
|
||||
if (!st.sig_ok) { strcpy(msg, "bad signature"); return false; }
|
||||
if (!st.trusted) { strcpy(msg, "untrusted signer (pubkey not in allowlist)"); return false; }
|
||||
}
|
||||
|
||||
// ---- FULL: payload already in slot[0]; verify hash + arm ----
|
||||
if (m.is_full()) {
|
||||
SHA256 sha; uint8_t buf[512];
|
||||
for (uint32_t off = 0; off < m.image_size; ) {
|
||||
uint32_t n = m.image_size - off; if (n > sizeof(buf)) n = sizeof(buf);
|
||||
if (esp_partition_read(slot, off, buf, n) != ESP_OK) { strcpy(msg, "slot read failed"); return false; }
|
||||
sha.update(buf, n); off += n;
|
||||
}
|
||||
uint8_t hh[32]; sha.finalize(hh, 32);
|
||||
st.slot_ok = (memcmp(hh, m.image_hash, 32) == 0);
|
||||
if (!st.slot_ok) { strcpy(msg, "image_hash MISMATCH (slot)"); return false; }
|
||||
if (esp_ota_set_boot_partition(slot) != ESP_OK) { strcpy(msg, "set_boot failed"); return false; }
|
||||
sprintf(msg, "verified%s full image %u B in slot — armed, rebooting to apply",
|
||||
m.is_signed() ? " (trusted)" : " (unsigned)", (unsigned)m.image_size);
|
||||
return true;
|
||||
}
|
||||
|
||||
// ---- DELTA ----
|
||||
if (m.codec_id == CODEC_DETOOLS_INPLACE) return esp32_inplace_apply(store, m, st, msg); // single-artifact codec
|
||||
if (m.codec_id != CODEC_DETOOLS_SEQUENTIAL) { strcpy(msg, "unknown delta codec"); return false; }
|
||||
|
||||
// delta must be built for the running firmware (cheap early gate; image_hash is the definitive check)
|
||||
if (m.base_hash) {
|
||||
SelfFwInfo fi;
|
||||
if (!ota_self_firmware(fi) || !fi.valid) { strcpy(msg, "cannot read running firmware (no EndF)"); return false; }
|
||||
if (memcmp(m.base_hash, fi.body_hash, 8) != 0) { strcpy(msg, "delta not built for the running firmware (base mismatch)"); return false; }
|
||||
}
|
||||
|
||||
const esp_partition_t* base = esp_ota_get_running_partition();
|
||||
if (!base) { strcpy(msg, "no running partition"); return false; }
|
||||
esp_ota_handle_t h;
|
||||
if (esp_ota_begin(slot, m.image_size, &h) != ESP_OK) { strcpy(msg, "ota_begin failed"); return false; }
|
||||
|
||||
SHA256 sha;
|
||||
DetoolsCtx ctx;
|
||||
ctx.base = base; ctx.from_pos = 0;
|
||||
ctx.store = &store; ctx.patch_base = store.meta_bytes(); ctx.patch_len = m.payload_size; ctx.patch_pos = 0;
|
||||
ctx.out = h; ctx.sha = &sha; ctx.out_pos = 0; ctx.io_ok = true;
|
||||
|
||||
int r = detools_apply_patch_callbacks(dt_from_read, dt_from_seek, dt_patch_read,
|
||||
(size_t)m.payload_size, dt_to_write, &ctx);
|
||||
if (r < 0 || !ctx.io_ok) { esp_ota_abort(h); sprintf(msg, "detools err %d @%u/%u",
|
||||
ctx.io_ok ? r : -DETOOLS_IO_FAILED, (unsigned)ctx.out_pos, (unsigned)m.image_size); return false; }
|
||||
if ((uint32_t)r != m.image_size || ctx.out_pos != m.image_size) {
|
||||
esp_ota_abort(h); sprintf(msg, "size mismatch %u!=%u", (unsigned)ctx.out_pos, (unsigned)m.image_size); return false; }
|
||||
uint8_t hh[32]; sha.finalize(hh, 32);
|
||||
st.slot_ok = (memcmp(hh, m.image_hash, 32) == 0);
|
||||
if (!st.slot_ok) { esp_ota_abort(h); strcpy(msg, "image_hash MISMATCH after decode"); return false; }
|
||||
if (esp_ota_end(h) != ESP_OK) { strcpy(msg, "ota_end failed"); return false; }
|
||||
if (esp_ota_set_boot_partition(slot) != ESP_OK) { strcpy(msg, "set_boot failed"); return false; }
|
||||
sprintf(msg, "verified%s; decoded %u B, image hash OK — armed, rebooting to apply",
|
||||
m.is_signed() ? " (signer trusted)" : " (unsigned)", (unsigned)m.image_size);
|
||||
return true;
|
||||
}
|
||||
|
||||
#else // !OTA_FLASH_STORE: RAM-staged apply (whole .mota in a contiguous RAM buffer; bring-up/host)
|
||||
|
||||
bool ota_apply_detools_mota(const uint8_t* buf, uint32_t len, const SignerAllowlist& allow,
|
||||
ApplyState& st, char* msg) {
|
||||
st = ApplyState();
|
||||
MotaManifest m;
|
||||
if (!mota_parse(buf, len, m)) { strcpy(msg, "no valid .mota (parse failed)"); return false; }
|
||||
if (m.is_full() || m.codec_id != CODEC_DETOOLS_SEQUENTIAL) { strcpy(msg, "not a detools-sequential delta"); return false; }
|
||||
st.image_size = m.image_size;
|
||||
memcpy(st.image_hash, m.image_hash, 32);
|
||||
st.manifest_ok = true;
|
||||
if (m.is_signed()) {
|
||||
mesh::Identity signer(m.signer_pubkey);
|
||||
st.sig_ok = signer.verify(m.signature, m.manifest_start, (int)m.signed_len);
|
||||
st.trusted = st.sig_ok && allow.contains(m.signer_pubkey);
|
||||
if (!st.sig_ok) { strcpy(msg, "bad signature"); return false; }
|
||||
if (!st.trusted) { strcpy(msg, "untrusted signer (pubkey not in allowlist)"); return false; }
|
||||
}
|
||||
const esp_partition_t* base = esp_ota_get_running_partition();
|
||||
const esp_partition_t* out = esp_ota_get_next_update_partition(nullptr);
|
||||
if (!base || !out) { strcpy(msg, "no A/B slot"); return false; }
|
||||
st.slot_addr = out->address; st.slot_size = out->size;
|
||||
if (m.image_size > out->size) { strcpy(msg, "image > slot"); return false; }
|
||||
esp_ota_handle_t h;
|
||||
if (esp_ota_begin(out, m.image_size, &h) != ESP_OK) { strcpy(msg, "ota_begin failed"); return false; }
|
||||
SHA256 sha;
|
||||
DetoolsCtx ctx;
|
||||
ctx.base = base; ctx.from_pos = 0;
|
||||
ctx.patch = m.payload; ctx.patch_len = m.payload_size; ctx.patch_pos = 0;
|
||||
ctx.out = h; ctx.sha = &sha; ctx.out_pos = 0; ctx.io_ok = true;
|
||||
int r = detools_apply_patch_callbacks(dt_from_read, dt_from_seek, dt_patch_read,
|
||||
(size_t)m.payload_size, dt_to_write, &ctx);
|
||||
if (r < 0 || !ctx.io_ok) { esp_ota_abort(h); sprintf(msg, "detools err %d @%u/%u",
|
||||
ctx.io_ok ? r : -DETOOLS_IO_FAILED, (unsigned)ctx.out_pos, (unsigned)m.image_size); return false; }
|
||||
if ((uint32_t)r != m.image_size || ctx.out_pos != m.image_size) {
|
||||
esp_ota_abort(h); sprintf(msg, "size mismatch %u!=%u", (unsigned)ctx.out_pos, (unsigned)m.image_size); return false; }
|
||||
uint8_t hh[32]; sha.finalize(hh, 32);
|
||||
st.slot_ok = (memcmp(hh, m.image_hash, 32) == 0);
|
||||
if (!st.slot_ok) { esp_ota_abort(h); strcpy(msg, "image_hash MISMATCH after decode"); return false; }
|
||||
if (esp_ota_end(h) != ESP_OK) { strcpy(msg, "ota_end failed"); return false; }
|
||||
if (esp_ota_set_boot_partition(out) != ESP_OK) { strcpy(msg, "set_boot failed"); return false; }
|
||||
sprintf(msg, "verified%s; decoded %u B, image hash OK — armed, rebooting to apply",
|
||||
m.is_signed() ? " (signer trusted)" : " (unsigned)", (unsigned)m.image_size);
|
||||
return true;
|
||||
}
|
||||
#endif // OTA_FLASH_STORE
|
||||
|
||||
bool ota_apply_mota_nrf52(const uint8_t*, uint32_t, const SignerAllowlist&, ApplyState& st, char* msg) {
|
||||
st = ApplyState(); strcpy(msg, "nRF52-only (ESP32 uses ota_apply_detools_mota)"); return false;
|
||||
}
|
||||
|
||||
void ota_reboot_to_apply() { esp_restart(); } // boots the slot armed by ota_apply_detools_mota; no return
|
||||
|
||||
#elif defined(NRF52_PLATFORM) // single-slot: verify + mark APPROVED + hand off to the bootloader
|
||||
|
||||
// ESP32 A/B-only entry points are unsupported on nRF52.
|
||||
bool ota_apply_slot_info(uint32_t*, uint32_t*) { return false; }
|
||||
bool ota_apply_set_manifest(const uint8_t*, uint32_t, const SignerAllowlist&, ApplyState& st) { st = ApplyState(); return false; }
|
||||
bool ota_apply_verify_slot(ApplyState&) { return false; }
|
||||
bool ota_apply_commit() { return false; }
|
||||
bool ota_apply_detools_mota(const uint8_t*, uint32_t, const SignerAllowlist&, ApplyState& st, char* msg) { st = ApplyState(); strcpy(msg, "use ota_apply_mota_nrf52"); return false; }
|
||||
|
||||
void ota_reboot_to_apply() { // public: set the apply magic + reset (does not return)
|
||||
uint8_t sd_en = 0;
|
||||
sd_softdevice_is_enabled(&sd_en);
|
||||
if (sd_en) { // POWER is SD-restricted while the SoftDevice runs
|
||||
sd_power_gpregret_clr(0, 0xFFFFFFFF);
|
||||
sd_power_gpregret_set(0, GPREGRET_OTA_APPLY);
|
||||
} else {
|
||||
NRF_POWER->GPREGRET = GPREGRET_OTA_APPLY;
|
||||
}
|
||||
NVIC_SystemReset(); // does not return
|
||||
}
|
||||
|
||||
uint8_t ota_bootloader_last_rc() { // bootloader's last in-place-apply code, stashed in GPREGRET2
|
||||
uint32_t v = 0;
|
||||
uint8_t en = 0; sd_softdevice_is_enabled(&en);
|
||||
if (en) sd_power_gpregret_get(1, &v); else v = NRF_POWER->GPREGRET2;
|
||||
return (uint8_t)v;
|
||||
}
|
||||
|
||||
bool ota_apply_mota_nrf52(const uint8_t* buf, uint32_t len, const SignerAllowlist& allow,
|
||||
ApplyState& st, char* msg) {
|
||||
st = ApplyState();
|
||||
MotaManifest m;
|
||||
if (!mota_parse(buf, len, m)) { strcpy(msg, "parse failed"); return false; }
|
||||
if (m.is_full() || m.codec_id != CODEC_DETOOLS_INPLACE) { strcpy(msg, "not an in-place delta"); return false; }
|
||||
st.image_size = m.image_size;
|
||||
memcpy(st.image_hash, m.image_hash, 32);
|
||||
st.manifest_ok = true;
|
||||
|
||||
// 0) THIS device's bootloader must be able to apply this .mota — otherwise staging + approving + rebooting
|
||||
// just bounces back unchanged (a legacy/stock/older-OTAFIX bootloader). Refuse here, before any reboot.
|
||||
{
|
||||
OtaBlCaps bl = ota_bootloader_caps();
|
||||
if (!bl.present) { strcpy(msg, "this bootloader has no OTA-apply support — update the bootloader first"); return false; }
|
||||
if (bl.apply_abi < m.format_ver || !(bl.codec_mask & (1u << m.codec_id))) {
|
||||
snprintf(msg, 159, "bootloader too old to apply this update (bl abi=%u codecs=0x%x; need fmt>=%u codec=%u) — update the bootloader",
|
||||
bl.apply_abi, bl.codec_mask, m.format_ver, m.codec_id);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
|
||||
// Gated verification, in order, returning the FIRST failing reason (the bootloader re-checks integrity
|
||||
// again before booting, so authenticity is gated here and re-validated there):
|
||||
VerifyResult vr = ota_verify(buf, len, allow);
|
||||
st.sig_ok = vr.sig_ok; st.trusted = vr.trusted;
|
||||
|
||||
// 1) downloaded payload: the fetched blocks must match the manifest's merkle root (intact + complete)
|
||||
if (!vr.root_ok || !vr.image_ok) { strcpy(msg, "payload hash mismatch (incomplete or corrupt .mota)"); return false; }
|
||||
|
||||
// 2) target firmware: the delta must be built against THIS running image (base_hash == our EndF body
|
||||
// hash). The resulting image_hash is re-checked by the bootloader after the in-place decode -- a
|
||||
// single-slot device cannot produce the target image to hash it before applying.
|
||||
SelfFwInfo fi;
|
||||
if (!ota_self_firmware(fi) || !fi.valid) { strcpy(msg, "cannot read running firmware (no EndF)"); return false; }
|
||||
if (!m.base_hash || memcmp(m.base_hash, fi.body_hash, 8) != 0) { strcpy(msg, "not built for the running firmware (base mismatch)"); return false; }
|
||||
st.slot_ok = true;
|
||||
|
||||
// 3) signature (only if the .mota is signed): valid Ed25519 AND signer in this device's allowlist
|
||||
if (vr.is_signed) {
|
||||
if (!vr.sig_ok) { strcpy(msg, "bad signature"); return false; }
|
||||
if (!vr.trusted) { strcpy(msg, "untrusted signer (pubkey not in allowlist)"); return false; }
|
||||
}
|
||||
|
||||
// mark the staged manifest APPROVED in flash (buf is the memory-mapped staging region, so
|
||||
// m.approval is a real flash address). NOR-clear over the erased 0xFFFFFFFF -> "APRV".
|
||||
uint32_t approval_addr = (uint32_t)(uintptr_t)m.approval;
|
||||
if (flash_nrf5x_write(approval_addr, APPROVAL_YES, 4) < 0) { strcpy(msg, "approval write failed"); return false; }
|
||||
flash_nrf5x_flush();
|
||||
if (memcmp((const void*)(uintptr_t)approval_addr, APPROVAL_YES, 4) != 0) { strcpy(msg, "approval not set"); return false; }
|
||||
|
||||
// Approved. Do NOT reset here — return so the caller can deliver `msg` to the operator first; the
|
||||
// deferred ota_reboot_to_apply() (after the reply is sent) does the actual handoff to the bootloader.
|
||||
sprintf(msg, "verified%s; applying — rebooting into bootloader once this reply is sent",
|
||||
vr.is_signed ? " (signer trusted)" : " (unsigned)");
|
||||
return true;
|
||||
}
|
||||
|
||||
#else // native / other platforms
|
||||
|
||||
bool ota_apply_slot_info(uint32_t*, uint32_t*) { return false; }
|
||||
bool ota_apply_set_manifest(const uint8_t*, uint32_t, const SignerAllowlist&, ApplyState& st) { st = ApplyState(); return false; }
|
||||
bool ota_apply_verify_slot(ApplyState&) { return false; }
|
||||
bool ota_apply_commit() { return false; }
|
||||
bool ota_apply_detools_mota(const uint8_t*, uint32_t, const SignerAllowlist&, ApplyState& st, char* msg) { st = ApplyState(); strcpy(msg, "unsupported"); return false; }
|
||||
bool ota_apply_mota_nrf52(const uint8_t*, uint32_t, const SignerAllowlist&, ApplyState& st, char* msg) { st = ApplyState(); strcpy(msg, "unsupported"); return false; }
|
||||
void ota_reboot_to_apply() {}
|
||||
uint8_t ota_bootloader_last_rc() { return 0; }
|
||||
|
||||
#endif
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,66 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "SignerAllowlist.h"
|
||||
|
||||
// P6 apply (full-image, ESP32 A/B). The new image is delivered into the inactive OTA slot; the device
|
||||
// then verifies that slot against the signed manifest's image_hash (+ Ed25519/allowlist), and commits
|
||||
// by setting it as the boot partition and rebooting. Safe + rollback-capable (the bootloader validates
|
||||
// the image; a bad image rolls back). nRF52 apply is the bootloader-handoff path (separate). Functions
|
||||
// return false on platforms without an A/B OTA layout.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
struct ApplyState {
|
||||
bool manifest_ok = false;
|
||||
bool sig_ok = false;
|
||||
bool trusted = false; // signer in allowlist
|
||||
bool slot_ok = false; // inactive slot image hashes to manifest.image_hash
|
||||
uint32_t slot_addr = 0, slot_size = 0;
|
||||
uint32_t image_size = 0;
|
||||
uint8_t image_hash[32] = {0};
|
||||
};
|
||||
|
||||
bool ota_apply_slot_info(uint32_t* addr, uint32_t* size); // the inactive A/B slot
|
||||
bool ota_apply_set_manifest(const uint8_t* mf, uint32_t len,
|
||||
const SignerAllowlist& allow, ApplyState& st); // parse + verify signature
|
||||
bool ota_apply_verify_slot(ApplyState& st); // hash the slot vs image_hash
|
||||
bool ota_apply_commit(); // set-boot + reboot (no return)
|
||||
|
||||
// Apply an ESP32 A/B `.mota` (CODEC_DETOOLS_SEQUENTIAL delta or CODEC_FULL image) and arm the inactive
|
||||
// slot; the caller reboots after the confirmation reply. `msg` (>=80 bytes) receives a human-readable
|
||||
// result. With OTA_FLASH_STORE the container is staged in the inactive slot (no contiguous RAM copy): a
|
||||
// full payload is already in the slot (just verified), a sequential delta is decoded from the running
|
||||
// slot over the staged patch. Without OTA_FLASH_STORE (bring-up) the whole container is a RAM buffer.
|
||||
#if defined(ESP32_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
class OtaStoreFlashEsp32;
|
||||
bool ota_apply_detools_mota(OtaStoreFlashEsp32& store,
|
||||
const SignerAllowlist& allow, ApplyState& st, char* msg);
|
||||
#else
|
||||
bool ota_apply_detools_mota(const uint8_t* buf, uint32_t len,
|
||||
const SignerAllowlist& allow, ApplyState& st, char* msg);
|
||||
#endif
|
||||
|
||||
// nRF52 (RAK4631) single-slot apply. The running app can't rewrite itself, so it does NOT decode: it
|
||||
// runs the gated verification chain (payload hash -> built-for-this-firmware -> signature/trust) and,
|
||||
// only if all pass, marks the staged manifest APPROVED in flash. It does NOT reboot — so the caller can
|
||||
// first send the result back to the operator — the actual handoff is ota_reboot_to_apply() below.
|
||||
// Returns true (msg = "verified...") when approved, false (msg = the first failing gate) otherwise.
|
||||
bool ota_apply_mota_nrf52(const uint8_t* buf, uint32_t len,
|
||||
const SignerAllowlist& allow, ApplyState& st, char* msg);
|
||||
|
||||
// Commit the (already approved/armed) update and reboot into it — does NOT return. Call this only after
|
||||
// a successful ota_apply_* AND after the confirmation reply has been delivered, so the operator knows
|
||||
// the apply started (over LoRa the device then goes silent while the bootloader applies). nRF52: set
|
||||
// the GPREGRET apply magic + reset (the bootloader does the in-place decode + verify). ESP32: reboot
|
||||
// into the slot already armed by ota_apply_detools_mota.
|
||||
void ota_reboot_to_apply();
|
||||
|
||||
// DIAGNOSTIC (nRF52): the bootloader stashes its last in-place-apply bail/progress code in GPREGRET2 (see
|
||||
// ota_delta.c). Read it back so `ota status` can show why an apply didn't take. 0 / other platforms = n/a.
|
||||
uint8_t ota_bootloader_last_rc();
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,54 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
|
||||
// Read the bootloader's OTA capability marker so the app can decide, BEFORE staging+approving+rebooting,
|
||||
// whether THIS device's bootloader can actually apply a `.mota`. Without this the app would reboot into a
|
||||
// bootloader that silently can't apply (stock Adafruit, or an OLDER OTAFIX predating a `.mota` format
|
||||
// change) and the device would just come back up unchanged.
|
||||
//
|
||||
// Mirror of Adafruit_nRF52_Bootloader_OTAFIX/src/ota_bl_info.h — keep byte-identical.
|
||||
// nRF52 only (the bootloader flash is memory-mapped + readable by the app); a no-op elsewhere.
|
||||
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#include "OtaFlashLayout_nrf52.h"
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// 16-byte marker: magic[8] "MOTABLDR" + apply_abi(2) + codec_mask(2) + reserved(4).
|
||||
static const uint8_t OTA_BL_MAGIC[8] = { 'M','O','T','A','B','L','D','R' };
|
||||
|
||||
struct OtaBlCaps {
|
||||
bool present = false;
|
||||
uint16_t apply_abi = 0; // max .mota format_ver the bootloader can apply
|
||||
uint16_t codec_mask = 0; // bit i set => can apply codec_id i (in-place delta = bit 2)
|
||||
};
|
||||
|
||||
// Scan the bootloader flash region for the marker. Returns {present=false} if not found / non-nRF52.
|
||||
inline OtaBlCaps ota_bootloader_caps() {
|
||||
OtaBlCaps c;
|
||||
#if defined(NRF52_PLATFORM)
|
||||
const uint8_t* lo = (const uint8_t*)(uintptr_t)MOTA_NRF52_BL_START;
|
||||
const uint8_t* hi = (const uint8_t*)(uintptr_t)MOTA_NRF52_BL_END;
|
||||
for (const uint8_t* p = lo; p + 16 <= hi; p++) {
|
||||
if (p[0] != OTA_BL_MAGIC[0] || memcmp(p, OTA_BL_MAGIC, 8) != 0) continue;
|
||||
c.present = true;
|
||||
c.apply_abi = (uint16_t)(p[8] | ((uint16_t)p[9] << 8));
|
||||
c.codec_mask = (uint16_t)(p[10] | ((uint16_t)p[11] << 8));
|
||||
break;
|
||||
}
|
||||
#endif
|
||||
return c;
|
||||
}
|
||||
|
||||
// True if this device's bootloader can apply a .mota of the given format_ver + codec_id.
|
||||
inline bool ota_bootloader_can_apply(uint8_t format_ver, uint8_t codec_id) {
|
||||
OtaBlCaps c = ota_bootloader_caps();
|
||||
return c.present && c.apply_abi >= format_ver && (c.codec_mask & (1u << codec_id)) != 0;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,58 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
// A tiny bounds-checked little-endian cursor for reading the `.mota` container (docs/ota_protocol.md §3-§4)
|
||||
// in a self-documenting way: each field is read by name in order, instead of hand-computed byte offsets
|
||||
// (`p[0]`, `rd_u32(p+3)`, `p += 89`, `NEED(n)` ...). Any over-read flips `ok` false and yields zero/null, so
|
||||
// callers parse the whole struct then check `r.ok` once. 32-bit offsets (a container can be >64 KB; the
|
||||
// 16-byte LoRa wire messages keep their own uint16 cursor in OtaProtocol.cpp). No allocation; `take()`
|
||||
// returns a pointer INTO the caller's buffer (zero-copy), matching the manifest's by-pointer fields.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// Little-endian scalar read/write for RANDOM-access fields (a specific offset into a buffer, e.g. a wire
|
||||
// row or a fixed manifest slot). Sequential parsing should prefer the ByteReader cursor below. These
|
||||
// replace the per-file `rd_u32`/`wr_u32` helpers that were copy-pasted across the OTA sources.
|
||||
inline uint16_t rd_u16le(const uint8_t* p) { return (uint16_t)p[0] | ((uint16_t)p[1] << 8); }
|
||||
inline uint32_t rd_u32le(const uint8_t* p) {
|
||||
return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24);
|
||||
}
|
||||
inline void wr_u16le(uint8_t* p, uint16_t v) { p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); }
|
||||
inline void wr_u32le(uint8_t* p, uint32_t v) {
|
||||
p[0] = (uint8_t)v; p[1] = (uint8_t)(v >> 8); p[2] = (uint8_t)(v >> 16); p[3] = (uint8_t)(v >> 24);
|
||||
}
|
||||
|
||||
// Round to a multiple of `unit` (a power of two — a flash sector/page size). Names the `& ~(unit-1)`
|
||||
// idiom so flash-geometry math in the stores reads as intent (align down / align up).
|
||||
inline uint32_t align_down(uint32_t x, uint32_t unit) { return x & ~(unit - 1); }
|
||||
inline uint32_t align_up(uint32_t x, uint32_t unit) { return (x + unit - 1) & ~(unit - 1); }
|
||||
|
||||
struct ByteReader {
|
||||
const uint8_t* p;
|
||||
uint32_t len;
|
||||
uint32_t n = 0;
|
||||
bool ok = true;
|
||||
|
||||
ByteReader(const uint8_t* buf, uint32_t length) : p(buf), len(length) {}
|
||||
|
||||
uint32_t pos() const { return n; }
|
||||
bool fits(uint32_t k) const { return ok && (uint64_t)n + k <= len; }
|
||||
|
||||
uint8_t u8() { if (!fits(1)) { ok = false; return 0; } return p[n++]; }
|
||||
uint32_t u32() { // little-endian
|
||||
if (!fits(4)) { ok = false; return 0; }
|
||||
uint32_t v = rd_u32le(p + n); n += 4; return v;
|
||||
}
|
||||
// Borrow `k` bytes at the cursor (e.g. merkle_root[4], leaves[4*BC]) and advance; null on overflow.
|
||||
const uint8_t* take(uint32_t k) {
|
||||
if (!fits(k)) { ok = false; return nullptr; }
|
||||
const uint8_t* r = p + n; n += k; return r;
|
||||
}
|
||||
void skip(uint32_t k) { if (!fits(k)) { ok = false; return; } n += k; }
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,495 @@
|
||||
#include "OtaCli.h"
|
||||
#include "OtaContext.h"
|
||||
#include "FolderMotaStore.h" // `ota pull <#> folder` destination (set_mid on the connected folder store)
|
||||
#include "OtaVerify.h"
|
||||
#include "OtaSelf.h"
|
||||
#include "OtaTargets.h" // ota_target_env_name(): human-readable name for a target_id (no string on the wire)
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#include "OtaBlInfo.h" // ota_bootloader_caps(): can this device's bootloader apply a .mota?
|
||||
#endif
|
||||
#include "Utils.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
#include <stdlib.h>
|
||||
#include <Arduino.h> // millis() for session-age display (device-only command surface)
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
static uint32_t parse_u32(const char* s) {
|
||||
uint32_t n = 0;
|
||||
while (*s == ' ') s++;
|
||||
while (*s >= '0' && *s <= '9') n = n * 10 + (uint32_t)(*s++ - '0');
|
||||
return n;
|
||||
}
|
||||
|
||||
static char fstate_char(OtaManager::FetchState s) {
|
||||
switch (s) {
|
||||
case OtaManager::IDLE: return 'I';
|
||||
case OtaManager::WANT_MANIFEST: return 'W';
|
||||
case OtaManager::WANT_LEAVES: return 'L';
|
||||
case OtaManager::FETCHING: return 'F';
|
||||
case OtaManager::COMPLETE: return 'C';
|
||||
case OtaManager::PAUSED: return 'P';
|
||||
default: return 'X';
|
||||
}
|
||||
}
|
||||
|
||||
// For users, the only distinction that matters is full image vs. delta (which delta codec is internal).
|
||||
static const char* codec_kind(uint8_t c) { return c == CODEC_FULL ? "full" : "delta"; }
|
||||
|
||||
// A plain-language word for the fetch state (shown in `ota status`).
|
||||
static const char* state_word(OtaManager::FetchState s) {
|
||||
switch (s) {
|
||||
case OtaManager::IDLE: return "idle";
|
||||
case OtaManager::WANT_MANIFEST: return "starting";
|
||||
case OtaManager::WANT_LEAVES: return "validating seed";
|
||||
case OtaManager::FETCHING: return "downloading";
|
||||
case OtaManager::COMPLETE: return "ready to install";
|
||||
case OtaManager::FAILED: return "failed";
|
||||
case OtaManager::PAUSED: return "paused (folder link lost — reconnect to resume)";
|
||||
default: return "?";
|
||||
}
|
||||
}
|
||||
|
||||
// A compact one-word fetch state for the dense `ota stats` line (state_word's phrases are too long).
|
||||
static const char* state_short(OtaManager::FetchState s) {
|
||||
switch (s) {
|
||||
case OtaManager::WANT_MANIFEST: return "manifest";
|
||||
case OtaManager::WANT_LEAVES: return "leaves";
|
||||
case OtaManager::FETCHING: return "dl";
|
||||
case OtaManager::COMPLETE: return "done";
|
||||
case OtaManager::FAILED: return "failed";
|
||||
case OtaManager::PAUSED: return "paused";
|
||||
default: return "idle";
|
||||
}
|
||||
}
|
||||
|
||||
// Render the packed fw_version as "v1.2.3" (or "v1.2.3.4" when a prerelease byte is set).
|
||||
static void ver_str(char* out, size_t cap, uint32_t v) {
|
||||
FwVersion fw = FwVersion::unpack(v);
|
||||
if (fw.prerelease) snprintf(out, cap, "v%u.%u.%u.%u", fw.major, fw.minor, fw.patch, fw.prerelease);
|
||||
else snprintf(out, cap, "v%u.%u.%u", fw.major, fw.minor, fw.patch);
|
||||
}
|
||||
|
||||
// Match the first word of `a` against any of the '|'-separated names (so commands have intuitive aliases
|
||||
// and short forms); on a match, point `*rest` at the argument text. Keeps the dispatch table readable.
|
||||
static bool is_cmd(const char* a, const char* names, const char** rest) {
|
||||
size_t tlen = 0; while (a[tlen] && a[tlen] != ' ') tlen++;
|
||||
for (const char* s = names; *s; ) {
|
||||
const char* d = s; while (*d && *d != '|') d++;
|
||||
if ((size_t)(d - s) == tlen && tlen && strncmp(a, s, tlen) == 0) {
|
||||
const char* r = a + tlen; while (*r == ' ') r++;
|
||||
if (rest) *rest = r;
|
||||
return true;
|
||||
}
|
||||
s = (*d == '|') ? d + 1 : d;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// The everyday OTA surface is BitTorrent-shaped: `ota` shows what you're holding (your running firmware
|
||||
// as a full mOTA + your one fetch session), `ota neighbors` shows the mOTAs heard around you, `ota pull`
|
||||
// starts fetching one, `ota drop` frees the session. The raw primitives (manual content load, low-level
|
||||
// apply steps) live under `ota dev ...` so they don't clutter the everyday surface. Every reply fits one
|
||||
// packet so it works as remote-admin over LoRa.
|
||||
static bool handle_dev(const char* d, char* reply, OtaContext& c);
|
||||
|
||||
bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board) {
|
||||
const char* a = command + 3;
|
||||
if (*a != 0 && *a != ' ') return false;
|
||||
while (*a == ' ') a++;
|
||||
OtaContext& c = ota_ctx();
|
||||
const char* rest = a;
|
||||
|
||||
// ---- raw / internal primitives, tucked under `ota dev ...` ----
|
||||
if (is_cmd(a, "dev", &rest)) {
|
||||
return handle_dev(rest, reply, c);
|
||||
}
|
||||
|
||||
// ---- help: list the commands in plain words (aliases in parentheses) ----
|
||||
if (is_cmd(a, "help|?|h", &rest)) {
|
||||
snprintf(reply, 160,
|
||||
"OTA: status | stats=admin ids/hashes | ls=find updates | get <#>=download | install | cancel | "
|
||||
"announce | self | folder | config | key. Try `ota ls`.");
|
||||
|
||||
// ---- inventory dashboard: running fw (self), the one fetch session, serving state ----
|
||||
} else if (*a == 0 || is_cmd(a, "status|st", &rest)) {
|
||||
SelfFwInfo fi; bool s = ota_self_firmware(fi);
|
||||
char selfhx[9]; if (s && fi.valid) mesh::Utils::toHex(selfhx, fi.body_hash, 4); else strcpy(selfhx, "?");
|
||||
OtaManager::FetchState fs = c.manager.fetchState();
|
||||
char dl[80];
|
||||
if (fs == OtaManager::IDLE) {
|
||||
strcpy(dl, "no download");
|
||||
} else {
|
||||
char midhx[9]; mesh::Utils::toHex(midhx, c.manager.fetchManifestId(), 4);
|
||||
unsigned have = (unsigned)c.manager.blocksHave(), tot = (unsigned)c.manager.blocksTotal();
|
||||
unsigned pct = tot ? (unsigned)((uint64_t)have * 100 / tot) : 0;
|
||||
unsigned age = c.session_started_ms ? (unsigned)((millis() - c.session_started_ms) / 1000) : 0;
|
||||
snprintf(dl, sizeof dl, "download: %s %u/%u (%u%%) id=%s %us", state_word(fs), have, tot, pct, midhx, age);
|
||||
}
|
||||
const char* hw = (c.hw_id[0]) ? c.hw_id : "?";
|
||||
const char* tenv = ota_target_env_name(c.manager.target()); // env name, or "?" if not in the table
|
||||
int n = snprintf(reply, 160, "OTA | this fw %s (%uK) hw=%s | %s | serving:%s (%u) | keys:%u | target:%08X (%s)",
|
||||
selfhx, (unsigned)((s ? fi.image_len : 0) / 1024), hw, dl,
|
||||
c.serving ? "on" : "off", (unsigned)c.manager.servedCount(),
|
||||
(unsigned)c.allow.count(), (unsigned)c.manager.target(), tenv ? tenv : "?");
|
||||
#if defined(NRF52_PLATFORM)
|
||||
// nRF52 applies via the bootloader — show (cached) whether it can, so `ota get`/`install` won't surprise.
|
||||
// blrc = the bootloader's last in-place-apply code (diagnostic; 0xB8=success, see ota_delta.c).
|
||||
if (n < 146) n += snprintf(reply + n, 160 - n, " | bl:%s blrc:%02X",
|
||||
c.bootloaderCaps().present ? "apply" : "NONE", ota_bootloader_last_rc());
|
||||
#endif
|
||||
|
||||
// ---- admin OTA stats: crypto identities (our fw's content-id + body_hash), serving set, live fetch,
|
||||
// policy — one dense line. The remote-admin CLI path is admin-gated, so this is admin-only over the
|
||||
// mesh (send it from the app's repeater command screen, or the WiFi/serial OTA console).
|
||||
} else if (is_cmd(a, "stats", &rest)) {
|
||||
// our running fw's merkle content-id (mid) comes from the self serve entry; the EndF body_hash (fw
|
||||
// identity, matched against a delta base) is separate — surface BOTH (only body_hash showed before).
|
||||
const OtaManager::ServeEntry* self = nullptr;
|
||||
for (uint8_t i = 0; i < c.manager.servedCount(); i++) {
|
||||
const OtaManager::ServeEntry* e = c.manager.servedEntry(i);
|
||||
if (e && e->is_self) { self = e; break; }
|
||||
}
|
||||
SelfFwInfo fi; bool sok = ota_self_firmware(fi);
|
||||
char midhx[9], bodyhx[9], verbuf[20], dighx[9];
|
||||
if (self) mesh::Utils::toHex(midhx, self->mid, 4); else strcpy(midhx, "?");
|
||||
if (sok && fi.valid) mesh::Utils::toHex(bodyhx, fi.body_hash, 4); else strcpy(bodyhx, "?");
|
||||
if (self) ver_str(verbuf, sizeof verbuf, self->fw_version); else strcpy(verbuf, "v?");
|
||||
uint8_t dig[4]; c.manager.servedDigest(dig); mesh::Utils::toHex(dighx, dig, 4);
|
||||
OtaManager::FetchState fs = c.manager.fetchState();
|
||||
char fbuf[72];
|
||||
if (fs == OtaManager::IDLE) {
|
||||
strcpy(fbuf, "fetch idle");
|
||||
} else {
|
||||
char fmid[9]; mesh::Utils::toHex(fmid, c.manager.fetchManifestId(), 4);
|
||||
unsigned have = (unsigned)c.manager.blocksHave(), tot = (unsigned)c.manager.blocksTotal();
|
||||
unsigned pct = tot ? (unsigned)((uint64_t)have * 100 / tot) : 0;
|
||||
unsigned age = c.session_started_ms ? (unsigned)((millis() - c.session_started_ms) / 1000) : 0;
|
||||
snprintf(fbuf, sizeof fbuf, "fetch %s %u/%u %u%% id=%s %us", state_short(fs), have, tot, pct, fmid, age);
|
||||
}
|
||||
uint8_t af = c.manager.autofetch();
|
||||
snprintf(reply, 160, "OTA | fw %s id=%s body=%s %ub %uK | serv %u dg=%s | %s | af=%s hops=%u",
|
||||
verbuf, midhx, bodyhx, (unsigned)(self ? self->have_count : 0),
|
||||
(unsigned)((sok ? fi.image_len : 0) / 1024), (unsigned)c.manager.servedCount(), dighx, fbuf,
|
||||
af == OtaManager::AUTOFETCH_ANY ? "any" : af == OtaManager::AUTOFETCH_SIGNED ? "signed" : "off",
|
||||
(unsigned)c.manager.max_hops());
|
||||
|
||||
// ---- what's available around me (catalogued from beacons + OTA_HAVE), best/most-recent first ----
|
||||
} else if (is_cmd(a, "neighbors|nbrs|updates|ls|n", &rest)) {
|
||||
// Kick a fresh round of catalog queries (async — rows arrive over the next seconds); render what we
|
||||
// have now in plain words. The reply buffer is 160 B (serial / one LoRa packet for remote-admin), so
|
||||
// writes are bounded and extra rows collapse to "+N more".
|
||||
c.manager.queryAll();
|
||||
const int CAP = 160;
|
||||
int n = snprintf(reply, CAP, "Updates nearby (%u src) — `ota get <#>` to download:",
|
||||
(unsigned)c.manager.sourceCount());
|
||||
const uint8_t* cur = (c.manager.fetchState() != OtaManager::IDLE) ? c.manager.fetchManifestId() : nullptr;
|
||||
uint32_t myt = c.manager.target(); // effective target (EndF identity if present, else build flag)
|
||||
uint32_t now = millis(); int shown = 0, more = 0;
|
||||
for (uint8_t i = 0; i < c.manager.catalogCount(); i++) {
|
||||
const OtaManager::CatRow* h = c.manager.catalogRow(i);
|
||||
if (CAP - n < 48) { more++; continue; }
|
||||
bool on = cur && memcmp(cur, h->mid, 4) == 0;
|
||||
uint32_t age = (now - h->last_ms) / 1000; if (age > 99999) age = 99999;
|
||||
char ver[20]; ver_str(ver, sizeof ver, h->fw_version);
|
||||
// What is this update for? "yours" if same target (hw+role) as us; else the target's env name when we
|
||||
// know it (named locally from its 4-byte target_id — no string travels on the wire); else the raw
|
||||
// target_id hex (an env this build's OtaTargets.h table doesn't know) or '?' for an unset target.
|
||||
char hwbuf[16];
|
||||
const char* fit;
|
||||
const char* env = ota_target_env_name(h->target_id);
|
||||
if (myt && h->target_id == myt) fit = "yours";
|
||||
else if (env) fit = env;
|
||||
else if (h->target_id == 0) fit = "?";
|
||||
else { snprintf(hwbuf, sizeof hwbuf, "hw %08X", (unsigned)h->target_id); fit = hwbuf; }
|
||||
n += snprintf(reply + n, CAP - n, "\n %d) %s %s [%s] %un %us%s", shown + 1, ver,
|
||||
codec_kind(h->codec), fit, (unsigned)h->n_seeders, (unsigned)age,
|
||||
on ? " [downloading]" : "");
|
||||
shown++;
|
||||
}
|
||||
if (more && n < CAP) snprintf(reply + n, CAP - n, "\n +%d more", more);
|
||||
if (shown == 0) strcpy(reply, "No updates seen yet — re-run `ota ls` in a few seconds (just asked around).");
|
||||
|
||||
// ---- start fetching a specific catalogued mOTA (by list index or manifest_id) ----
|
||||
} else if (is_cmd(a, "pull|get|download", &rest)) {
|
||||
const char* p = rest; while (*p == ' ') p++;
|
||||
// split into "<selector> [destination]": selector = #N / N (catalogue index) or mid hex; destination =
|
||||
// flash | folder (MANDATORY — `folder` captures the .mota onto the connected motatool folder as <mid>.mota).
|
||||
char selstr[24]; int i = 0;
|
||||
while (p[i] && p[i] != ' ' && i < (int)sizeof(selstr) - 1) { selstr[i] = p[i]; i++; }
|
||||
selstr[i] = 0;
|
||||
const char* dst = p + i; while (*dst == ' ') dst++;
|
||||
if (selstr[0] == 0) { strcpy(reply, "usage: ota pull <#> <flash|folder> (see `ota ls`)"); return true; }
|
||||
// resolve the catalogue row (index or explicit manifest_id)
|
||||
const OtaManager::CatRow* sel = nullptr; uint8_t mid[4];
|
||||
bool isnum = (selstr[0] == '#');
|
||||
if (!isnum) { isnum = true; for (const char* x = selstr; *x; x++) if (*x < '0' || *x > '9') { isnum = false; break; } }
|
||||
if (isnum) {
|
||||
int idx = atoi(selstr[0] == '#' ? selstr + 1 : selstr);
|
||||
if (idx >= 1 && idx <= c.manager.catalogCount()) sel = c.manager.catalogRow((uint8_t)(idx - 1));
|
||||
} else if (mesh::Utils::fromHex(mid, 4, selstr)) {
|
||||
for (uint8_t k = 0; k < c.manager.catalogCount(); k++)
|
||||
if (memcmp(c.manager.catalogRow(k)->mid, mid, 4) == 0) { sel = c.manager.catalogRow(k); break; }
|
||||
}
|
||||
if (!sel) { strcpy(reply, "ERR no such update (see the numbers in `ota ls`)"); return true; }
|
||||
// destination is MANDATORY: with none given, show the choices (flash always; folder iff a link is up).
|
||||
if (*dst == 0) {
|
||||
if (c.folder_dest)
|
||||
snprintf(reply, 160, "choose a destination: `ota pull %s flash` | `ota pull %s folder` (folder: %s)",
|
||||
selstr, selstr, c.folder_dest_info);
|
||||
else
|
||||
snprintf(reply, 160, "choose a destination: `ota pull %s flash` (folder: none connected — motatool serve)",
|
||||
selstr);
|
||||
return true;
|
||||
}
|
||||
if (c.apply_pending) { strcpy(reply, "ERR busy applying"); return true; }
|
||||
// optional 3rd token: `folder validate` -> leaf-diff warm-start against a seed motatool staged (capture only)
|
||||
bool validate = false;
|
||||
{ const char* q = dst; while (*q && *q != ' ') q++; while (*q == ' ') q++;
|
||||
if (strncmp(q, "validate", 8) == 0) validate = true; }
|
||||
uint8_t selmid[4]; uint32_t seltgt = sel->target_id; memcpy(selmid, sel->mid, 4); // sel may move on reset
|
||||
OtaStore* store; const char* dname;
|
||||
if (strncmp(dst, "flash", 5) == 0) {
|
||||
store = &c.fetch_store; c.fetch_store.clear(); dname = "flash"; validate = false; // seed lives in the folder
|
||||
} else if (strncmp(dst, "folder", 6) == 0) {
|
||||
if (!c.folder_dest) { strcpy(reply, "ERR no folder connected (run motatool serve --tcp/--serial)"); return true; }
|
||||
c.folder_dest->set_mid(selmid); store = c.folder_dest; dname = validate ? "folder+validate" : "folder";
|
||||
} else { strcpy(reply, "ERR destination must be `flash` or `folder`"); return true; }
|
||||
c.manager.reset_session();
|
||||
c.manager.set_fetch_store(store); // stage this pull to the chosen destination
|
||||
c.manager.pull(selmid, seltgt, validate); // sets want + begins the manifest fetch now
|
||||
char midhx[9]; mesh::Utils::toHex(midhx, selmid, 4);
|
||||
snprintf(reply, 160, "OK pulling mid=%s -> %s (low priority)", midhx, dname);
|
||||
|
||||
// ---- discard the current session (e.g. a stalled old fetch) to free the slot ----
|
||||
} else if (is_cmd(a, "drop|cancel|stop", &rest)) {
|
||||
OtaManager::FetchState fs = c.manager.fetchState();
|
||||
char midhx[9]; strcpy(midhx, "-");
|
||||
if (fs != OtaManager::IDLE) mesh::Utils::toHex(midhx, c.manager.fetchManifestId(), 4);
|
||||
c.manager.reset_session(); c.manager.want(0); c.manager.want_mid(nullptr);
|
||||
c.manager.set_fetch_store(&c.fetch_store); // revert to the default flash store (a folder pull switched it)
|
||||
c.fetch_store.clear(); c.serving = false; c.serve_expected = 0; c.session_started_ms = 0;
|
||||
snprintf(reply, 160, "OK dropped session (was %c mid=%s); slot free for a new pull", fstate_char(fs), midhx);
|
||||
|
||||
// ---- broadcast our tiny beacon so peers discover us. If not already serving, set up flash-backed
|
||||
// self-serve first (so we're a real, fetchable source of our own running firmware). ----
|
||||
} else if (is_cmd(a, "announce|adv", &rest)) {
|
||||
if (!c.serving) c.serving = ota_serve_self(c, 0);
|
||||
c.manager.announce();
|
||||
sprintf(reply, "OK beacon sent (serving=%s)", c.serving ? "self fw" : "nothing");
|
||||
|
||||
// ---- running firmware identity (compare against a delta's base_hash) ----
|
||||
} else if (is_cmd(a, "self|id", &rest)) {
|
||||
SelfFwInfo fi;
|
||||
if (!ota_self_firmware(fi) || !fi.valid) { strcpy(reply, "ERR no EndF (firmware lacks the trailer?)"); return true; }
|
||||
char hx[17]; mesh::Utils::toHex(hx, fi.body_hash, 8);
|
||||
int n = snprintf(reply, 160, "self body=%u image=%u base_hash=%s", (unsigned)fi.body_len, (unsigned)fi.image_len, hx);
|
||||
#if defined(NRF52_PLATFORM)
|
||||
// nRF52 applies via the bootloader, so surface whether THIS device's bootloader can (delta install gate)
|
||||
const OtaBlCaps& bl = c.bootloaderCaps(); // cached (flash scanned once)
|
||||
if (bl.present) snprintf(reply + n, 160 - n, " | bootloader: apply OK (abi=%u codecs=0x%x)", bl.apply_abi, bl.codec_mask);
|
||||
else snprintf(reply + n, 160 - n, " | bootloader: NO mota-apply support (delta install will refuse)");
|
||||
#endif
|
||||
|
||||
} else if (is_cmd(a, "install|apply|applydelta", &rest)) {
|
||||
// Apply the fetched update. Destructive (reflashes + reboots) and GATED, not interactive (no "type
|
||||
// yes" round-trip — unreliable over LoRa): refuse unless the fetch is COMPLETE, then the apply path
|
||||
// validates in order (payload hash -> built-for-this-firmware -> signature/trust) and returns the
|
||||
// FIRST failing gate, so the operator knows exactly why it refused; it proceeds only if all pass.
|
||||
if (c.manager.fetchState() != OtaManager::COMPLETE || c.fetch_store.staged_size() == 0) {
|
||||
sprintf(reply, "ERR no complete update fetched (fetch=%c %u/%u)",
|
||||
fstate_char(c.manager.fetchState()), (unsigned)c.manager.blocksHave(),
|
||||
(unsigned)c.manager.blocksTotal());
|
||||
return true;
|
||||
}
|
||||
// On success the slot is armed but NOT yet rebooted — defer so this reply reaches the operator first;
|
||||
// the mesh loop reboots once it has been transmitted (same path used by auto-install).
|
||||
char m2[100];
|
||||
bool ok = c.apply_fetched(m2);
|
||||
sprintf(reply, "%s | %s", ok ? "OK" : "ERR", m2);
|
||||
|
||||
// ---- external folder relay: advertise + serve `.mota` from a host daemon over the seeder UART, so the
|
||||
// node hosts MANY images (any architecture) it doesn't hold in flash. Trustless (fetchers verify). --
|
||||
} else if (is_cmd(a, "folder|fold", &rest)) {
|
||||
const char* p = rest;
|
||||
if (strncmp(p, "on", 2) == 0) {
|
||||
#if defined(OTA_FOLDER_SERIAL)
|
||||
if (!c.serving) c.serving = ota_serve_self(c, 0); // keep serving our own fw alongside the folder
|
||||
char m2[120]; c.attach_folder(m2, sizeof(m2)); c.manager.announce();
|
||||
strncpy(reply, m2, 159); reply[159] = 0;
|
||||
#else
|
||||
strcpy(reply, "ERR not built with OTA_FOLDER_SERIAL (set the seeder UART in platformio.ini)");
|
||||
#endif
|
||||
} else if (strncmp(p, "off", 3) == 0) {
|
||||
c.detach_folder(); c.manager.announce();
|
||||
strcpy(reply, "OK folder detached (still serving own fw)");
|
||||
} else { // status + list served entries (* = our own fw)
|
||||
int n = snprintf(reply, 159, "folder=%s serving=%u:", c.folder_active ? "on" : "off",
|
||||
(unsigned)c.manager.servedCount());
|
||||
for (uint8_t i = 0; i < c.manager.servedCount() && n < 148; i++) {
|
||||
const OtaManager::ServeEntry* e = c.manager.servedEntry(i);
|
||||
if (!e) break;
|
||||
char midhx[9]; mesh::Utils::toHex(midhx, e->mid, 4);
|
||||
n += snprintf(reply + n, 159 - n, " %s%s/%08X", e->is_self ? "*" : "", midhx, (unsigned)e->target_id);
|
||||
}
|
||||
}
|
||||
|
||||
// ---- policy config (persisted via NodePrefs). conservative defaults: autofetch/autoinstall off ----
|
||||
} else if (is_cmd(a, "config|cfg|set", &rest)) {
|
||||
const char* p = rest;
|
||||
if (strncmp(p, "autofetch ", 10) == 0) {
|
||||
const char* v = p + 10;
|
||||
uint8_t pol = strncmp(v, "any", 3) == 0 ? OtaManager::AUTOFETCH_ANY
|
||||
: strncmp(v, "signed", 6) == 0 ? OtaManager::AUTOFETCH_SIGNED
|
||||
: strncmp(v, "off", 3) == 0 ? OtaManager::AUTOFETCH_OFF : 0xFF;
|
||||
if (pol == 0xFF) { strcpy(reply, "ERR usage: ota config autofetch <off|any|signed>"); return true; }
|
||||
c.manager.set_autofetch(pol); c.config_dirty = true; strcpy(reply, "OK autofetch updated (saved)");
|
||||
} else if (strncmp(p, "autoinstall ", 12) == 0) {
|
||||
const char* v = p + 12;
|
||||
uint8_t pol = strncmp(v, "trusted", 7) == 0 ? OtaContext::AUTOINSTALL_TRUSTED
|
||||
: strncmp(v, "off", 3) == 0 ? OtaContext::AUTOINSTALL_OFF : 0xFF;
|
||||
if (pol == 0xFF) { strcpy(reply, "ERR usage: ota config autoinstall <off|trusted>"); return true; }
|
||||
c.autoinstall = pol; c.config_dirty = true; strcpy(reply, "OK autoinstall updated (saved)");
|
||||
} else if (strncmp(p, "checkpoint ", 11) == 0) { // resume checkpoint cadence (blocks; 0=never)
|
||||
long n = atol(p + 11);
|
||||
if (n < 0 || n > 4096) { strcpy(reply, "ERR usage: ota config checkpoint <0..4096> (blocks; 0=never)"); return true; }
|
||||
c.manager.set_checkpoint_blocks((uint16_t)n); c.config_dirty = true;
|
||||
sprintf(reply, "OK checkpoint every %ld blocks (saved)%s", n, n == 0 ? " — periodic resume disabled" : "");
|
||||
} else if (strncmp(p, "advert ", 7) == 0) { // beacon re-advertise cadence (minutes; 0=disable)
|
||||
long m = atol(p + 7);
|
||||
if (m < 0 || m > 10080) { strcpy(reply, "ERR usage: ota config advert <0..10080> (minutes; 0=disable)"); return true; }
|
||||
c.manager.set_advert_mins((uint16_t)m); c.config_dirty = true;
|
||||
sprintf(reply, "OK re-advertise every %ld min (saved)%s", m, m == 0 ? " — periodic advert disabled" : "");
|
||||
} else if (strncmp(p, "hops ", 5) == 0) { // OTA flood reach in hops (0 = direct only)
|
||||
long h = atol(p + 5);
|
||||
if (h < 0 || h > 8) { strcpy(reply, "ERR usage: ota config hops <0..8> (hops; 0 = direct only)"); return true; }
|
||||
c.manager.set_max_hops((uint8_t)h); c.config_dirty = true;
|
||||
sprintf(reply, "OK OTA reach = %ld hop%s (saved)%s", h, h == 1 ? "" : "s", h == 0 ? " — direct only" : "");
|
||||
} else { // show current policy
|
||||
uint8_t af = c.manager.autofetch();
|
||||
sprintf(reply, "ota config: autofetch=%s autoinstall=%s checkpoint=%u advert=%umin hops=%u keys=%u (persisted)",
|
||||
af == OtaManager::AUTOFETCH_ANY ? "any" : af == OtaManager::AUTOFETCH_SIGNED ? "signed" : "off",
|
||||
c.autoinstall == OtaContext::AUTOINSTALL_TRUSTED ? "trusted" : "off",
|
||||
(unsigned)c.manager.checkpoint_blocks(), (unsigned)c.manager.advert_mins(),
|
||||
(unsigned)c.manager.max_hops(), (unsigned)c.allow.count());
|
||||
}
|
||||
|
||||
// ---- trusted signer allowlist (security config; persisted): `ota key add|rm <hex>` / `ota key` lists ----
|
||||
} else if (is_cmd(a, "key|keys", &rest)) {
|
||||
const char* p = rest;
|
||||
if (strncmp(p, "add ", 4) == 0) {
|
||||
uint8_t pub[32];
|
||||
if (mesh::Utils::fromHex(pub, 32, p + 4) && c.allow.add(pub)) { c.config_dirty = true; strcpy(reply, "OK key added (saved)"); }
|
||||
else strcpy(reply, "ERR key");
|
||||
} else if (strncmp(p, "rm ", 3) == 0 || strncmp(p, "remove ", 7) == 0) {
|
||||
uint8_t pub[32]; const char* h = p + (p[0] == 'r' && p[1] == 'm' ? 3 : 7);
|
||||
if (mesh::Utils::fromHex(pub, 32, h) && c.allow.remove(pub)) { c.config_dirty = true; strcpy(reply, "OK removed (saved)"); }
|
||||
else strcpy(reply, "ERR");
|
||||
} else { // bare `ota key` (or `key list`) -> show them
|
||||
int n = snprintf(reply, 160, "trusted signer keys (%u):", (unsigned)c.allow.count());
|
||||
for (uint8_t i = 0; i < c.allow.count() && n < 140; i++) {
|
||||
char hx[17]; mesh::Utils::toHex(hx, c.allow.get(i), 8);
|
||||
n += snprintf(reply + n, 160 - n, " %s", hx);
|
||||
}
|
||||
if (c.allow.count() == 0) strcpy(reply, "no trusted signer keys yet (add one with `ota key add <hex>`)");
|
||||
}
|
||||
|
||||
} else {
|
||||
strcpy(reply, "Unknown OTA command. Type `ota help`.");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// Raw / internal primitives (manual content load + low-level apply steps), under `ota dev ...`.
|
||||
static bool handle_dev(const char* d, char* reply, OtaContext& c) {
|
||||
if (strncmp(d, "stage ", 6) == 0) {
|
||||
uint32_t sz = parse_u32(d + 6);
|
||||
if (sz == 0 || sz > OTA_SERVE_BUF_SIZE) { sprintf(reply, "ERR size 1..%u", OTA_SERVE_BUF_SIZE); }
|
||||
else { memset(c.serve_buf, 0xFF, sz); c.serve_expected = sz; c.serving = false;
|
||||
sprintf(reply, "OK stage %u bytes", (unsigned)sz); }
|
||||
|
||||
} else if (strncmp(d, "recv ", 5) == 0) {
|
||||
const char* p = d + 5; uint32_t off = parse_u32(p);
|
||||
const char* hex = strchr(p, ' ');
|
||||
if (!hex) { strcpy(reply, "ERR usage: ota dev recv <off> <hex>"); return true; }
|
||||
hex++;
|
||||
int blen = (int)strlen(hex) / 2;
|
||||
uint8_t tmp[80];
|
||||
if (blen <= 0 || blen > (int)sizeof(tmp) || !mesh::Utils::fromHex(tmp, blen, hex)) strcpy(reply, "ERR hex");
|
||||
else if (off + blen > c.serve_expected) strcpy(reply, "ERR off>size (stage first)");
|
||||
else { memcpy(c.serve_buf + off, tmp, blen); sprintf(reply, "OK %d@%u", blen, (unsigned)off); }
|
||||
|
||||
} else if (strncmp(d, "serve self", 10) == 0) { // host our own running firmware, served from flash
|
||||
if (ota_serve_self(c, 0)) {
|
||||
c.serving = true;
|
||||
char midhx[9]; mesh::Utils::toHex(midhx, c.serve_self_manifest + 20, 4);
|
||||
uint32_t img = (uint32_t)c.serve_self_manifest[11] | ((uint32_t)c.serve_self_manifest[12] << 8)
|
||||
| ((uint32_t)c.serve_self_manifest[13] << 16) | ((uint32_t)c.serve_self_manifest[14] << 24);
|
||||
sprintf(reply, "OK serving self fw mid=%s (%u B, flash-backed) — peers can pull it", midhx, (unsigned)img);
|
||||
} else strcpy(reply, "ERR serve self (no EndF / image too big / OOM)");
|
||||
} else if (strncmp(d, "serve", 5) == 0) {
|
||||
c.serving = c.manager.serve(c.serve_buf, c.serve_expected);
|
||||
if (!c.serving) { strcpy(reply, "ERR serve (bad .mota)"); return true; }
|
||||
VerifyResult r = ota_verify(c.serve_buf, c.serve_expected, c.allow);
|
||||
sprintf(reply, "OK serving | root=%d img=%d sig=%d trust=%d", r.root_ok, r.image_ok, r.sig_ok, r.trusted);
|
||||
|
||||
} else if (strncmp(d, "resume", 6) == 0) { // re-adopt a container already staged in flash (test/debug)
|
||||
bool ok = c.manager.resumeStaged(nullptr);
|
||||
sprintf(reply, "%s resume: sess=%c %u/%u", ok ? "OK" : "ERR", fstate_char(c.manager.fetchState()),
|
||||
(unsigned)c.manager.blocksHave(), (unsigned)c.manager.blocksTotal());
|
||||
|
||||
} else if (strncmp(d, "announce", 8) == 0) {
|
||||
if (!c.serving) { strcpy(reply, "ERR not serving (ota dev serve first)"); return true; }
|
||||
c.manager.announce();
|
||||
strcpy(reply, "OK announced");
|
||||
|
||||
} else if (strncmp(d, "verify", 6) == 0) {
|
||||
const uint8_t* buf; uint32_t len;
|
||||
if (c.manager.fetchState() == OtaManager::COMPLETE) { buf = c.fetch_store.data(); len = c.fetch_store.staged_size(); }
|
||||
else { buf = c.serve_buf; len = c.serve_expected; }
|
||||
if (len == 0 || !buf) { strcpy(reply, "ERR nothing to verify (flash-staged: applydelta verifies)"); return true; }
|
||||
VerifyResult r = ota_verify(buf, len, c.allow);
|
||||
sprintf(reply, "verify parsed=%d root=%d img=%d signed=%d sig=%d trust=%d | ok=%d auto=%d",
|
||||
r.parsed, r.root_ok, r.image_ok, r.is_signed, r.sig_ok, r.trusted, r.integrity_ok(), r.auto_appliable());
|
||||
|
||||
} else if (strncmp(d, "want ", 5) == 0) {
|
||||
const char* p = d + 5; while (*p == ' ') p++;
|
||||
if (strncmp(p, "auto", 4) == 0) { c.manager.want(0); c.manager.want_mid(nullptr); strcpy(reply, "OK auto (own target only)"); }
|
||||
else { uint32_t t = (uint32_t)strtoul(p, nullptr, 16); c.manager.want(t); c.manager.want_mid(nullptr);
|
||||
sprintf(reply, "OK cross-target: will fetch %08X (you ensure HW compatible)", (unsigned)t); }
|
||||
|
||||
} else if (strncmp(d, "apply", 5) == 0) {
|
||||
const char* sub = d + 5; while (*sub == ' ') sub++;
|
||||
if (strncmp(sub, "slot", 4) == 0) {
|
||||
uint32_t addr = 0, size = 0;
|
||||
if (ota_apply_slot_info(&addr, &size)) sprintf(reply, "inactive slot addr=0x%X size=%u", (unsigned)addr, (unsigned)size);
|
||||
else strcpy(reply, "ERR no A/B slot (apply unsupported on this build)");
|
||||
} else if (strncmp(sub, "manifest", 8) == 0) {
|
||||
if (ota_apply_set_manifest(c.serve_buf, c.serve_expected, c.allow, c.apply_st))
|
||||
sprintf(reply, "manifest ok img=%u sig=%d trust=%d", (unsigned)c.apply_st.image_size, c.apply_st.sig_ok, c.apply_st.trusted);
|
||||
else strcpy(reply, "ERR manifest parse / not full-image / unsupported");
|
||||
} else if (strncmp(sub, "verify", 6) == 0) {
|
||||
bool ok = ota_apply_verify_slot(c.apply_st);
|
||||
sprintf(reply, "slot image_hash %s (size=%u)", ok ? "MATCH" : "MISMATCH", (unsigned)c.apply_st.image_size);
|
||||
} else if (strncmp(sub, "commit", 6) == 0) {
|
||||
if (!c.apply_st.slot_ok) { strcpy(reply, "ERR run 'ota dev apply verify' first (slot must match)"); return true; }
|
||||
ota_apply_commit(); // set boot partition + reboot; no return
|
||||
strcpy(reply, "ERR commit failed (no A/B slot?)");
|
||||
} else {
|
||||
strcpy(reply, "ERR ota dev apply (slot|manifest|verify|commit)");
|
||||
}
|
||||
|
||||
} else if (strncmp(d, "clear", 5) == 0) {
|
||||
c.serve_expected = 0; c.serving = false; c.fetch_store.clear(); c.manager.reset_session();
|
||||
strcpy(reply, "OK cleared");
|
||||
|
||||
} else {
|
||||
strcpy(reply, "ota dev: stage|recv|serve|announce|verify|want|apply slot|manifest|verify|commit|clear");
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,16 @@
|
||||
#pragma once
|
||||
|
||||
#include <MeshCore.h>
|
||||
|
||||
// Text-CLI surface for OTA (P3/P5). Wired from CommonCLI (and reachable over LoRa remote-admin).
|
||||
// Kept out of CommonCLI.cpp itself so the OTA state (allowlist, staging store) lives in the OTA module.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// Handle an "ota ..." command. `command` is the full line (starts with "ota"). Fills `reply`
|
||||
// (<= ~160 bytes, as per the CLI buffer). Returns true if it was an OTA command.
|
||||
bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board);
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,12 @@
|
||||
#include "OtaContext.h"
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
OtaContext& ota_ctx() {
|
||||
static OtaContext ctx;
|
||||
return ctx;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,206 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdio.h> // snprintf (hw_id mismatch message)
|
||||
#include <string.h> // strncmp/strncpy (hw_id)
|
||||
#include "OtaManager.h"
|
||||
#include "OtaStore.h"
|
||||
#include "SignerAllowlist.h"
|
||||
#include "OtaApply.h"
|
||||
#include "OtaFormat.h"
|
||||
#include "OtaSelf.h" // ota_self_firmware() — prefer self-describing EndF identity at begin()
|
||||
#include "OtaBlInfo.h" // bootloader OTA-apply capability marker (nRF52); cached after first read
|
||||
#if defined(NRF52_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
#include "OtaStoreFlashNrf52.h"
|
||||
#elif defined(ESP32_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
#include "OtaStoreFlashEsp32.h"
|
||||
#endif
|
||||
#if defined(OTA_FOLDER_SERIAL)
|
||||
#include "MotaSourceSerial.h" // relay an external folder served by a host daemon over the USB serial
|
||||
#ifndef OTA_FOLDER_SERIAL_STREAM
|
||||
#define OTA_FOLDER_SERIAL_STREAM Serial // default: the same USB console the CLI uses (no extra HW)
|
||||
#endif
|
||||
#ifndef OTA_FOLDER_SERIAL_BAUD
|
||||
#define OTA_FOLDER_SERIAL_BAUD 115200
|
||||
#endif
|
||||
// The console Serial is already begun by the example; a DEDICATED UART (override the stream) needs init,
|
||||
// so define OTA_FOLDER_SERIAL_BEGIN to have attach_folder() call .begin(baud) on it.
|
||||
#endif
|
||||
|
||||
// Per-device OTA singleton shared by the CLI (OtaCli) and the mesh adapter (the example's MyMesh).
|
||||
// Holds the session engine, a staging store (fetch), a RAM serve buffer, and the signer allowlist.
|
||||
// nRF52 stages into FLASH (OtaStoreFlashNrf52): a delta can be 100 KB+, too big to hold in RAM, and the
|
||||
// COMPLETE container must persist so the bootloader can apply it after reboot. A flash page-erase halts
|
||||
// the CPU (~85 ms) and starves the LoRa RX, so the store COALESCES writes to the 4 KB page (the erase
|
||||
// unit) and commits each page once, off the per-packet path (see OtaManager.h) — RAM stays O(one page).
|
||||
// (v1 has no mid-transfer resume; an interrupted fetch simply restarts.) ESP32/native use the RAM store.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
class FolderMotaStore; // pull destination over the seeder link (full type only where instantiated/used)
|
||||
|
||||
#ifndef OTA_SERVE_BUF_SIZE
|
||||
#define OTA_SERVE_BUF_SIZE 16384
|
||||
#endif
|
||||
#ifndef OTA_FETCH_BUF_SIZE
|
||||
#define OTA_FETCH_BUF_SIZE 16384
|
||||
#endif
|
||||
|
||||
struct OtaContext {
|
||||
OtaManager manager;
|
||||
#if defined(NRF52_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
OtaStoreFlashNrf52 fetch_store; // persistent flash staging (survives reboot; large deltas)
|
||||
#elif defined(ESP32_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
OtaStoreFlashEsp32 fetch_store; // stages in the inactive A/B slot (delta + full, RX-safe)
|
||||
#else
|
||||
OtaStoreRam<OTA_FETCH_BUF_SIZE> fetch_store;
|
||||
#endif
|
||||
SignerAllowlist allow;
|
||||
uint8_t serve_buf[OTA_SERVE_BUF_SIZE];
|
||||
uint32_t serve_expected = 0; // size declared by `ota stage`
|
||||
bool serving = false; // manager.serve() succeeded
|
||||
// flash-backed self-serve: cached merkle leaves (heap, freed on re-serve) + assembled manifest of our
|
||||
// own running firmware. The payload is read from flash per block; only the metadata is held in RAM.
|
||||
// serve_self_proof is the proof-gen working buffer (>= block_count*4) — sized to OUR image's block
|
||||
// count (the manager's fixed 4 KB scratch only covers <=1024 blocks; a >1 MB image needs more).
|
||||
uint8_t* serve_self_leaves = nullptr;
|
||||
uint8_t* serve_self_proof = nullptr;
|
||||
uint8_t serve_self_manifest[MOTA_MFL]; // fixed-layout full+unsigned manifest-minus-leaves (197 B)
|
||||
ApplyState apply_st; // pending apply (P6)
|
||||
|
||||
// OTA policy (persisted via NodePrefs; autofetch lives in the manager). Conservative defaults: a fresh
|
||||
// node discovers + announces but never fetches/installs without operator intent.
|
||||
static const uint8_t AUTOINSTALL_OFF = 0, AUTOINSTALL_TRUSTED = 1;
|
||||
uint8_t autoinstall = AUTOINSTALL_OFF; // 1 = auto-apply a COMPLETE fetch IF signed + allowlisted
|
||||
bool config_dirty = false; // CLI set a policy/key -> CommonCLI persists + clears
|
||||
char hw_id[33] = {0}; // this device's hardware tag (from board.getOtaHwId(), set in begin)
|
||||
|
||||
// ---- Pull destinations (`ota pull <#> <dest>`): where a fetched .mota is staged. `flash` (fetch_store,
|
||||
// always present) or `folder` — an external host folder over the seeder link, registered by the app
|
||||
// while a motatool `serve` connection is attached (else no `folder` dest is offered). Captures the
|
||||
// container to the host as <mid>.mota so an exact firmware copy can be pulled for delta-building. ----
|
||||
FolderMotaStore* folder_dest = nullptr; // non-null == a folder destination is currently connected
|
||||
char folder_dest_info[24] = {0}; // human id of the link (e.g. "tcp 192.168.4.5", "serial")
|
||||
void set_folder_dest(FolderMotaStore* fs, const char* info) {
|
||||
folder_dest = fs;
|
||||
strncpy(folder_dest_info, info ? info : "?", sizeof(folder_dest_info) - 1);
|
||||
folder_dest_info[sizeof(folder_dest_info) - 1] = 0;
|
||||
}
|
||||
void clear_folder_dest() { folder_dest = nullptr; folder_dest_info[0] = 0; }
|
||||
|
||||
// True if the staged .mota's hw_id is compatible with this device: equal tags, or either side empty
|
||||
// ("unknown" -> can't enforce -> permissive). Brick-safety gate for apply (esp. manual cross-target).
|
||||
bool hwMatches(const uint8_t* mhw /*32B, may be null*/) const {
|
||||
if (!hw_id[0] || !mhw) return true;
|
||||
bool declared = false; for (int i = 0; i < 32; i++) if (mhw[i]) { declared = true; break; }
|
||||
if (!declared) return true;
|
||||
return strncmp((const char*)mhw, hw_id, 32) == 0;
|
||||
}
|
||||
|
||||
// Apply the COMPLETE fetched .mota (platform dispatch) and arm the slot; sets apply_pending on success
|
||||
// so the deferred-reboot path (mesh loop) takes over. Caller ensures the fetch is COMPLETE. Shared by
|
||||
// manual `ota applydelta` and the auto-install path.
|
||||
bool apply_fetched(char* msg) {
|
||||
// hardware-compatibility gate (brick-safety) — refuse a .mota whose hw_id is for different hardware,
|
||||
// independent of signature; covers a manual cross-target `ota dev want` onto an incompatible board.
|
||||
{
|
||||
uint8_t hdr[8], mb[256];
|
||||
uint32_t total = fetch_store.staged_size();
|
||||
if (total >= 13 && fetch_store.read(0, hdr, 8) && memcmp(hdr, MOTA_MAGIC, 4) == 0) {
|
||||
uint32_t mr = total - 8; if (mr > sizeof(mb)) mr = sizeof(mb);
|
||||
MotaManifest mm;
|
||||
if (fetch_store.read(8, mb, mr) && mota_parse_manifest(mb, mr, mm) && !hwMatches(mm.hw_id)) {
|
||||
char want[33] = {0}; memcpy(want, mm.hw_id, 32);
|
||||
snprintf(msg, 96, "refused: .mota hw_id '%.32s' != this device '%s' (incompatible hardware)", want, hw_id);
|
||||
return false;
|
||||
}
|
||||
}
|
||||
}
|
||||
bool ok;
|
||||
#if defined(NRF52_PLATFORM)
|
||||
ok = ota_apply_mota_nrf52(fetch_store.data(), fetch_store.staged_size(), allow, apply_st, msg);
|
||||
#elif defined(ESP32_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
ok = ota_apply_detools_mota(fetch_store, allow, apply_st, msg);
|
||||
#else
|
||||
ok = ota_apply_detools_mota(fetch_store.data(), fetch_store.staged_size(), allow, apply_st, msg);
|
||||
#endif
|
||||
if (ok) apply_pending = true;
|
||||
return ok;
|
||||
}
|
||||
|
||||
// Deferred apply-reboot: a verified `ota applydelta` approves the update but does NOT reboot inline,
|
||||
// so the CLI can first deliver the "verified; applying" reply (over LoRa it's the only way the
|
||||
// operator learns the apply started). The mesh loop then calls ota_reboot_to_apply() once that reply
|
||||
// has actually been transmitted. apply_at/apply_hard are mesh-clock deadlines the loop fills in.
|
||||
bool apply_pending = false;
|
||||
uint32_t apply_at = 0; // earliest reboot time (lets the reply get queued + start sending)
|
||||
uint32_t apply_hard = 0; // hard cap, in case the TX queue never idles on a busy node
|
||||
|
||||
// Bootloader OTA-apply capability (nRF52): can THIS device's bootloader apply a .mota? Read from flash
|
||||
// ONCE (the scan is ~40 KB) and cached in RAM. On other platforms present=false (apply is in-app).
|
||||
OtaBlCaps _bl_caps;
|
||||
bool _bl_caps_read = false;
|
||||
const OtaBlCaps& bootloaderCaps() {
|
||||
if (!_bl_caps_read) { _bl_caps = ota_bootloader_caps(); _bl_caps_read = true; }
|
||||
return _bl_caps;
|
||||
}
|
||||
|
||||
// --- discovery: the "what mOTAs are available around me" view ----------------------------------
|
||||
// The catalog (heard mOTAs) + the heard-sources table now live in OtaManager (built from beacons +
|
||||
// OTA_HAVE catalog replies, the two-tier discovery). `ota neighbors` renders manager.catalogRow();
|
||||
// `ota pull` acts on a mid. Here we only keep the fetch-session age stamp.
|
||||
uint32_t session_started_ms = 0; // when the fetch session last left IDLE (for the age display)
|
||||
uint8_t prev_fstate = OtaManager::IDLE;
|
||||
bool folder_active = false; // an external `.mota` folder is attached + being relayed
|
||||
|
||||
// Attach/detach an external folder of `.mota` served by a host daemon over the seeder UART (the node
|
||||
// then advertises + relays them alongside its own fw). Only built when OTA_FOLDER_SERIAL is configured.
|
||||
#if defined(OTA_FOLDER_SERIAL)
|
||||
bool attach_folder(char* msg, size_t cap) {
|
||||
static SerialMotaSource src(OTA_FOLDER_SERIAL_STREAM, 600);
|
||||
#ifdef OTA_FOLDER_SERIAL_BEGIN
|
||||
OTA_FOLDER_SERIAL_STREAM.begin(OTA_FOLDER_SERIAL_BAUD); // dedicated UART; console is already up
|
||||
#endif
|
||||
manager.clear_sources(); // idempotent re-attach
|
||||
if (!manager.add_source(&src)) { strncpy(msg, "ERR no free source slot", cap); return false; }
|
||||
folder_active = true;
|
||||
snprintf(msg, cap, "OK folder attached (serial) — serving %u mOTA total (own fw + folder)",
|
||||
(unsigned)manager.servedCount());
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
void detach_folder() { manager.clear_sources(); folder_active = false; }
|
||||
|
||||
void track_session(uint8_t fstate, uint32_t now) { // stamp the session start (age display)
|
||||
if (fstate != prev_fstate) {
|
||||
if (prev_fstate == OtaManager::IDLE && fstate != OtaManager::IDLE) session_started_ms = now;
|
||||
prev_fstate = fstate;
|
||||
}
|
||||
}
|
||||
|
||||
void begin(uint32_t target_id, OtaSend send, void* ctx, const char* hw = nullptr) {
|
||||
// Prefer the firmware's SELF-DESCRIBING EndF identity (docs §2) over the build-flag values the caller
|
||||
// passed — it's correct on any build (build.sh injection, bare IDE build, ...), so `ota ls`/`status`
|
||||
// and fetch-routing show the right hardware/role instead of 0 / "".
|
||||
SelfFwInfo _fi;
|
||||
if (ota_self_firmware(_fi) && _fi.valid) {
|
||||
if (_fi.target_id) target_id = _fi.target_id;
|
||||
if (_fi.hw_id[0]) hw = _fi.hw_id;
|
||||
}
|
||||
manager.begin(target_id, send, ctx);
|
||||
if (hw) { strncpy(hw_id, hw, sizeof(hw_id) - 1); hw_id[sizeof(hw_id) - 1] = 0; }
|
||||
// a node only fetches firmware it can apply: ESP32 A/B -> sequential, nRF52 single-slot -> in-place
|
||||
#if defined(NRF52_PLATFORM)
|
||||
manager.set_apply_codec(CODEC_DETOOLS_INPLACE);
|
||||
#elif defined(ESP32_PLATFORM)
|
||||
manager.set_apply_codec(CODEC_DETOOLS_SEQUENTIAL); // preferred (streams straight to the slot)
|
||||
manager.set_apply_codec2(CODEC_DETOOLS_INPLACE); // also accepted -> a single in-place .mota fits both
|
||||
#endif
|
||||
manager.set_fetch_store(&fetch_store);
|
||||
}
|
||||
};
|
||||
|
||||
OtaContext& ota_ctx(); // process-wide singleton
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,11 @@
|
||||
#pragma once
|
||||
|
||||
// Opt-in OTA tracing over Serial: build with -D OTA_DEBUG to watch the fetch (ADV/REQ/block/page-flush)
|
||||
// during bring-up. Compiles to nothing otherwise, and on the native host (no Arduino), so it never
|
||||
// touches a non-debug or test build.
|
||||
#if defined(OTA_DEBUG) && defined(ARDUINO)
|
||||
#include <Arduino.h>
|
||||
#define OTA_DBG(...) do { Serial.printf(__VA_ARGS__); } while (0)
|
||||
#else
|
||||
#define OTA_DBG(...) do {} while (0)
|
||||
#endif
|
||||
@@ -0,0 +1,67 @@
|
||||
#pragma once
|
||||
|
||||
// Shared OTA flash-layout constants for the nRF52840 (RAK4631) single-slot delta-apply path.
|
||||
// SINGLE SOURCE OF TRUTH — keep byte-identical with the bootloader's src/ota_layout.h.
|
||||
//
|
||||
// The running app occupies [APP_BASE, app_end]; the primary LittleFS (InternalFS) starts at FS_START.
|
||||
// MeshCore stages a verified+approved `.mota` in the free flash below FS_START (bottom-aligned), then
|
||||
// sets GPREGRET_OTA_APPLY and resets; the bootloader scans [APP_BASE, FS_START) for it and applies it
|
||||
// in place. These must match the bootloader and the running SoftDevice's app base.
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
static const uint32_t MOTA_NRF52_APP_BASE = 0x00026000u; // S140 end (== CODE_REGION_1_START)
|
||||
// Staging ceiling: the lowest filesystem region above the app. RAK4631 companion builds use the
|
||||
// extrafs ldscript with ExtraFS at 0xD4000..0xED000 (and InternalFS at 0xED000), while the repeater
|
||||
// uses the default ldscript (InternalFS at 0xED000, 0xD4000..0xED000 free). 0xD4000 is the safe
|
||||
// universal ceiling for ALL RAK4631 roles: staging below it never touches ExtraFS or InternalFS, and
|
||||
// the app (~520 KB) sits well below 0xD4000 either way.
|
||||
static const uint32_t MOTA_NRF52_FS_START = 0x000D4000u; // ExtraFS start (universal staging ceiling)
|
||||
static const uint32_t MOTA_NRF52_FLASH_PAGE = 4096u;
|
||||
static const uint8_t GPREGRET_OTA_APPLY = 0x6Au; // distinct from DFU magics 0x57/0x4E/0xA8
|
||||
|
||||
// In-place patches are built with --inplace-memory = this (the apply workspace, from APP_BASE up).
|
||||
// It must hold the new image (~520 KB) yet leave the staged mota room below FS_START: workspace ends
|
||||
// at APP_BASE+this = 0xBE000, leaving 0xBE000..0xD4000 (~88 KB) for the staged delta. The bootloader
|
||||
// also bounds writes to < the (scanned) mota start, so a mis-sized memory still fails safe.
|
||||
static const uint32_t MOTA_NRF52_INPLACE_MEMORY = 0x00098000u; // 608 KB (APP_BASE .. 0xBE000)
|
||||
|
||||
// Bootloader flash region (nRF52840: 39 KB ending just below the CF2/MBR-params pages). The app scans
|
||||
// this for the bootloader capability marker (OtaBlInfo.h) to know whether THIS device's bootloader can
|
||||
// actually apply a .mota before staging+approving+rebooting.
|
||||
static const uint32_t MOTA_NRF52_BL_START = 0x000F4000u;
|
||||
static const uint32_t MOTA_NRF52_BL_END = 0x000FE000u;
|
||||
|
||||
// Compile-time layout-ordering invariants. If a constant above is edited inconsistently these fail the
|
||||
// BUILD rather than silently letting a stage/apply corrupt the filesystem (user prefs) or the app.
|
||||
static_assert((MOTA_NRF52_APP_BASE % MOTA_NRF52_FLASH_PAGE) == 0, "APP_BASE must be page-aligned");
|
||||
static_assert((MOTA_NRF52_FS_START % MOTA_NRF52_FLASH_PAGE) == 0, "FS_START must be page-aligned");
|
||||
static_assert(MOTA_NRF52_APP_BASE < MOTA_NRF52_FS_START, "app must precede the staging ceiling");
|
||||
static_assert(MOTA_NRF52_FS_START < MOTA_NRF52_BL_START, "staging (+FS) must end below the bootloader");
|
||||
static_assert(MOTA_NRF52_BL_START < MOTA_NRF52_BL_END, "bootloader region must be non-empty");
|
||||
// The in-place apply workspace [APP_BASE, APP_BASE+INPLACE_MEMORY) must end at/below the staging ceiling,
|
||||
// so an in-place apply never writes into ExtraFS/InternalFS (where user prefs live).
|
||||
static_assert(MOTA_NRF52_APP_BASE + MOTA_NRF52_INPLACE_MEMORY <= MOTA_NRF52_FS_START,
|
||||
"in-place apply workspace must end at or below the staging ceiling");
|
||||
|
||||
// Plan where to stage a received `.mota` of `total_size` bytes. It is placed bottom-aligned so its
|
||||
// 5-byte trailer ends exactly at FS_START (the bootloader scans downward from there), and it must sit
|
||||
// ENTIRELY within [app_end, FS_START): above the running image (`app_end` = APP_BASE + its EndF image_len)
|
||||
// and below the filesystem region (ExtraFS/InternalFS — where user prefs live, assumed immutable).
|
||||
// Returns false (and leaves out_start untouched) if it does not fit. This is the SINGLE place the FS
|
||||
// ceiling + app-collision bounds are enforced; begin()/reopen() both go through it. Pure — no flash I/O —
|
||||
// so it is unit-tested natively in test/test_ota/test_ota_flashplan.cpp.
|
||||
inline bool mota_nrf52_stage_plan(uint32_t total_size, uint32_t app_end, uint32_t& out_start) {
|
||||
const uint32_t capacity = MOTA_NRF52_FS_START - MOTA_NRF52_APP_BASE;
|
||||
if (total_size < 13 || total_size > capacity) return false; // 13 = header(8)+trailer(5); must fit below FS
|
||||
uint32_t start = (MOTA_NRF52_FS_START - total_size) & ~(MOTA_NRF52_FLASH_PAGE - 1); // bottom-align down
|
||||
if (start < app_end) return false; // would overlap the running image
|
||||
out_start = start;
|
||||
return true;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,94 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
|
||||
// On-the-wire constants for the MeshCore OTA `.mota` container and protocol.
|
||||
// Normative definition: docs/ota_protocol.md (v1). Mirrors tools/mota/motalib.py.
|
||||
//
|
||||
// Portable: no Arduino / RadioLib includes. Compiles on the native host (unit tests) and on device.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// ---- container framing ----------------------------------------------------
|
||||
static const uint8_t MOTA_MAGIC[4] = { 'm', 'O', 'T', 'A' }; // 6D 4F 54 41
|
||||
static const uint8_t MOTA_TRAILER[5] = { 'v', 'k', '4', '9', '6' }; // 76 6B 34 39 36
|
||||
static const uint8_t ENDF_MAGIC[4] = { 'E', 'n', 'd', 'F' }; // 45 6E 64 46
|
||||
// Fixed 56-byte trailer (docs/ota_protocol.md §2): marker(4) body_len(4) body_hash8(8) + a self-describing
|
||||
// identity block fw_version(4) target_id(4) hw_id(32). No optional/variable parts.
|
||||
static const uint32_t ENDF_LEN = 56;
|
||||
|
||||
// ---- manifest -------------------------------------------------------------
|
||||
static const uint8_t MOTA_FORMAT_VER = 2; // fixed-layout manifest (see offsets below)
|
||||
static const uint8_t HASH_ALGO_SHA256 = 0x12; // multihash code
|
||||
|
||||
// Fixed manifest layout (manifest-minus-leaves) — every field is present at a constant offset, so the
|
||||
// parser is plain offset reads (docs/ota_protocol.md §4). base_hash/signer_pubkey/signature are always
|
||||
// present (zero-filled when not applicable); only leaves[] (after `approval`) is variable.
|
||||
static const uint32_t MOTA_OFF_BASE_HASH = 89; // 8 (zero for a full image)
|
||||
static const uint32_t MOTA_OFF_SIGNER = 97; // 32 (zero when unsigned)
|
||||
static const uint32_t MOTA_OFF_SIGNATURE = 129; // 64 (zero when unsigned) — covers manifest[0,129)
|
||||
static const uint32_t MOTA_OFF_APPROVAL = 193; // 4
|
||||
static const uint32_t MOTA_MFL = 197; // manifest-minus-leaves length (constant)
|
||||
static const uint32_t MOTA_SIGNED_LEN = 129; // bytes the signature covers (manifest[0, signer_end))
|
||||
|
||||
// hw_id: a fixed 32-byte, NUL-padded ASCII string naming the hardware a firmware can boot on (e.g.
|
||||
// "RAK4631", "Heltec_v3"). Same hw_id == bootable-compatible (a role switch on the same board keeps it;
|
||||
// different MCU/board differs). It sits in the SIGNED region of the manifest, so it can't be tampered.
|
||||
// The applier refuses a `.mota` whose hw_id differs from the device's own (brick-safety, esp. for a manual
|
||||
// cross-target `ota dev want`). An empty hw_id on either side = "unknown", and the check is skipped.
|
||||
static const uint8_t MOTA_HW_ID_LEN = 32;
|
||||
|
||||
static const uint8_t MFLAG_FULL = 0x01; // 0 = delta/partial, 1 = full image
|
||||
static const uint8_t MFLAG_SIGNED = 0x02;
|
||||
|
||||
static const uint8_t CODEC_FULL = 0;
|
||||
static const uint8_t CODEC_DETOOLS_SEQUENTIAL = 1;
|
||||
static const uint8_t CODEC_DETOOLS_INPLACE = 2;
|
||||
|
||||
// ---- firmware version ------------------------------------------------------
|
||||
// The comparable uint32 carried in the manifest + EndF identity: MAJOR<<24 | MINOR<<16 | PATCH<<8 | PRE.
|
||||
// 0 == "unknown" (e.g. a dev build with no dotted version). Defined once here so the pack/unpack layout
|
||||
// isn't re-derived with raw shifts at each call site (OtaSelf builds it, OtaCli renders it).
|
||||
struct FwVersion {
|
||||
uint8_t major, minor, patch, prerelease;
|
||||
static FwVersion unpack(uint32_t v) {
|
||||
return { (uint8_t)(v >> 24), (uint8_t)(v >> 16), (uint8_t)(v >> 8), (uint8_t)v };
|
||||
}
|
||||
uint32_t pack() const {
|
||||
return ((uint32_t)major << 24) | ((uint32_t)minor << 16) | ((uint32_t)patch << 8) | prerelease;
|
||||
}
|
||||
};
|
||||
|
||||
// ---- hash truncations -----------------------------------------------------
|
||||
static const uint8_t MH4 = 4; // sha2-256:4 (merkle leaves/nodes/root/proofs)
|
||||
static const uint8_t MH8 = 8; // sha2-256:8 (base/EndF body hash)
|
||||
static const uint8_t MH32 = 32; // sha2-256:32 (image security anchor)
|
||||
|
||||
// ---- approval marker (manifest field, after the signature) ----------------
|
||||
static const uint8_t APPROVAL_NOT[4] = { 0xFF, 0xFF, 0xFF, 0xFF };
|
||||
static const uint8_t APPROVAL_YES[4] = { 'A', 'P', 'R', 'V' }; // 41 50 52 56
|
||||
|
||||
// ---- LoRa protocol --------------------------------------------------------
|
||||
// The packet payload type is PAYLOAD_TYPE_OTA (0x0C), defined in src/Packet.h for the core dispatch.
|
||||
|
||||
enum OtaMsgType : uint8_t {
|
||||
OTA_ADV = 0x01,
|
||||
OTA_QUERY = 0x02,
|
||||
OTA_HAVE = 0x03,
|
||||
OTA_GET_MANIFEST = 0x04,
|
||||
OTA_MANIFEST = 0x05,
|
||||
OTA_REQ = 0x06, // request a window of blocks' DATA fragments
|
||||
OTA_DATA = 0x07, // one fragment of a block's data (self-describing by frag_off; no proof)
|
||||
OTA_REQ_PROOF = 0x08, // request the merkle proof for one block (data + proof are fetched separately)
|
||||
OTA_PROOF = 0x09, // the merkle proof for one block
|
||||
OTA_GET_LEAVES = 0x0A, // request the target's merkle leaves[] (motatool warm-start; bitmap-fragmented)
|
||||
OTA_LEAVES = 0x0B, // a fragment of the leaves[] array (for host-side seed leaf-diff)
|
||||
};
|
||||
|
||||
static const uint16_t OTA_DEFAULT_BLOCK_SIZE = 1024;
|
||||
static const uint8_t OTA_DEFAULT_HOP_LIMIT = 3;
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,809 @@
|
||||
#include "OtaManager.h"
|
||||
#include "OtaProtocol.h"
|
||||
#include "MerkleTree.h"
|
||||
#include "Multihash.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include "OtaDebug.h"
|
||||
#include <string.h>
|
||||
#include <stdlib.h> // malloc/free for the (transient) leaf-diff buffer
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
void OtaManager::begin(uint32_t my_target_id, OtaSend send, void* ctx) {
|
||||
_target = my_target_id; _send = send; _ctx = ctx;
|
||||
_fstate = IDLE; _have = 0; _fbc = 0;
|
||||
_n_serve = 0; _n_src_obj = 0; _view0.valid = false; _srcv.valid = false;
|
||||
}
|
||||
|
||||
// ---------------- serve (multi-mota registry) ----------------
|
||||
//
|
||||
// A node offers a SET of mOTAs: its own firmware (view0) plus any external "folder" sources (OtaSource).
|
||||
// Every fetch message carries the manifest_id, so a request dispatches to the matching ServeView via
|
||||
// resolve() — view0 is resident; an external mota is (re)loaded on demand into _srcv. The catalog (what
|
||||
// we advertise / answer OTA_QUERY with) is the lightweight _serve[] registry.
|
||||
|
||||
bool OtaManager::serve(const uint8_t* mota, uint32_t len) {
|
||||
if (!mota_parse(mota, len, _view0.m)) return false;
|
||||
_view0.mfl = (uint16_t)(_view0.m.leaves - _view0.m.manifest_start); // contiguous container
|
||||
_view0.read = nullptr; _view0.read_ctx = nullptr; // payload is contiguous _view0.m.payload
|
||||
_view0.scratch = _scratch; _view0.scratch_sz = sizeof(_scratch); // <=1024 blocks (RAM .mota is small)
|
||||
_view0.valid = true;
|
||||
registerSelfEntry();
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OtaManager::serve_self(const uint8_t* manifest, uint16_t mfl, const uint8_t* leaves,
|
||||
uint32_t block_count, uint8_t* proof_scratch, uint32_t proof_scratch_sz,
|
||||
ServeReadFn read, void* ctx) {
|
||||
if (proof_scratch_sz < (uint64_t)block_count * 4) return false; // proof-gen needs count*4 working bytes
|
||||
if (!mota_parse_manifest(manifest, mfl, _view0.m)) return false; // fixed fields: root, image_hash, sizes
|
||||
_view0.m.manifest_start = manifest;
|
||||
_view0.m.leaves = leaves; // pre-computed, caller-owned (heap)
|
||||
_view0.m.payload = nullptr; // read on demand via `read`
|
||||
_view0.m.block_count = block_count;
|
||||
_view0.mfl = mfl; _view0.read = read; _view0.read_ctx = ctx;
|
||||
_view0.scratch = proof_scratch; _view0.scratch_sz = proof_scratch_sz; // sized for our (large) image
|
||||
_view0.valid = true;
|
||||
registerSelfEntry();
|
||||
return true;
|
||||
}
|
||||
|
||||
// (Re)build registry slot 0 from view0 (our own fw / RAM mota). Keeps any source entries in [1..].
|
||||
void OtaManager::registerSelfEntry() {
|
||||
if (!_view0.valid) return;
|
||||
ServeEntry& e = _serve[0];
|
||||
memcpy(e.mid, _view0.m.merkle_root, 4);
|
||||
e.target_id = _view0.m.target_id; e.fw_version = _view0.m.fw_version;
|
||||
e.codec_id = _view0.m.codec_id; e.flags = _view0.m.flags; e.have_count = _view0.m.block_count;
|
||||
e.is_self = true; e.src = nullptr; e.src_idx = 0;
|
||||
if (_n_serve == 0) _n_serve = 1;
|
||||
}
|
||||
|
||||
bool OtaManager::add_source(MotaSource* src) {
|
||||
if (!src || _n_src_obj >= OTA_MAX_SOURCE_OBJ) return false;
|
||||
_src_list[_n_src_obj++] = src;
|
||||
refresh_sources();
|
||||
return true;
|
||||
}
|
||||
|
||||
void OtaManager::refresh_sources() {
|
||||
uint8_t base = _view0.valid ? 1 : 0; // entry 0 stays our own fw
|
||||
if (_view0.valid) registerSelfEntry();
|
||||
_n_serve = base;
|
||||
for (uint8_t s = 0; s < _n_src_obj; s++) {
|
||||
MotaSource* src = _src_list[s];
|
||||
if (!src) continue;
|
||||
uint8_t cnt = src->count();
|
||||
for (uint8_t i = 0; i < cnt && _n_serve < OTA_MAX_SERVE; i++) {
|
||||
MotaDesc d;
|
||||
if (!src->describe(i, d)) continue;
|
||||
if (serveEntryIndex(d.mid) >= 0) continue; // already offered (e.g. our own fw in the folder)
|
||||
ServeEntry& e = _serve[_n_serve++];
|
||||
memcpy(e.mid, d.mid, 4);
|
||||
e.target_id = d.target_id; e.fw_version = d.fw_version;
|
||||
e.codec_id = d.codec_id; e.flags = d.flags; e.have_count = d.block_count; // a folder mota is fully held
|
||||
e.is_self = false; e.src = src; e.src_idx = i; e.desc = d;
|
||||
}
|
||||
}
|
||||
_srcv.valid = false; // a loaded source view may now be stale; reloads on demand
|
||||
}
|
||||
|
||||
void OtaManager::clear_sources() {
|
||||
_n_src_obj = 0; _srcv.valid = false;
|
||||
_n_serve = _view0.valid ? 1 : 0;
|
||||
if (_view0.valid) registerSelfEntry();
|
||||
}
|
||||
|
||||
int OtaManager::serveEntryIndex(const uint8_t* mid) const {
|
||||
for (uint8_t i = 0; i < _n_serve; i++)
|
||||
if (memcmp(_serve[i].mid, mid, 4) == 0) return i;
|
||||
return -1;
|
||||
}
|
||||
|
||||
OtaManager::ServeView* OtaManager::resolve(const uint8_t* mid) {
|
||||
if (_view0.valid && memcmp(mid, _view0.m.merkle_root, 4) == 0) return &_view0;
|
||||
if (_srcv.valid && memcmp(mid, _srcv_mid, 4) == 0) return &_srcv;
|
||||
int i = serveEntryIndex(mid);
|
||||
if (i < 0) return nullptr;
|
||||
if (_serve[i].is_self) return _view0.valid ? &_view0 : nullptr;
|
||||
return loadSource(_serve[i]) ? &_srcv : nullptr;
|
||||
}
|
||||
|
||||
// Load an external mota into the on-demand _srcv: read its manifest-minus-leaves + leaves[] from the
|
||||
// source into RAM, parse, and wire a payload reader that streams blocks from the source on REQ. (The
|
||||
// payload itself is NOT held in RAM — only the small head + the leaves, <=4 KB for <=1024 blocks.)
|
||||
bool OtaManager::loadSource(const ServeEntry& e) {
|
||||
const MotaDesc& d = e.desc;
|
||||
if (d.leaves_off < 8) return false;
|
||||
if (!e.src) return false;
|
||||
uint16_t mfl = (uint16_t)(d.leaves_off - 8);
|
||||
if (mfl == 0 || mfl > sizeof(_src_manifest)) return false;
|
||||
if (d.block_count == 0 || (uint64_t)d.block_count * 4 > sizeof(_src_leaves)) return false;
|
||||
bool ok = e.src->read(e.src_idx, 8, _src_manifest, mfl);
|
||||
if (!ok || !mota_parse_manifest(_src_manifest, mfl, _srcv.m)) return false;
|
||||
if (memcmp(_srcv.m.merkle_root, d.mid, 4) != 0) return false; // descriptor/bytes disagree
|
||||
if (_srcv.m.block_count != d.block_count) return false;
|
||||
ok = e.src->read(e.src_idx, d.leaves_off, _src_leaves, d.block_count * 4);
|
||||
if (!ok) return false;
|
||||
_srcv.m.manifest_start = _src_manifest;
|
||||
_srcv.m.leaves = _src_leaves;
|
||||
_srcv.m.payload = nullptr;
|
||||
_srcv.mfl = mfl;
|
||||
_srcv_rdctx.src = e.src; _srcv_rdctx.idx = e.src_idx;
|
||||
_srcv_rdctx.payload_off = d.payload_off;
|
||||
_srcv.read = srcReadTramp; _srcv.read_ctx = &_srcv_rdctx;
|
||||
_srcv.scratch = _scratch; _srcv.scratch_sz = sizeof(_scratch);
|
||||
memcpy(_srcv_mid, d.mid, 4);
|
||||
_srcv.valid = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
// ServeReadFn trampoline: payload-relative offset -> absolute read of the backing (external source or fetch store).
|
||||
bool OtaManager::srcReadTramp(void* c, uint32_t off, uint8_t* buf, uint32_t len) {
|
||||
SrcReadCtx* x = (SrcReadCtx*)c;
|
||||
return x->src->read(x->idx, x->payload_off + off, buf, len);
|
||||
}
|
||||
|
||||
// sha2-256:4 over the SORTED set of mids we serve — peers use it to tell if our offering changed. Sorting
|
||||
// makes it canonical across nodes regardless of insert order; for a single mota it is mh4(mid) (unchanged).
|
||||
void OtaManager::setDigest(uint8_t out[4]) const {
|
||||
if (_n_serve == 0) { memset(out, 0, 4); return; }
|
||||
uint8_t order[OTA_MAX_SERVE];
|
||||
for (uint8_t i = 0; i < _n_serve; i++) order[i] = i;
|
||||
for (uint8_t i = 1; i < _n_serve; i++) { // insertion sort by mid (n <= 12)
|
||||
uint8_t v = order[i]; int j = (int)i - 1;
|
||||
while (j >= 0 && memcmp(_serve[order[j]].mid, _serve[v].mid, 4) > 0) { order[j+1] = order[j]; j--; }
|
||||
order[j+1] = v;
|
||||
}
|
||||
uint8_t cat[OTA_MAX_SERVE * 4];
|
||||
for (uint8_t i = 0; i < _n_serve; i++) memcpy(cat + (uint32_t)i * 4, _serve[order[i]].mid, 4);
|
||||
mh4(out, cat, (size_t)_n_serve * 4);
|
||||
}
|
||||
|
||||
void OtaManager::announce() { // tiny per-node beacon (constant size, independent of how many mOTAs)
|
||||
AdvMsg a;
|
||||
memcpy(a.seeder_id, _seeder_id, 4);
|
||||
a.n_motas = _n_serve;
|
||||
setDigest(a.set_digest);
|
||||
uint8_t b[16];
|
||||
emit(b, encode_adv(b, sizeof(b), a), true);
|
||||
}
|
||||
|
||||
// OTA_QUERY: two roles. (1) OVERHEAR-SUPPRESSION — any node that has a pending query for the same
|
||||
// {source,digest} cancels it (someone else already asked; the broadcast HAVE is coming). (2) If the query
|
||||
// is addressed to US, reply with our catalog (broadcast, tagged with our digest so every overhearer caches
|
||||
// it). All served mOTAs matching filter_target are returned, fragmented if they exceed one packet.
|
||||
void OtaManager::handleQuery(const uint8_t* m, uint16_t n) {
|
||||
QueryMsg q;
|
||||
if (!decode_query(m, n, q)) return;
|
||||
if (_pq_active && memcmp(_pq_seeder, q.seeder_id, 4) == 0 && memcmp(_pq_digest, q.set_digest, 4) == 0)
|
||||
_pq_active = false; // (1) suppress our own pending query
|
||||
if (_n_serve == 0 || memcmp(q.seeder_id, _seeder_id, 4) != 0) return; // (2) only WE answer queries to us
|
||||
uint8_t dg[4]; setDigest(dg);
|
||||
uint8_t rowbuf[OTA_MAX_SERVE * OTA_HAVE_ROW_BYTES];
|
||||
uint8_t nm = 0;
|
||||
for (uint8_t i = 0; i < _n_serve; i++) {
|
||||
const ServeEntry& e = _serve[i];
|
||||
if (q.filter_target != 0 && q.filter_target != e.target_id) continue;
|
||||
uint8_t* row = rowbuf + (uint32_t)nm * OTA_HAVE_ROW_BYTES;
|
||||
memcpy(row, e.mid, 4);
|
||||
wr_u32le(row + 4, e.target_id); wr_u32le(row + 8, e.fw_version);
|
||||
row[12] = e.codec_id; row[13] = e.flags;
|
||||
uint32_t hc = e.have_count > 0xFFFFu ? 0xFFFFu : e.have_count; // blocks we hold (awareness for fetchers)
|
||||
row[14] = (uint8_t)(hc & 0xFF); row[15] = (uint8_t)(hc >> 8);
|
||||
nm++;
|
||||
}
|
||||
const uint8_t per = (uint8_t)((MAX_PACKET_PAYLOAD - 12) / OTA_HAVE_ROW_BYTES); // rows per HAVE fragment
|
||||
uint8_t ftotal = (uint8_t)((nm + per - 1) / per); if (ftotal == 0) ftotal = 1;
|
||||
for (uint8_t fi = 0; fi < ftotal; fi++) {
|
||||
uint8_t bse = (uint8_t)(fi * per);
|
||||
uint8_t cnt = (uint8_t)((nm - bse > per) ? per : (nm - bse));
|
||||
HaveMsg hv; memcpy(hv.seeder_id, _seeder_id, 4); memcpy(hv.set_digest, dg, 4);
|
||||
hv.frag_idx = fi; hv.frag_total = ftotal; hv.n_rows = cnt;
|
||||
hv.rows = cnt ? (rowbuf + (uint32_t)bse * OTA_HAVE_ROW_BYTES) : nullptr;
|
||||
uint8_t b[MAX_PACKET_PAYLOAD];
|
||||
emit(b, encode_have(b, sizeof(b), hv), true); // broadcast: all neighbours cache it
|
||||
}
|
||||
}
|
||||
|
||||
void OtaManager::handleGetManifest(const uint8_t* m, uint16_t n) {
|
||||
GetManifestMsg gm;
|
||||
if (!decode_get_manifest(m, n, gm)) return;
|
||||
ServeView* v = resolve(gm.manifest_id);
|
||||
if (!v) return;
|
||||
// A signed v2 manifest (with hw_id[32]) exceeds one LoRa packet, so send it as fragments. Each carries
|
||||
// up to OTA_MF_FRAG manifest bytes; the client reassembles by frag_idx. Only the fragments requested in
|
||||
// want_mask are sent (0xFFFF = all), so a retry re-sends just the holes, not the whole manifest.
|
||||
uint32_t mfl = v->mfl;
|
||||
const uint8_t* src = v->m.manifest_start;
|
||||
uint8_t ftotal = (uint8_t)((mfl + OTA_MF_FRAG - 1) / OTA_MF_FRAG); if (ftotal == 0) ftotal = 1;
|
||||
for (uint8_t fi = 0; fi < ftotal; fi++) {
|
||||
if (!(gm.want_mask & (1u << fi))) continue; // fetcher didn't ask for this manifest fragment
|
||||
uint32_t off = (uint32_t)fi * OTA_MF_FRAG;
|
||||
uint32_t fl = mfl - off; if (fl > OTA_MF_FRAG) fl = OTA_MF_FRAG;
|
||||
ManifestMsg mm;
|
||||
memcpy(mm.manifest_id, v->m.merkle_root, 4);
|
||||
mm.frag_idx = fi; mm.frag_total = ftotal;
|
||||
mm.bytes = src + off; mm.len = (uint16_t)fl;
|
||||
uint8_t b[MAX_PACKET_PAYLOAD];
|
||||
emit(b, encode_manifest(b, sizeof(b), mm), false);
|
||||
}
|
||||
}
|
||||
|
||||
// Serve the target's merkle leaves[] in fragments (for a motatool folder-capture warm-start). Only the
|
||||
// fragments set in want_mask are emitted, so a want_mask retry re-sends just the holes — never a full burst
|
||||
// (same anti-deadlock rationale as OTA_MANIFEST). This is the only leaf-diff piece that runs on every node.
|
||||
void OtaManager::handleGetLeaves(const uint8_t* m, uint16_t n) {
|
||||
GetLeavesMsg gl;
|
||||
if (!decode_get_leaves(m, n, gl)) return;
|
||||
ServeView* v = resolve(gl.manifest_id);
|
||||
if (!v || !v->m.leaves) return;
|
||||
uint32_t leaves_len = v->m.block_count * 4;
|
||||
uint8_t ftotal = (uint8_t)((leaves_len + OTA_LEAVES_FRAG - 1) / OTA_LEAVES_FRAG); if (ftotal == 0) ftotal = 1;
|
||||
for (uint8_t fi = 0; fi < ftotal; fi++) {
|
||||
if (!(gl.want_mask & (1u << fi))) continue; // fetcher didn't ask for this leaves fragment
|
||||
uint32_t off = (uint32_t)fi * OTA_LEAVES_FRAG;
|
||||
uint32_t fl = leaves_len - off; if (fl > OTA_LEAVES_FRAG) fl = OTA_LEAVES_FRAG;
|
||||
LeavesMsg lm;
|
||||
memcpy(lm.manifest_id, v->m.merkle_root, 4);
|
||||
lm.frag_idx = fi; lm.frag_total = ftotal;
|
||||
lm.bytes = v->m.leaves + off; lm.len = (uint16_t)fl;
|
||||
uint8_t b[MAX_PACKET_PAYLOAD];
|
||||
emit(b, encode_leaves(b, sizeof(b), lm), false);
|
||||
}
|
||||
}
|
||||
|
||||
// Smallest mask covering `nf` fragments: bit k set for k in [0, nf). Caps at 16 (matches _reasm_mask and
|
||||
// the manifest reassembly), which bounds a block at 16 fragments — our 1 KB blocks are 7.
|
||||
static inline uint16_t frag_full_mask(uint32_t nf) {
|
||||
return (nf >= 16) ? 0xFFFFu : (uint16_t)((1u << nf) - 1);
|
||||
}
|
||||
|
||||
// Emit one block's data as self-describing DATA fragments (frag_off); only the fragments whose bit is set
|
||||
// in `want_mask` are sent (bit k = the slice at k*OTA_FRAG_DATA). The proof is fetched separately.
|
||||
void OtaManager::emitBlockData(const uint8_t* mid, uint32_t idx, const uint8_t* data, uint32_t blen,
|
||||
uint16_t want_mask) {
|
||||
uint32_t k = 0;
|
||||
for (uint32_t fo = 0; fo < blen; fo += OTA_FRAG_DATA, k++) {
|
||||
if (!(want_mask & (1u << k))) continue; // fetcher didn't ask for this fragment
|
||||
uint32_t fl = (fo + OTA_FRAG_DATA <= blen) ? OTA_FRAG_DATA : (blen - fo);
|
||||
DataMsg dm;
|
||||
memcpy(dm.manifest_id, mid, 4);
|
||||
dm.block_idx = (uint16_t)idx; dm.frag_off = (uint16_t)fo;
|
||||
dm.data = data + fo; dm.data_len = (uint16_t)fl;
|
||||
uint8_t b[MAX_PACKET_PAYLOAD];
|
||||
emit(b, encode_data(b, sizeof(b), dm), false);
|
||||
}
|
||||
}
|
||||
|
||||
void OtaManager::handleReq(const uint8_t* m, uint16_t n) {
|
||||
ReqMsg rq;
|
||||
if (!decode_req(m, n, rq)) return;
|
||||
uint32_t idx = rq.block_idx;
|
||||
ServeView* v = resolve(rq.manifest_id);
|
||||
if (v) { // serve a fully-held mota (own fw or attached folder)
|
||||
if (idx >= v->m.block_count) return;
|
||||
uint32_t bs = v->m.block_size();
|
||||
uint32_t off = idx * bs;
|
||||
uint32_t blen = (off + bs <= v->m.payload_size) ? bs : (v->m.payload_size - off);
|
||||
uint8_t blk[OTA_MAX_BLOCK];
|
||||
const uint8_t* data;
|
||||
if (v->read) { if (!v->read(v->read_ctx, off, blk, blen)) return; data = blk; }
|
||||
else { data = v->m.payload + off; }
|
||||
emitBlockData(v->m.merkle_root, idx, data, blen, rq.want_mask);
|
||||
}
|
||||
}
|
||||
|
||||
void OtaManager::handleReqProof(const uint8_t* m, uint16_t n) {
|
||||
ReqProofMsg rp;
|
||||
if (!decode_req_proof(m, n, rp)) return;
|
||||
ServeView* v = resolve(rp.manifest_id);
|
||||
if (!v) return;
|
||||
if (rp.block_idx >= v->m.block_count) return;
|
||||
if ((uint64_t)v->m.block_count * 4 > v->scratch_sz) return; // proof-gen needs block_count*4 scratch
|
||||
uint8_t proof[32 * 4];
|
||||
uint8_t np = merkle_gen_proof(v->m.leaves, v->m.block_count, rp.block_idx, v->scratch, proof);
|
||||
ProofMsg pm;
|
||||
memcpy(pm.manifest_id, v->m.merkle_root, 4);
|
||||
pm.block_idx = rp.block_idx; pm.n_proof = np; pm.proof = proof;
|
||||
uint8_t b[MAX_PACKET_PAYLOAD];
|
||||
emit(b, encode_proof(b, sizeof(b), pm), false);
|
||||
}
|
||||
|
||||
// ---------------- fetch ----------------
|
||||
|
||||
// A tiny per-node BEACON: record the source; ask it for its catalog (OTA_QUERY) only when we're
|
||||
// interested AND its set-digest is one we haven't catalogued yet (so a stable mesh is query-free).
|
||||
void OtaManager::handleAdv(const uint8_t* m, uint16_t n) {
|
||||
AdvMsg a;
|
||||
if (!decode_adv(m, n, a)) return;
|
||||
bool have_sid = (_seeder_id[0] | _seeder_id[1] | _seeder_id[2] | _seeder_id[3]) != 0;
|
||||
if (have_sid && memcmp(a.seeder_id, _seeder_id, 4) == 0) return; // our own beacon, re-flooded
|
||||
if (a.n_motas == 0) return; // source offers nothing
|
||||
|
||||
int slot = -1, lru = 0; // find/insert the source (LRU evict)
|
||||
for (int i = 0; i < _n_src; i++) {
|
||||
if (memcmp(_sources[i].seeder, a.seeder_id, 4) == 0) { slot = i; break; }
|
||||
if (_sources[i].last_ms < _sources[lru].last_ms) lru = i;
|
||||
}
|
||||
bool fresh = (slot < 0);
|
||||
if (fresh) { slot = (_n_src < OTA_MAX_SOURCES) ? _n_src++ : lru; _sources[slot] = Source{}; }
|
||||
Source& s = _sources[slot];
|
||||
bool changed = fresh || memcmp(s.digest, a.set_digest, 4) != 0;
|
||||
memcpy(s.seeder, a.seeder_id, 4); memcpy(s.digest, a.set_digest, 4);
|
||||
s.n_motas = a.n_motas; s.last_ms = _now_ms;
|
||||
if (changed) s.have_catalog = false;
|
||||
|
||||
// interested = auto-fetch enabled, or a manual pull/want is pending. (Browsing queries via queryAll().)
|
||||
bool interested = (_autofetch != AUTOFETCH_OFF) || _have_desired_mid || _desired_target;
|
||||
if (interested && !s.have_catalog) scheduleQuery(a.seeder_id, a.set_digest); // jittered + suppressible
|
||||
}
|
||||
|
||||
// Schedule a catalog query after a random jitter (id ⊕ digest, so neighbours pick different delays). The
|
||||
// node with the shortest jitter sends; the rest overhear that QUERY (or the broadcast HAVE) and suppress.
|
||||
void OtaManager::scheduleQuery(const uint8_t* seeder, const uint8_t* digest) {
|
||||
if (_pq_active && memcmp(_pq_seeder, seeder, 4) == 0 && memcmp(_pq_digest, digest, 4) == 0) return; // already pending
|
||||
memcpy(_pq_seeder, seeder, 4); memcpy(_pq_digest, digest, 4);
|
||||
uint32_t j = (rd_u32le(seeder) ^ rd_u32le(digest) ^ rd_u32le(_seeder_id)) % OTA_QUERY_SPREAD_MS;
|
||||
_pq_at = _now_ms + OTA_QUERY_MIN_MS + j;
|
||||
_pq_active = true;
|
||||
}
|
||||
|
||||
void OtaManager::sendQuery(const uint8_t* seeder, const uint8_t* digest, uint32_t filter_target) {
|
||||
QueryMsg q; memcpy(q.seeder_id, seeder, 4); memcpy(q.set_digest, digest, 4); q.filter_target = filter_target;
|
||||
uint8_t b[16];
|
||||
emit(b, encode_query(b, sizeof(b), q), true); // FLOODED so neighbours overhear it and suppress
|
||||
}
|
||||
|
||||
// User-initiated browse (`ota neighbors`): ask every known source now (no jitter — infrequent + explicit).
|
||||
void OtaManager::queryAll() { for (uint8_t i = 0; i < _n_src; i++) sendQuery(_sources[i].seeder, _sources[i].digest, 0); }
|
||||
|
||||
// A catalog reply: record each mOTA (deduped by mid; distinct-source count for the UI), and if a row
|
||||
// matches our fetch interest (auto-fetch own-target, or a pending pull/want), begin fetching it.
|
||||
void OtaManager::handleHave(const uint8_t* m, uint16_t n) {
|
||||
HaveMsg hv;
|
||||
if (!decode_have(m, n, hv)) return;
|
||||
bool have_sid = (_seeder_id[0] | _seeder_id[1] | _seeder_id[2] | _seeder_id[3]) != 0;
|
||||
if (have_sid && memcmp(hv.seeder_id, _seeder_id, 4) == 0) return; // our own catalog
|
||||
// PASSIVE: any overheard HAVE marks its source catalogued + cancels a pending query for it (storm
|
||||
// suppression) — every node caches the rows below, even one that never queried.
|
||||
for (uint8_t i = 0; i < _n_src; i++)
|
||||
if (memcmp(_sources[i].seeder, hv.seeder_id, 4) == 0 && memcmp(_sources[i].digest, hv.set_digest, 4) == 0)
|
||||
_sources[i].have_catalog = true;
|
||||
if (_pq_active && memcmp(_pq_seeder, hv.seeder_id, 4) == 0 && memcmp(_pq_digest, hv.set_digest, 4) == 0)
|
||||
_pq_active = false;
|
||||
for (uint8_t r = 0; r < hv.n_rows && hv.rows; r++) {
|
||||
const uint8_t* row = hv.rows + (uint32_t)r * OTA_HAVE_ROW_BYTES;
|
||||
const uint8_t* mid = row;
|
||||
uint32_t target = rd_u32le(row + 4), fwver = rd_u32le(row + 8);
|
||||
uint8_t codec = row[12], flags = row[13];
|
||||
uint32_t have_count = rd_u16le(row + 14); // this source's progress
|
||||
int slot = -1, lru = 0; // upsert into the catalog (dedup by mid)
|
||||
for (int i = 0; i < _n_cat; i++) {
|
||||
if (memcmp(_catalog[i].mid, mid, 4) == 0) { slot = i; break; }
|
||||
if (_catalog[i].last_ms < _catalog[lru].last_ms) lru = i;
|
||||
}
|
||||
if (slot < 0) {
|
||||
slot = (_n_cat < OTA_MAX_CATALOG) ? _n_cat++ : lru;
|
||||
_catalog[slot] = CatRow{};
|
||||
memcpy(_catalog[slot].mid, mid, 4);
|
||||
memcpy(_catalog[slot].seeders[0], hv.seeder_id, 4);
|
||||
_catalog[slot].n_seeders = 1;
|
||||
} else {
|
||||
CatRow& cc = _catalog[slot]; // count DISTINCT sources (no double-count)
|
||||
bool known = false;
|
||||
for (uint8_t k = 0; k < cc.n_seeders; k++)
|
||||
if (memcmp(cc.seeders[k], hv.seeder_id, 4) == 0) { known = true; break; }
|
||||
if (!known && cc.n_seeders < OTA_CAT_SEEDERS) memcpy(cc.seeders[cc.n_seeders++], hv.seeder_id, 4);
|
||||
}
|
||||
CatRow& c = _catalog[slot];
|
||||
c.target_id = target; c.fw_version = fwver; c.codec = codec; c.flags = flags; c.last_ms = _now_ms;
|
||||
if (have_count > c.have_max) c.have_max = have_count; // best-known progress among sources
|
||||
if (wantRow(mid, target, codec, flags)) startFetch(mid, target);
|
||||
}
|
||||
}
|
||||
|
||||
bool OtaManager::wantRow(const uint8_t* mid, uint32_t target, uint8_t codec, uint8_t flags) const {
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST || _fstate == PAUSED) return false; // busy
|
||||
if (_fstate == COMPLETE && memcmp(mid, _fid, 4) == 0) return false; // already have it
|
||||
if (!codecOk(codec)) return false; // can't apply this codec
|
||||
if (_have_desired_mid) // manual pull of a specific mid
|
||||
return memcmp(mid, _desired_mid, 4) == 0 && (_desired_target == 0 || target == _desired_target);
|
||||
if (_desired_target) return target == _desired_target; // cross-target want (role switch)
|
||||
if (_autofetch == AUTOFETCH_OFF) return false; // discover only
|
||||
if (target != _target) return false; // auto-fetch = our own target
|
||||
if (_autofetch == AUTOFETCH_SIGNED && !(flags & MFLAG_SIGNED)) return false; // signed-only policy
|
||||
return true;
|
||||
}
|
||||
|
||||
// Forget the block currently being reassembled / awaited (back to NO_BLOCK). Safe to call between blocks:
|
||||
// the next DATA fragment re-derives the slice mask for whatever block it belongs to.
|
||||
void OtaManager::clearReassembly() {
|
||||
_reasm_block = NO_BLOCK; _reasm_mask = 0; _reasm_need = 0; _awaiting_proof = false;
|
||||
}
|
||||
|
||||
// Begin (or resume) fetching a chosen mid: try a staged-partial resume first, else request the manifest.
|
||||
void OtaManager::startFetch(const uint8_t* mid, uint32_t target, bool validate) {
|
||||
(void)target;
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST || _fstate == WANT_LEAVES || _fstate == PAUSED) return;
|
||||
_validate = validate; // motatool folder-capture warm-start (seed leaf-diff)
|
||||
// A validate pull is a FRESH seed capture, not a resume: the store already holds the seed's payload (not a
|
||||
// real partial), so never adopt it via resumeStaged — always re-begin and run the manifest→leaves→diff.
|
||||
if (!validate && resumeStaged(mid)) return; // (non-validate) resume a partial container left in flash
|
||||
memcpy(_fid, mid, 4);
|
||||
_fstate = WANT_MANIFEST;
|
||||
_mf_total = 0; _mf_mask = 0; _mf_len = 0; _mf_retries = 0; _loop_last_mfmask = 0; // fresh manifest reassembly
|
||||
GetManifestMsg gm; memcpy(gm.manifest_id, _fid, 4); gm.want_mask = 0xFFFF; // first ask: send all fragments
|
||||
uint8_t b[16];
|
||||
emit(b, encode_get_manifest(b, sizeof(b), gm), false);
|
||||
}
|
||||
|
||||
void OtaManager::handleManifest(const uint8_t* m, uint16_t n) {
|
||||
ManifestMsg mm;
|
||||
if (!decode_manifest(m, n, mm) || !_fetch) return;
|
||||
if (_fstate != WANT_MANIFEST || memcmp(mm.manifest_id, _fid, 4) != 0) return;
|
||||
if (mm.frag_total == 0 || mm.frag_total > OTA_MF_MAXFRAG || mm.frag_idx >= mm.frag_total) return;
|
||||
|
||||
// reassemble the (possibly multi-fragment) manifest into _mf_buf; place fragment frag_idx at its offset
|
||||
uint32_t foff = (uint32_t)mm.frag_idx * OTA_MF_FRAG;
|
||||
if (foff + mm.len > sizeof(_mf_buf)) return;
|
||||
if (mm.frag_total != _mf_total) { _mf_total = mm.frag_total; _mf_mask = 0; _mf_len = 0; } // (re)start
|
||||
memcpy(_mf_buf + foff, mm.bytes, mm.len);
|
||||
_mf_mask |= (uint16_t)(1u << mm.frag_idx);
|
||||
if (mm.frag_idx == mm.frag_total - 1) _mf_len = foff + mm.len; // last fragment fixes the length
|
||||
uint16_t full = (mm.frag_total >= 16) ? 0xFFFF : (uint16_t)((1u << mm.frag_total) - 1);
|
||||
if (_mf_mask != full || _mf_len == 0) return; // wait until every fragment is in
|
||||
|
||||
const uint8_t* mf = _mf_buf; // fully reassembled manifest-minus-leaves
|
||||
uint32_t mfl = _mf_len;
|
||||
if (mfl != MOTA_MFL) { _fstate = FAILED; return; } // manifest-minus-leaves is a fixed 197 bytes
|
||||
if (!codecOk(mf[56])) { _fstate = IDLE; return; } // codec we can't apply (lying/stale ADV) — abort
|
||||
uint32_t payload_size = rd_u32le(mf + 15);
|
||||
uint8_t bsl = mf[19];
|
||||
uint32_t bs = 1u << bsl;
|
||||
// a block must fit our reassembly buffer (and be non-empty) — reject an oversized block_size up front
|
||||
if (bs == 0 || bs > OTA_MAX_BLOCK || payload_size == 0) { _fstate = FAILED; return; }
|
||||
uint32_t bc = (payload_size + bs - 1) / bs;
|
||||
if (bc > 0xFFFFu) { _fstate = FAILED; return; } // block_idx is uint16 on the wire — can't address more
|
||||
memcpy(_froot, mf + 20, 4);
|
||||
|
||||
uint32_t leaves_off = 8 + mfl;
|
||||
uint32_t payload_off = leaves_off + bc * 4;
|
||||
uint32_t total = payload_off + payload_size + 5;
|
||||
|
||||
// Hand the store the parsed layout BEFORE begin(), so a partition-backed store (ESP32) can choose
|
||||
// placement and refuse an unfittable fetch up front: a FULL payload streams to the inactive slot,
|
||||
// a delta's whole container is staged together. (image_size at mf+11, is_full from flags at mf+1.)
|
||||
bool is_full = (mf[1] & MFLAG_FULL) != 0;
|
||||
if (!_fetch->plan_layout(is_full, rd_u32le(mf + 11), payload_off, payload_size)) { _fstate = FAILED; return; }
|
||||
if (!_fetch->begin(total)) { _fstate = FAILED; return; }
|
||||
// declare the metadata extent so a flash store can pin it (leaves are written all transfer long)
|
||||
if (!_fetch->set_meta_size(payload_off)) { _fstate = FAILED; return; }
|
||||
uint8_t hdr[8];
|
||||
memcpy(hdr, MOTA_MAGIC, 4);
|
||||
wr_u32le(hdr + 4, total);
|
||||
if (!_fetch->write(0, hdr, 8) ||
|
||||
!_fetch->write(8, mf, mfl) ||
|
||||
!_fetch->write(total - 5, MOTA_TRAILER, 5)) { _fstate = FAILED; return; }
|
||||
|
||||
_fflags = mf[1]; // manifest flags (FULL/SIGNED) of the fetch in progress (auto-install gate)
|
||||
_fpoff = payload_off; _floff = leaves_off; _fpsize = payload_size; _fbc = bc; _fbs = bs;
|
||||
_ftotal = total; _have = 0;
|
||||
clearReassembly(); // fresh transfer: drop any prior per-block state
|
||||
_loop_last_have = 0; _loop_last_mask = 0;
|
||||
// Warm-start (folder-capture): if requested and the image is small enough for the fixed leaves bitmap,
|
||||
// bulk-fetch the target leaves and diff the seed already staged in the store; else just transfer normally.
|
||||
if (_validate && beginLeafDiff()) {
|
||||
OTA_DBG("OTA: WANT_LEAVES bc=%u (seed leaf-diff)\n", (unsigned)bc);
|
||||
return;
|
||||
}
|
||||
_fstate = FETCHING;
|
||||
OTA_DBG("OTA: FETCHING bc=%u bs=%u total=%u\n", (unsigned)bc, (unsigned)bs, (unsigned)total);
|
||||
}
|
||||
|
||||
// --- leaf-diff warm-start (fetcher side; motatool folder-capture only) -----------------------------
|
||||
|
||||
void OtaManager::freeLeaves() {
|
||||
if (_leaves_buf) { free(_leaves_buf); _leaves_buf = nullptr; }
|
||||
_lv_total = 0; _lv_mask = 0; _diffing = false; _diff_idx = 0;
|
||||
}
|
||||
|
||||
// Enter WANT_LEAVES: allocate the target-leaves buffer and request them (bitmap-fragmented). Returns false
|
||||
// — caller falls back to a normal full fetch — if the image is too big for the fixed uint16 leaves bitmap or
|
||||
// the heap allocation fails. Called from handleManifest once geometry is known.
|
||||
bool OtaManager::beginLeafDiff() {
|
||||
freeLeaves();
|
||||
if (_fbc == 0 || _fbc > OTA_DIFF_MAX_BLOCKS) return false; // must fit the fixed want_mask (16 fragments)
|
||||
_leaves_buf = (uint8_t*)malloc((size_t)_fbc * 4);
|
||||
if (!_leaves_buf) return false;
|
||||
_lv_total = 0; _lv_mask = 0; _lv_retries = 0; _loop_last_lvmask = 0;
|
||||
_fstate = WANT_LEAVES;
|
||||
GetLeavesMsg gl; memcpy(gl.manifest_id, _fid, 4); gl.want_mask = 0xFFFF; // first ask: all fragments
|
||||
uint8_t b[16];
|
||||
emit(b, encode_get_leaves(b, sizeof(b), gl), false);
|
||||
return true;
|
||||
}
|
||||
|
||||
// Reassemble the target leaves[] (like the manifest), authenticate them against _froot, then diff the seed.
|
||||
void OtaManager::handleLeaves(const uint8_t* m, uint16_t n) {
|
||||
LeavesMsg lv;
|
||||
if (!decode_leaves(m, n, lv) || !_fetch || !_leaves_buf) return;
|
||||
if (_fstate != WANT_LEAVES || memcmp(lv.manifest_id, _fid, 4) != 0) return;
|
||||
uint32_t leaves_len = _fbc * 4;
|
||||
uint8_t ftotal = (uint8_t)((leaves_len + OTA_LEAVES_FRAG - 1) / OTA_LEAVES_FRAG); if (ftotal == 0) ftotal = 1;
|
||||
if (lv.frag_total != ftotal || lv.frag_idx >= ftotal) return;
|
||||
uint32_t foff = (uint32_t)lv.frag_idx * OTA_LEAVES_FRAG;
|
||||
if (foff + lv.len > leaves_len) return; // slice out of range
|
||||
if (lv.frag_total != _lv_total) { _lv_total = lv.frag_total; _lv_mask = 0; } // (re)start
|
||||
memcpy(_leaves_buf + foff, lv.bytes, lv.len);
|
||||
_lv_mask |= (uint16_t)(1u << lv.frag_idx);
|
||||
OTA_DBG("OTA: LEAVES rx frag=%u/%u len=%u mask=%04x\n",
|
||||
(unsigned)lv.frag_idx, (unsigned)lv.frag_total, (unsigned)lv.len, (unsigned)_lv_mask);
|
||||
uint16_t full = (ftotal >= 16) ? 0xFFFF : (uint16_t)((1u << ftotal) - 1);
|
||||
if (_lv_mask != full) return; // wait for every fragment
|
||||
uint8_t root[4]; merkle_root(root, _leaves_buf, _fbc); // authenticate the leaves against the manifest root
|
||||
if (memcmp(root, _froot, 4) != 0) { // can't trust them -> just fetch normally
|
||||
OTA_DBG("OTA: leaves root mismatch -> full fetch\n");
|
||||
freeLeaves(); _fstate = FETCHING; requestMissing(); return;
|
||||
}
|
||||
// leaves authenticated -> diff the seed against them a batch at a time in loop() (559 store reads must not
|
||||
// block the mesh loop / starve the radio / trip the watchdog). Stay WANT_LEAVES; diffStep() drives it.
|
||||
_diffing = true; _diff_idx = 0;
|
||||
OTA_DBG("OTA: leaves ok (root match); diffing seed...\n");
|
||||
}
|
||||
|
||||
// Diff up to OTA_DIFF_BATCH seed blocks per call: every block whose seed bytes (already staged in the store
|
||||
// payload) hash to the authenticated target leaf is marked present; the rest stay missing and are pulled over
|
||||
// LoRa. When all blocks are diffed, continue as a normal FETCHING of the holes (or finalize if none differ).
|
||||
void OtaManager::diffStep() {
|
||||
uint8_t blk[OTA_MAX_BLOCK];
|
||||
for (uint32_t k = 0; k < OTA_DIFF_BATCH && _diff_idx < _fbc; k++, _diff_idx++) {
|
||||
uint32_t blen = blockLen(_diff_idx);
|
||||
if (!_fetch->read(_fpoff + _diff_idx * _fbs, blk, blen)) continue; // read fail -> leave missing
|
||||
uint8_t leaf[4]; merkle_leaf(leaf, blk, blen);
|
||||
if (memcmp(leaf, _leaves_buf + (size_t)_diff_idx * 4, 4) == 0 && // seed block == target block
|
||||
_fetch->write(_floff + _diff_idx * 4, _leaves_buf + (size_t)_diff_idx * 4, 4))
|
||||
_have++; // mark present (payload already seeded)
|
||||
}
|
||||
if (_diff_idx < _fbc) return; // more to diff on the next tick
|
||||
OTA_DBG("OTA: leaf-diff %u/%u already valid; fetching the rest\n", (unsigned)_have, (unsigned)_fbc);
|
||||
freeLeaves(); // clears _diffing + frees the buffer
|
||||
if (_have >= _fbc) { // seed covered the whole image
|
||||
_fstate = COMPLETE; _fetch->finalize();
|
||||
return;
|
||||
}
|
||||
_fstate = FETCHING; requestMissing();
|
||||
}
|
||||
|
||||
bool OtaManager::resumeStaged(const uint8_t* want_mid) {
|
||||
if (!_fetch || _fstate == FETCHING || _fstate == WANT_MANIFEST) return false;
|
||||
if (!_fetch->reopen()) return false; // nothing persisted in the store
|
||||
uint32_t total = _fetch->staged_size();
|
||||
uint8_t hdr[8];
|
||||
if (total < 13 || !_fetch->read(0, hdr, 8) || memcmp(hdr, MOTA_MAGIC, 4) != 0) return false;
|
||||
// read + parse the stored manifest (everything before leaves[]) to recompute the geometry
|
||||
uint8_t mbuf[256];
|
||||
uint32_t mread = total - 8; if (mread > sizeof(mbuf)) mread = sizeof(mbuf);
|
||||
MotaManifest m;
|
||||
if (!_fetch->read(8, mbuf, mread) || !mota_parse_manifest(mbuf, mread, m)) return false;
|
||||
if (want_mid && memcmp(m.merkle_root, want_mid, 4) != 0) return false; // a different fw is staged
|
||||
if (!codecOk(m.codec_id)) return false;
|
||||
uint32_t mfl = (uint32_t)(m.approval - m.manifest_start) + 4; // manifest-minus-leaves length
|
||||
uint32_t bs = m.block_size();
|
||||
if (bs == 0 || bs > OTA_MAX_BLOCK) return false;
|
||||
uint32_t bc = m.block_count;
|
||||
uint32_t leaves_off = 8 + mfl;
|
||||
uint32_t payload_off = leaves_off + bc * 4;
|
||||
if ((uint64_t)payload_off + m.payload_size + 5 != total) return false; // geometry must match the header
|
||||
|
||||
memcpy(_fid, m.merkle_root, 4);
|
||||
memcpy(_froot, m.merkle_root, 4);
|
||||
_fflags = m.flags;
|
||||
_fpoff = payload_off; _floff = leaves_off; _fpsize = m.payload_size; _fbc = bc; _fbs = bs;
|
||||
_ftotal = total;
|
||||
_have = 0;
|
||||
for (uint32_t i = 0; i < bc; i++) if (blockPresent(i)) _have++; // count blocks whose leaf survived
|
||||
clearReassembly();
|
||||
_loop_last_have = 0; _loop_last_mask = 0;
|
||||
OTA_DBG("OTA: RESUME have=%u/%u total=%u\n", (unsigned)_have, (unsigned)bc, (unsigned)total);
|
||||
|
||||
if (_have >= bc) { // already complete -> verify root + finalize
|
||||
if (bc * 4 <= sizeof(_scratch) && _fetch->read(_floff, _scratch, bc * 4)) {
|
||||
uint8_t root[4]; merkle_root(root, _scratch, bc);
|
||||
_fstate = (memcmp(root, _froot, 4) == 0) ? COMPLETE : FAILED;
|
||||
} else {
|
||||
_fstate = COMPLETE;
|
||||
}
|
||||
if (_fstate == COMPLETE) _fetch->finalize();
|
||||
return true;
|
||||
}
|
||||
_fstate = FETCHING; // resume fetching the holes
|
||||
_loop_last_have = _have; _loop_last_mask = _reasm_mask;
|
||||
return true;
|
||||
}
|
||||
|
||||
uint32_t OtaManager::blockLen(uint32_t i) const {
|
||||
uint32_t off = i * _fbs;
|
||||
return (off + _fbs <= _fpsize) ? _fbs : (_fpsize - off);
|
||||
}
|
||||
|
||||
bool OtaManager::blockPresent(uint32_t i) const {
|
||||
uint8_t leaf[4];
|
||||
if (!_fetch->read(_floff + i * 4, leaf, 4)) return false;
|
||||
return !(leaf[0]==0xFF && leaf[1]==0xFF && leaf[2]==0xFF && leaf[3]==0xFF);
|
||||
}
|
||||
|
||||
void OtaManager::handleData(const uint8_t* m, uint16_t n) {
|
||||
DataMsg dm;
|
||||
if (!decode_data(m, n, dm) || !_fetch) return;
|
||||
if (_fstate != FETCHING || memcmp(dm.manifest_id, _fid, 4) != 0) return;
|
||||
if (dm.block_idx >= _fbc) return;
|
||||
if (blockPresent(dm.block_idx)) return; // already stored + verified
|
||||
uint32_t blen = blockLen(dm.block_idx);
|
||||
if (dm.frag_off % OTA_FRAG_DATA != 0) return; // canonical FRAG_DATA-aligned slices only
|
||||
if ((uint32_t)dm.frag_off + dm.data_len > blen) return; // slice out of the block
|
||||
if (dm.block_idx != _reasm_block) { // (re)start reassembly for this block
|
||||
_reasm_block = dm.block_idx; _reasm_mask = 0; _awaiting_proof = false;
|
||||
uint32_t nf = (blen + OTA_FRAG_DATA - 1) / OTA_FRAG_DATA;
|
||||
_reasm_need = (nf >= 16) ? 0xFFFF : (uint16_t)((1u << nf) - 1);
|
||||
}
|
||||
uint32_t kf = dm.frag_off / OTA_FRAG_DATA;
|
||||
if (kf >= 16) return;
|
||||
memcpy(_reasm_buf + dm.frag_off, dm.data, dm.data_len);
|
||||
_reasm_mask |= (uint16_t)(1u << kf);
|
||||
if (_reasm_mask != _reasm_need || _awaiting_proof) return; // wait for all slices (or proof already asked)
|
||||
// block fully reassembled -> request its proof (data + proof are fetched separately)
|
||||
_awaiting_proof = true;
|
||||
ReqProofMsg rp; memcpy(rp.manifest_id, _fid, 4); rp.block_idx = (uint16_t)_reasm_block;
|
||||
uint8_t b[16]; emit(b, encode_req_proof(b, sizeof(b), rp), false);
|
||||
}
|
||||
|
||||
void OtaManager::handleProof(const uint8_t* m, uint16_t n) {
|
||||
ProofMsg pm;
|
||||
if (!decode_proof(m, n, pm) || !_fetch) return;
|
||||
if (_fstate != FETCHING || memcmp(pm.manifest_id, _fid, 4) != 0) return;
|
||||
if (!_awaiting_proof || pm.block_idx != _reasm_block) return; // not the block we're verifying
|
||||
uint32_t blen = blockLen(_reasm_block);
|
||||
if (!merkle_verify(_reasm_buf, blen, _reasm_block, pm.proof, pm.n_proof, _froot, _fbc)) {
|
||||
clearReassembly(); // bad -> drop, re-fetch the block
|
||||
return;
|
||||
}
|
||||
// verified -> commit the payload block, then its leaf (the present marker). A write failure here means a
|
||||
// FOLDER destination's seeder link dropped mid-transfer: PAUSE (hold progress on the host, stop
|
||||
// requesting, do NOT fall back to RAM/flash). The block is left uncommitted (its leaf stays 0xFF), so on
|
||||
// reconnect resumeStaged() re-requests exactly it. (A flash store never fails these writes.)
|
||||
uint8_t leaf[4]; merkle_leaf(leaf, _reasm_buf, blen);
|
||||
if (!_fetch->write(_fpoff + (uint32_t)_reasm_block * _fbs, _reasm_buf, blen) ||
|
||||
!_fetch->write(_floff + (uint32_t)_reasm_block * 4, leaf, 4)) {
|
||||
_fstate = PAUSED; clearReassembly(); return;
|
||||
}
|
||||
_have++;
|
||||
OTA_DBG("OTA: block %u OK have=%u/%u\n", (unsigned)_reasm_block, (unsigned)_have, (unsigned)_fbc);
|
||||
clearReassembly();
|
||||
// periodically persist progress (meta/leaf page + open payload) so a reboot can resume (no-op for RAM);
|
||||
// cadence is runtime-tunable via `ota config checkpoint <N>` (0 = never)
|
||||
if (_checkpoint_blocks && _have % _checkpoint_blocks == 0) _fetch->checkpoint();
|
||||
if (_have < _fbc) { requestMissing(); return; } // next block
|
||||
// all blocks present -> final root cross-check + finalize
|
||||
if (_fbc * 4 <= sizeof(_scratch) && _fetch->read(_floff, _scratch, _fbc * 4)) {
|
||||
uint8_t root[4]; merkle_root(root, _scratch, _fbc);
|
||||
_fstate = (memcmp(root, _froot, 4) == 0) ? COMPLETE : FAILED;
|
||||
} else {
|
||||
_fstate = COMPLETE; // per-block proofs already guaranteed integrity vs the root
|
||||
}
|
||||
if (_fstate == COMPLETE) _fetch->finalize();
|
||||
OTA_DBG("OTA: transfer %s\n", _fstate == COMPLETE ? "COMPLETE" : "FAILED(root)");
|
||||
}
|
||||
|
||||
void OtaManager::requestMissing() {
|
||||
if (_fstate != FETCHING) return;
|
||||
// Per-block serial flow (split data/proof). If the current block's data is fully reassembled and we
|
||||
// are waiting on its proof, (re)send the proof request rather than re-fetching the data — this also
|
||||
// recovers from a lost PROOF reply.
|
||||
if (_awaiting_proof && _reasm_block != NO_BLOCK) {
|
||||
ReqProofMsg rp; memcpy(rp.manifest_id, _fid, 4); rp.block_idx = (uint16_t)_reasm_block;
|
||||
uint8_t b[16]; emit(b, encode_req_proof(b, sizeof(b), rp), false);
|
||||
OTA_DBG("OTA: REQ_PROOF block=%u (have=%u/%u)\n",
|
||||
(unsigned)_reasm_block, (unsigned)_have, (unsigned)_fbc);
|
||||
return;
|
||||
}
|
||||
// Otherwise request the DATA fragments of the next missing block. One block at a time keeps the
|
||||
// server's TX queue tiny so OTA never floods the mesh (docs/ota_protocol.md §8); a block's fragments
|
||||
// are self-describing (frag_off) so missing slices can be retried without re-sending a full block.
|
||||
uint32_t start = pickMissingBlock();
|
||||
if (start >= _fbc) return;
|
||||
_req_start = start; _req_count = 1;
|
||||
// Ask only for fragments we still lack: the holes of the in-flight partial block (_reasm_need & ~mask),
|
||||
// or all fragments of a fresh block. A lost fragment then costs one fragment to re-fetch, not the whole
|
||||
// block — and the re-REQ can't collide with a multi-fragment burst (half-duplex) as before.
|
||||
uint32_t nf = (blockLen(start) + OTA_FRAG_DATA - 1) / OTA_FRAG_DATA;
|
||||
uint16_t need = frag_full_mask(nf);
|
||||
uint16_t have = (start == _reasm_block) ? _reasm_mask : 0;
|
||||
uint16_t want = (uint16_t)(need & ~have);
|
||||
if (want == 0) want = need; // safety: never send an empty request
|
||||
ReqMsg rq; memcpy(rq.manifest_id, _fid, 4);
|
||||
rq.block_idx = (uint16_t)start; rq.want_mask = want;
|
||||
uint8_t b[16];
|
||||
OTA_DBG("OTA: REQ block=%u want=%04x (have=%u/%u mask=%04x)\n",
|
||||
(unsigned)start, (unsigned)want, (unsigned)_have, (unsigned)_fbc, (unsigned)_reasm_mask);
|
||||
emit(b, encode_req(b, sizeof(b), rq), false);
|
||||
}
|
||||
|
||||
// One receiver walks missing blocks in serial order. A partially-reassembled block is always finished first.
|
||||
uint32_t OtaManager::pickMissingBlock() {
|
||||
if (_fbc == 0) return _fbc;
|
||||
if (_reasm_block < _fbc && !blockPresent(_reasm_block) && _reasm_mask != 0) return _reasm_block;
|
||||
for (uint32_t i = 0; i < _fbc; i++) if (!blockPresent(i)) return i;
|
||||
return _fbc;
|
||||
}
|
||||
|
||||
void OtaManager::loop() {
|
||||
// fire a scheduled catalog query once its jitter has elapsed (unless overhearing already suppressed it)
|
||||
if (_pq_active && (int32_t)(_now_ms - _pq_at) >= 0) {
|
||||
_pq_active = false;
|
||||
sendQuery(_pq_seeder, _pq_digest, 0); // unfiltered: one broadcast HAVE serves everyone
|
||||
}
|
||||
if (_fstate == WANT_MANIFEST) {
|
||||
// Retry GET_MANIFEST ONLY when a tick passed with no new fragment — re-bursting every tick would congest
|
||||
// the link and burn the retry cap while fragments are still arriving (mirrors FETCHING + WANT_LEAVES).
|
||||
// Give up after a cap of stalled retries so an unreachable mid doesn't pin the single fetch slot forever.
|
||||
if (_mf_mask == _loop_last_mfmask) {
|
||||
if (++_mf_retries > OTA_MANIFEST_MAX_RETRY) { _fstate = FAILED; return; }
|
||||
GetManifestMsg gm; memcpy(gm.manifest_id, _fid, 4);
|
||||
// request only the manifest fragments still missing; 0xFFFF ("send all") until we know frag_total
|
||||
gm.want_mask = (_mf_total > 0) ? (uint16_t)(frag_full_mask(_mf_total) & ~_mf_mask) : 0xFFFF;
|
||||
if (gm.want_mask == 0) gm.want_mask = 0xFFFF; // safety: never send an empty request
|
||||
uint8_t b[16];
|
||||
emit(b, encode_get_manifest(b, sizeof(b), gm), false);
|
||||
}
|
||||
_loop_last_mfmask = _mf_mask;
|
||||
return;
|
||||
}
|
||||
if (_fstate == WANT_LEAVES) {
|
||||
if (_diffing) { diffStep(); return; } // leaves in — diff the seed a batch at a time (non-blocking)
|
||||
// Re-request ONLY when a whole tick passed with no new fragment — otherwise re-bursting the holes every
|
||||
// tick congests the link (and burns the retry cap) while fragments are still streaming in. On a stall,
|
||||
// ask for just the missing bitmap (anti-burst); give up (FAILED) after a cap of stalled retries.
|
||||
if (_lv_mask == _loop_last_lvmask) {
|
||||
if (++_lv_retries > OTA_LEAVES_MAX_RETRY) { freeLeaves(); _fstate = FAILED; return; }
|
||||
GetLeavesMsg gl; memcpy(gl.manifest_id, _fid, 4);
|
||||
gl.want_mask = (_lv_total > 0) ? (uint16_t)(frag_full_mask(_lv_total) & ~_lv_mask) : 0xFFFF;
|
||||
if (gl.want_mask == 0) gl.want_mask = 0xFFFF; // safety: never send an empty request
|
||||
OTA_DBG("OTA: GET_LEAVES retry=%u want=%04x (mask=%04x/%u)\n",
|
||||
(unsigned)_lv_retries, (unsigned)gl.want_mask, (unsigned)_lv_mask, (unsigned)_lv_total);
|
||||
uint8_t b[16];
|
||||
emit(b, encode_get_leaves(b, sizeof(b), gl), false);
|
||||
}
|
||||
_loop_last_lvmask = _lv_mask;
|
||||
return;
|
||||
}
|
||||
if (_fstate != FETCHING) return;
|
||||
// retry only when a whole tick passed with NO progress — neither a committed block nor a new fragment
|
||||
// of the in-flight block. This avoids re-request spam while a block's fragments are still streaming in.
|
||||
if (_have == _loop_last_have && _reasm_mask == _loop_last_mask) requestMissing();
|
||||
_loop_last_have = _have;
|
||||
_loop_last_mask = _reasm_mask;
|
||||
}
|
||||
|
||||
// ---------------- dispatch ----------------
|
||||
|
||||
void OtaManager::on_message(const uint8_t* msg, uint16_t len) {
|
||||
switch (ota_msg_type(msg, len)) {
|
||||
case OTA_ADV: handleAdv(msg, len); break;
|
||||
case OTA_QUERY: handleQuery(msg, len); break;
|
||||
case OTA_HAVE: handleHave(msg, len); break;
|
||||
case OTA_GET_MANIFEST: handleGetManifest(msg, len); break;
|
||||
case OTA_MANIFEST: handleManifest(msg, len); break;
|
||||
case OTA_GET_LEAVES: handleGetLeaves(msg, len); break;
|
||||
case OTA_LEAVES: handleLeaves(msg, len); break;
|
||||
case OTA_REQ: handleReq(msg, len); break;
|
||||
case OTA_DATA: handleData(msg, len); break;
|
||||
case OTA_REQ_PROOF: handleReqProof(msg, len); break;
|
||||
case OTA_PROOF: handleProof(msg, len); break;
|
||||
default: break;
|
||||
}
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,400 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "OtaFormat.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include "OtaStore.h"
|
||||
#include "MotaContainer.h"
|
||||
#include "OtaSource.h"
|
||||
|
||||
// Transport-agnostic OTA session engine (docs/ota_protocol.md §5/§8). It SERVES a complete `.mota`
|
||||
// (answering GET_MANIFEST / REQ) and/or FETCHES one into an OtaStore (verifying every block against
|
||||
// the signed merkle root via proofs). It is portable (no Arduino / radio / Ed25519) so it can be
|
||||
// driven by a host simulation; a thin Mesh adapter wires it to PAYLOAD_TYPE_OTA on device.
|
||||
//
|
||||
// Transfer is per-block and 2-phase: a 1 KB logical block is fetched as self-describing DATA fragments
|
||||
// (frag_off), reassembled, then its merkle PROOF
|
||||
// is requested separately and verified against the signed root before the block is committed.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// Emit an OTA message (one packet payload). `flood`=true for announce/query, false for direct replies.
|
||||
typedef void (*OtaSend)(void* ctx, const uint8_t* msg, uint16_t len, bool flood);
|
||||
|
||||
// Read `len` payload bytes at offset `off` from the serve source (flash-backed self-serve); false on
|
||||
// error. nullptr means the payload is a contiguous RAM buffer (the staged `.mota`).
|
||||
typedef bool (*ServeReadFn)(void* ctx, uint32_t off, uint8_t* buf, uint32_t len);
|
||||
|
||||
#ifndef OTA_PROOFGEN_SCRATCH
|
||||
#define OTA_PROOFGEN_SCRATCH 4096 // server proof-gen working buffer (supports up to 1024 blocks)
|
||||
#endif
|
||||
|
||||
#ifndef OTA_MAX_BLOCK
|
||||
#define OTA_MAX_BLOCK 1024 // largest logical block (merkle leaf unit) = reassembly buffer size
|
||||
#endif
|
||||
#ifndef OTA_CHECKPOINT_BLOCKS
|
||||
#define OTA_CHECKPOINT_BLOCKS 4 // persist progress (store.checkpoint) every N committed blocks (resume)
|
||||
#endif
|
||||
#ifndef OTA_ADVERT_INTERVAL_MINS
|
||||
#define OTA_ADVERT_INTERVAL_MINS 1440 // re-advertise our served set every N minutes after the boot burst (24h)
|
||||
#endif
|
||||
#ifndef OTA_HOP_LIMIT_DEFAULT
|
||||
#define OTA_HOP_LIMIT_DEFAULT 3 // default OTA flood reach in hops: accept <= N, relay while < N (0=direct)
|
||||
#endif
|
||||
#ifndef OTA_MF_FRAG
|
||||
#define OTA_MF_FRAG 176 // manifest bytes per OTA_MANIFEST fragment (<= MAX_PACKET_PAYLOAD - header)
|
||||
#endif
|
||||
#ifndef OTA_MF_MAXFRAG
|
||||
#define OTA_MF_MAXFRAG 4 // max manifest fragments (the fixed 197 B manifest is always 2)
|
||||
#endif
|
||||
#ifndef OTA_MANIFEST_MAX_RETRY
|
||||
#define OTA_MANIFEST_MAX_RETRY 20 // give up (FAILED) after this many GET_MANIFEST retries — frees the slot
|
||||
#endif
|
||||
// Leaf-diff warm-start (motatool folder-capture only): bulk-fetch the target's leaves[], diff a seed build
|
||||
// locally, pull DATA only for mismatches. OTA_LEAVES is bitmap-fragmented like OTA_MANIFEST so a want_mask
|
||||
// retry never re-bursts (anti-deadlock). The mask is a fixed uint16, so leaves are capped at MAXFRAG frags.
|
||||
#ifndef OTA_LEAVES_FRAG
|
||||
#define OTA_LEAVES_FRAG 176 // leaf bytes per OTA_LEAVES fragment (<= MAX_PACKET_PAYLOAD - 7 header) = 44 leaves
|
||||
#endif
|
||||
#ifndef OTA_LEAVES_MAXFRAG
|
||||
#define OTA_LEAVES_MAXFRAG 16 // fixed want_mask width (uint16) -> at most 16 leaf fragments
|
||||
#endif
|
||||
#ifndef OTA_DIFF_MAX_BLOCKS
|
||||
#define OTA_DIFF_MAX_BLOCKS 704 // = MAXFRAG*(OTA_LEAVES_FRAG/4); warm-start unavailable above this (full fetch)
|
||||
#endif
|
||||
#ifndef OTA_LEAVES_MAX_RETRY
|
||||
#define OTA_LEAVES_MAX_RETRY 20 // give up (FAILED) after this many GET_LEAVES retries
|
||||
#endif
|
||||
#ifndef OTA_DIFF_BATCH
|
||||
#define OTA_DIFF_BATCH 48 // seed blocks diffed per loop tick (bounded so the diff never blocks the
|
||||
#endif // main loop long enough to starve the radio / trip the watchdog)
|
||||
#ifndef OTA_MAX_SOURCES
|
||||
#define OTA_MAX_SOURCES 12 // heard OTA sources (beacon senders) tracked (LRU); ~12 B each
|
||||
#endif
|
||||
#ifndef OTA_MAX_SERVE
|
||||
#define OTA_MAX_SERVE 12 // mOTAs THIS node offers (own fw + external folder); == one HAVE fragment
|
||||
#endif
|
||||
#ifndef OTA_MAX_SOURCE_OBJ
|
||||
#define OTA_MAX_SOURCE_OBJ 4 // external MotaSource objects (folders/transports) attached at once
|
||||
#endif
|
||||
#ifndef OTA_SRC_MANIFEST_MAX
|
||||
#define OTA_SRC_MANIFEST_MAX 256 // manifest-minus-leaves buffer for the loaded source mota (head+sig+approval)
|
||||
#endif
|
||||
#ifndef OTA_MAX_CATALOG
|
||||
#define OTA_MAX_CATALOG 12 // distinct mOTAs catalogued from OTA_HAVE replies (LRU)
|
||||
#endif
|
||||
#ifndef OTA_QUERY_MIN_MS
|
||||
#define OTA_QUERY_MIN_MS 300 // min delay before sending a catalog query (overhear-suppression window)
|
||||
#endif
|
||||
#ifndef OTA_QUERY_SPREAD_MS
|
||||
#define OTA_QUERY_SPREAD_MS 4000 // random jitter span so 50 neighbours don't all query at once (storm)
|
||||
#endif
|
||||
#ifndef OTA_REQ_SPREAD_MS
|
||||
#define OTA_REQ_SPREAD_MS 3000 // initial random hold before a fetch's first REQ (de-sync N fetchers)
|
||||
#endif
|
||||
#ifndef OTA_REQ_SUPPRESS_MS
|
||||
#define OTA_REQ_SUPPRESS_MS 2500 // after overhearing a peer's REQ for a block, don't also request it —
|
||||
#endif // its DATA is broadcast and will fill our hole too (swarm de-dup)
|
||||
#ifndef OTA_SERVE_SUPPRESS_MS
|
||||
#define OTA_SERVE_SUPPRESS_MS 1500 // don't re-serve a block whose DATA we just overheard another holder send
|
||||
#endif // (so multiple sources of the same mota don't duplicate-broadcast it)
|
||||
#ifndef OTA_FRAG_DATA
|
||||
#define OTA_FRAG_DATA 160 // data bytes per DATA fragment (<= MAX_PACKET_PAYLOAD - 9-byte header)
|
||||
#endif
|
||||
// nRF52 note: a flash page-erase halts the CPU (~85 ms, code runs from flash) and starves the LoRa RX,
|
||||
// so writing to flash on every received packet drops in-flight DATA and the transfer stalls. The SD-safe
|
||||
// driver (Adafruit flash_nrf5x) always erases on flush, so there is no erase-free write; instead
|
||||
// OtaStoreFlashNrf52 COALESCES to the 4 KB page (the erase unit) and writes each page once — RAM stays
|
||||
// O(one page), never O(mota). It pins flash page 0 (header+manifest+merkle leaves, which update all
|
||||
// transfer long) in RAM and streams the payload through one sliding page buffer, flushing page 0 and the
|
||||
// last page at finalize() (radio idle). Flash is then touched ~once per 4 KB (≈1 per 4 blocks), not per
|
||||
// packet; a small delta that fits page 0 does ZERO flash I/O until COMPLETE. (Pacing alone is not enough.)
|
||||
|
||||
class OtaManager {
|
||||
public:
|
||||
// PAUSED: a folder-destination write failed mid-transfer (the seeder link dropped). Progress is held on
|
||||
// the host; the manager stops requesting and does NOT fall back to RAM/flash. resumeStaged() (called on
|
||||
// reconnect) re-STATs the host file, recomputes which blocks are missing, and resumes.
|
||||
enum FetchState : uint8_t { IDLE, WANT_MANIFEST, WANT_LEAVES, FETCHING, COMPLETE, FAILED, PAUSED };
|
||||
|
||||
// Sentinel for "no block" in the reassembly / peer-REQ / recently-served slots (a real block index is
|
||||
// a small uint16, so 0xFFFFFFFF is never valid).
|
||||
static const uint32_t NO_BLOCK = 0xFFFFFFFFu;
|
||||
|
||||
// --- multi-mota serve --- A ServeView is everything a serve handler needs for ONE mota. Two can be
|
||||
// resident: view0 = our own fw / a RAM `.mota` (always loaded), plus one on-demand source view that is
|
||||
// (re)loaded from a MotaSource when a request targets a different external mota. Requests dispatch by
|
||||
// manifest_id (carried in every fetch message) -> the matching ServeView via resolve().
|
||||
struct ServeView {
|
||||
bool valid = false;
|
||||
MotaManifest m; // parsed manifest (fields/pointers into the backing buffers)
|
||||
uint16_t mfl = 0; // manifest-minus-leaves length (the OTA_MANIFEST payload)
|
||||
ServeReadFn read = nullptr; // payload reader (nullptr => m.payload is contiguous in RAM)
|
||||
void* read_ctx = nullptr;
|
||||
uint8_t* scratch = nullptr; // proof-gen working buffer (>= block_count*4)
|
||||
uint32_t scratch_sz = 0;
|
||||
};
|
||||
// A lightweight catalog entry: what we advertise per mota + how to load its ServeView on demand.
|
||||
struct ServeEntry {
|
||||
uint8_t mid[4];
|
||||
uint32_t target_id, fw_version;
|
||||
uint8_t codec_id, flags;
|
||||
uint32_t have_count; // blocks we currently hold (== block_count when complete)
|
||||
bool is_self; // true => entry is view0 (our own fw / RAM mota)
|
||||
MotaSource* src; // load from this external source ...
|
||||
uint8_t src_idx; // ... at this index
|
||||
MotaDesc desc; // cached region offsets for the source entry
|
||||
};
|
||||
// Context for the source-payload reader trampoline.
|
||||
struct SrcReadCtx { MotaSource* src; uint8_t idx; uint32_t payload_off; };
|
||||
|
||||
void begin(uint32_t my_target_id, OtaSend send, void* ctx);
|
||||
|
||||
// --- serve --- Provide a complete, contiguous `.mota` to serve (caller keeps it alive).
|
||||
bool serve(const uint8_t* mota, uint32_t len);
|
||||
// Serve from a non-contiguous source (e.g. our own firmware in flash): a pre-assembled manifest
|
||||
// (manifest-minus-leaves, `mfl` bytes), the pre-computed merkle `leaves` (kept alive by caller), and a
|
||||
// `read` callback for payload blocks. Lets a node host its own image without holding it in RAM.
|
||||
bool serve_self(const uint8_t* manifest, uint16_t mfl, const uint8_t* leaves, uint32_t block_count,
|
||||
uint8_t* proof_scratch, uint32_t proof_scratch_sz, ServeReadFn read, void* ctx);
|
||||
// Attach an external "folder" of `.mota` images (USB-serial daemon, BLE, WiFi URLs, NFS/samba, ...).
|
||||
// The node then advertises + RELAYS them transparently alongside its own fw — peers just see more mOTAs.
|
||||
// Re-enumerates the source into the serve registry. Returns false if no slots remain. (Trustless: the
|
||||
// fetcher verifies merkle+signature, so the source is never trusted — see OtaSource.h.)
|
||||
bool add_source(MotaSource* src);
|
||||
// Re-read every attached source's catalog (call when the folder's contents change). Rebuilds entries
|
||||
// [1..] from the sources; entry 0 (our own fw) is preserved.
|
||||
void refresh_sources();
|
||||
// Drop all external sources (keep serving our own fw).
|
||||
void clear_sources();
|
||||
uint8_t servedCount() const { return _n_serve; } // total mOTAs we offer (own fw + folder)
|
||||
// Read-only view of one served entry (for `ota serve` listing): mid/target/fwver/codec/flags + is_self.
|
||||
const ServeEntry* servedEntry(uint8_t i) const { return i < _n_serve ? &_serve[i] : nullptr; }
|
||||
// 4-byte fingerprint of our served set (== the set_digest carried in the beacon); for admin OTA stats.
|
||||
void servedDigest(uint8_t out[4]) const { setDigest(out); }
|
||||
|
||||
// Broadcast the tiny per-node BEACON (OTA_ADV): seeder_id + count + set-digest of everything we serve.
|
||||
// Constant size regardless of how many mOTAs — peers ask for the catalog via OTA_QUERY only on interest.
|
||||
void announce();
|
||||
|
||||
// --- fetch --- Provide the staging store; fetching starts on a matching OTA_ADV.
|
||||
void set_fetch_store(OtaStore* s) { _fetch = s; }
|
||||
|
||||
// Resume a fetch from a container already persisted in the store (after a reboot). want_mid=nullptr
|
||||
// accepts whatever is staged; otherwise only resumes if the staged manifest_id matches. Re-parses the
|
||||
// stored manifest, recomputes geometry, counts present blocks, and continues FETCHING the holes (or goes
|
||||
// straight to COMPLETE if all blocks are present). Returns true if it adopted a staged container.
|
||||
bool resumeStaged(const uint8_t* want_mid);
|
||||
|
||||
// Manual cross-target override (decision: deliberate role switch, e.g. companion -> repeater on the
|
||||
// same hardware). Normally a node only auto-fetches its OWN target_id; `want(T)` makes it accept an
|
||||
// ADV for target T instead (T=0 restores auto). The user takes responsibility for HW compatibility;
|
||||
// a hw_id brick-safety check is the planned safety layer (see docs/ota_protocol.md / plan).
|
||||
void want(uint32_t target_id) { _desired_target = target_id; reDiscover(); }
|
||||
uint32_t wanted() const { return _desired_target; }
|
||||
uint32_t target() const { return _target; } // this node's own OTA target_id (set in begin)
|
||||
|
||||
// Pull a SPECIFIC advertised mOTA by manifest_id (e.g. `ota pull <#>` picks the one more peers have),
|
||||
// not just any firmware for the target. mid=nullptr clears the filter (accept any mid for the target).
|
||||
void want_mid(const uint8_t* mid) {
|
||||
if (mid) { for (int i = 0; i < 4; i++) _desired_mid[i] = mid[i]; _have_desired_mid = true; }
|
||||
else _have_desired_mid = false;
|
||||
reDiscover();
|
||||
}
|
||||
|
||||
// Begin fetching a chosen mid now (sets want + starts the manifest fetch / resume). Used by `ota pull`
|
||||
// once the user picks a catalogued mOTA (the source is reached via the flooded GET_MANIFEST).
|
||||
// `validate` enables the motatool folder-capture warm-start: bulk-fetch the target leaves, diff a seed
|
||||
// build already staged in the destination, and pull DATA only for the differing blocks. Ignored unless a
|
||||
// seed is present (a plain fetch just re-transfers everything). Normal P2P pulls pass false.
|
||||
void pull(const uint8_t* mid, uint32_t target, bool validate = false) {
|
||||
want(target); want_mid(mid); startFetch(mid, target, validate);
|
||||
}
|
||||
// Ask every known source for its catalog (populates `ota neighbors`). Async — rows arrive via OTA_HAVE.
|
||||
void queryAll();
|
||||
// Coarse clock for source/catalog ages + LRU (the Mesh adapter feeds millis; 0 in host tests is fine).
|
||||
void set_clock(uint32_t ms) { _now_ms = ms; }
|
||||
|
||||
// Codec compatibility: a node only fetches/accepts fw it can actually apply. CODEC_FULL is always
|
||||
// acceptable; the platform's single delta codec is set here (ESP32 A/B -> sequential, nRF52 single-
|
||||
// slot -> in-place). A mismatching `.mota` is rejected at OTA_ADV time, before fetching anything.
|
||||
void set_apply_codec(uint8_t c) { _apply_codec = c; }
|
||||
// A platform may apply MORE than one delta codec (ESP32 does both sequential AND in-place, so a single
|
||||
// in-place `.mota` can target both ESP32 and nRF52). 0xFF = unset.
|
||||
void set_apply_codec2(uint8_t c) { _apply_codec2 = c; }
|
||||
bool codecOk(uint8_t c) const { return c == CODEC_FULL || c == _apply_codec || c == _apply_codec2; }
|
||||
|
||||
// Auto-fetch policy (manual `ota pull` always works regardless): 0=off (discover only), 1=any
|
||||
// compatible own-target advert, 2=only signed adverts. Conservative default = off.
|
||||
static const uint8_t AUTOFETCH_OFF = 0, AUTOFETCH_ANY = 1, AUTOFETCH_SIGNED = 2;
|
||||
void set_autofetch(uint8_t p) { _autofetch = p; reDiscover(); }
|
||||
uint8_t autofetch() const { return _autofetch; }
|
||||
|
||||
// Resume checkpoint cadence (runtime-tunable, persisted in NodePrefs): persist progress every N
|
||||
// committed blocks. 0 = never (resume only from a finalized container). Default OTA_CHECKPOINT_BLOCKS.
|
||||
void set_checkpoint_blocks(uint16_t n) { _checkpoint_blocks = n; }
|
||||
uint16_t checkpoint_blocks() const { return _checkpoint_blocks; }
|
||||
|
||||
// Beacon re-advertise cadence in MINUTES (runtime-tunable, persisted in NodePrefs): after the boot burst,
|
||||
// re-send the discovery beacon every N minutes so a long-running node stays discoverable. 0 = disabled
|
||||
// (boot burst only). Default OTA_ADVERT_INTERVAL_MINS (24h).
|
||||
void set_advert_mins(uint16_t m) { _advert_mins = m; }
|
||||
uint16_t advert_mins() const { return _advert_mins; }
|
||||
|
||||
// Max OTA flood reach in HOPS (runtime-tunable, persisted): a node accepts OTA from up to N hops away and
|
||||
// relays packets still under N hops; 0 = direct only (accept path_count 0, never relay). Bounds duty-cycle
|
||||
// when crossing repeaters. Default OTA_HOP_LIMIT_DEFAULT. Set via `ota config hops`.
|
||||
void set_max_hops(uint8_t h) { _max_hops = h; }
|
||||
uint8_t max_hops() const { return _max_hops; }
|
||||
bool fetched_is_signed() const { return (_fflags & MFLAG_SIGNED) != 0; } // flags of the fetched manifest
|
||||
|
||||
// This node's id (pubkey[0:4]), stamped into adverts we send so receivers can count distinct seeders.
|
||||
void set_seeder_id(const uint8_t* id4) { if (id4) for (int i = 0; i < 4; i++) _seeder_id[i] = id4[i]; }
|
||||
|
||||
void on_message(const uint8_t* msg, uint16_t len); // feed one received OTA message
|
||||
void loop(); // drive fetch (re-request missing blocks)
|
||||
|
||||
// Drop the current fetch session back to IDLE so a fresh `ota pull` / advert starts a new one.
|
||||
void reset_session() {
|
||||
_fstate = IDLE; _have = 0; _req_count = 0; _mf_retries = 0;
|
||||
clearReassembly();
|
||||
_loop_last_have = 0; _loop_last_mask = 0;
|
||||
_mf_total = 0; _mf_mask = 0; _mf_len = 0; _loop_last_mfmask = 0;
|
||||
freeLeaves(); _validate = false; _lv_retries = 0; _loop_last_lvmask = 0;
|
||||
}
|
||||
|
||||
FetchState fetchState() const { return _fstate; }
|
||||
uint32_t blocksHave() const { return _have; }
|
||||
uint32_t blocksTotal() const { return _fbc; }
|
||||
const uint8_t* fetchManifestId() const { return _fid; }
|
||||
|
||||
// --- discovery catalog (for `ota neighbors`): mOTAs heard around us via OTA_HAVE, deduped by mid ---
|
||||
static const uint8_t OTA_CAT_SEEDERS = 4; // distinct sources tracked per catalog row (for "N nodes have it")
|
||||
struct CatRow {
|
||||
uint8_t mid[4];
|
||||
uint32_t target_id, fw_version;
|
||||
uint8_t codec, flags;
|
||||
uint8_t seeders[OTA_CAT_SEEDERS][4]; // distinct sources advertising this mid (deduped; capped)
|
||||
uint8_t n_seeders; // count of the above (capped at OTA_CAT_SEEDERS) — "N+ nodes have it"
|
||||
uint32_t have_max; // best block-count any source reported (== total when a full copy exists)
|
||||
uint32_t last_ms;
|
||||
};
|
||||
uint8_t catalogCount() const { return _n_cat; }
|
||||
const CatRow* catalogRow(uint8_t i) const { return i < _n_cat ? &_catalog[i] : nullptr; }
|
||||
uint8_t sourceCount() const { return _n_src; } // distinct OTA sources (beacon senders) heard
|
||||
|
||||
private:
|
||||
void emit(const uint8_t* b, uint16_t n, bool flood) { if (_send && n) _send(_ctx, b, n, flood); }
|
||||
void handleAdv(const uint8_t* m, uint16_t n); // beacon -> sources table (+ query if interested)
|
||||
void handleQuery(const uint8_t* m, uint16_t n); // serve: reply OTA_HAVE catalog
|
||||
void handleHave(const uint8_t* m, uint16_t n); // peer: catalog rows (+ startFetch if a row matches)
|
||||
void handleGetManifest(const uint8_t* m, uint16_t n);
|
||||
void handleManifest(const uint8_t* m, uint16_t n);
|
||||
void handleGetLeaves(const uint8_t* m, uint16_t n); // serve: send the requested leaf fragments
|
||||
void handleLeaves(const uint8_t* m, uint16_t n); // fetcher (validate): reassemble the target leaves
|
||||
bool beginLeafDiff(); // enter WANT_LEAVES if a seed diff is viable
|
||||
void diffStep(); // diff one batch of seed blocks per loop tick
|
||||
void freeLeaves(); // release the heap leaves buffer + diff state
|
||||
void handleReq(const uint8_t* m, uint16_t n);
|
||||
void handleData(const uint8_t* m, uint16_t n);
|
||||
void handleReqProof(const uint8_t* m, uint16_t n);
|
||||
void handleProof(const uint8_t* m, uint16_t n);
|
||||
void startFetch(const uint8_t* mid, uint32_t target, bool validate = false); // begin/resume a fetch
|
||||
bool wantRow(const uint8_t* mid, uint32_t target, uint8_t codec, uint8_t flags) const; // fetch this row?
|
||||
void clearReassembly(); // forget the in-flight block (reset to NO_BLOCK)
|
||||
uint32_t pickMissingBlock(); // choose the next missing block in serial order
|
||||
int serveEntryIndex(const uint8_t* mid) const; // registry slot serving this mid (-1 if none)
|
||||
ServeView* resolve(const uint8_t* mid); // pick/load the ServeView for this mid (nullptr)
|
||||
bool loadSource(const ServeEntry& e); // load an external mota into _srcv (head+leaves)
|
||||
void registerSelfEntry(); // (re)build entry[0] from view0
|
||||
static bool srcReadTramp(void* c, uint32_t off, uint8_t* buf, uint32_t len); // source payload reader
|
||||
void emitBlockData(const uint8_t* mid, uint32_t idx, const uint8_t* data, uint32_t blen,
|
||||
uint16_t want_mask); // emit only the requested DATA fragments of one block
|
||||
void sendQuery(const uint8_t* seeder, const uint8_t* digest, uint32_t filter_target); // ask a source for its catalog
|
||||
void scheduleQuery(const uint8_t* seeder, const uint8_t* digest); // jittered + suppressible
|
||||
void reDiscover() { for (uint8_t i = 0; i < _n_src; i++) _sources[i].have_catalog = false; _pq_active = false; }
|
||||
void setDigest(uint8_t out[4]) const; // sha2-256:4 over our served mids
|
||||
bool blockPresent(uint32_t i) const;
|
||||
void requestMissing();
|
||||
uint32_t blockLen(uint32_t i) const;
|
||||
|
||||
uint32_t _target = 0;
|
||||
OtaSend _send = nullptr;
|
||||
void* _ctx = nullptr;
|
||||
|
||||
// serve (multi-mota): view0 = our own fw / a RAM `.mota`; _srcv = the currently-loaded external mota.
|
||||
ServeView _view0;
|
||||
ServeView _srcv;
|
||||
uint8_t _srcv_mid[4] = {0};
|
||||
SrcReadCtx _srcv_rdctx = {nullptr, 0, 0};
|
||||
ServeEntry _serve[OTA_MAX_SERVE]; // catalog (what we advertise) — entry 0 is view0
|
||||
uint8_t _n_serve = 0;
|
||||
MotaSource* _src_list[OTA_MAX_SOURCE_OBJ] = {nullptr};
|
||||
uint8_t _n_src_obj = 0;
|
||||
uint8_t _src_manifest[OTA_SRC_MANIFEST_MAX]; // manifest-minus-leaves of the loaded source mota
|
||||
uint8_t _src_leaves[OTA_PROOFGEN_SCRATCH]; // leaves[] of the loaded source mota (<=1024 blocks)
|
||||
uint8_t _scratch[OTA_PROOFGEN_SCRATCH]; // proof-gen / fetch root-check working buffer
|
||||
|
||||
// fetch
|
||||
OtaStore* _fetch = nullptr;
|
||||
FetchState _fstate = IDLE;
|
||||
uint8_t _fid[4] = {0};
|
||||
uint8_t _froot[4] = {0};
|
||||
uint32_t _ftotal = 0, _fpoff = 0, _floff = 0, _fpsize = 0, _fbc = 0, _fbs = 0;
|
||||
uint32_t _have = 0;
|
||||
uint32_t _req_start = 0, _req_count = 0; // last block requested (per-block serial flow; telemetry)
|
||||
uint32_t _loop_last_have = 0; // for stall detection in loop()
|
||||
uint32_t _desired_target = 0; // manual cross-target override (0 = auto / own target)
|
||||
uint8_t _desired_mid[4] = {0,0,0,0}; // pull a specific manifest_id (see want_mid)
|
||||
bool _have_desired_mid = false;
|
||||
uint8_t _apply_codec = CODEC_DETOOLS_SEQUENTIAL; // platform's delta codec (OtaContext sets it)
|
||||
uint8_t _apply_codec2 = 0xFF; // optional 2nd accepted delta codec (ESP32: in-place)
|
||||
uint8_t _seeder_id[4] = {0,0,0,0}; // our node id (pubkey[0:4]) for advert seeder counting
|
||||
uint8_t _autofetch = AUTOFETCH_OFF; // auto-fetch policy (persisted in NodePrefs)
|
||||
uint16_t _checkpoint_blocks = OTA_CHECKPOINT_BLOCKS; // resume checkpoint cadence (persisted)
|
||||
uint16_t _advert_mins = OTA_ADVERT_INTERVAL_MINS; // beacon re-advertise cadence, minutes; 0=off (persisted)
|
||||
uint8_t _max_hops = OTA_HOP_LIMIT_DEFAULT; // OTA flood reach in hops; 0=direct only (persisted)
|
||||
uint8_t _fflags = 0; // flags of the manifest currently being fetched
|
||||
// multi-fragment reassembly of the current block (per-block 2-phase: fetch data, then its proof)
|
||||
uint32_t _reasm_block = NO_BLOCK; // block being reassembled / awaiting proof (none)
|
||||
uint16_t _reasm_mask = 0; // received FRAG_DATA-slice bitmap (bit k = slice @ k*FRAG_DATA)
|
||||
uint16_t _reasm_need = 0; // full mask once all slices of the current block are in
|
||||
bool _awaiting_proof = false; // data complete; REQ_PROOF sent, verify on PROOF
|
||||
uint16_t _loop_last_mask = 0; // fragment-level stall detection in loop()
|
||||
uint8_t _reasm_buf[OTA_MAX_BLOCK];
|
||||
// multi-fragment manifest reassembly (a signed v2 manifest exceeds one packet)
|
||||
uint8_t _mf_buf[OTA_MF_MAXFRAG * OTA_MF_FRAG]; // sized to the fragment cap so no valid manifest is silently dropped
|
||||
uint16_t _mf_retries = 0; // GET_MANIFEST retries while WANT_MANIFEST (give up after a cap)
|
||||
uint8_t _mf_total = 0; // frag_total of the manifest being reassembled (0 = none)
|
||||
uint16_t _mf_mask = 0; // received manifest-fragment bitmap
|
||||
uint16_t _loop_last_mfmask = 0; // manifest bitmap last loop tick (retry only on no-progress)
|
||||
uint32_t _mf_len = 0; // assembled manifest length (set by the last fragment)
|
||||
|
||||
// leaf-diff warm-start (motatool folder-capture only; buffer is heap-allocated only while WANT_LEAVES)
|
||||
bool _validate = false; // this fetch should try the seed leaf-diff before transferring
|
||||
uint8_t* _leaves_buf = nullptr; // target leaves[] (bc*4), malloc'd on WANT_LEAVES, freed after diff
|
||||
uint8_t _lv_total = 0; // frag_total of the leaves reply being reassembled (0 = none)
|
||||
uint16_t _lv_mask = 0; // received leaves-fragment bitmap
|
||||
uint16_t _lv_retries = 0; // GET_LEAVES *stalled* retries while WANT_LEAVES
|
||||
uint16_t _loop_last_lvmask = 0; // leaves bitmap last loop tick (retry only on no-progress)
|
||||
bool _diffing = false; // leaves are in; diffing the seed a batch per tick
|
||||
uint32_t _diff_idx = 0; // next block index to diff against the seed
|
||||
|
||||
// discovery: heard sources (beacon senders) + the catalog assembled from their OTA_HAVE replies
|
||||
struct Source { uint8_t seeder[4]; uint8_t digest[4]; uint8_t n_motas; uint32_t last_ms; bool have_catalog; };
|
||||
Source _sources[OTA_MAX_SOURCES];
|
||||
uint8_t _n_src = 0;
|
||||
CatRow _catalog[OTA_MAX_CATALOG];
|
||||
uint8_t _n_cat = 0;
|
||||
uint32_t _now_ms = 0; // coarse clock (fed by set_clock; for ages/LRU/jitter)
|
||||
// pending catalog query (jittered + suppressed on overhearing a matching QUERY/HAVE — anti-storm)
|
||||
bool _pq_active = false;
|
||||
uint8_t _pq_seeder[4] = {0};
|
||||
uint8_t _pq_digest[4] = {0};
|
||||
uint32_t _pq_at = 0; // _now_ms deadline to actually send the query
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,162 @@
|
||||
#include "OtaProtocol.h"
|
||||
#include <string.h>
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// Little-endian cursor helpers.
|
||||
namespace {
|
||||
struct W {
|
||||
uint8_t* p; uint16_t cap; uint16_t n; bool ok;
|
||||
W(uint8_t* b, uint16_t c) : p(b), cap(c), n(0), ok(true) {}
|
||||
void u8(uint8_t v) { if (n + 1 > cap) { ok = false; return; } p[n++] = v; }
|
||||
void u16(uint16_t v){ u8(v & 0xFF); u8(v >> 8); }
|
||||
void u32(uint32_t v){ u8(v); u8(v >> 8); u8(v >> 16); u8(v >> 24); }
|
||||
void raw(const uint8_t* d, uint16_t l) { if (n + l > cap) { ok = false; return; } memcpy(p + n, d, l); n += l; }
|
||||
};
|
||||
struct R {
|
||||
const uint8_t* p; uint16_t len; uint16_t n; bool ok;
|
||||
R(const uint8_t* b, uint16_t l) : p(b), len(l), n(0), ok(true) {}
|
||||
uint8_t u8() { if (n + 1 > len) { ok = false; return 0; } return p[n++]; }
|
||||
uint16_t u16() { uint16_t a = u8(); return a | ((uint16_t)u8() << 8); }
|
||||
uint32_t u32() { uint32_t a = u8(); a |= (uint32_t)u8() << 8; a |= (uint32_t)u8() << 16; a |= (uint32_t)u8() << 24; return a; }
|
||||
const uint8_t* raw(uint16_t l) { if (n + l > len) { ok = false; return nullptr; } const uint8_t* r = p + n; n += l; return r; }
|
||||
uint16_t remaining() const { return len - n; }
|
||||
};
|
||||
} // namespace
|
||||
|
||||
uint16_t encode_adv(uint8_t* buf, uint16_t cap, const AdvMsg& m) { // tiny per-node beacon
|
||||
W w(buf, cap); w.u8(OTA_ADV); w.raw(m.seeder_id, 4); w.u8(m.n_motas); w.raw(m.set_digest, 4);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_adv(const uint8_t* buf, uint16_t len, AdvMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_ADV) return false;
|
||||
const uint8_t* sid = r.raw(4); if (sid) memcpy(m.seeder_id, sid, 4);
|
||||
m.n_motas = r.u8();
|
||||
const uint8_t* d = r.raw(4); if (d) memcpy(m.set_digest, d, 4);
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_query(uint8_t* buf, uint16_t cap, const QueryMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_QUERY); w.raw(m.seeder_id, 4); w.raw(m.set_digest, 4); w.u32(m.filter_target);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_query(const uint8_t* buf, uint16_t len, QueryMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_QUERY) return false;
|
||||
const uint8_t* sid = r.raw(4); if (sid) memcpy(m.seeder_id, sid, 4);
|
||||
const uint8_t* dg = r.raw(4); if (dg) memcpy(m.set_digest, dg, 4);
|
||||
m.filter_target = r.u32();
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_have(uint8_t* buf, uint16_t cap, const HaveMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_HAVE); w.raw(m.seeder_id, 4); w.raw(m.set_digest, 4);
|
||||
w.u8(m.frag_idx); w.u8(m.frag_total); w.u8(m.n_rows); w.raw(m.rows, (uint16_t)m.n_rows * OTA_HAVE_ROW_BYTES);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_have(const uint8_t* buf, uint16_t len, HaveMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_HAVE) return false;
|
||||
const uint8_t* sid = r.raw(4); if (sid) memcpy(m.seeder_id, sid, 4);
|
||||
const uint8_t* dg = r.raw(4); if (dg) memcpy(m.set_digest, dg, 4);
|
||||
m.frag_idx = r.u8(); m.frag_total = r.u8(); m.n_rows = r.u8();
|
||||
m.rows = r.raw((uint16_t)m.n_rows * OTA_HAVE_ROW_BYTES);
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_get_manifest(uint8_t* buf, uint16_t cap, const GetManifestMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_GET_MANIFEST); w.raw(m.manifest_id, 4); w.u16(m.want_mask);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_get_manifest(const uint8_t* buf, uint16_t len, GetManifestMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_GET_MANIFEST) return false;
|
||||
const uint8_t* id = r.raw(4); if (id) memcpy(m.manifest_id, id, 4);
|
||||
m.want_mask = r.u16();
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_manifest(uint8_t* buf, uint16_t cap, const ManifestMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_MANIFEST); w.raw(m.manifest_id, 4); w.u8(m.frag_idx); w.u8(m.frag_total);
|
||||
w.raw(m.bytes, m.len);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_manifest(const uint8_t* buf, uint16_t len, ManifestMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_MANIFEST) return false;
|
||||
const uint8_t* id = r.raw(4); if (id) memcpy(m.manifest_id, id, 4);
|
||||
m.frag_idx = r.u8(); m.frag_total = r.u8();
|
||||
m.len = r.remaining(); m.bytes = r.raw(m.len);
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_req(uint8_t* buf, uint16_t cap, const ReqMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_REQ); w.raw(m.manifest_id, 4); w.u16(m.block_idx); w.u16(m.want_mask);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_req(const uint8_t* buf, uint16_t len, ReqMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_REQ) return false;
|
||||
const uint8_t* id = r.raw(4); if (id) memcpy(m.manifest_id, id, 4);
|
||||
m.block_idx = r.u16(); m.want_mask = r.u16();
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_data(uint8_t* buf, uint16_t cap, const DataMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_DATA); w.raw(m.manifest_id, 4); w.u16(m.block_idx); w.u16(m.frag_off);
|
||||
w.raw(m.data, m.data_len);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_data(const uint8_t* buf, uint16_t len, DataMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_DATA) return false;
|
||||
const uint8_t* id = r.raw(4); if (id) memcpy(m.manifest_id, id, 4);
|
||||
m.block_idx = r.u16(); m.frag_off = r.u16();
|
||||
m.data_len = r.remaining(); m.data = r.raw(m.data_len);
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_req_proof(uint8_t* buf, uint16_t cap, const ReqProofMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_REQ_PROOF); w.raw(m.manifest_id, 4); w.u16(m.block_idx);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_req_proof(const uint8_t* buf, uint16_t len, ReqProofMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_REQ_PROOF) return false;
|
||||
const uint8_t* id = r.raw(4); if (id) memcpy(m.manifest_id, id, 4);
|
||||
m.block_idx = r.u16();
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_proof(uint8_t* buf, uint16_t cap, const ProofMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_PROOF); w.raw(m.manifest_id, 4); w.u16(m.block_idx);
|
||||
w.u8(m.n_proof); w.raw(m.proof, (uint16_t)m.n_proof * 4);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_proof(const uint8_t* buf, uint16_t len, ProofMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_PROOF) return false;
|
||||
const uint8_t* id = r.raw(4); if (id) memcpy(m.manifest_id, id, 4);
|
||||
m.block_idx = r.u16(); m.n_proof = r.u8(); m.proof = r.raw((uint16_t)m.n_proof * 4);
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_get_leaves(uint8_t* buf, uint16_t cap, const GetLeavesMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_GET_LEAVES); w.raw(m.manifest_id, 4); w.u16(m.want_mask);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_get_leaves(const uint8_t* buf, uint16_t len, GetLeavesMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_GET_LEAVES) return false;
|
||||
const uint8_t* id = r.raw(4); if (id) memcpy(m.manifest_id, id, 4);
|
||||
m.want_mask = r.u16();
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
uint16_t encode_leaves(uint8_t* buf, uint16_t cap, const LeavesMsg& m) {
|
||||
W w(buf, cap); w.u8(OTA_LEAVES); w.raw(m.manifest_id, 4); w.u8(m.frag_idx); w.u8(m.frag_total);
|
||||
w.raw(m.bytes, m.len);
|
||||
return w.ok ? w.n : 0;
|
||||
}
|
||||
bool decode_leaves(const uint8_t* buf, uint16_t len, LeavesMsg& m) {
|
||||
R r(buf, len); if (r.u8() != OTA_LEAVES) return false;
|
||||
const uint8_t* id = r.raw(4); if (id) memcpy(m.manifest_id, id, 4);
|
||||
m.frag_idx = r.u8(); m.frag_total = r.u8();
|
||||
m.len = r.remaining(); m.bytes = r.raw(m.len);
|
||||
return r.ok;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,140 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "OtaFormat.h"
|
||||
|
||||
// Encode/decode for the OTA LoRa messages (docs/ota_protocol.md §8). Each message is a packet payload:
|
||||
// [0]=ota_msg_type, then a fixed body. Portable + allocation-free; unit-tested on the host.
|
||||
//
|
||||
// manifest_id == the manifest's merkle_root (4 bytes), a compact content id.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// ---- OTA_ADV: tiny per-NODE beacon (flood, periodic). CONSTANT size regardless of how many mOTAs a
|
||||
// node serves — it just says "I'm a source, here's how many + a digest of my set". A peer that's
|
||||
// interested asks for the catalog via OTA_QUERY. (Replaces the old per-mOTA advert so a folder node with
|
||||
// N images costs one 10-byte beacon, not N adverts.) ----
|
||||
struct AdvMsg {
|
||||
uint8_t seeder_id[4]; // advertiser's node id = pubkey[0:4]; the QUERY address + distinct-source id
|
||||
uint8_t n_motas; // # of complete, servable mOTAs (saturates at 255)
|
||||
uint8_t set_digest[4]; // sha2-256:4 over the sorted set of served mids; "did my offering change?"
|
||||
};
|
||||
|
||||
// ---- OTA_QUERY: "list what you serve" — addressed to a source by seeder_id, FLOODED so neighbours
|
||||
// overhear it (storm suppression). set_digest identifies the offering being asked about (so an overhearer
|
||||
// can suppress its own pending query for the same {source,digest}). filter_target=0 = everything. ----
|
||||
struct QueryMsg {
|
||||
uint8_t seeder_id[4]; // which source this query is for (the source matches its own id)
|
||||
uint8_t set_digest[4]; // the offering digest we're asking about (for overhear-suppression)
|
||||
uint32_t filter_target; // 0 = all (the scalable default); else only mOTAs for this target_id
|
||||
};
|
||||
|
||||
// ---- OTA_HAVE: the compact catalog (source -> mesh), FLOODED + tagged with set_digest so EVERY node
|
||||
// that overhears it caches the rows (passive, no query needed). Fragmented. ----
|
||||
// body: seeder_id(4) set_digest(4) frag_idx(1) frag_total(1) n_rows(1) rows[ mid(4) target(4) fwver(4) codec(1) flags(1) ]
|
||||
struct HaveRow { uint8_t mid[4]; uint32_t target_id; uint32_t fw_version; uint8_t codec_id; uint8_t flags;
|
||||
uint16_t have_count; }; // blocks the advertiser holds (== block_count if complete; less => partial source)
|
||||
struct HaveMsg {
|
||||
uint8_t seeder_id[4];
|
||||
uint8_t set_digest[4]; // the offering this catalog describes (overhearers cache by it)
|
||||
uint8_t frag_idx, frag_total;
|
||||
uint8_t n_rows; // rows in THIS fragment
|
||||
const uint8_t* rows; // points into buf: n_rows * OTA_HAVE_ROW_BYTES
|
||||
};
|
||||
static const uint8_t OTA_HAVE_ROW_BYTES = 16; // mid4 + target4 + fwver4 + codec1 + flags1 + have_count2
|
||||
|
||||
// ---- OTA_GET_MANIFEST: request the manifest for a content id (direct) ----
|
||||
// body: manifest_id(4) want_mask(2). want_mask bit k = "send manifest fragment k"; 0xFFFF = "send all"
|
||||
// (used on the first ask, before frag_total is known). A retry requests only the still-missing fragments,
|
||||
// so a lost manifest fragment doesn't force the whole manifest to be re-bursted (same rationale as OTA_REQ).
|
||||
struct GetManifestMsg { uint8_t manifest_id[4]; uint16_t want_mask; };
|
||||
|
||||
// ---- OTA_MANIFEST: the manifest-minus-leaves[], fragmented (direct) ----
|
||||
// body: manifest_id(4) frag_idx(1) frag_total(1) bytes[]
|
||||
struct ManifestMsg {
|
||||
uint8_t manifest_id[4];
|
||||
uint8_t frag_idx, frag_total;
|
||||
const uint8_t* bytes; uint16_t len;
|
||||
};
|
||||
|
||||
// ---- OTA_REQ: request specific fragments of ONE block (direct) ----
|
||||
// body: manifest_id(4) block_idx(2) want_mask(2). want_mask bit k = "send fragment k" (the slice at byte
|
||||
// offset k*OTA_FRAG_DATA). A fetcher requests the full mask ((1<<nf)-1) for a fresh block and only the
|
||||
// missing bits to recover holes, so a lost fragment costs one fragment to re-send — not the whole block
|
||||
// (saves airtime and avoids the re-REQ colliding with a multi-fragment burst on half-duplex radios).
|
||||
struct ReqMsg { uint8_t manifest_id[4]; uint16_t block_idx; uint16_t want_mask; };
|
||||
|
||||
// ---- OTA_DATA: one self-describing fragment of a block's data (proof is fetched separately) ----
|
||||
// body: manifest_id(4) block_idx(2) frag_off(2) data[]
|
||||
// `frag_off` is the byte offset of `data` within block `block_idx` (global position = block_idx*block_size
|
||||
// + frag_off), so a fragment is self-placing when received from the selected source.
|
||||
struct DataMsg {
|
||||
uint8_t manifest_id[4];
|
||||
uint16_t block_idx;
|
||||
uint16_t frag_off;
|
||||
const uint8_t* data; uint16_t data_len;
|
||||
};
|
||||
|
||||
// ---- OTA_GET_LEAVES: request the target's merkle leaves[] in bulk (direct; motatool warm-start only) ----
|
||||
// body: manifest_id(4) want_mask(2). want_mask bit k = "send leaves fragment k"; 0xFFFF = "send all" on the
|
||||
// first ask (before frag_total is known); a retry requests only the still-missing fragments (anti-burst,
|
||||
// same rationale as OTA_GET_MANIFEST). Lets a folder-capture fetcher diff a seed build's blocks against the
|
||||
// target's authenticated leaves and pull DATA only for the ones that differ.
|
||||
struct GetLeavesMsg { uint8_t manifest_id[4]; uint16_t want_mask; };
|
||||
|
||||
// ---- OTA_LEAVES: one fragment of the leaves[] array (block_count*4 bytes total), direct ----
|
||||
// body: manifest_id(4) frag_idx(1) frag_total(1) bytes[] (up to OTA_LEAVES_FRAG leaf bytes per fragment)
|
||||
struct LeavesMsg {
|
||||
uint8_t manifest_id[4];
|
||||
uint8_t frag_idx, frag_total;
|
||||
const uint8_t* bytes; uint16_t len;
|
||||
};
|
||||
|
||||
// ---- OTA_REQ_PROOF: request the merkle proof for one (reassembled) block (direct) ----
|
||||
struct ReqProofMsg { uint8_t manifest_id[4]; uint16_t block_idx; };
|
||||
|
||||
// ---- OTA_PROOF: the merkle proof (ordered sibling digests) for one block (direct) ----
|
||||
struct ProofMsg { uint8_t manifest_id[4]; uint16_t block_idx; uint8_t n_proof; const uint8_t* proof; };
|
||||
|
||||
// Each encode_* returns the total payload length (incl. the leading msg-type byte), 0 on overflow.
|
||||
// Each decode_* returns true on success (and points struct fields into `buf`).
|
||||
|
||||
uint16_t encode_adv(uint8_t* buf, uint16_t cap, const AdvMsg& m);
|
||||
bool decode_adv(const uint8_t* buf, uint16_t len, AdvMsg& m);
|
||||
|
||||
uint16_t encode_query(uint8_t* buf, uint16_t cap, const QueryMsg& m);
|
||||
bool decode_query(const uint8_t* buf, uint16_t len, QueryMsg& m);
|
||||
|
||||
uint16_t encode_have(uint8_t* buf, uint16_t cap, const HaveMsg& m);
|
||||
bool decode_have(const uint8_t* buf, uint16_t len, HaveMsg& m);
|
||||
|
||||
uint16_t encode_get_manifest(uint8_t* buf, uint16_t cap, const GetManifestMsg& m);
|
||||
bool decode_get_manifest(const uint8_t* buf, uint16_t len, GetManifestMsg& m);
|
||||
|
||||
uint16_t encode_manifest(uint8_t* buf, uint16_t cap, const ManifestMsg& m);
|
||||
bool decode_manifest(const uint8_t* buf, uint16_t len, ManifestMsg& m);
|
||||
|
||||
uint16_t encode_req(uint8_t* buf, uint16_t cap, const ReqMsg& m);
|
||||
bool decode_req(const uint8_t* buf, uint16_t len, ReqMsg& m);
|
||||
|
||||
uint16_t encode_data(uint8_t* buf, uint16_t cap, const DataMsg& m);
|
||||
bool decode_data(const uint8_t* buf, uint16_t len, DataMsg& m);
|
||||
|
||||
uint16_t encode_get_leaves(uint8_t* buf, uint16_t cap, const GetLeavesMsg& m);
|
||||
bool decode_get_leaves(const uint8_t* buf, uint16_t len, GetLeavesMsg& m);
|
||||
|
||||
uint16_t encode_leaves(uint8_t* buf, uint16_t cap, const LeavesMsg& m);
|
||||
bool decode_leaves(const uint8_t* buf, uint16_t len, LeavesMsg& m);
|
||||
|
||||
uint16_t encode_req_proof(uint8_t* buf, uint16_t cap, const ReqProofMsg& m);
|
||||
bool decode_req_proof(const uint8_t* buf, uint16_t len, ReqProofMsg& m);
|
||||
|
||||
uint16_t encode_proof(uint8_t* buf, uint16_t cap, const ProofMsg& m);
|
||||
bool decode_proof(const uint8_t* buf, uint16_t len, ProofMsg& m);
|
||||
|
||||
inline uint8_t ota_msg_type(const uint8_t* buf, uint16_t len) { return len ? buf[0] : 0xFF; }
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,186 @@
|
||||
#include "OtaSelf.h"
|
||||
#include "FirmwareInfo.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include <string.h>
|
||||
|
||||
#if defined(ESP32_PLATFORM)
|
||||
#include "esp_ota_ops.h"
|
||||
#include "esp_partition.h"
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
#include "OtaFlashLayout_nrf52.h"
|
||||
#endif
|
||||
|
||||
#if defined(ESP32_PLATFORM) || defined(NRF52_PLATFORM)
|
||||
#include "OtaContext.h" // serve our own fw from flash (cache leaves, read payload on demand)
|
||||
#include "MerkleTree.h"
|
||||
#include <SHA256.h>
|
||||
#include <stdlib.h>
|
||||
#ifndef OTA_SELF_LEAVES_MAX
|
||||
#define OTA_SELF_LEAVES_MAX 65536u // cap heap for cached leaves (~16k blocks @1 KB = up to ~16 MB image)
|
||||
#endif
|
||||
#endif
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
#if defined(ESP32_PLATFORM)
|
||||
// Scan the running app partition for the firmware's EndF trailer using esp_partition_read (stable
|
||||
// across IDF versions — no mmap). Same rule as find_self_firmware(): the marker's absolute offset
|
||||
// must equal its stored body_len, which uniquely identifies the running firmware's own trailer.
|
||||
bool ota_self_firmware(SelfFwInfo& out) {
|
||||
out = SelfFwInfo();
|
||||
const esp_partition_t* p = esp_ota_get_running_partition();
|
||||
if (!p) return false;
|
||||
|
||||
const uint32_t CH = 512;
|
||||
uint8_t buf[CH + ENDF_LEN]; // overlap so a marker spanning a chunk edge is still seen
|
||||
for (uint32_t base = 0; base + ENDF_LEN <= p->size; base += CH) {
|
||||
uint32_t want = CH + ENDF_LEN;
|
||||
if (base + want > p->size) want = p->size - base;
|
||||
if (esp_partition_read(p, base, buf, want) != ESP_OK) return false;
|
||||
for (uint32_t i = 0; i + ENDF_LEN <= want; i++) {
|
||||
if (buf[i] != ENDF_MAGIC[0]) continue;
|
||||
if (memcmp(buf + i, ENDF_MAGIC, 4) != 0) continue;
|
||||
uint32_t body_len = rd_u32le(buf + i + 4);
|
||||
if (body_len != base + i) continue; // must sit immediately after a body of that length
|
||||
out.valid = true;
|
||||
out.endf_offset = body_len;
|
||||
out.body_len = body_len;
|
||||
out.image_len = body_len + ENDF_LEN;
|
||||
memcpy(out.body_hash, buf + i + 8, 8);
|
||||
// Fixed 56-byte trailer: re-read it whole at the marker (it may straddle the chunk window, so the
|
||||
// identity fields aren't reliably in `buf`) and pull identity from constant offsets (docs §2).
|
||||
uint8_t tr[ENDF_LEN];
|
||||
if (body_len + ENDF_LEN <= p->size &&
|
||||
esp_partition_read(p, body_len, tr, ENDF_LEN) == ESP_OK) {
|
||||
out.fw_version = (uint32_t)tr[16] | ((uint32_t)tr[17]<<8) | ((uint32_t)tr[18]<<16) | ((uint32_t)tr[19]<<24);
|
||||
out.target_id = (uint32_t)tr[20] | ((uint32_t)tr[21]<<8) | ((uint32_t)tr[22]<<16) | ((uint32_t)tr[23]<<24);
|
||||
memcpy(out.hw_id, tr + 24, 32); out.hw_id[32] = 0;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
// nRF52 internal flash is memory-mapped, so the running app is directly scannable. The body starts at
|
||||
// APP_BASE; find_self_firmware() picks the EndF whose stored body_len equals its offset (the running
|
||||
// firmware's own trailer), ignoring any staged `.mota` (which carries its own embedded EndF) higher up.
|
||||
bool ota_self_firmware(SelfFwInfo& out) {
|
||||
const uint8_t* region = (const uint8_t*)(uintptr_t)MOTA_NRF52_APP_BASE;
|
||||
uint32_t region_len = MOTA_NRF52_FS_START - MOTA_NRF52_APP_BASE;
|
||||
return find_self_firmware(region, region_len, out, /*verify_body=*/true);
|
||||
}
|
||||
#else
|
||||
bool ota_self_firmware(SelfFwInfo& out) {
|
||||
// STM32/RP2040: app-region access lands with their apply path.
|
||||
out = SelfFwInfo();
|
||||
return false;
|
||||
}
|
||||
#endif
|
||||
|
||||
#if defined(ESP32_PLATFORM)
|
||||
bool ota_self_read(uint32_t off, uint8_t* buf, uint32_t len) {
|
||||
const esp_partition_t* p = esp_ota_get_running_partition();
|
||||
return p && esp_partition_read(p, off, buf, len) == ESP_OK;
|
||||
}
|
||||
#elif defined(NRF52_PLATFORM)
|
||||
bool ota_self_read(uint32_t off, uint8_t* buf, uint32_t len) {
|
||||
if ((uint64_t)MOTA_NRF52_APP_BASE + off + len > MOTA_NRF52_FS_START) return false;
|
||||
memcpy(buf, (const uint8_t*)(uintptr_t)(MOTA_NRF52_APP_BASE + off), len);
|
||||
return true;
|
||||
}
|
||||
#else
|
||||
bool ota_self_read(uint32_t, uint8_t*, uint32_t) { return false; }
|
||||
#endif
|
||||
|
||||
#if defined(ESP32_PLATFORM) || defined(NRF52_PLATFORM)
|
||||
static bool self_read_cb(void* ctx, uint32_t off, uint8_t* buf, uint32_t len) {
|
||||
(void)ctx; return ota_self_read(off, buf, len);
|
||||
}
|
||||
// Build (once) the full-image manifest + merkle leaves for the running firmware, cache them in `c`, and
|
||||
// hand the manager a flash-read callback for the payload. The image is read ONCE here to compute the
|
||||
// leaves + image_hash; thereafter a block REQ reads only that block (proof comes from the cached leaves).
|
||||
// Pack the first "MAJOR.MINOR.PATCH" found in `s` into the comparable uint32 the manifest uses
|
||||
// (MAJOR<<24 | MINOR<<16 | PATCH<<8). Returns 0 if there's no dotted number (e.g. a "dev-<sha>" build).
|
||||
static uint32_t parse_fw_version(const char* s) {
|
||||
if (!s) return 0;
|
||||
for (; *s; s++) { // find the start of a "d.d" run
|
||||
if (*s < '0' || *s > '9') continue;
|
||||
const char* p = s; uint32_t a = 0, b = 0, d = 0; int dots = 0;
|
||||
uint32_t* cur = &a;
|
||||
for (; *p; p++) {
|
||||
if (*p >= '0' && *p <= '9') { *cur = *cur * 10 + (uint32_t)(*p - '0'); }
|
||||
else if (*p == '.' && dots < 2) { dots++; cur = (dots == 1) ? &b : &d; }
|
||||
else break;
|
||||
}
|
||||
if (dots >= 1) return FwVersion{ (uint8_t)a, (uint8_t)b, (uint8_t)d, 0 }.pack();
|
||||
s = p - 1; // a bare number, no dots — keep scanning
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
|
||||
bool ota_serve_self(OtaContext& c, uint32_t fw_version) {
|
||||
// Derive our version from the build string when the caller didn't supply one, so the mOTA we advertise
|
||||
// carries a real version (was hard-coded 0 -> peers saw "v0.0.0"). A dev build with no dotted number
|
||||
// still reads 0 — the self-describing EndF identity (docs) is the durable fix for that.
|
||||
#ifdef FIRMWARE_VERSION
|
||||
if (fw_version == 0) fw_version = parse_fw_version(FIRMWARE_VERSION);
|
||||
#endif
|
||||
SelfFwInfo fi;
|
||||
if (!ota_self_firmware(fi) || !fi.valid) return false;
|
||||
// 1 KB logical blocks (delivered as multiple LoRa fragments): 8x fewer merkle leaves than 128 B, so a
|
||||
// ~530 KB image is ~518 blocks (proof-gen scratch ~2 KB) instead of ~4150 (which overflowed the scratch).
|
||||
const uint32_t image_size = fi.image_len, BS = OTA_DEFAULT_BLOCK_SIZE;
|
||||
const uint32_t bc = (image_size + BS - 1) / BS;
|
||||
if ((uint64_t)bc * 4 > OTA_SELF_LEAVES_MAX) return false;
|
||||
|
||||
free(c.serve_self_leaves); free(c.serve_self_proof);
|
||||
c.serve_self_leaves = (uint8_t*)malloc((size_t)bc * 4);
|
||||
c.serve_self_proof = (uint8_t*)malloc((size_t)bc * 4); // proof-gen working buffer (sized to OUR image)
|
||||
if (!c.serve_self_leaves || !c.serve_self_proof) {
|
||||
free(c.serve_self_leaves); free(c.serve_self_proof);
|
||||
c.serve_self_leaves = c.serve_self_proof = nullptr;
|
||||
return false;
|
||||
}
|
||||
|
||||
SHA256 sha; uint8_t blk[BS];
|
||||
for (uint32_t i = 0, off = 0; i < bc; i++, off += BS) {
|
||||
uint32_t blen = (off + BS <= image_size) ? BS : (image_size - off);
|
||||
if (!ota_self_read(off, blk, blen)) {
|
||||
free(c.serve_self_leaves); free(c.serve_self_proof);
|
||||
c.serve_self_leaves = c.serve_self_proof = nullptr;
|
||||
return false;
|
||||
}
|
||||
merkle_leaf(c.serve_self_leaves + (size_t)i * 4, blk, blen);
|
||||
sha.update(blk, blen);
|
||||
}
|
||||
uint8_t image_hash[32]; sha.finalize(image_hash, 32);
|
||||
uint8_t root[4]; merkle_root(root, c.serve_self_leaves, bc);
|
||||
|
||||
// Prefer the SELF-DESCRIBING identity embedded in our own EndF (docs §2) over build flags / the param —
|
||||
// it's correct regardless of how the firmware was built (build.sh injection, IDE, etc.).
|
||||
uint32_t out_target = fi.target_id ? fi.target_id : c.manager.target();
|
||||
uint32_t out_ver = fi.fw_version ? fi.fw_version : fw_version;
|
||||
const char* out_hw = fi.hw_id[0] ? fi.hw_id : c.hw_id;
|
||||
|
||||
// Assemble the fixed-layout manifest-minus-leaves (full, unsigned) = MOTA_MFL bytes. base_hash(89),
|
||||
// signer_pubkey(97) and signature(129) stay zero-filled (full + unsigned); only `approval` is set.
|
||||
uint8_t* m = c.serve_self_manifest;
|
||||
memset(m, 0, MOTA_MFL);
|
||||
m[0] = MOTA_FORMAT_VER; m[1] = MFLAG_FULL; m[2] = HASH_ALGO_SHA256;
|
||||
wr_u32le(m + 3, out_target); wr_u32le(m + 7, out_ver);
|
||||
wr_u32le(m + 11, image_size); wr_u32le(m + 15, image_size); // full: payload == image
|
||||
m[19] = 10; // block_size_log2 = 10 (1024 B logical block)
|
||||
memcpy(m + 20, root, 4);
|
||||
memcpy(m + 24, image_hash, 32);
|
||||
m[56] = CODEC_FULL;
|
||||
memcpy(m + 57, out_hw, strlen(out_hw) < 32 ? strlen(out_hw) : 32); // hw_id[32] (NUL-padded by memset)
|
||||
memcpy(m + MOTA_OFF_APPROVAL, APPROVAL_NOT, 4); // approval (fetching device's apply-gate handles it)
|
||||
return c.manager.serve_self(m, MOTA_MFL, c.serve_self_leaves, bc,
|
||||
c.serve_self_proof, (size_t)bc * 4, self_read_cb, nullptr);
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
#include "FirmwareInfo.h"
|
||||
|
||||
// Device-side accessor for the running firmware's own image (to read its EndF trailer).
|
||||
// Per-platform: ESP32 memory-maps the running app partition; other platforms TBD (nRF52 uses the
|
||||
// bootloader-apply path, so its app-region wiring lands with that work). Not compiled on the native
|
||||
// host — the portable scan logic in FirmwareInfo.{h,cpp} is what gets unit-tested there.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// Locate this firmware's EndF trailer in its own flash image. Returns false if unsupported on this
|
||||
// platform or no valid EndF is present (e.g. firmware built without the EndF build hook).
|
||||
bool ota_self_firmware(SelfFwInfo& out);
|
||||
|
||||
// Read `len` bytes of the running firmware image at offset `off` (ESP32: running partition via
|
||||
// esp_partition_read; nRF52: memory-mapped app region). false on unsupported platforms.
|
||||
bool ota_self_read(uint32_t off, uint8_t* buf, uint32_t len);
|
||||
|
||||
// Compute (once) + cache our running firmware's manifest + merkle leaves in `c`, then serve it from
|
||||
// flash as a full `.mota` (payload read on demand per block; only metadata held in RAM). Returns false
|
||||
// if no EndF / image too big / OOM. Device platforms only.
|
||||
struct OtaContext;
|
||||
bool ota_serve_self(OtaContext& c, uint32_t fw_version); // target = this node's own (c.manager.target())
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,55 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include "OtaFormat.h"
|
||||
|
||||
// Transport-agnostic "folder of firmware" abstraction (docs/ota_protocol.md §9). A node can RELAY
|
||||
// `.mota` images it does not hold in flash — a user drops several `.mota` (different architectures) into
|
||||
// some external store and the node advertises + serves them as if it held them. Peers just see "this node
|
||||
// has N mOTAs"; the node knows they are external. The store is reached through a MotaSource, so the SAME
|
||||
// serve code drives a USB-serial host daemon, BLE, a WiFi URL list, an NFS/samba mount, ... — only the
|
||||
// `read()` plumbing differs per transport.
|
||||
//
|
||||
// The relay is TRUSTLESS: the fetcher verifies every block against the signed merkle root, so a source is
|
||||
// never trusted. A wrong descriptor or wrong bytes simply makes the fetch fail its merkle/signature check
|
||||
// — a malicious or buggy source cannot forge firmware, only deny it.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// A parsed top-level descriptor of one `.mota` a source provides: enough to advertise it in the catalog
|
||||
// AND to locate every region for serving, WITHOUT holding the whole image in RAM. Offsets are absolute
|
||||
// byte positions within the `.mota` container (which always begins MAGIC(4) total(4) manifest...).
|
||||
struct MotaDesc {
|
||||
uint8_t mid[4] = {0}; // merkle_root (the content id peers fetch by)
|
||||
uint32_t target_id = 0;
|
||||
uint32_t fw_version = 0;
|
||||
uint8_t codec_id = 0;
|
||||
uint8_t flags = 0;
|
||||
uint32_t total_size = 0; // full `.mota` length (bytes)
|
||||
uint32_t leaves_off = 0; // byte offset of the merkle leaves[] (manifest-minus-leaves = [8, leaves_off))
|
||||
uint32_t block_count = 0; // == number of leaves (== number of payload blocks)
|
||||
uint32_t payload_off = 0; // byte offset of the payload
|
||||
uint32_t payload_size = 0;
|
||||
};
|
||||
|
||||
// One or more complete `.mota` images, reachable as random-access bytes. Implementations are device-side
|
||||
// and transport-specific (the engine in OtaManager is portable and never includes this directly for I/O;
|
||||
// it only calls through the interface).
|
||||
class MotaSource {
|
||||
public:
|
||||
virtual ~MotaSource() {}
|
||||
// Number of complete, servable mOTAs this source currently offers (may change as the folder changes;
|
||||
// the manager re-enumerates on add_source / refresh).
|
||||
virtual uint8_t count() = 0;
|
||||
// Cheap metadata + region offsets for mota `idx`. False if idx is out of range or unparsable.
|
||||
virtual bool describe(uint8_t idx, MotaDesc& out) = 0;
|
||||
// Random-access read of `len` bytes at absolute offset `off` of mota `idx` into `buf`. Returns true iff
|
||||
// exactly `len` bytes were produced. May block on the transport (serial round-trip); OTA is lowest
|
||||
// priority so latency here is acceptable.
|
||||
virtual bool read(uint8_t idx, uint32_t off, uint8_t* buf, uint32_t len) = 0;
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,103 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
#include "OtaFormat.h" // MOTA_MAGIC (resume: detect a persisted partial container)
|
||||
|
||||
// Staging backend for an in-transit `.mota` (docs/ota_protocol.md §7). Blocks may arrive out of order
|
||||
// and progress must survive reboots, so the store is random-access. The transfer/verify logic is
|
||||
// written against this interface; concrete impls are per-platform (RAM for tests/bring-up; persistent
|
||||
// flash — ESP32 OTA slot / nRF52 raw region — for production, dropped in behind the same interface).
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
class OtaStore {
|
||||
public:
|
||||
virtual ~OtaStore() {}
|
||||
// Prepare staging for a container of `total_size` bytes (erases/clears). false if it won't fit.
|
||||
virtual bool begin(uint32_t total_size) = 0;
|
||||
virtual bool write(uint32_t offset, const uint8_t* data, uint32_t len) = 0;
|
||||
virtual bool read(uint32_t offset, uint8_t* buf, uint32_t len) const = 0;
|
||||
virtual uint32_t capacity() const = 0;
|
||||
virtual uint32_t staged_size() const = 0; // total_size from begin(), 0 if none
|
||||
virtual void clear() = 0;
|
||||
|
||||
// Optional: declare the size of the leading metadata (header + manifest + merkle leaves, i.e.
|
||||
// everything before the payload). A flash-backed store keeps that region — which is updated
|
||||
// throughout the transfer (a leaf is committed per block) — pinned in one RAM page, so it can
|
||||
// flush the bulk payload page-by-page without re-erasing the leaves' page on every block.
|
||||
// Returns false if the metadata won't fit the store's pinned region (transfer is then refused).
|
||||
virtual bool set_meta_size(uint32_t meta_bytes) { (void)meta_bytes; return true; }
|
||||
|
||||
// Optional: commit any RAM-buffered data to persistent storage. Called once when the transfer
|
||||
// reaches COMPLETE (radio idle), so a flash store does its page writes off the RX critical path.
|
||||
// After this returns, a flash store's data() view is coherent. No-op for purely in-RAM stores.
|
||||
virtual void finalize() {}
|
||||
|
||||
// Optional: persist in-progress state (the metadata/leaf-progress page + any open payload buffer) so a
|
||||
// reboot mid-transfer can resume. Called by OtaManager every OTA_CHECKPOINT_BLOCKS committed blocks.
|
||||
// A flash store flushes its pinned meta page + the open payload page (consistency: payload-before-leaves)
|
||||
// so every block whose leaf is persisted also has its payload in flash. No-op for RAM stores. Infrequent
|
||||
// (at LoRa block rates, ~once per many minutes) so the extra erases don't matter.
|
||||
virtual void checkpoint() {}
|
||||
|
||||
// Optional: re-attach to a container ALREADY persisted in the backing store (after a reboot), WITHOUT
|
||||
// erasing. Returns true if a syntactically valid container (MOTA_MAGIC header + plausible total) is
|
||||
// present and the store is now set up to read/continue-writing it; false if none (caller starts fresh).
|
||||
// OtaManager then reads + parses the stored manifest to recompute geometry and resume the fetch.
|
||||
virtual bool reopen() { return false; }
|
||||
|
||||
// Optional: declare the container's logical layout once the manifest is parsed, BEFORE begin(), so a
|
||||
// store backed by a single spare A/B partition (ESP32) can choose placement and reject an unfittable
|
||||
// fetch up front. A FULL image's payload IS the final firmware (no decode), so it can stream straight
|
||||
// to the inactive slot's offset 0 while the small meta/leaves/trailer persist elsewhere; a delta's
|
||||
// whole container is staged together (the decoder reads the patch from it at apply). image_size is the
|
||||
// reconstructed image; [payload_off, payload_off+payload_size) is the payload region in the container.
|
||||
// Return false if it cannot fit the backing store (the transfer is then refused before any block).
|
||||
virtual bool plan_layout(bool is_full, uint32_t image_size, uint32_t payload_off, uint32_t payload_size) {
|
||||
(void)is_full; (void)image_size; (void)payload_off; (void)payload_size; return true;
|
||||
}
|
||||
};
|
||||
|
||||
// Fixed-capacity RAM store — for native tests and device bring-up of the transfer/verify path.
|
||||
// (Does NOT survive reboot; a persistent flash store replaces it for production — see D1.)
|
||||
template <uint32_t CAP>
|
||||
class OtaStoreRam : public OtaStore {
|
||||
uint8_t _buf[CAP] = {}; // zero-init so a never-written store's reopen() finds no MOTA_MAGIC
|
||||
uint32_t _total = 0;
|
||||
public:
|
||||
bool begin(uint32_t total_size) override {
|
||||
if (total_size > CAP) return false;
|
||||
_total = total_size;
|
||||
memset(_buf, 0xFF, total_size); // mimic erased flash (so unfilled leaf slots read as 'missing')
|
||||
return true;
|
||||
}
|
||||
bool write(uint32_t off, const uint8_t* d, uint32_t len) override {
|
||||
if ((uint64_t)off + len > _total) return false;
|
||||
memcpy(_buf + off, d, len);
|
||||
return true;
|
||||
}
|
||||
bool read(uint32_t off, uint8_t* b, uint32_t len) const override {
|
||||
if ((uint64_t)off + len > _total) return false;
|
||||
memcpy(b, _buf + off, len);
|
||||
return true;
|
||||
}
|
||||
uint32_t capacity() const override { return CAP; }
|
||||
uint32_t staged_size() const override { return _total; }
|
||||
void clear() override { _total = 0; }
|
||||
// RAM doesn't survive a real reboot, but the buffer persists within a process — enough to exercise the
|
||||
// manager's resume path in native tests. Recover `total` from the stored header so read() bounds work.
|
||||
bool reopen() override {
|
||||
if (memcmp(_buf, MOTA_MAGIC, 4) != 0) return false;
|
||||
uint32_t t = (uint32_t)_buf[4] | ((uint32_t)_buf[5] << 8) | ((uint32_t)_buf[6] << 16) | ((uint32_t)_buf[7] << 24);
|
||||
if (t < 13 || t > CAP) return false;
|
||||
_total = t;
|
||||
return true;
|
||||
}
|
||||
const uint8_t* data() const { return _buf; } // contiguous view (RAM store only)
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,243 @@
|
||||
#include "OtaStoreFlashEsp32.h"
|
||||
|
||||
#if defined(ESP32_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
|
||||
#include "OtaDebug.h"
|
||||
#include "OtaByteIO.h" // align_up / align_down (flash-sector geometry)
|
||||
#include "MotaContainer.h" // mota_parse_manifest (reopen: rebuild geometry from the staged manifest)
|
||||
#include <string.h>
|
||||
#include <stdlib.h> // malloc/free (the meta buffer is sized per fetch)
|
||||
#include "esp_ota_ops.h" // esp_ota_get_next_update_partition (the inactive A/B slot)
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
OtaStoreFlashEsp32::~OtaStoreFlashEsp32() { free(_meta); }
|
||||
|
||||
bool OtaStoreFlashEsp32::acquire() {
|
||||
if (!_part) {
|
||||
_part = esp_ota_get_next_update_partition(nullptr);
|
||||
_psize = _part ? _part->size : 0;
|
||||
}
|
||||
return _part != nullptr;
|
||||
}
|
||||
|
||||
// Compute the slot placement from _full/_image_size/_meta_bytes/_pay_size (already set). Returns false if
|
||||
// it won't fit. Shared by plan_layout (fresh fetch) and reopen (resume) so both derive identical geometry.
|
||||
bool OtaStoreFlashEsp32::layout() {
|
||||
uint32_t total = _meta_bytes + _pay_size + 5;
|
||||
if (_full) {
|
||||
// payload streams to slot offset 0 (it IS the image); header+manifest+leaves+trailer persist at the
|
||||
// bottom so the container survives a reboot (resume / re-serve).
|
||||
_meta_span = _meta_bytes; // routing boundary: [0,meta) -> RAM meta buffer
|
||||
_meta_flush = align_up(_meta_bytes + 5, SEC); // meta + 5-byte trailer, whole sectors
|
||||
if (_meta_flush > OTA_ESP32_META_CAP) return false;
|
||||
uint32_t bottom = align_down(_psize - _meta_flush, SEC);
|
||||
_meta_part = bottom;
|
||||
_pay_log0 = _meta_bytes; _pay_part0 = 0;
|
||||
_write_start = 0;
|
||||
if (_image_size > bottom) return false; // image would overrun the bottom meta region
|
||||
} else {
|
||||
// whole container staged bottom-aligned; the decoded image fills the slot from offset 0.
|
||||
_meta_span = align_up(_meta_bytes, SEC); // pin whole sectors covering meta (+ spillover payload)
|
||||
_meta_flush = _meta_span;
|
||||
if (_meta_flush > OTA_ESP32_META_CAP) return false;
|
||||
if (total > _psize) return false;
|
||||
_write_start = align_down(_psize - total, SEC);
|
||||
_meta_part = _write_start;
|
||||
_pay_log0 = _meta_span; _pay_part0 = _write_start + _meta_span;
|
||||
if (_image_size > _write_start) return false; // decoded output would overlap the staged container
|
||||
}
|
||||
_total = total;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Choose placement from the parsed manifest and refuse anything that won't fit, BEFORE any block is
|
||||
// staged. (See the header for the delta-vs-full layout rationale.)
|
||||
bool OtaStoreFlashEsp32::plan_layout(bool is_full, uint32_t image_size, uint32_t payload_off, uint32_t payload_size) {
|
||||
if (!acquire()) return false;
|
||||
_full = is_full; _image_size = image_size; _meta_bytes = payload_off; _pay_size = payload_size;
|
||||
bool ok = layout();
|
||||
OTA_DBG("OTA esp32: plan %s total=%u image=%u meta=%u write_start=%u meta_part=%u ok=%d\n",
|
||||
is_full ? "FULL" : "DELTA", (unsigned)_total, (unsigned)image_size, (unsigned)_meta_bytes,
|
||||
(unsigned)_write_start, (unsigned)_meta_part, (int)ok);
|
||||
return ok;
|
||||
}
|
||||
|
||||
bool OtaStoreFlashEsp32::begin(uint32_t total_size) {
|
||||
if (!_part || _total == 0 || total_size != _total) return false; // plan_layout must have run + agreed
|
||||
free(_meta);
|
||||
_meta = (uint8_t*)malloc(_meta_flush); // header+manifest+leaves(+full trailer)
|
||||
if (!_meta) { _total = 0; return false; }
|
||||
memset(_meta, 0xFF, _meta_flush);
|
||||
memset(_trailer, 0xFF, sizeof(_trailer));
|
||||
_pay_open = false; _pay_sec = 0; _pay_max_sec = 0; _flushed = false;
|
||||
_io_ok = true;
|
||||
return true;
|
||||
}
|
||||
|
||||
void OtaStoreFlashEsp32::clear() {
|
||||
free(_meta); _meta = nullptr;
|
||||
_total = 0; _pay_open = false; _flushed = false; // _part kept (re-acquire is fine)
|
||||
}
|
||||
|
||||
uint8_t* OtaStoreFlashEsp32::meta_slot(uint32_t L) {
|
||||
if (in_trailer(L)) return _full ? (_meta + _meta_bytes + (L - (_total - 5)))
|
||||
: (_trailer + (L - (_total - 5)));
|
||||
if (L < _meta_span) return _meta + L;
|
||||
return nullptr; // payload -> sliding sector / flash
|
||||
}
|
||||
const uint8_t* OtaStoreFlashEsp32::meta_slot_c(uint32_t L) const {
|
||||
if (in_trailer(L)) return _full ? (_meta + _meta_bytes + (L - (_total - 5)))
|
||||
: (_trailer + (L - (_total - 5)));
|
||||
if (L < _meta_span) return _meta + L;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
// Bytes from `pos` that stay in one region, and (for payload) one flash sector.
|
||||
uint32_t OtaStoreFlashEsp32::run(uint32_t pos, uint32_t remain) const {
|
||||
if (pos >= _total - 5) return remain; // trailer (<=5, one buffer)
|
||||
if (pos < _meta_span) { uint32_t c = _meta_span - pos; return remain < c ? remain : c; }
|
||||
uint32_t poff = pay_part(pos);
|
||||
uint32_t to_sec = SEC - (poff % SEC);
|
||||
uint32_t to_end = (_total - 5) - pos; // don't cross into the trailer
|
||||
uint32_t c = remain;
|
||||
if (to_sec < c) c = to_sec;
|
||||
if (to_end < c) c = to_end;
|
||||
return c;
|
||||
}
|
||||
|
||||
void OtaStoreFlashEsp32::flush_sector(uint32_t slot_off, const uint8_t* buf, uint32_t n) {
|
||||
if (!_io_ok) return;
|
||||
if (esp_partition_erase_range(_part, slot_off, n) != ESP_OK) { _io_ok = false; return; }
|
||||
if (esp_partition_write(_part, slot_off, buf, n) != ESP_OK) { _io_ok = false; return; }
|
||||
OTA_DBG("OTA esp32: flushed %u B @ slot+%u\n", (unsigned)n, (unsigned)slot_off);
|
||||
}
|
||||
|
||||
void OtaStoreFlashEsp32::flush_pay() {
|
||||
if (_pay_open) { flush_sector((uint32_t)_pay_sec * SEC, _pay, SEC); _pay_open = false; }
|
||||
}
|
||||
|
||||
void OtaStoreFlashEsp32::open_pay(uint32_t sec) {
|
||||
if (_pay_open) flush_pay();
|
||||
if (sec < _pay_max_sec) {
|
||||
// revisiting an already-flushed sector (out-of-order block) -> read it back so the gaps we don't
|
||||
// touch are preserved (they were programmed as 0xFF or earlier block data); we erase+reprogram on flush.
|
||||
if (esp_partition_read(_part, (size_t)sec * SEC, _pay, SEC) != ESP_OK) _io_ok = false;
|
||||
} else {
|
||||
memset(_pay, 0xFF, SEC); // fresh sector
|
||||
_pay_max_sec = sec;
|
||||
}
|
||||
_pay_sec = sec; _pay_open = true;
|
||||
}
|
||||
|
||||
bool OtaStoreFlashEsp32::write(uint32_t offset, const uint8_t* d, uint32_t len) {
|
||||
if ((uint64_t)offset + len > _total || !_io_ok) return false;
|
||||
for (uint32_t pos = offset, end = offset + len; pos < end; ) {
|
||||
uint32_t n = run(pos, end - pos);
|
||||
if (uint8_t* dst = meta_slot(pos)) { // meta / leaves / trailer -> pinned RAM
|
||||
memcpy(dst, d, n);
|
||||
} else { // payload -> sliding sector
|
||||
uint32_t poff = pay_part(pos);
|
||||
uint32_t sec = poff / SEC;
|
||||
if (!_pay_open || sec != _pay_sec) open_pay(sec);
|
||||
memcpy(_pay + (poff % SEC), d, n);
|
||||
}
|
||||
pos += n; d += n;
|
||||
if (!_io_ok) return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OtaStoreFlashEsp32::read(uint32_t offset, uint8_t* buf, uint32_t len) const {
|
||||
if ((uint64_t)offset + len > _total) return false;
|
||||
for (uint32_t pos = offset, end = offset + len; pos < end; ) {
|
||||
uint32_t n = run(pos, end - pos);
|
||||
if (const uint8_t* src = meta_slot_c(pos)) {
|
||||
memcpy(buf, src, n);
|
||||
} else {
|
||||
uint32_t poff = pay_part(pos);
|
||||
if (_pay_open && poff / SEC == _pay_sec) memcpy(buf, _pay + (poff % SEC), n); // still in RAM
|
||||
else if (esp_partition_read(_part, poff, buf, n) != ESP_OK) return false; // flushed -> flash
|
||||
}
|
||||
pos += n; buf += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void OtaStoreFlashEsp32::finalize() {
|
||||
if (_flushed || _total == 0) return;
|
||||
if (!_full) {
|
||||
// delta: drop the 5-byte trailer into the sliding payload sector(s) so it flushes with them (the
|
||||
// trailer sits right after the payload; this also covers the rare case it spills into a fresh sector).
|
||||
uint32_t tpoff = _write_start + (_total - 5);
|
||||
for (uint32_t off = 0; off < 5; ) {
|
||||
uint32_t sec = (tpoff + off) / SEC;
|
||||
if (!_pay_open || sec != _pay_sec) open_pay(sec);
|
||||
uint32_t in = SEC - ((tpoff + off) % SEC); if (in > 5 - off) in = 5 - off;
|
||||
memcpy(_pay + ((tpoff + off) % SEC), _trailer + off, in);
|
||||
off += in;
|
||||
}
|
||||
}
|
||||
flush_pay(); // last payload sector(s) (+ delta trailer)
|
||||
flush_sector(_meta_part, _meta, _meta_flush); // meta (+ trailer for full)
|
||||
_flushed = true;
|
||||
OTA_DBG("OTA esp32: finalize %s io_ok=%d\n", _full ? "FULL" : "DELTA", (int)_io_ok);
|
||||
}
|
||||
|
||||
// Persist mid-transfer progress so a reboot can resume. Flush the open payload sector (KEEP it buffered so
|
||||
// continued in-order writes aren't lost), then the meta region (leaves). Payload-before-leaves keeps it
|
||||
// consistent: every block whose leaf is now in flash also has its payload in flash. Infrequent.
|
||||
void OtaStoreFlashEsp32::checkpoint() {
|
||||
if (_total == 0 || _flushed || !_io_ok) return;
|
||||
if (_pay_open) flush_sector((uint32_t)_pay_sec * SEC, _pay, SEC); // flush but leave _pay/_pay_open intact
|
||||
flush_sector(_meta_part, _meta, _meta_flush); // header + manifest + leaves (+full trailer)
|
||||
}
|
||||
|
||||
// Re-attach to a container already staged in the slot (after a reboot), WITHOUT erasing. The header
|
||||
// (MOTA_MAGIC + total) sits at a sector boundary (meta_part for full, write_start for delta — both
|
||||
// sector-aligned), so scan sector starts from the bottom up. A candidate is accepted only if: magic +
|
||||
// plausible total, the manifest parses, the container geometry is self-consistent with the total, AND the
|
||||
// recomputed placement lands the meta exactly where we found the magic. Any miss -> false (fetch fresh),
|
||||
// so a stray/stale match can only cost a restart, never a corrupt adopt.
|
||||
bool OtaStoreFlashEsp32::reopen() {
|
||||
if (!acquire() || _psize < SEC) return false;
|
||||
uint8_t hb[8];
|
||||
// the meta/container is staged at the BOTTOM of the slot, so scan upward from there; cap the scan (a
|
||||
// miss just means "fetch fresh"). 128 sectors (512 KB) covers any full image's meta + typical deltas.
|
||||
uint32_t scanned = 0;
|
||||
for (uint32_t o = align_down(_psize - SEC, SEC); ; o -= SEC) {
|
||||
if (esp_partition_read(_part, o, hb, 8) == ESP_OK && memcmp(hb, MOTA_MAGIC, 4) == 0) {
|
||||
uint32_t total = rd_u32le(hb + 4);
|
||||
if (total >= 13 && total <= _psize) {
|
||||
uint8_t mbuf[256]; uint32_t mread = total - 8; if (mread > sizeof(mbuf)) mread = sizeof(mbuf);
|
||||
MotaManifest m;
|
||||
if (esp_partition_read(_part, o + 8, mbuf, mread) == ESP_OK && mota_parse_manifest(mbuf, mread, m)) {
|
||||
uint32_t mfl = (uint32_t)(m.approval - m.manifest_start) + 4;
|
||||
uint32_t payload_off = 8 + mfl + m.block_count * 4;
|
||||
if ((uint64_t)payload_off + m.payload_size + 5 == total) {
|
||||
_full = m.is_full(); _image_size = m.image_size; _meta_bytes = payload_off; _pay_size = m.payload_size;
|
||||
if (layout() && _meta_part == o) { // geometry agrees AND magic is where we'd place meta
|
||||
free(_meta); _meta = (uint8_t*)malloc(_meta_flush);
|
||||
if (!_meta) { _total = 0; return false; }
|
||||
if (esp_partition_read(_part, _meta_part, _meta, _meta_flush) != ESP_OK) {
|
||||
free(_meta); _meta = nullptr; _total = 0; return false; }
|
||||
memset(_trailer, 0xFF, sizeof(_trailer)); // delta trailer (re-written at finalize); full reads it from _meta
|
||||
_pay_open = false; _pay_sec = 0; _flushed = false; _io_ok = true;
|
||||
_pay_max_sec = (_pay_part0 + _pay_size + SEC) / SEC; // treat all payload sectors as seen -> RMW preserves committed blocks
|
||||
OTA_DBG("OTA esp32: reopen %s total=%u meta_part=%u\n", _full ? "FULL" : "DELTA", (unsigned)total, (unsigned)o);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
if (o == 0 || ++scanned >= 128) break;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,116 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(ESP32_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
|
||||
#include "OtaStore.h"
|
||||
#include "esp_partition.h"
|
||||
|
||||
// Persistent flash-backed OtaStore for ESP32 (A/B). Stages the received `.mota` in the INACTIVE OTA
|
||||
// slot, so a delta/full of any size is bounded to O(one sector) of RAM, never O(mota) -- lifting the old
|
||||
// RAM store's ~16 KB ceiling (a full 1 MB+ image now fetches over the air). Placement is chosen from the
|
||||
// parsed manifest (plan_layout), keyed only on full-vs-delta:
|
||||
//
|
||||
// - DELTA (codec sequential/in-place): the whole container is staged bottom-aligned in the slot. At
|
||||
// apply the decoder reads the patch from it -- sequential: base from the running slot -> output to
|
||||
// the inactive slot from offset 0; in-place: copy running->slot then patch in place. The decoded
|
||||
// image fills the slot from offset 0, so plan_layout refuses unless `image_size + container` fits
|
||||
// (the output must never reach the bottom-staged container; the fit makes them disjoint).
|
||||
//
|
||||
// - FULL (codec full): the payload IS the final image (no decode), so it streams straight to slot
|
||||
// offset 0 while the small header+manifest+merkle-leaves and the trailer persist at the bottom of the
|
||||
// slot (so the whole container survives a reboot -- for fetch-resume and for re-serving to other
|
||||
// nodes). One default for every A/B full payload; plan_layout refuses unless `image_size + meta`
|
||||
// fits, and if that doesn't fit nothing would.
|
||||
//
|
||||
// RX-safety: an ESP32 flash erase+write disables the XIP instruction cache and stalls code running from
|
||||
// flash (the dispatcher loop), exactly like the nRF52 page erase that starved the LoRa RX. So writes are
|
||||
// COALESCED to the 4 KB sector and each sector is programmed once. The meta region (header+manifest+
|
||||
// leaves -- written all transfer long as blocks/leaves arrive, often out of order) is PINNED in RAM and
|
||||
// flushed at finalize() with the radio idle; the bulk payload streams through ONE sliding sector buffer,
|
||||
// flushing the sector it leaves behind (~1 flush per 4 KB, off the per-packet path). OTA is also the
|
||||
// lowest-priority TX, so a brief stall yields to real traffic. A small delta whose container fits the
|
||||
// pinned meta region does ZERO flash I/O until COMPLETE.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
#ifndef OTA_ESP32_META_CAP
|
||||
#define OTA_ESP32_META_CAP 65536 // max heap for header+manifest+merkle leaves (4 B/block) -> ~16k blocks
|
||||
#endif // (a 1.27 MB full image at 128 B LoRa blocks ~= 40 KB of leaves)
|
||||
|
||||
class OtaStoreFlashEsp32 : public OtaStore {
|
||||
static const uint32_t SEC = 4096; // ESP32 NOR flash erase unit
|
||||
|
||||
const esp_partition_t* _part = nullptr; // inactive OTA slot (acquired in plan_layout/begin)
|
||||
uint32_t _psize = 0; // slot size
|
||||
|
||||
// container geometry (from plan_layout / handleManifest)
|
||||
uint32_t _total = 0; // container size (0 = none staged)
|
||||
uint32_t _meta_bytes = 0; // header+manifest+leaves (== payload offset in the container)
|
||||
uint32_t _pay_size = 0; // payload bytes
|
||||
uint32_t _image_size = 0; // reconstructed image (delta) / == _pay_size (full)
|
||||
bool _full = false;
|
||||
|
||||
// logical->partition placement (see header doc). For delta everything is contiguous at _write_start;
|
||||
// for full the payload lands at slot 0 and meta+trailer at the bottom.
|
||||
uint32_t _write_start = 0; // delta: container offset 0 in the slot (sector-aligned)
|
||||
uint32_t _meta_span = 0; // container bytes held in the RAM meta buffer (whole sectors)
|
||||
uint32_t _meta_part = 0; // slot offset the meta buffer flushes to
|
||||
uint32_t _pay_log0 = 0; // first container offset that streams to the payload region
|
||||
uint32_t _pay_part0 = 0; // slot offset of that first payload byte
|
||||
uint32_t _trailer_part = 0; // slot offset of the 5-byte trailer
|
||||
|
||||
// RX-safe staging buffers
|
||||
uint8_t* _meta = nullptr; // heap, sized per fetch: header+manifest+leaves(+full trailer)
|
||||
uint8_t _pay[SEC]; // one sliding payload sector (slot-sector aligned)
|
||||
uint32_t _pay_sec = 0; // slot sector index currently in _pay (0 = none open)
|
||||
uint8_t _trailer[5];
|
||||
uint32_t _meta_flush = 0; // whole-sector byte count to program for the meta buffer
|
||||
uint32_t _pay_max_sec = 0; // highest payload slot-sector opened (out-of-order detection)
|
||||
bool _pay_open = false; // a sliding sector is currently buffered in _pay
|
||||
bool _flushed = false;
|
||||
bool _io_ok = true; // cleared if any flash erase/write/read fails
|
||||
|
||||
bool acquire(); // resolve the inactive slot (idempotent)
|
||||
bool layout(); // compute placement from _full/_image_size/_meta_bytes/_pay_size
|
||||
uint32_t pay_part(uint32_t L) const { return _pay_part0 + (L - _pay_log0); } // payload slot offset
|
||||
bool in_trailer(uint32_t L) const { return L >= _total - 5; }
|
||||
uint32_t run(uint32_t pos, uint32_t remain) const; // bytes from `pos` that stay in one region+sector
|
||||
uint8_t* meta_slot(uint32_t L); // RAM home of a meta/trailer byte (nullptr if it's payload)
|
||||
const uint8_t* meta_slot_c(uint32_t L) const;
|
||||
void open_pay(uint32_t sec); // make `sec` the buffered sliding sector (RMW if revisited)
|
||||
void flush_pay(); // erase+write the open sliding sector
|
||||
void flush_sector(uint32_t slot_off, const uint8_t* buf, uint32_t n); // erase+program sector(s)
|
||||
|
||||
public:
|
||||
~OtaStoreFlashEsp32() override;
|
||||
bool plan_layout(bool is_full, uint32_t image_size, uint32_t payload_off, uint32_t payload_size) override;
|
||||
bool begin(uint32_t total_size) override;
|
||||
bool write(uint32_t offset, const uint8_t* data, uint32_t len) override;
|
||||
bool read(uint32_t offset, uint8_t* buf, uint32_t len) const override;
|
||||
uint32_t capacity() const override { return _psize; } // loose bound; plan_layout does the real check
|
||||
uint32_t staged_size() const override { return _total; }
|
||||
void clear() override;
|
||||
bool set_meta_size(uint32_t meta_bytes) override { return meta_bytes < OTA_ESP32_META_CAP; }
|
||||
void finalize() override;
|
||||
void checkpoint() override; // persist meta(leaves) + open payload sector so a reboot can resume
|
||||
bool reopen() override; // re-attach to a container already staged in the slot (scan + rebuild geometry)
|
||||
|
||||
// No contiguous RAM/mmap view: the staged container lives in the slot (split for FULL). The ESP32
|
||||
// apply path reads what it needs via read()/esp_partition_read instead of a data() pointer, so this
|
||||
// returns nullptr (kept for interface parity with the nRF52 store, whose flash is memory-mapped).
|
||||
const uint8_t* data() const { return nullptr; }
|
||||
|
||||
// Apply-path accessors: where the staged container physically lives in the inactive slot.
|
||||
const esp_partition_t* partition() const { return _part; }
|
||||
uint32_t write_start() const { return _write_start; } // delta: container offset 0 in the slot
|
||||
bool is_full() const { return _full; }
|
||||
uint32_t image_size() const { return _image_size; }
|
||||
uint32_t meta_bytes() const { return _meta_bytes; }
|
||||
uint32_t payload_slot_off(uint32_t k) const { return _pay_part0 + k; } // slot off of payload byte k
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,159 @@
|
||||
#include "OtaStoreFlashNrf52.h"
|
||||
|
||||
#if defined(NRF52_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
|
||||
#include "OtaSelf.h"
|
||||
#include "OtaDebug.h"
|
||||
#include "OtaByteIO.h" // align_down / rd_u32le (flash-page geometry + header read)
|
||||
#include <string.h>
|
||||
#include "flash/flash_nrf5x.h" // Adafruit core internal-flash driver (SoftDevice-safe; LittleFS path)
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// Write one whole 4 KB page from `buf` to flash (erase + program, ~85 ms). `buf` is PG bytes, 0xFF-padded
|
||||
// past the container, so the program is clean. The last container page ends exactly at FS_START (both
|
||||
// FS_START and _write_start are page-aligned and the container ends <= FS_START), so a full-page write
|
||||
// never reaches into ExtraFS.
|
||||
void OtaStoreFlashNrf52::flush_page(uint32_t page_idx, const uint8_t* buf) {
|
||||
uint32_t addr = _write_start + page_idx * PG;
|
||||
if (addr + PG > MOTA_NRF52_FS_START) return; // defensive: never cross the staging ceiling
|
||||
OTA_DBG("OTA flash: write page %u @ %08x\n", (unsigned)page_idx, (unsigned)addr);
|
||||
flash_nrf5x_write(addr, buf, PG);
|
||||
flash_nrf5x_flush();
|
||||
}
|
||||
|
||||
void OtaStoreFlashNrf52::flush_pay() {
|
||||
if (_pay_idx != 0) flush_page(_pay_idx, _pay_page); // _pay_idx 0 == no payload page open
|
||||
}
|
||||
|
||||
uint32_t OtaStoreFlashNrf52::run(uint32_t pos, uint32_t remain) const {
|
||||
uint32_t trailer = _total - 5; // container is always >= 13 bytes (begin checks)
|
||||
if (pos >= trailer) return remain; // tail: caller bounds remain to <= 5 already
|
||||
uint32_t end = pos + remain;
|
||||
uint32_t page_end = (pos / PG + 1) * PG;
|
||||
if (end > page_end) end = page_end; // a run stays within one flash page,
|
||||
if (end > trailer) end = trailer; // and never crosses into the trailer tail
|
||||
return end - pos;
|
||||
}
|
||||
|
||||
const uint8_t* OtaStoreFlashNrf52::read_slot(uint32_t pos) const {
|
||||
if (pos >= _total - 5) return _trailer + (pos - (_total - 5)); // trailer tail (RAM until finalize)
|
||||
uint32_t page = pos / PG;
|
||||
if (page == 0) return _meta_page + pos; // pinned page 0 (incl. leaves)
|
||||
if (page == _pay_idx) return _pay_page + (pos - page * PG); // current sliding payload page
|
||||
return (const uint8_t*)(uintptr_t)(_write_start + pos); // already flushed -> memory-mapped
|
||||
}
|
||||
|
||||
uint8_t* OtaStoreFlashNrf52::write_slot(uint32_t pos) {
|
||||
if (pos >= _total - 5) return _trailer + (pos - (_total - 5));
|
||||
uint32_t page = pos / PG;
|
||||
if (page == 0) return _meta_page + pos;
|
||||
if (page > _pay_idx) { flush_pay(); _pay_idx = page; memset(_pay_page, 0xFF, PG); } // advance, fresh page
|
||||
if (page == _pay_idx) return _pay_page + (pos - page * PG);
|
||||
return nullptr; // page < _pay_idx: already flushed
|
||||
}
|
||||
|
||||
bool OtaStoreFlashNrf52::begin(uint32_t total_size) {
|
||||
clear();
|
||||
|
||||
// never collide with the running application image (its extent comes from its EndF trailer)
|
||||
uint32_t app_end = MOTA_NRF52_APP_BASE;
|
||||
SelfFwInfo fi;
|
||||
if (ota_self_firmware(fi) && fi.valid) app_end = MOTA_NRF52_APP_BASE + fi.image_len;
|
||||
|
||||
// bottom-align below FS_START + reject if it won't fit above the running image (the FS/prefs-safe
|
||||
// bounds check; pure + unit-tested in test/test_ota/test_ota_flashplan.cpp)
|
||||
uint32_t start;
|
||||
if (!mota_nrf52_stage_plan(total_size, app_end, start)) return false;
|
||||
|
||||
_write_start = start;
|
||||
_total = total_size;
|
||||
memset(_meta_page, 0xFF, PG); // assemble page 0 in RAM; 0xFF = erased sentinel (unfilled leaf slots)
|
||||
memset(_trailer, 0xFF, sizeof(_trailer));
|
||||
_pay_idx = 0;
|
||||
_flushed = false;
|
||||
OTA_DBG("OTA flash: begin total=%u start=%08x app_end=%08x\n",
|
||||
(unsigned)total_size, (unsigned)start, (unsigned)app_end);
|
||||
return true; // no pre-erase: each page is erased by its own (single) flush
|
||||
}
|
||||
|
||||
bool OtaStoreFlashNrf52::write(uint32_t offset, const uint8_t* d, uint32_t len) {
|
||||
if ((uint64_t)offset + len > _total) return false;
|
||||
for (uint32_t pos = offset, end = offset + len; pos < end; ) {
|
||||
uint32_t n = run(pos, end - pos);
|
||||
if (uint8_t* dst = write_slot(pos)) {
|
||||
memcpy(dst, d, n);
|
||||
} else {
|
||||
// out-of-order write to an already-flushed page: read-modify-write straight to flash. Safe -- the
|
||||
// driver erases the page before programming, so re-touching it never breaks writes-per-word.
|
||||
OTA_DBG("OTA flash: RMW page %u (out-of-order) @ off %u\n", (unsigned)(pos / PG), (unsigned)pos);
|
||||
if (flash_nrf5x_write(_write_start + pos, d, n) < 0) return false;
|
||||
flash_nrf5x_flush();
|
||||
}
|
||||
pos += n; d += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool OtaStoreFlashNrf52::read(uint32_t offset, uint8_t* buf, uint32_t len) const {
|
||||
if ((uint64_t)offset + len > _total) return false;
|
||||
for (uint32_t pos = offset, end = offset + len; pos < end; ) {
|
||||
uint32_t n = run(pos, end - pos);
|
||||
memcpy(buf, read_slot(pos), n);
|
||||
pos += n; buf += n;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
void OtaStoreFlashNrf52::finalize() {
|
||||
if (_flushed || _total == 0) return;
|
||||
OTA_DBG("OTA flash: finalize total=%u\n", (unsigned)_total);
|
||||
flush_pay(); // the last (highest) payload page, if one is open
|
||||
flush_page(0, _meta_page); // page 0: header + manifest + leaves + first payload bytes
|
||||
flash_nrf5x_write(_write_start + _total - 5, _trailer, 5); // trailer tail (radio idle at COMPLETE)
|
||||
flash_nrf5x_flush();
|
||||
_flushed = true;
|
||||
}
|
||||
|
||||
// Persist mid-transfer progress so a reboot can resume. Order matters for consistency: flush the open
|
||||
// payload page FIRST, then page 0 (the leaf-progress markers) -- so every block whose leaf is now in flash
|
||||
// also has its payload in flash. Infrequent (every OTA_CHECKPOINT_BLOCKS blocks), so the 2 extra page
|
||||
// erases don't matter; at LoRa block rates it's roughly once per many minutes.
|
||||
void OtaStoreFlashNrf52::checkpoint() {
|
||||
if (_total == 0 || _flushed) return;
|
||||
flush_pay(); // keep _pay_idx open (it may still receive writes); just re-flush its bytes
|
||||
flush_page(0, _meta_page); // header + manifest + leaves accumulated so far
|
||||
}
|
||||
|
||||
// Re-attach to a container already staged in flash (after a reboot), without erasing. The container is
|
||||
// bottom-aligned (begin: start = (FS_START - total) & ~(PG-1)) and flash is memory-mapped, so scan page
|
||||
// starts from just below FS_START down to the app end for MOTA_MAGIC with a self-consistent total; adopt
|
||||
// the first match (highest address = most recent for the common single-container case). The manager then
|
||||
// parses the loaded manifest and validates geometry/root, so a stale leftover is rejected there.
|
||||
bool OtaStoreFlashNrf52::reopen() {
|
||||
uint32_t app_end = MOTA_NRF52_APP_BASE;
|
||||
SelfFwInfo fi;
|
||||
if (ota_self_firmware(fi) && fi.valid) app_end = MOTA_NRF52_APP_BASE + fi.image_len;
|
||||
for (uint32_t start = align_down(MOTA_NRF52_FS_START - PG, PG); start >= app_end; start -= PG) {
|
||||
const uint8_t* p = (const uint8_t*)(uintptr_t)start;
|
||||
if (memcmp(p, MOTA_MAGIC, 4) != 0) continue;
|
||||
uint32_t total = rd_u32le(p + 4);
|
||||
uint32_t want; // must be valid + placed exactly where begin() would have staged it (same bounds fn)
|
||||
if (!mota_nrf52_stage_plan(total, app_end, want) || want != start) continue;
|
||||
_write_start = start;
|
||||
_total = total;
|
||||
memcpy(_meta_page, p, PG); // load page 0 (header+manifest+leaves) into RAM to continue
|
||||
memcpy(_trailer, p + (total - 5), 5); // recover the trailer tail (flushed at last finalize, if any)
|
||||
_pay_idx = 0;
|
||||
_flushed = false;
|
||||
OTA_DBG("OTA flash: reopen total=%u start=%08x\n", (unsigned)total, (unsigned)start);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,77 @@
|
||||
#pragma once
|
||||
|
||||
#if defined(NRF52_PLATFORM) && defined(OTA_FLASH_STORE)
|
||||
|
||||
#include "OtaStore.h"
|
||||
#include "OtaFlashLayout_nrf52.h"
|
||||
|
||||
// Persistent flash-backed OtaStore for nRF52 (RAK4631). Stages the received `.mota` in the free flash
|
||||
// below the primary LittleFS (FS_START), bottom-aligned so its trailer ends at FS_START and the
|
||||
// bootloader can scan for it. Survives reboot — the whole point — so the bootloader can apply the
|
||||
// staged delta on the next boot.
|
||||
//
|
||||
// RAM is bounded to O(one flash page), NEVER O(mota): a 100 KB+ delta must not live in RAM.
|
||||
// - On nRF52 the flash *erase* unit is one 4 KB page and the only SoftDevice-safe writer
|
||||
// (Adafruit `flash_nrf5x`) erases the whole page on every flush (~85 ms, CPU stalled → LoRa RX
|
||||
// starved). Writing to flash per received packet therefore drops in-flight DATA and the transfer
|
||||
// stalls. The fix: coalesce to the *page*, the hardware-natural unit, and write each page once.
|
||||
// - `_meta_page` pins flash page 0 (header + manifest + the merkle-leaf progress markers, which are
|
||||
// written one-per-block all transfer long). Keeping it in RAM means streaming the payload never
|
||||
// re-erases the leaves' page. Flushed once at finalize(). Requires metadata <= one page
|
||||
// (set_meta_size enforces it; true for <= ~979 blocks, i.e. any realistic MeshCore image).
|
||||
// - `_pay_page` is a single sliding buffer for one payload page (index >= 1). It advances
|
||||
// monotonically with the (mostly in-order) block stream and flushes the page it leaves behind.
|
||||
// Rare out-of-order writes to an already-flushed page go straight to flash as a safe read-modify-
|
||||
// write (flash_nrf5x erases before programming, so re-touching a page never violates the
|
||||
// writes-per-word limit — it just costs one extra erase).
|
||||
// - The 5-byte trailer is buffered and written at finalize().
|
||||
// Net: flash is touched ~once per 4 KB page (≈ 1 per 4 blocks at 1 KB), off the per-packet path; page
|
||||
// 0 and the last page are written at finalize() with the radio idle. For a small delta (whole .mota
|
||||
// in page 0) there is ZERO flash I/O during the transfer.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
class OtaStoreFlashNrf52 : public OtaStore {
|
||||
static const uint32_t PG = MOTA_NRF52_FLASH_PAGE; // 4096
|
||||
|
||||
uint32_t _write_start = 0; // flash address of container offset 0 (page-aligned)
|
||||
uint32_t _total = 0; // staged container size (0 = none)
|
||||
bool _flushed = false; // finalize() committed everything to flash
|
||||
|
||||
uint8_t _meta_page[PG]; // pinned flash page 0 (header + manifest + leaves + 1st payload)
|
||||
uint8_t _pay_page[PG]; // sliding buffer for one payload page (index _pay_idx)
|
||||
uint32_t _pay_idx = 0; // page index currently held in _pay_page (0 = none open; pages >= 1)
|
||||
uint8_t _trailer[5]; // last 5 container bytes (kept in RAM, written at finalize)
|
||||
|
||||
// Bytes from `pos` that stay in one store region (a single flash page, or the trailer tail).
|
||||
uint32_t run(uint32_t pos, uint32_t remain) const;
|
||||
// RAM home of byte `pos`: read_slot always resolves (flushed pages → memory-mapped flash); write_slot
|
||||
// opens/advances the sliding payload page and returns nullptr if `pos` is in an already-flushed page.
|
||||
const uint8_t* read_slot(uint32_t pos) const;
|
||||
uint8_t* write_slot(uint32_t pos);
|
||||
void flush_pay(); // commit _pay_page to flash (erase + program, one page)
|
||||
void flush_page(uint32_t page_idx, const uint8_t* buf); // write a full page to flash
|
||||
|
||||
public:
|
||||
bool begin(uint32_t total_size) override;
|
||||
bool write(uint32_t offset, const uint8_t* data, uint32_t len) override;
|
||||
bool read(uint32_t offset, uint8_t* buf, uint32_t len) const override;
|
||||
uint32_t capacity() const override { return MOTA_NRF52_FS_START - MOTA_NRF52_APP_BASE; }
|
||||
uint32_t staged_size() const override { return _total; }
|
||||
void clear() override { _total = 0; _pay_idx = 0; _flushed = false; }
|
||||
bool set_meta_size(uint32_t meta_bytes) override { return meta_bytes <= PG; } // leaves must fit page 0
|
||||
void finalize() override;
|
||||
void checkpoint() override; // persist page 0 (leaves) + the open payload page so a reboot can resume
|
||||
bool reopen() override; // re-attach to a container already staged in flash (scan for it)
|
||||
|
||||
// Contiguous view (flash is memory-mapped). VALID ONLY AFTER finalize() — before that, page 0 and the
|
||||
// tail are still in RAM. OtaManager/OtaCli/verify use this only once the transfer is COMPLETE.
|
||||
const uint8_t* data() const { return (const uint8_t*)(uintptr_t)_write_start; }
|
||||
uint32_t write_start() const { return _write_start; }
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
|
||||
#endif
|
||||
@@ -0,0 +1,438 @@
|
||||
#pragma once
|
||||
#include <stdint.h>
|
||||
|
||||
// AUTO-GENERATED by tools/mota/gen_targets.py — do not edit by hand.
|
||||
// 418 OTA-capable PlatformIO envs. Maps target_id (= sha2-256:4 of the env name, LE uint32)
|
||||
// to the human-readable env name, so a node/tool can name a target seen over the air WITHOUT
|
||||
// transmitting the string in the .mota / LoRa protocol. Regenerate when the OTA env set changes.
|
||||
|
||||
namespace mesh { namespace ota {
|
||||
|
||||
// target_id -> env name, or nullptr if unknown. Linear scan (table is small; lookups are rare).
|
||||
inline const char* ota_target_env_name(uint32_t target_id) {
|
||||
static const struct { uint32_t id; const char* env; } T[] = {
|
||||
{ 0x149bcb23, "Ebyte_EoRa-S3_companion_radio_ble" },
|
||||
{ 0x30d4e442, "Ebyte_EoRa-S3_companion_radio_usb" },
|
||||
{ 0x263a8d80, "Ebyte_EoRa-S3_kiss_modem" },
|
||||
{ 0x9070ae2c, "Ebyte_EoRa-S3_Repeater" },
|
||||
{ 0xf190d834, "Ebyte_EoRa-S3_room_server" },
|
||||
{ 0x32890982, "Ebyte_EoRa-S3_terminal_chat" },
|
||||
{ 0xacb599d5, "GAT562_30S_Mesh_Kit_companion_radio_ble" },
|
||||
{ 0x82d3b273, "GAT562_30S_Mesh_Kit_companion_radio_usb" },
|
||||
{ 0xe96a6af8, "GAT562_30S_Mesh_Kit_kiss_modem" },
|
||||
{ 0x70d8478d, "GAT562_30S_Mesh_Kit_repeater" },
|
||||
{ 0xf9986af5, "GAT562_30S_Mesh_Kit_room_server" },
|
||||
{ 0x98519a1d, "GAT562_Mesh_EVB_Pro_kiss_modem" },
|
||||
{ 0x06b71719, "GAT562_Mesh_EVB_Pro_repeater" },
|
||||
{ 0x4c0461c8, "GAT562_Mesh_EVB_Pro_room_server" },
|
||||
{ 0x4fa88992, "GAT562_Mesh_Tracker_Pro_companion_radio_ble" },
|
||||
{ 0xcd6604d0, "GAT562_Mesh_Tracker_Pro_companion_radio_usb" },
|
||||
{ 0xc54ea258, "GAT562_Mesh_Tracker_Pro_kiss_modem" },
|
||||
{ 0x0b3985a8, "GAT562_Mesh_Tracker_Pro_repeater" },
|
||||
{ 0x03d9704a, "GAT562_Mesh_Tracker_Pro_room_server" },
|
||||
{ 0x8456f753, "GAT562_Mesh_Watch13_companion_radio_ble" },
|
||||
{ 0xc8104197, "GAT562_Mesh_Watch13_kiss_modem" },
|
||||
{ 0xf5eb61ec, "Generic_E22_kiss_modem" },
|
||||
{ 0x70d2d590, "Generic_E22_sx1262_repeater" },
|
||||
{ 0xe1a7ffdf, "Generic_E22_sx1262_repeater_bridge_espnow" },
|
||||
{ 0xd5e04824, "Generic_E22_sx1268_repeater" },
|
||||
{ 0x61a7b2dd, "Generic_E22_sx1268_repeater_bridge_espnow" },
|
||||
{ 0xa416bb20, "Generic_ESPNOW_comp_radio_usb" },
|
||||
{ 0x875f3744, "Generic_ESPNOW_repeatr" },
|
||||
{ 0xdaf349be, "Generic_ESPNOW_room_svr" },
|
||||
{ 0x93b93199, "Generic_ESPNOW_terminal_chat" },
|
||||
{ 0x5293da13, "Heltec_ct62_companion_radio_ble" },
|
||||
{ 0xf2eec98c, "Heltec_ct62_companion_radio_usb" },
|
||||
{ 0x48a986f1, "Heltec_ct62_kiss_modem" },
|
||||
{ 0xd2cf978c, "Heltec_ct62_repeater" },
|
||||
{ 0x53626334, "Heltec_ct62_repeater_bridge_espnow" },
|
||||
{ 0xefe4f19f, "Heltec_ct62_sensor" },
|
||||
{ 0xfcaf3730, "Heltec_E213_companion_radio_ble" },
|
||||
{ 0xd90deef7, "Heltec_E213_companion_radio_usb" },
|
||||
{ 0x2d2a4089, "Heltec_E213_kiss_modem" },
|
||||
{ 0x89ea5c4e, "Heltec_E213_repeater" },
|
||||
{ 0xc0eb712a, "Heltec_E213_repeater_bridge_espnow" },
|
||||
{ 0x67293f43, "Heltec_E213_room_server" },
|
||||
{ 0x3f364910, "Heltec_E290_companion_ble" },
|
||||
{ 0xac4b4eb5, "Heltec_E290_companion_usb" },
|
||||
{ 0xe077fb8d, "Heltec_E290_kiss_modem" },
|
||||
{ 0x2bbe7fd8, "Heltec_E290_repeater" },
|
||||
{ 0x9e40157c, "Heltec_E290_repeater_bridge_espnow" },
|
||||
{ 0xb12e6e01, "Heltec_E290_room_server" },
|
||||
{ 0x32bcdd14, "Heltec_t114_companion_radio_ble" },
|
||||
{ 0xfe937f14, "Heltec_t114_companion_radio_usb" },
|
||||
{ 0x5b9b1933, "Heltec_t114_kiss_modem" },
|
||||
{ 0x191f3545, "Heltec_t114_repeater" },
|
||||
{ 0x1b4399de, "Heltec_t114_repeater_bridge_rs232" },
|
||||
{ 0xb1153422, "Heltec_t114_room_server" },
|
||||
{ 0x075ca3f9, "Heltec_t114_without_display_companion_radio_ble" },
|
||||
{ 0x2f9f8e7d, "Heltec_t114_without_display_companion_radio_usb" },
|
||||
{ 0xc9dc5d8c, "Heltec_t114_without_display_repeater" },
|
||||
{ 0x34b0e5f3, "Heltec_t114_without_display_repeater_bridge_rs232" },
|
||||
{ 0xcfa0e233, "Heltec_t114_without_display_room_server" },
|
||||
{ 0x17d5e1ff, "Heltec_T190_companion_radio_ble_" },
|
||||
{ 0xc99313c6, "Heltec_T190_companion_radio_usb_" },
|
||||
{ 0x21a73973, "Heltec_T190_kiss_modem" },
|
||||
{ 0x3067f656, "Heltec_T190_repeater_" },
|
||||
{ 0xfdb25057, "Heltec_T190_repeater_bridge_espnow_" },
|
||||
{ 0x0f1767cd, "Heltec_T190_room_server_" },
|
||||
{ 0x73387372, "heltec_tracker_v2_companion_radio_ble" },
|
||||
{ 0xe6eeffe1, "heltec_tracker_v2_companion_radio_usb" },
|
||||
{ 0x35f4e7ac, "heltec_tracker_v2_companion_radio_wifi" },
|
||||
{ 0xb62a1e75, "heltec_tracker_v2_kiss_modem" },
|
||||
{ 0x9e64845d, "heltec_tracker_v2_repeater" },
|
||||
{ 0x19232e8b, "heltec_tracker_v2_repeater_bridge_espnow" },
|
||||
{ 0x38b948b4, "heltec_tracker_v2_room_server" },
|
||||
{ 0xed21ca4f, "heltec_tracker_v2_sensor" },
|
||||
{ 0x9f5f39a7, "heltec_tracker_v2_terminal_chat" },
|
||||
{ 0x081d2219, "Heltec_v2_companion_radio_ble" },
|
||||
{ 0xc283ad60, "Heltec_v2_companion_radio_usb" },
|
||||
{ 0x4fbdc1e1, "Heltec_v2_companion_radio_wifi" },
|
||||
{ 0xc797fd73, "Heltec_v2_kiss_modem" },
|
||||
{ 0xab9871c8, "Heltec_v2_repeater" },
|
||||
{ 0x5caaf9bf, "Heltec_v2_repeater_bridge_espnow" },
|
||||
{ 0x2075687c, "Heltec_v2_room_server" },
|
||||
{ 0x5d726067, "Heltec_v2_terminal_chat" },
|
||||
{ 0x9969bbc9, "Heltec_v3_companion_radio_ble" },
|
||||
{ 0x22f900de, "Heltec_v3_companion_radio_usb" },
|
||||
{ 0xaca0e153, "Heltec_v3_companion_radio_wifi" },
|
||||
{ 0xcb1c2e65, "Heltec_v3_kiss_modem" },
|
||||
{ 0x9f2a6b84, "Heltec_v3_ota_test" },
|
||||
{ 0xd1b29b18, "Heltec_v3_repeater" },
|
||||
{ 0x644bb68d, "Heltec_v3_repeater_bridge_espnow" },
|
||||
{ 0xd19a9759, "Heltec_v3_repeater_bridge_rs232" },
|
||||
{ 0xc59d294e, "Heltec_v3_room_server" },
|
||||
{ 0x21519537, "Heltec_v3_sensor" },
|
||||
{ 0x382bb181, "Heltec_v3_terminal_chat" },
|
||||
{ 0x01d8f124, "heltec_v4_companion_radio_ble" },
|
||||
{ 0x1a4d0096, "heltec_v4_companion_radio_usb" },
|
||||
{ 0x34240e36, "heltec_v4_companion_radio_wifi" },
|
||||
{ 0xd522a14f, "heltec_v4_expansionkit_repeater" },
|
||||
{ 0xf75feb3e, "heltec_v4_kiss_modem" },
|
||||
{ 0xe792a051, "heltec_v4_repeater" },
|
||||
{ 0x2d5ea842, "heltec_v4_repeater_bridge_espnow" },
|
||||
{ 0xeed78ce4, "heltec_v4_room_server" },
|
||||
{ 0x0b6847ed, "heltec_v4_sensor" },
|
||||
{ 0xab3e1ad3, "heltec_v4_terminal_chat" },
|
||||
{ 0x60fca2ae, "heltec_v4_tft_companion_radio_ble" },
|
||||
{ 0xf6b40343, "heltec_v4_tft_companion_radio_usb" },
|
||||
{ 0x76640bcc, "heltec_v4_tft_companion_radio_wifi" },
|
||||
{ 0x87513d56, "heltec_v4_tft_repeater" },
|
||||
{ 0xca812b41, "heltec_v4_tft_repeater_bridge_espnow" },
|
||||
{ 0x18594231, "heltec_v4_tft_room_server" },
|
||||
{ 0x188f3ac1, "heltec_v4_tft_sensor" },
|
||||
{ 0x402055ec, "heltec_v4_tft_terminal_chat" },
|
||||
{ 0x12393f1f, "Heltec_Wireless_Paper_companion_radio_ble" },
|
||||
{ 0xed3ef5b8, "Heltec_Wireless_Paper_companion_radio_usb" },
|
||||
{ 0x8ea86381, "Heltec_Wireless_Paper_kiss_modem" },
|
||||
{ 0x09f57289, "Heltec_Wireless_Paper_repeater" },
|
||||
{ 0x148aeaab, "Heltec_Wireless_Paper_repeater_bridge_espnow" },
|
||||
{ 0x6e9f7fec, "Heltec_Wireless_Paper_room_server" },
|
||||
{ 0x6a25d024, "Heltec_Wireless_Tracker_companion_radio_ble" },
|
||||
{ 0xc4a11710, "Heltec_Wireless_Tracker_companion_radio_usb" },
|
||||
{ 0x753947a4, "Heltec_Wireless_Tracker_kiss_modem" },
|
||||
{ 0xe6fa98b4, "Heltec_Wireless_Tracker_repeater" },
|
||||
{ 0xf8c27cf4, "Heltec_Wireless_Tracker_repeater_bridge_espnow" },
|
||||
{ 0x90e227d9, "Heltec_Wireless_Tracker_room_server" },
|
||||
{ 0x812f5e52, "Heltec_WSL3_companion_radio_ble" },
|
||||
{ 0x1ddd15c8, "Heltec_WSL3_companion_radio_usb" },
|
||||
{ 0x49d67d0d, "Heltec_WSL3_companion_radio_wifi" },
|
||||
{ 0xbc003322, "Heltec_WSL3_repeater" },
|
||||
{ 0x835b70c0, "Heltec_WSL3_repeater_bridge_espnow" },
|
||||
{ 0xd7460575, "Heltec_WSL3_repeater_bridge_rs232" },
|
||||
{ 0x33e2c171, "Heltec_WSL3_room_server" },
|
||||
{ 0xa165ae99, "Heltec_WSL3_sensor" },
|
||||
{ 0x04c5c2b7, "ikoka_handheld_nrf_e22_30dbm_096_companion_radio_ble" },
|
||||
{ 0x6c1ca659, "ikoka_handheld_nrf_e22_30dbm_096_companion_radio_usb" },
|
||||
{ 0xa295fb04, "ikoka_handheld_nrf_e22_30dbm_096_rotated_companion_radio_ble" },
|
||||
{ 0x61c405ca, "ikoka_handheld_nrf_e22_30dbm_096_rotated_companion_radio_usb" },
|
||||
{ 0xe893fe91, "ikoka_handheld_nrf_e22_30dbm_repeater" },
|
||||
{ 0x2b599d31, "ikoka_handheld_nrf_e22_30dbm_room_server" },
|
||||
{ 0xf1442d25, "ikoka_handheld_nrf_kiss_modem" },
|
||||
{ 0x15082ede, "ikoka_nano_nrf_22dbm_companion_radio_ble" },
|
||||
{ 0x6ff350d1, "ikoka_nano_nrf_22dbm_companion_radio_usb" },
|
||||
{ 0xe03d0cd9, "ikoka_nano_nrf_22dbm_kiss_modem" },
|
||||
{ 0x82e1eb2c, "ikoka_nano_nrf_22dbm_repeater" },
|
||||
{ 0x0ee19b12, "ikoka_nano_nrf_22dbm_room_server" },
|
||||
{ 0x6c67ed89, "ikoka_nano_nrf_30dbm_companion_radio_ble" },
|
||||
{ 0xd1c05d0d, "ikoka_nano_nrf_30dbm_companion_radio_usb" },
|
||||
{ 0xb90150b0, "ikoka_nano_nrf_30dbm_kiss_modem" },
|
||||
{ 0x7285bdb3, "ikoka_nano_nrf_30dbm_repeater" },
|
||||
{ 0x77cadc99, "ikoka_nano_nrf_30dbm_room_server" },
|
||||
{ 0xc177e6cd, "ikoka_nano_nrf_33dbm_companion_radio_ble" },
|
||||
{ 0xf7a38993, "ikoka_nano_nrf_33dbm_companion_radio_usb" },
|
||||
{ 0x83762f33, "ikoka_nano_nrf_33dbm_kiss_modem" },
|
||||
{ 0x86cadda9, "ikoka_nano_nrf_33dbm_repeater" },
|
||||
{ 0x7e49da49, "ikoka_nano_nrf_33dbm_room_server" },
|
||||
{ 0x305d6f92, "ikoka_stick_nrf_22dbm_companion_radio_ble" },
|
||||
{ 0xbc6b870b, "ikoka_stick_nrf_22dbm_companion_radio_usb" },
|
||||
{ 0x78845fdd, "ikoka_stick_nrf_22dbm_kiss_modem" },
|
||||
{ 0x6d35f434, "ikoka_stick_nrf_22dbm_repeater" },
|
||||
{ 0xa52d76a8, "ikoka_stick_nrf_22dbm_room_server" },
|
||||
{ 0xd8de9639, "ikoka_stick_nrf_30dbm_companion_radio_ble" },
|
||||
{ 0x8ab5c51b, "ikoka_stick_nrf_30dbm_companion_radio_usb" },
|
||||
{ 0x80097676, "ikoka_stick_nrf_30dbm_kiss_modem" },
|
||||
{ 0xffe70df5, "ikoka_stick_nrf_30dbm_repeater" },
|
||||
{ 0x3da80417, "ikoka_stick_nrf_30dbm_room_server" },
|
||||
{ 0x47ca3c13, "ikoka_stick_nrf_33dbm_companion_radio_ble" },
|
||||
{ 0x28b499c7, "ikoka_stick_nrf_33dbm_companion_radio_usb" },
|
||||
{ 0xf1ab4c28, "ikoka_stick_nrf_33dbm_kiss_modem" },
|
||||
{ 0xe5331f02, "ikoka_stick_nrf_33dbm_repeater" },
|
||||
{ 0xfba7177b, "ikoka_stick_nrf_33dbm_room_server" },
|
||||
{ 0x69df7765, "LilyGo_T-Echo-Lite_companion_radio_ble" },
|
||||
{ 0xe9fbc9be, "LilyGo_T-Echo-Lite_kiss_modem" },
|
||||
{ 0x40818863, "LilyGo_T-Echo-Lite_non_shell_companion_radio_ble" },
|
||||
{ 0x65deac33, "LilyGo_T-Echo-Lite_non_shell_companion_radio_usb" },
|
||||
{ 0xd86cf67a, "LilyGo_T-Echo-Lite_repeater" },
|
||||
{ 0xed73ac03, "LilyGo_T-Echo-Lite_room_server" },
|
||||
{ 0xab0d550a, "LilyGo_T-Echo_Card_companion_radio_ble" },
|
||||
{ 0x1bd2a266, "LilyGo_T-Echo_Card_companion_radio_usb" },
|
||||
{ 0x9a5ae8fc, "LilyGo_T-Echo_Card_repeater" },
|
||||
{ 0x1e9eb97a, "LilyGo_T-Echo_Card_room_server" },
|
||||
{ 0x139536f4, "LilyGo_T-Echo_companion_radio_ble" },
|
||||
{ 0x0716c724, "LilyGo_T-Echo_companion_radio_usb" },
|
||||
{ 0x8de23fa7, "LilyGo_T-Echo_kiss_modem" },
|
||||
{ 0xb92ec96b, "LilyGo_T-Echo_repeater" },
|
||||
{ 0x420ebc63, "LilyGo_T-Echo_room_server" },
|
||||
{ 0x967ccaee, "LilyGo_T3S3_sx1262_companion_radio_ble" },
|
||||
{ 0x5f7c7688, "LilyGo_T3S3_sx1262_companion_radio_usb" },
|
||||
{ 0xbd04e6e7, "LilyGo_T3S3_sx1262_kiss_modem" },
|
||||
{ 0x1aeac884, "LilyGo_T3S3_sx1262_repeater" },
|
||||
{ 0x07849209, "LilyGo_T3S3_sx1262_repeater_bridge_espnow" },
|
||||
{ 0xbfb60e7c, "LilyGo_T3S3_sx1262_room_server" },
|
||||
{ 0x96036a68, "LilyGo_T3S3_sx1262_terminal_chat" },
|
||||
{ 0xb76a745c, "LilyGo_T3S3_sx1276_companion_radio_ble" },
|
||||
{ 0x43023193, "LilyGo_T3S3_sx1276_companion_radio_usb" },
|
||||
{ 0xa7d97db7, "LilyGo_T3S3_sx1276_kiss_modem" },
|
||||
{ 0x468a133e, "LilyGo_T3S3_sx1276_repeater" },
|
||||
{ 0xb59ea2ed, "LilyGo_T3S3_sx1276_repeater_bridge_espnow" },
|
||||
{ 0xbe372c6d, "LilyGo_T3S3_sx1276_room_server" },
|
||||
{ 0x6215e9eb, "LilyGo_T3S3_sx1276_terminal_chat" },
|
||||
{ 0x3898ea56, "LilyGo_TBeam_1W_companion_radio_ble" },
|
||||
{ 0x4f722e70, "LilyGo_TBeam_1W_companion_radio_usb" },
|
||||
{ 0x694eed25, "LilyGo_TBeam_1W_companion_radio_wifi" },
|
||||
{ 0x85b8b9d7, "LilyGo_TBeam_1W_kiss_modem" },
|
||||
{ 0xe8421e36, "LilyGo_TBeam_1W_repeater" },
|
||||
{ 0x82eaaf9e, "LilyGo_TBeam_1W_repeater_bridge_espnow" },
|
||||
{ 0xe4a2de74, "LilyGo_TBeam_1W_room_server" },
|
||||
{ 0xaeb637f1, "LilyGo_TDeck_companion_radio_ble" },
|
||||
{ 0x86813271, "LilyGo_TDeck_companion_radio_usb" },
|
||||
{ 0x67b2ff84, "LilyGo_TDeck_kiss_modem" },
|
||||
{ 0xd0e2e616, "LilyGo_TDeck_repeater" },
|
||||
{ 0x3f9edfe3, "LilyGo_TETH_Elite_sx1262_companion_radio_ble" },
|
||||
{ 0xc23f8082, "LilyGo_TETH_Elite_sx1262_companion_radio_usb" },
|
||||
{ 0x8f256e56, "LilyGo_TETH_Elite_sx1262_repeater" },
|
||||
{ 0xf1407f39, "LilyGo_TETH_Elite_sx1262_room_server" },
|
||||
{ 0xe90a3181, "LilyGo_Tlora_C6_companion_radio_ble_" },
|
||||
{ 0x3b1b4237, "LilyGo_Tlora_C6_kiss_modem" },
|
||||
{ 0x21c6d08d, "LilyGo_Tlora_C6_repeater_" },
|
||||
{ 0x34302c14, "LilyGo_Tlora_C6_room_server_" },
|
||||
{ 0x268d6fc1, "LilyGo_TLora_V2_1_1_6_companion_radio_ble" },
|
||||
{ 0x3c172d27, "LilyGo_TLora_V2_1_1_6_companion_radio_usb" },
|
||||
{ 0xf7c5d584, "LilyGo_TLora_V2_1_1_6_companion_radio_wifi" },
|
||||
{ 0x81960cc0, "LilyGo_TLora_V2_1_1_6_kiss_modem" },
|
||||
{ 0x504020ea, "LilyGo_TLora_V2_1_1_6_repeater" },
|
||||
{ 0x8e5c0c88, "LilyGo_TLora_V2_1_1_6_repeater_bridge_espnow" },
|
||||
{ 0x4e42e0ad, "LilyGo_TLora_V2_1_1_6_repeater_bridge_rs232" },
|
||||
{ 0xa2ce002f, "LilyGo_TLora_V2_1_1_6_room_server" },
|
||||
{ 0x6f16479e, "LilyGo_TLora_V2_1_1_6_terminal_chat" },
|
||||
{ 0x1018e5d1, "M5Stack_Unit_C6L_companion_radio_ble" },
|
||||
{ 0xc0ab5040, "M5Stack_Unit_C6L_companion_radio_usb" },
|
||||
{ 0xa2bf90bd, "M5Stack_Unit_C6L_kiss_modem" },
|
||||
{ 0xe6bff8f9, "M5Stack_Unit_C6L_repeater" },
|
||||
{ 0xb9cd26cb, "M5Stack_Unit_C6L_room_server" },
|
||||
{ 0xdbfe2675, "Meshadventurer_sx1262_companion_radio_ble" },
|
||||
{ 0xb00241d0, "Meshadventurer_sx1262_companion_radio_usb" },
|
||||
{ 0x88e77fee, "Meshadventurer_sx1262_kiss_modem" },
|
||||
{ 0xae2d9caa, "Meshadventurer_sx1262_repeater" },
|
||||
{ 0xecea445b, "Meshadventurer_sx1262_repeater_bridge_espnow" },
|
||||
{ 0xa0043e00, "Meshadventurer_sx1262_room_server" },
|
||||
{ 0x26bbf4ed, "Meshadventurer_sx1262_terminal_chat" },
|
||||
{ 0xdcc0f158, "Meshadventurer_sx1268_companion_radio_ble" },
|
||||
{ 0xe3320463, "Meshadventurer_sx1268_companion_radio_usb" },
|
||||
{ 0x852b928a, "Meshadventurer_sx1268_kiss_modem" },
|
||||
{ 0x0ec870e9, "Meshadventurer_sx1268_repeater" },
|
||||
{ 0xc845072e, "Meshadventurer_sx1268_repeater_bridge_espnow" },
|
||||
{ 0x8f00c1f2, "Meshadventurer_sx1268_room_server" },
|
||||
{ 0xcea95e20, "Meshadventurer_sx1268_terminal_chat" },
|
||||
{ 0xd45277ff, "Meshimi_companion_radio_ble_" },
|
||||
{ 0x2cad9a9d, "Meshimi_repeater_" },
|
||||
{ 0x063f1f00, "nibble_screen_connect_companion_radio_ble_" },
|
||||
{ 0xa8a79da5, "nibble_screen_connect_companion_radio_usb_" },
|
||||
{ 0xc0d3815b, "nibble_screen_connect_companion_radio_wifi_" },
|
||||
{ 0x966ac88e, "nibble_screen_connect_kiss_modem_" },
|
||||
{ 0x104b3f8b, "nibble_screen_connect_repeater_" },
|
||||
{ 0x23b49348, "nibble_screen_connect_repeater_bridge_espnow_" },
|
||||
{ 0xc42cc90d, "nibble_screen_connect_room_server_" },
|
||||
{ 0xc24791c3, "nibble_screen_connect_terminal_chat_" },
|
||||
{ 0x15e11067, "nibble_zero_connect_companion_radio_ble_" },
|
||||
{ 0x90799c32, "nibble_zero_connect_companion_radio_usb_" },
|
||||
{ 0x881a6a48, "nibble_zero_connect_companion_radio_wifi_" },
|
||||
{ 0xf26af51c, "nibble_zero_connect_repeater_" },
|
||||
{ 0x8174cbdc, "nibble_zero_connect_repeater_bridge_espnow_" },
|
||||
{ 0x0bf0f061, "nibble_zero_connect_room_server_" },
|
||||
{ 0x2509dd80, "nibble_zero_connect_terminal_chat_" },
|
||||
{ 0x56293b24, "ProMicro_companion_radio_ble" },
|
||||
{ 0x8c81078c, "ProMicro_companion_radio_usb" },
|
||||
{ 0xbd6a1c97, "ProMicro_kiss_modem" },
|
||||
{ 0xf4d98c12, "ProMicro_repeater" },
|
||||
{ 0xccac4283, "ProMicro_repeater_bridge_rs232_serial1" },
|
||||
{ 0x5f606274, "ProMicro_room_server" },
|
||||
{ 0x84923735, "ProMicro_sensor" },
|
||||
{ 0x2c0b8b05, "ProMicro_terminal_chat" },
|
||||
{ 0xdba69401, "R1Neo_companion_radio_ble" },
|
||||
{ 0xcb6555ee, "R1Neo_companion_radio_usb" },
|
||||
{ 0xd60daf25, "R1Neo_kiss_modem" },
|
||||
{ 0x410bd800, "R1Neo_repeater" },
|
||||
{ 0xd8641710, "R1Neo_room_server" },
|
||||
{ 0x4d0b1601, "R1Neo_sensor" },
|
||||
{ 0xab2ac09e, "R1Neo_terminal_chat" },
|
||||
{ 0xa17fc4f7, "RAK_3112_companion_radio_ble" },
|
||||
{ 0x90c4eb3f, "RAK_3112_companion_radio_usb" },
|
||||
{ 0x19d9ce91, "RAK_3112_companion_radio_wifi" },
|
||||
{ 0x121cc72f, "RAK_3112_kiss_modem" },
|
||||
{ 0xfa8510fa, "RAK_3112_repeater" },
|
||||
{ 0xd34d8461, "RAK_3112_repeater_bridge_espnow" },
|
||||
{ 0x98077550, "RAK_3112_repeater_bridge_rs232" },
|
||||
{ 0x2ed959aa, "RAK_3112_room_server" },
|
||||
{ 0xced7e127, "RAK_3112_sensor" },
|
||||
{ 0x6925aaf0, "RAK_3112_terminal_chat" },
|
||||
{ 0x9f4d58ac, "RAK_4631_companion_radio_ble" },
|
||||
{ 0x48d3b5d4, "RAK_4631_companion_radio_usb" },
|
||||
{ 0x14e6965d, "RAK_4631_kiss_modem" },
|
||||
{ 0x04d413fd, "RAK_4631_repeater" },
|
||||
{ 0x22ea8497, "RAK_4631_repeater_bridge_rs232_serial1" },
|
||||
{ 0x21bae522, "RAK_4631_repeater_bridge_rs232_serial2" },
|
||||
{ 0x626d80ed, "RAK_4631_room_server" },
|
||||
{ 0x8b1d6850, "RAK_4631_sensor" },
|
||||
{ 0xf1d3c5a8, "RAK_4631_terminal_chat" },
|
||||
{ 0xc6d55752, "RAK_WisMesh_Tag_companion_radio_ble" },
|
||||
{ 0x60683191, "RAK_WisMesh_Tag_companion_radio_usb" },
|
||||
{ 0x8a7cb79b, "RAK_WisMesh_Tag_kiss_modem" },
|
||||
{ 0x4fa4ae55, "RAK_WisMesh_Tag_repeater" },
|
||||
{ 0x9cb0b232, "RAK_WisMesh_Tag_room_server" },
|
||||
{ 0x51fa1a49, "RAK_WisMesh_Tag_sensor" },
|
||||
{ 0xd904c2d5, "SenseCapIndicator-ESPNow_comp_radio_usb" },
|
||||
{ 0xd0df8303, "Station_G2_companion_radio_ble" },
|
||||
{ 0x5c1a54f8, "Station_G2_companion_radio_usb" },
|
||||
{ 0x79cc029e, "Station_G2_companion_radio_wifi" },
|
||||
{ 0x41197b92, "Station_G2_kiss_modem" },
|
||||
{ 0x05747eb6, "Station_G2_logging_repeater" },
|
||||
{ 0x75587f24, "Station_G2_logging_repeater_bridge_espnow" },
|
||||
{ 0xf2128c81, "Station_G2_repeater" },
|
||||
{ 0x1b34e7b4, "Station_G2_repeater_bridge_espnow" },
|
||||
{ 0x73c4a019, "Station_G2_room_server" },
|
||||
{ 0x8e549407, "Station_G3_ESP32_companion_radio_ble" },
|
||||
{ 0x1deac038, "Station_G3_ESP32_companion_radio_usb" },
|
||||
{ 0x2a2f303b, "Station_G3_ESP32_companion_radio_wifi" },
|
||||
{ 0x0ba4453d, "Station_G3_ESP32_kiss_modem" },
|
||||
{ 0xf8d1958f, "Station_G3_ESP32_logging_repeater" },
|
||||
{ 0x3c49caf8, "Station_G3_ESP32_repeater" },
|
||||
{ 0x91878dd8, "Station_G3_ESP32_room_server" },
|
||||
{ 0x4dbf035e, "t1000e_companion_radio_ble" },
|
||||
{ 0xff4102d6, "t1000e_companion_radio_usb" },
|
||||
{ 0x2f9a9185, "t1000e_kiss_modem" },
|
||||
{ 0x000fc519, "t1000e_repeater" },
|
||||
{ 0x3e55e34d, "t1000e_room_server" },
|
||||
{ 0x16482630, "T_Beam_S3_Supreme_SX1262_companion_radio_ble" },
|
||||
{ 0x01c43d49, "T_Beam_S3_Supreme_SX1262_companion_radio_wifi" },
|
||||
{ 0x51fe3801, "T_Beam_S3_Supreme_SX1262_kiss_modem" },
|
||||
{ 0x857149e5, "T_Beam_S3_Supreme_SX1262_repeater" },
|
||||
{ 0xd9d64938, "T_Beam_S3_Supreme_SX1262_repeater_bridge_espnow" },
|
||||
{ 0x9952fbe3, "T_Beam_S3_Supreme_SX1262_room_server" },
|
||||
{ 0xdc27c37c, "Tbeam_SX1262_companion_radio_ble" },
|
||||
{ 0xb27514a3, "Tbeam_SX1262_kiss_modem" },
|
||||
{ 0xe9ce038c, "Tbeam_SX1262_repeater" },
|
||||
{ 0x06406dd4, "Tbeam_SX1262_repeater_bridge_espnow" },
|
||||
{ 0x189660b3, "Tbeam_SX1262_room_server" },
|
||||
{ 0x2082078d, "Tbeam_SX1276_companion_radio_ble" },
|
||||
{ 0x3750e80d, "Tbeam_SX1276_kiss_modem" },
|
||||
{ 0xe4b49973, "Tbeam_SX1276_repeater" },
|
||||
{ 0x0c0c4605, "Tbeam_SX1276_repeater_bridge_espnow" },
|
||||
{ 0x5a79bac1, "Tbeam_SX1276_room_server" },
|
||||
{ 0x8eaa289e, "Tenstar_C3_sx1262_kiss_modem" },
|
||||
{ 0x70e91bd9, "Tenstar_C3_sx1262_repeater" },
|
||||
{ 0x5a7e9c2d, "Tenstar_C3_sx1262_repeater_bridge_espnow" },
|
||||
{ 0x1211b151, "Tenstar_C3_sx1268_kiss_modem" },
|
||||
{ 0x0a32044b, "Tenstar_C3_sx1268_repeater" },
|
||||
{ 0xa13fe853, "Tenstar_C3_sx1268_repeater_bridge_espnow" },
|
||||
{ 0x79b9ff01, "ThinkNode_M1_companion_radio_ble" },
|
||||
{ 0xc3decea2, "ThinkNode_M1_companion_radio_usb" },
|
||||
{ 0x3c012018, "ThinkNode_M1_kiss_modem" },
|
||||
{ 0x6afd6f75, "ThinkNode_M1_repeater" },
|
||||
{ 0x7517d400, "ThinkNode_M1_room_server" },
|
||||
{ 0xd7598668, "ThinkNode_M2_companion_radio_ble" },
|
||||
{ 0x413287d8, "ThinkNode_M2_companion_radio_serial" },
|
||||
{ 0xe8cd2377, "ThinkNode_M2_companion_radio_usb" },
|
||||
{ 0x3309bdaf, "ThinkNode_M2_companion_radio_wifi" },
|
||||
{ 0x7330afbb, "ThinkNode_M2_kiss_modem" },
|
||||
{ 0x9df48ce6, "ThinkNode_M2_Repeater" },
|
||||
{ 0xa5cb783a, "ThinkNode_M2_Repeater_bridge_espnow" },
|
||||
{ 0x4b9f8283, "ThinkNode_M2_room_server" },
|
||||
{ 0x311846c9, "ThinkNode_M2_terminal_chat" },
|
||||
{ 0x8b6b29b7, "ThinkNode_M3_companion_radio_ble" },
|
||||
{ 0x37928233, "ThinkNode_M3_companion_radio_usb" },
|
||||
{ 0x88ac45da, "ThinkNode_M3_kiss_modem" },
|
||||
{ 0x087f99c0, "ThinkNode_M3_repeater" },
|
||||
{ 0x2afe6c63, "ThinkNode_M3_room_server" },
|
||||
{ 0xf2d61a1c, "ThinkNode_M5_companion_radio_ble" },
|
||||
{ 0x1da30414, "ThinkNode_M5_companion_radio_serial" },
|
||||
{ 0xae8fe1c9, "ThinkNode_M5_companion_radio_usb" },
|
||||
{ 0x67acd73f, "ThinkNode_M5_companion_radio_wifi" },
|
||||
{ 0xfb118ed8, "ThinkNode_M5_kiss_modem" },
|
||||
{ 0xe4213729, "ThinkNode_M5_Repeater" },
|
||||
{ 0x1298038d, "ThinkNode_M5_Repeater_bridge_espnow" },
|
||||
{ 0x2c47acff, "ThinkNode_M5_room_server" },
|
||||
{ 0x7d641646, "ThinkNode_M5_terminal_chat" },
|
||||
{ 0x51efdbfe, "ThinkNode_M6_companion_radio_ble" },
|
||||
{ 0xf2aada5b, "ThinkNode_M6_companion_radio_usb" },
|
||||
{ 0xe59c9373, "ThinkNode_M6_kiss_modem" },
|
||||
{ 0x236f605c, "ThinkNode_M6_repeater" },
|
||||
{ 0x93994fed, "ThinkNode_M6_room_server" },
|
||||
{ 0x37443a5b, "WHY2025_badge_companion_radio_ble_" },
|
||||
{ 0x603384a7, "WHY2025_badge_repeater_" },
|
||||
{ 0x475a2a6a, "WioTrackerL1_companion_radio_ble" },
|
||||
{ 0xf4175d2c, "WioTrackerL1_companion_radio_usb" },
|
||||
{ 0x3d831006, "WioTrackerL1_kiss_modem" },
|
||||
{ 0x556eb1bc, "WioTrackerL1_repeater" },
|
||||
{ 0x0c689b90, "WioTrackerL1_room_server" },
|
||||
{ 0x91eac424, "WioTrackerL1Eink_companion_radio_ble" },
|
||||
{ 0x7a84a8c4, "WioTrackerL1Eink_kiss_modem" },
|
||||
{ 0x67843a5f, "Xiao_C3_companion_radio_ble" },
|
||||
{ 0xfad357ab, "Xiao_C3_companion_radio_usb" },
|
||||
{ 0x16af5c67, "Xiao_C3_companion_radio_wifi" },
|
||||
{ 0x8c105104, "Xiao_C3_kiss_modem" },
|
||||
{ 0xa80042a0, "Xiao_C3_repeater" },
|
||||
{ 0x4bff0748, "Xiao_C3_room_server" },
|
||||
{ 0x77c8f2b5, "Xiao_C6_companion_radio_ble_" },
|
||||
{ 0x71ee0e15, "Xiao_C6_kiss_modem" },
|
||||
{ 0x8824cd0c, "Xiao_C6_repeater_" },
|
||||
{ 0xe5439198, "Xiao_nrf52_companion_radio_ble" },
|
||||
{ 0xe90a6e74, "Xiao_nrf52_companion_radio_usb" },
|
||||
{ 0x833e5cdc, "Xiao_nrf52_kiss_modem" },
|
||||
{ 0x93145fbb, "Xiao_nrf52_repeater" },
|
||||
{ 0x33a154ff, "Xiao_nrf52_room_server" },
|
||||
{ 0x6658b418, "Xiao_S3_companion_radio_ble" },
|
||||
{ 0x964f4f5c, "Xiao_S3_companion_radio_usb" },
|
||||
{ 0x0a5dc760, "Xiao_S3_kiss_modem" },
|
||||
{ 0xd08496ce, "Xiao_S3_repeater" },
|
||||
{ 0x293ac2c8, "Xiao_S3_repeater_bridge_espnow" },
|
||||
{ 0x60ebfa87, "Xiao_S3_room_server" },
|
||||
{ 0x60f5fdc2, "Xiao_S3_sensor" },
|
||||
{ 0xe8f79d22, "Xiao_S3_WIO_companion_radio_ble" },
|
||||
{ 0x9f27be15, "Xiao_S3_WIO_companion_radio_serial" },
|
||||
{ 0x396fecc7, "Xiao_S3_WIO_companion_radio_usb" },
|
||||
{ 0xf94e3407, "Xiao_S3_WIO_companion_radio_wifi" },
|
||||
{ 0xe1930103, "Xiao_S3_WIO_kiss_modem" },
|
||||
{ 0x9f19bcd1, "Xiao_S3_WIO_repeater" },
|
||||
{ 0xfcebff61, "Xiao_S3_WIO_repeater_bridge_espnow" },
|
||||
{ 0xccb734e2, "Xiao_S3_WIO_room_server" },
|
||||
{ 0xf967a300, "Xiao_S3_WIO_sensor" },
|
||||
{ 0xa0cc1c36, "Xiao_S3_WIO_terminal_chat" },
|
||||
};
|
||||
for (unsigned i = 0; i < sizeof(T) / sizeof(T[0]); i++)
|
||||
if (T[i].id == target_id) return T[i].env;
|
||||
return nullptr;
|
||||
}
|
||||
|
||||
} } // namespace mesh::ota
|
||||
@@ -0,0 +1,27 @@
|
||||
#include "OtaVerify.h"
|
||||
#include "MerkleTree.h"
|
||||
#include "Multihash.h"
|
||||
#include "Identity.h"
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
VerifyResult ota_verify(const uint8_t* buf, uint32_t len, const SignerAllowlist& allow) {
|
||||
VerifyResult r;
|
||||
MotaManifest m;
|
||||
if (!mota_parse(buf, len, m)) return r;
|
||||
r.parsed = true;
|
||||
r.root_ok = mota_check_root(m);
|
||||
r.image_ok = m.is_full() ? mota_check_image_hash_full(m)
|
||||
: true; // delta image_hash needs the base; verified at apply time
|
||||
r.is_signed = m.is_signed();
|
||||
if (r.is_signed) {
|
||||
mesh::Identity signer(m.signer_pubkey);
|
||||
r.sig_ok = signer.verify(m.signature, m.manifest_start, (int)m.signed_len);
|
||||
r.trusted = r.sig_ok && allow.contains(m.signer_pubkey);
|
||||
}
|
||||
return r;
|
||||
}
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,29 @@
|
||||
#pragma once
|
||||
|
||||
#include "MotaContainer.h"
|
||||
#include "SignerAllowlist.h"
|
||||
|
||||
// Full verification of a staged `.mota` (device-side: uses Ed25519 via mesh::Identity, so NOT compiled
|
||||
// on the native host — the portable integrity checks live in MotaContainer and are unit-tested there).
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
struct VerifyResult {
|
||||
bool parsed = false; // container + manifest parsed
|
||||
bool root_ok = false; // merkle_root recomputed from leaves[] matches
|
||||
bool image_ok = false; // full: sha2-256(payload)==image_hash; delta: deferred to apply (set true)
|
||||
bool is_signed = false;
|
||||
bool sig_ok = false; // Ed25519 signature valid for signer_pubkey
|
||||
bool trusted = false; // signer_pubkey is in the allowlist
|
||||
|
||||
// Integrity holds (safe to keep/serve). For a signed image, the signature must also verify.
|
||||
bool integrity_ok() const { return parsed && root_ok && image_ok && (!is_signed || sig_ok); }
|
||||
// Eligible for AUTO-apply: integrity + signed by an allowlisted key (decision D2).
|
||||
bool auto_appliable() const { return integrity_ok() && is_signed && sig_ok && trusted; }
|
||||
};
|
||||
|
||||
VerifyResult ota_verify(const uint8_t* buf, uint32_t len, const SignerAllowlist& allow);
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,72 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include <stddef.h>
|
||||
#include <string.h>
|
||||
|
||||
// Runtime-managed allowlist of trusted Ed25519 firmware-signer public keys (docs/ota_protocol.md §9,
|
||||
// decision D2 + Q1: no key embedded in firmware; only allowlist-signed firmware may auto-apply).
|
||||
// Portable + fixed-capacity (no dynamic allocation). Persistence (load/save) is layered on per-platform.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
#ifndef MAX_OTA_SIGNERS
|
||||
#define MAX_OTA_SIGNERS 4
|
||||
#endif
|
||||
|
||||
class SignerAllowlist {
|
||||
uint8_t _keys[MAX_OTA_SIGNERS][32];
|
||||
uint8_t _count = 0;
|
||||
|
||||
public:
|
||||
void clear() { _count = 0; }
|
||||
uint8_t count() const { return _count; }
|
||||
const uint8_t* get(uint8_t i) const { return (i < _count) ? _keys[i] : nullptr; }
|
||||
|
||||
bool contains(const uint8_t* pub) const {
|
||||
for (uint8_t i = 0; i < _count; i++)
|
||||
if (memcmp(_keys[i], pub, 32) == 0) return true;
|
||||
return false;
|
||||
}
|
||||
|
||||
// Add a key (idempotent). Returns false if the list is full.
|
||||
bool add(const uint8_t* pub) {
|
||||
if (contains(pub)) return true;
|
||||
if (_count >= MAX_OTA_SIGNERS) return false;
|
||||
memcpy(_keys[_count++], pub, 32);
|
||||
return true;
|
||||
}
|
||||
|
||||
bool remove(const uint8_t* pub) {
|
||||
for (uint8_t i = 0; i < _count; i++) {
|
||||
if (memcmp(_keys[i], pub, 32) == 0) {
|
||||
memmove(_keys[i], _keys[i + 1], (size_t)(_count - i - 1) * 32);
|
||||
_count--;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
// Serialize as: count(1) || key0(32) || key1(32) ... Returns bytes written.
|
||||
uint32_t serialize(uint8_t* out, uint32_t max_len) const {
|
||||
uint32_t need = 1 + (uint32_t)_count * 32;
|
||||
if (max_len < need) return 0;
|
||||
out[0] = _count;
|
||||
memcpy(out + 1, _keys, (size_t)_count * 32);
|
||||
return need;
|
||||
}
|
||||
|
||||
bool deserialize(const uint8_t* in, uint32_t len) {
|
||||
if (len < 1) return false;
|
||||
uint8_t n = in[0];
|
||||
if (n > MAX_OTA_SIGNERS || (uint32_t)1 + n * 32 > len) return false;
|
||||
_count = n;
|
||||
memcpy(_keys, in + 1, (size_t)n * 32);
|
||||
return true;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,42 @@
|
||||
Vendored detools embeddable C decoder
|
||||
=====================================
|
||||
|
||||
Source : https://github.com/eerimoq/detools (tag 0.53.0, c/ directory)
|
||||
Files : detools.c, detools.h
|
||||
License : BSD 2-Clause (Erik Moqvist; original bsdiff (c) Colin Percival).
|
||||
sais.c (host packager only, not vendored) is MIT.
|
||||
Compatible with MeshCore's MIT license; notices retained in-file.
|
||||
|
||||
Why vendored
|
||||
------------
|
||||
The detools PyPI package (used by tools/mota to *create* patches with
|
||||
detools.create_patch) ships only the Python library + patch-creation C
|
||||
extensions -- NOT the embeddable decoder. The on-device delta applier needs
|
||||
detools' own decoder, so we vendor c/detools.{c,h} verbatim. This is detools'
|
||||
official C implementation; MeshCore does not reimplement the delta codec.
|
||||
|
||||
Local modifications
|
||||
-------------------
|
||||
Only the config defaults at the top of detools.h were changed (upstream = 1):
|
||||
DETOOLS_CONFIG_FILE_IO -> 0 (no <stdio> file IO on device)
|
||||
DETOOLS_CONFIG_COMPRESSION_LZMA -> 0 (would need liblzma)
|
||||
DETOOLS_CONFIG_COMPRESSION_HEATSHRINK -> 0 (would need malloc + heatshrink/)
|
||||
DETOOLS_CONFIG_COMPRESSION_NONE = 1 (kept)
|
||||
DETOOLS_CONFIG_COMPRESSION_CRLE = 1 (kept)
|
||||
detools.c is byte-for-byte upstream.
|
||||
|
||||
With this config the decoder is self-contained (no malloc, no liblzma, no
|
||||
heatshrink/, no file IO) and applies `--codec sequential --compression crle`
|
||||
patches, which is what tools/mota produces for MeshCore .mota deltas.
|
||||
|
||||
Usage on device
|
||||
---------------
|
||||
src/helpers/ota/OtaApply.cpp wraps detools_apply_patch_callbacks():
|
||||
from_read/from_seek -> running OTA slot (the delta base, via esp_partition_read)
|
||||
patch_read -> the .mota payload held in RAM (fetched over LoRa)
|
||||
to_write -> inactive OTA slot (via esp_ota_write) + running SHA-256
|
||||
The decoded image is verified against the signed manifest image_hash before the
|
||||
slot is armed as boot partition.
|
||||
|
||||
To update: re-copy c/detools.{c,h} from the pinned detools tag and re-apply the
|
||||
three config-default edits above.
|
||||
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,639 @@
|
||||
/**
|
||||
* BSD 2-Clause License
|
||||
*
|
||||
* Copyright (c) 2019-2020, Erik Moqvist
|
||||
* All rights reserved.
|
||||
*
|
||||
* Redistribution and use in source and binary forms, with or without
|
||||
* modification, are permitted provided that the following conditions are met:
|
||||
*
|
||||
* * Redistributions of source code must retain the above copyright notice, this
|
||||
* list of conditions and the following disclaimer.
|
||||
*
|
||||
* * Redistributions in binary form must reproduce the above copyright notice,
|
||||
* this list of conditions and the following disclaimer in the documentation
|
||||
* and/or other materials provided with the distribution.
|
||||
*
|
||||
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
|
||||
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
|
||||
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
|
||||
* DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
|
||||
* FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
|
||||
* DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
|
||||
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
|
||||
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
|
||||
* OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
|
||||
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
|
||||
*/
|
||||
|
||||
#ifndef DETOOLS_H
|
||||
#define DETOOLS_H
|
||||
|
||||
/*
|
||||
* Configuration.
|
||||
*
|
||||
* Define any of the defines below to 0 to disable given feature.
|
||||
*
|
||||
* MeshCore note: upstream defaults are all 1. We flip FILE_IO, LZMA and
|
||||
* HEATSHRINK off here so this vendored copy is safe-by-default on bare-metal
|
||||
* targets (no liblzma, no malloc/heatshrink, no <stdio> file IO) regardless of
|
||||
* build flags. MeshCore .mota deltas use --codec sequential --compression crle,
|
||||
* which is fully self-contained in detools.c (NONE + CRLE only). Re-enable a
|
||||
* feature by passing -DDETOOLS_CONFIG_..=1. See detools/README.meshcore.txt.
|
||||
*/
|
||||
|
||||
#ifndef DETOOLS_CONFIG_FILE_IO
|
||||
# define DETOOLS_CONFIG_FILE_IO 0
|
||||
#endif
|
||||
|
||||
#ifndef DETOOLS_CONFIG_COMPRESSION_NONE
|
||||
# define DETOOLS_CONFIG_COMPRESSION_NONE 1
|
||||
#endif
|
||||
|
||||
#ifndef DETOOLS_CONFIG_COMPRESSION_LZMA
|
||||
# define DETOOLS_CONFIG_COMPRESSION_LZMA 0
|
||||
#endif
|
||||
|
||||
#ifndef DETOOLS_CONFIG_COMPRESSION_CRLE
|
||||
# define DETOOLS_CONFIG_COMPRESSION_CRLE 1
|
||||
#endif
|
||||
|
||||
#ifndef DETOOLS_CONFIG_COMPRESSION_HEATSHRINK
|
||||
# define DETOOLS_CONFIG_COMPRESSION_HEATSHRINK 0
|
||||
#endif
|
||||
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <stdio.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#define DETOOLS_VERSION "0.53.0"
|
||||
|
||||
/* Error codes. */
|
||||
#define DETOOLS_OK 0
|
||||
#define DETOOLS_NOT_IMPLEMENTED 1
|
||||
#define DETOOLS_NOT_DONE 2
|
||||
#define DETOOLS_BAD_PATCH_TYPE 3
|
||||
#define DETOOLS_BAD_COMPRESSION 4
|
||||
#define DETOOLS_INTERNAL_ERROR 5
|
||||
#define DETOOLS_LZMA_INIT 6
|
||||
#define DETOOLS_LZMA_DECODE 7
|
||||
#define DETOOLS_OUT_OF_MEMORY 8
|
||||
#define DETOOLS_CORRUPT_PATCH 9
|
||||
#define DETOOLS_IO_FAILED 10
|
||||
#define DETOOLS_ALREADY_DONE 11
|
||||
#define DETOOLS_FILE_OPEN_FAILED 12
|
||||
#define DETOOLS_FILE_CLOSE_FAILED 13
|
||||
#define DETOOLS_FILE_READ_FAILED 14
|
||||
#define DETOOLS_FILE_WRITE_FAILED 15
|
||||
#define DETOOLS_FILE_SEEK_FAILED 16
|
||||
#define DETOOLS_FILE_TELL_FAILED 17
|
||||
#define DETOOLS_SHORT_HEADER 18
|
||||
#define DETOOLS_NOT_ENOUGH_PATCH_DATA 19
|
||||
#define DETOOLS_HEATSHRINK_SINK 20
|
||||
#define DETOOLS_HEATSHRINK_POLL 21
|
||||
#define DETOOLS_STEP_SET_FAILED 22
|
||||
#define DETOOLS_STEP_GET_FAILED 23
|
||||
#define DETOOLS_ALREADY_FAILED 24
|
||||
#define DETOOLS_CORRUPT_PATCH_OVERFLOW 25
|
||||
#define DETOOLS_CORRUPT_PATCH_CRLE_KIND 26
|
||||
#define DETOOLS_HEATSHRINK_HEADER 27
|
||||
|
||||
/**
|
||||
* Read callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[out] buf_p Buffer to read into.
|
||||
* @param[in] size Number of bytes to read.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_read_t)(void *arg_p, uint8_t *buf_p, size_t size);
|
||||
|
||||
/**
|
||||
* Write callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] buf_p Buffer to write.
|
||||
* @param[in] size Number of bytes to write.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_write_t)(void *arg_p, const uint8_t *buf_p, size_t size);
|
||||
|
||||
/**
|
||||
* Seek from current position callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] offset Offset to seek to from current position.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_seek_t)(void *arg_p, int offset);
|
||||
|
||||
/**
|
||||
* Memory read callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[out] dst_p Buffer to read into.
|
||||
* @param[in] src Address to read from.
|
||||
* @param[in] size Number of bytes to read.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_mem_read_t)(void *arg_p,
|
||||
void *dst_p,
|
||||
uintptr_t src,
|
||||
size_t size);
|
||||
|
||||
/**
|
||||
* Memory write callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] dst Address to write to.
|
||||
* @param[in] addr src_p Buffer to write from.
|
||||
* @param[in] size Number of bytes to write.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_mem_write_t)(void *arg_p,
|
||||
uintptr_t dst,
|
||||
void *src_p,
|
||||
size_t size);
|
||||
|
||||
/**
|
||||
* Memory erase callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] addr Address to erase from.
|
||||
* @param[in] size Number of bytes to erase.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_mem_erase_t)(void *arg_p, uintptr_t addr, size_t size);
|
||||
|
||||
/**
|
||||
* State read callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[out] buf_p Buffer to read into.
|
||||
* @param[in] size Number of bytes to read.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_state_read_t)(void *arg_p, void *buf_p, size_t size);
|
||||
|
||||
/**
|
||||
* State write callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] buf_p Buffer to write.
|
||||
* @param[in] size Number of bytes to write.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_state_write_t)(void *arg_p, const void *buf_p, size_t size);
|
||||
|
||||
/**
|
||||
* Step set callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[in] step Step to set. Later read by the step get callback.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_step_set_t)(void *arg_p, int step);
|
||||
|
||||
/**
|
||||
* Step get callback.
|
||||
*
|
||||
* @param[in] arg_p User data passed to detools_apply_patch_init().
|
||||
* @param[out] step_p Outputs the most recently set step by the set
|
||||
* callback, or zero(0) if not yet set.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
typedef int (*detools_step_get_t)(void *arg_p, int *step_p);
|
||||
|
||||
struct detools_apply_patch_size_t {
|
||||
int state;
|
||||
int value;
|
||||
int offset;
|
||||
bool is_signed;
|
||||
};
|
||||
|
||||
struct detools_apply_patch_patch_reader_none_t {
|
||||
size_t patch_size;
|
||||
size_t patch_offset;
|
||||
};
|
||||
|
||||
#if DETOOLS_CONFIG_COMPRESSION_LZMA == 1
|
||||
|
||||
#include <lzma.h>
|
||||
|
||||
struct detools_apply_patch_patch_reader_lzma_t {
|
||||
lzma_stream stream;
|
||||
uint8_t *input_p;
|
||||
uint8_t *output_p;
|
||||
size_t output_size;
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
#if DETOOLS_CONFIG_COMPRESSION_HEATSHRINK == 1
|
||||
|
||||
#include "heatshrink_decoder.h"
|
||||
|
||||
struct detools_apply_patch_patch_reader_heatshrink_t {
|
||||
int8_t window_sz2;
|
||||
int8_t lookahead_sz2;
|
||||
heatshrink_decoder *decoder_p;
|
||||
#if HEATSHRINK_DYNAMIC_ALLOC == 0
|
||||
heatshrink_decoder decoder;
|
||||
#endif
|
||||
};
|
||||
|
||||
#endif
|
||||
|
||||
enum detools_unpack_usize_state_t {
|
||||
detools_unpack_usize_state_first_t = 0,
|
||||
detools_unpack_usize_state_consecutive_t
|
||||
};
|
||||
|
||||
struct detools_unpack_usize_t {
|
||||
enum detools_unpack_usize_state_t state;
|
||||
int value;
|
||||
int offset;
|
||||
};
|
||||
|
||||
enum detools_crle_state_t {
|
||||
detools_crle_state_idle_t = 0,
|
||||
detools_crle_state_scattered_size_t,
|
||||
detools_crle_state_scattered_data_t,
|
||||
detools_crle_state_repeated_repetitions_t,
|
||||
detools_crle_state_repeated_data_t,
|
||||
detools_crle_state_repeated_data_read_t
|
||||
};
|
||||
|
||||
struct detools_apply_patch_patch_reader_crle_t {
|
||||
enum detools_crle_state_t state;
|
||||
union {
|
||||
struct {
|
||||
size_t number_of_bytes_left;
|
||||
struct detools_unpack_usize_t size;
|
||||
} scattered;
|
||||
struct {
|
||||
uint8_t value;
|
||||
size_t number_of_bytes_left;
|
||||
struct detools_unpack_usize_t size;
|
||||
} repeated;
|
||||
} kind;
|
||||
};
|
||||
|
||||
struct detools_apply_patch_patch_reader_t {
|
||||
struct detools_apply_patch_chunk_t *patch_chunk_p;
|
||||
struct detools_apply_patch_size_t size;
|
||||
union {
|
||||
#if DETOOLS_CONFIG_COMPRESSION_NONE == 1
|
||||
struct detools_apply_patch_patch_reader_none_t none;
|
||||
#endif
|
||||
#if DETOOLS_CONFIG_COMPRESSION_LZMA == 1
|
||||
struct detools_apply_patch_patch_reader_lzma_t lzma;
|
||||
#endif
|
||||
#if DETOOLS_CONFIG_COMPRESSION_CRLE == 1
|
||||
struct detools_apply_patch_patch_reader_crle_t crle;
|
||||
#endif
|
||||
#if DETOOLS_CONFIG_COMPRESSION_HEATSHRINK == 1
|
||||
struct detools_apply_patch_patch_reader_heatshrink_t heatshrink;
|
||||
#endif
|
||||
} compression;
|
||||
int (*destroy)(struct detools_apply_patch_patch_reader_t *self_p);
|
||||
int (*decompress)(struct detools_apply_patch_patch_reader_t *self_p,
|
||||
uint8_t *buf_p,
|
||||
size_t *size_p);
|
||||
};
|
||||
|
||||
struct detools_apply_patch_chunk_t {
|
||||
const uint8_t *buf_p;
|
||||
size_t size;
|
||||
size_t offset;
|
||||
};
|
||||
|
||||
enum detools_apply_patch_state_t {
|
||||
detools_apply_patch_state_init_t = 0,
|
||||
detools_apply_patch_state_dfpatch_size_t,
|
||||
detools_apply_patch_state_diff_size_t,
|
||||
detools_apply_patch_state_diff_data_t,
|
||||
detools_apply_patch_state_extra_size_t,
|
||||
detools_apply_patch_state_extra_data_t,
|
||||
detools_apply_patch_state_adjustment_t,
|
||||
detools_apply_patch_state_done_t,
|
||||
detools_apply_patch_state_failed_t
|
||||
};
|
||||
|
||||
enum detools_apply_patch_init_state_t {
|
||||
detools_apply_patch_init_state_fixed_header_t = 0,
|
||||
detools_apply_patch_init_state_to_size_t
|
||||
};
|
||||
|
||||
/**
|
||||
* The apply patch data structure.
|
||||
*/
|
||||
struct detools_apply_patch_t {
|
||||
detools_read_t from_read;
|
||||
detools_seek_t from_seek;
|
||||
size_t patch_size;
|
||||
detools_write_t to_write;
|
||||
void *arg_p;
|
||||
enum detools_apply_patch_state_t state;
|
||||
enum detools_apply_patch_init_state_t init_state;
|
||||
int compression;
|
||||
size_t patch_offset;
|
||||
size_t to_offset;
|
||||
size_t to_size;
|
||||
int from_offset;
|
||||
size_t chunk_size;
|
||||
struct detools_apply_patch_patch_reader_t patch_reader;
|
||||
struct detools_apply_patch_chunk_t chunk;
|
||||
struct detools_apply_patch_size_t size;
|
||||
};
|
||||
|
||||
enum detools_apply_patch_in_place_init_state_t {
|
||||
detools_apply_patch_in_place_init_state_fixed_header_t = 0,
|
||||
detools_apply_patch_in_place_init_state_memory_size_t,
|
||||
detools_apply_patch_in_place_init_state_segment_size_t,
|
||||
detools_apply_patch_in_place_init_state_shift_size_t,
|
||||
detools_apply_patch_in_place_init_state_from_size_t,
|
||||
detools_apply_patch_in_place_init_state_to_size_t
|
||||
};
|
||||
|
||||
/**
|
||||
* The in-place apply patch data structure.
|
||||
*/
|
||||
struct detools_apply_patch_in_place_t {
|
||||
detools_mem_read_t mem_read;
|
||||
detools_mem_write_t mem_write;
|
||||
detools_mem_erase_t mem_erase;
|
||||
detools_step_set_t step_set;
|
||||
detools_step_get_t step_get;
|
||||
size_t patch_size;
|
||||
void *arg_p;
|
||||
enum detools_apply_patch_state_t state;
|
||||
enum detools_apply_patch_in_place_init_state_t init_state;
|
||||
int compression;
|
||||
int ongoing_step;
|
||||
size_t to_pos;
|
||||
size_t to_size;
|
||||
size_t from_size;
|
||||
size_t memory_size;
|
||||
size_t segment_size;
|
||||
size_t shift_size;
|
||||
size_t chunk_size;
|
||||
struct {
|
||||
size_t index;
|
||||
int from_offset;
|
||||
size_t to_offset;
|
||||
size_t to_size;
|
||||
size_t to_pos;
|
||||
} segment;
|
||||
struct detools_apply_patch_patch_reader_t patch_reader;
|
||||
struct detools_apply_patch_chunk_t chunk;
|
||||
struct detools_apply_patch_size_t size;
|
||||
};
|
||||
|
||||
/**
|
||||
* Initialize given apply patch object.
|
||||
*
|
||||
* @param[out] self_p Apply patch object to initialize.
|
||||
* @param[in] from_read Callback to read from-data.
|
||||
* @param[in] from_seek Callback to seek from current position in from-data.
|
||||
* @param[in] patch_size Patch size in bytes. Not used if
|
||||
* `detools_apply_patch_restore()` is called
|
||||
* immediately after this function.
|
||||
* @param[in] to_write Destination callback.
|
||||
* @param[in] arg_p Argument passed to the callbacks.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_init(struct detools_apply_patch_t *self_p,
|
||||
detools_read_t from_read,
|
||||
detools_seek_t from_seek,
|
||||
size_t patch_size,
|
||||
detools_write_t to_write,
|
||||
void *arg_p);
|
||||
|
||||
/**
|
||||
* Dump given apply patch object state. Call
|
||||
* `detools_apply_patch_restore()` to restore an apply patch object to
|
||||
* the dumped state.
|
||||
*
|
||||
* @param[in] self_p Apply patch object to dump.
|
||||
* @param[in] write Write callback.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_dump(struct detools_apply_patch_t *self_p,
|
||||
detools_state_write_t state_write);
|
||||
|
||||
/**
|
||||
* Restore given apply patch object to given dumped
|
||||
* state.
|
||||
*
|
||||
* `detools_apply_patch_get_to_offset()` and
|
||||
* `detools_apply_patch_get_patch_offset()` are often called after
|
||||
* this function to restore the to and patch streams.
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object to restore.
|
||||
* @param[in] read Callback to read the dumped state.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_restore(struct detools_apply_patch_t *self_p,
|
||||
detools_state_read_t state_read);
|
||||
|
||||
/**
|
||||
* Get the current to stream offset. Often used to restore the to
|
||||
* stream after restore.
|
||||
*
|
||||
* @param[in] self_p Apply patch object.
|
||||
*
|
||||
* @return The current to stream offset.
|
||||
*/
|
||||
size_t detools_apply_patch_get_to_offset(struct detools_apply_patch_t *self_p);
|
||||
|
||||
/**
|
||||
* Get the current patch stream offset. Often used to restore the
|
||||
* patch stream after restore.
|
||||
*
|
||||
* @param[in] self_p Apply patch object.
|
||||
*
|
||||
* @return The current patch stream offset.
|
||||
*/
|
||||
size_t detools_apply_patch_get_patch_offset(struct detools_apply_patch_t *self_p);
|
||||
|
||||
/**
|
||||
* Call this function repeatedly until all patch data has been
|
||||
* processed or an error occurres. Call detools_apply_patch_finalize()
|
||||
* to finalize the patching, even if an error occurred.
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object.
|
||||
* @param[in] patch_p Next chunk of the patch.
|
||||
* @param[in] size Patch buffer size.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_process(struct detools_apply_patch_t *self_p,
|
||||
const uint8_t *patch_p,
|
||||
size_t size);
|
||||
|
||||
/**
|
||||
* Call once after all data has been processed to finalize the
|
||||
* patching. The value returned from this function should be ignored
|
||||
* if an error occurred in detools_apply_patch_process().
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object.
|
||||
*
|
||||
* @return Size of to-data in bytes if the patch was applied
|
||||
* successfully, or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_finalize(struct detools_apply_patch_t *self_p);
|
||||
|
||||
/**
|
||||
* Initialize given in-place apply patch object.
|
||||
*
|
||||
* @param[out] self_p In-place apply patch object to initialize.
|
||||
* @param[in] mem_read Callback to read data.
|
||||
* @param[in] mem_write Callback to write data.
|
||||
* @param[in] mem_erase Callback to erase data.
|
||||
* @param[in] step_set Callback to set the step.
|
||||
* @param[in] step_get Callback to get the step.
|
||||
* @param[in] patch_size Patch size in bytes.
|
||||
* @param[in] arg_p Argument passed to the callbacks.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_init(
|
||||
struct detools_apply_patch_in_place_t *self_p,
|
||||
detools_mem_read_t mem_read,
|
||||
detools_mem_write_t mem_write,
|
||||
detools_mem_erase_t mem_erase,
|
||||
detools_step_set_t step_set,
|
||||
detools_step_get_t step_get,
|
||||
size_t patch_size,
|
||||
void *arg_p);
|
||||
|
||||
/**
|
||||
* Call this function repeatedly until all patch data has been
|
||||
* processed or an error occurres. Call
|
||||
* detools_apply_patch_in_place_finalize() to finalize the patching,
|
||||
* even if an error occurred.
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object.
|
||||
* @param[in] patch_p Next chunk of the patch.
|
||||
* @param[in] size Patch buffer size.
|
||||
*
|
||||
* @return zero(0) or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_process(
|
||||
struct detools_apply_patch_in_place_t *self_p,
|
||||
const uint8_t *patch_p,
|
||||
size_t size);
|
||||
|
||||
/**
|
||||
* Call once after all data has been processed to finalize the
|
||||
* patching. The value returned from this function should be ignored
|
||||
* if an error occurred in detools_apply_patch_in_place_process().
|
||||
*
|
||||
* @param[in,out] self_p Initialized apply patch object.
|
||||
*
|
||||
* @return Size of to-data in bytes if the patch was applied
|
||||
* successfully, or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_finalize(
|
||||
struct detools_apply_patch_in_place_t *self_p);
|
||||
|
||||
/**
|
||||
* Apply given patch using read, write and seek callbacks.
|
||||
*
|
||||
* @param[in] from_read Source read callback.
|
||||
* @param[in] from_seek Source seek callback.
|
||||
* @param[in] patch_read Patch read callback.
|
||||
* @param[in] patch_size Patch size in bytes.
|
||||
* @param[in] to_write Destination write callback.
|
||||
* @param[in] arg_p Argument passed to all callbacks.
|
||||
*
|
||||
* @return Size of to-data in bytes or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_callbacks(detools_read_t from_read,
|
||||
detools_seek_t from_seek,
|
||||
detools_read_t patch_read,
|
||||
size_t patch_size,
|
||||
detools_write_t to_write,
|
||||
void *arg_p);
|
||||
|
||||
/**
|
||||
* Apply given in-place patch using read, write and erase callbacks.
|
||||
*
|
||||
* @param[in] mem_read Callback to read data.
|
||||
* @param[in] mem_write Callback to write data.
|
||||
* @param[in] mem_erase Callback to erase data.
|
||||
* @param[in] step_set Callback to set the step.
|
||||
* @param[in] step_get Callback to get the step.
|
||||
* @param[in] patch_read Patch read callback.
|
||||
* @param[in] patch_size Patch size in bytes.
|
||||
* @param[in] arg_p Argument passed to the callbacks.
|
||||
*
|
||||
* @return Size of to-data in bytes or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_callbacks(detools_mem_read_t mem_read,
|
||||
detools_mem_write_t mem_write,
|
||||
detools_mem_erase_t mem_erase,
|
||||
detools_step_set_t step_set,
|
||||
detools_step_get_t step_get,
|
||||
detools_read_t patch_read,
|
||||
size_t patch_size,
|
||||
void *arg_p);
|
||||
|
||||
#if DETOOLS_CONFIG_FILE_IO == 1
|
||||
|
||||
/**
|
||||
* Apply given patch file to given from file and write the output to
|
||||
* given to file.
|
||||
*
|
||||
* @param[in] from_p Source file name.
|
||||
* @param[in] patch_p Patch file name.
|
||||
* @param[in] to_p Destination file name.
|
||||
*
|
||||
* @return Size of to-data in bytes or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_filenames(const char *from_p,
|
||||
const char *patch_p,
|
||||
const char *to_p);
|
||||
|
||||
/**
|
||||
* Apply given patch file to given memory file.
|
||||
*
|
||||
* @param[in] memory_p Memory file name.
|
||||
* @param[in] patch_p Patch file name.
|
||||
* @param[in] step_set Callback to set the step.
|
||||
* @param[in] step_get Callback to get the step.
|
||||
*
|
||||
* @return Size of to-data in bytes or negative error code.
|
||||
*/
|
||||
int detools_apply_patch_in_place_filenames(const char *memory_p,
|
||||
const char *patch_p,
|
||||
detools_step_set_t step_set,
|
||||
detools_step_get_t step_get);
|
||||
|
||||
#endif
|
||||
|
||||
/**
|
||||
* Get the error string for given error code.
|
||||
*
|
||||
* @param[in] Error code.
|
||||
*
|
||||
* @return Error string.
|
||||
*/
|
||||
const char *detools_error_as_string(int error);
|
||||
|
||||
#endif
|
||||
Reference in new issue
Block a user