diff --git a/README.md b/README.md index a0dfe08c..8e29340d 100644 --- a/README.md +++ b/README.md @@ -1,7 +1,7 @@ # MeshCore β€” Repeater Firmware with a Remote-Configurable Packet Filter This is a feature fork of [MeshCore](https://github.com/meshcore-dev/MeshCore). -It tracks upstream `main` releases and adds seven repeater-focused capabilities +It tracks upstream `main` releases and adds eight repeater-focused capabilities on top of stock firmware. Everything else β€” supported boards, clients, protocols, build system β€” is identical to upstream; see the @@ -110,6 +110,23 @@ bounded best-effort queue that rides out broker outages. β†’ Full guide, including the build targets, broker setup, CLI reference, and the message schema: **[MQTT_OBSERVER.md](./MQTT_OBSERVER.md)** +### πŸ“² LoRa OTA + +Over-the-air firmware updates for ESP32 repeaters: the update rides the +existing mesh as zero-hop or explicit-path DIRECT packets (never flooded), the +image is staged into the inactive A/B app slot and verified byte-for-byte +against the contract's SHA-256 before anything is applied, and a freshly +applied image re-verifies itself at boot β€” on any failure it flips back to +the previous firmware automatically. Unchanged bytes are sent as copy ops, so +release-to-release updates are a fraction of a full image. The node side is a +receive contract and a verifier; an Android app drives the transfer. Stock +relays in the path need no changes. `ota status` is the progress feed; +`ota abort` discards a session, `ota rollback` flips back manually. + +Boards without a dual app partition and non-ESP32 builds report the feature +unsupported. The OTA wire format and `ota status` layout are frozen in the +M0 milestone of the plan. + ## Why run this instead of stock repeater firmware? Stock repeaters forward everything they hear, until the battery dies. This diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 867f37b8..658ac343 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -449,7 +449,11 @@ bool MyMesh::allowPacketForward(const mesh::Packet *packet) { // only when the filter is enabled; with `filter off` nothing about the // receive path is spent on it (the value would never be read). const uint32_t filter_air_ms = filter.isEnabled() ? _radio->getEstAirtimeFor(packet->getRawLength()) : 0; - if (filter.checkPacket(packet, millis(), recv_pkt_region, filter_air_ms) == FILTER_ACT_DROP) return false; // packet filter rules + advert rate limiter + // OTA op packets (payload magic 'O','T') must never be dropped by a filter + // rule: a type=raw rule anywhere in the path would sever an update in + // transit. The battery gate and the stock checks still apply. + if (!otaIsOtaPacket(packet) + && filter.checkPacket(packet, millis(), recv_pkt_region, filter_air_ms) == FILTER_ACT_DROP) return false; // packet filter rules + advert rate limiter if (_prefs.disable_fwd) return false; if (packet->isRouteFlood() && mesh::isFloodHopLimitExceeded(packet, _prefs.flood_max, _prefs.flood_max_unscoped, _prefs.flood_max_advert)) { @@ -584,6 +588,7 @@ void MyMesh::logTx(mesh::Packet *pkt, int len) { bridge.sendPacket(pkt); } #endif + ota.onTxResult(pkt, true); if (_logging) { File f = openAppend(PACKET_LOG_FILE); @@ -604,6 +609,7 @@ void MyMesh::logTx(mesh::Packet *pkt, int len) { } void MyMesh::logTxFail(mesh::Packet *pkt, int len) { + ota.onTxResult(pkt, false); if (_logging) { File f = openAppend(PACKET_LOG_FILE); if (f) { @@ -981,6 +987,13 @@ void MyMesh::onControlDataRecv(mesh::Packet* packet) { } } +// OTA op packets (payload magic 'O','T') ride DIRECT raw-custom payloads; +// anything that is not a valid OTA frame is inert. The node arms only via +// OP_START, so a stray packet from a stranger configures nothing. +void MyMesh::onRawDataRecv(mesh::Packet* packet) { + ota.onPacket(packet); +} + void MyMesh::sendNodeDiscoverReq() { uint8_t data[10]; data[0] = CTL_TYPE_NODE_DISCOVER_REQ; // prefix_only=0 @@ -1164,6 +1177,25 @@ void MyMesh::mqttStatusStats(void* context, MQTTObserverFormat::StatusStats& sta } #endif +// OTA replies are originated here: zero-hop, or DIRECT along the return path +// the app supplied in OP_START. A RAW_CUSTOM payload carries no sender +// identity, so this is the only route back to the app. +static bool otaSend(void* ctx, const uint8_t* payload, size_t len, + const uint8_t* ret_path, uint8_t ret_path_len) { + MyMesh* m = (MyMesh*)ctx; + mesh::Packet* pkt = m->obtainNewPacket(); + if (!pkt) return false; + pkt->header = (PAYLOAD_TYPE_RAW_CUSTOM << PH_TYPE_SHIFT); + pkt->payload_len = (uint16_t)len; + memcpy(pkt->payload, payload, len); + if (ret_path_len != 0) { + m->sendDirect(pkt, ret_path, ret_path_len); + } else { + m->sendZeroHop(pkt, (uint32_t)0); + } + return true; +} + void MyMesh::begin(FILESYSTEM *fs) { mesh::Mesh::begin(); _fs = fs; @@ -1178,6 +1210,8 @@ void MyMesh::begin(FILESYSTEM *fs) { acl.load(_fs, self_id); filter.begin(fs); battGate.begin(fs); + ota.begin(fs, &battGate, &board, FIRMWARE_VERSION); + ota.setSender(otaSend, this); fleet.setClock(fleetClock, this); fleet.setJitter(fleetJitter, this); fleet.setNameProvider(fleetNodeName, this); @@ -1589,6 +1623,10 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply // radio.rxps and radio2 are mutually exclusive; turning RXPS off stays // available so the operator can recover, and `get radio.rxps` is read-only. strcpy(reply, "Err - radio2 is on; set radio2 off first"); + } else if (memcmp(command, "ota", 3) == 0 && (command[3] == ' ' || command[3] == 0)) { + const char* sub = command + 3; + while (*sub == ' ') sub++; + otaCLI(ota, sub, reply); } else if (memcmp(command, "clock mesh", 10) == 0 && (command[10] == 0 || command[10] == ' ')) { // before the common CLI's bare "clock" prefix match, which would swallow it char now[32]; @@ -1623,6 +1661,8 @@ void MyMesh::loop() { // One sample per interval, not one per packet. battGate.loop(_fs, board); batteryAlerts(battGate, fleet); + // OTA boot health check (only active right after a freshly-applied boot) + ota.loop(); mesh::Mesh::loop(); diff --git a/examples/simple_repeater/MyMesh.h b/examples/simple_repeater/MyMesh.h index 1f781112..06f67338 100644 --- a/examples/simple_repeater/MyMesh.h +++ b/examples/simple_repeater/MyMesh.h @@ -41,6 +41,7 @@ #include "FleetManager.h" #include "MeshClockSync.h" #include "Radio2.h" +#include "OtaUpdate.h" #ifdef WITH_MQTT_OBSERVER #include "../mqtt_observer/MQTTObserver.h" #endif @@ -125,6 +126,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks { BatteryGate battGate; FleetManager fleet; MeshClockSync meshClock; + OtaUpdate ota; Radio2DeviceImpl radio2_device; Radio2 radio2; bool rx_forward_allowed = true; @@ -212,6 +214,7 @@ protected: void onPeerDataRecv(mesh::Packet* packet, uint8_t type, int sender_idx, const uint8_t* secret, uint8_t* data, size_t len) override; bool onPeerPathRecv(mesh::Packet* packet, int sender_idx, const uint8_t* secret, uint8_t* path, uint8_t path_len, uint8_t extra_type, uint8_t* extra, uint8_t extra_len) override; void onControlDataRecv(mesh::Packet* packet) override; + void onRawDataRecv(mesh::Packet* packet) override; void sendFloodReply(mesh::Packet* packet, unsigned long delay_millis, uint8_t path_hash_size); diff --git a/examples/simple_repeater/OtaUpdate.cpp b/examples/simple_repeater/OtaUpdate.cpp new file mode 100644 index 00000000..5f674c3f --- /dev/null +++ b/examples/simple_repeater/OtaUpdate.cpp @@ -0,0 +1,638 @@ +// OtaUpdate.cpp β€” the LoRa OTA engine for the ESP32 simple_repeater firmware. +// See OtaUpdate.h for the wire format, the op semantics, the /ota_pend boot +// health record, and the CLI contract. Personal fork feature; fork-owned. + +#include "OtaUpdate.h" + +#include +#include +#include + +#include "BatteryGate.h" +#include "CliUtil.h" + +#if defined(ESP32) +#include +#endif + +#include + +#define OTA_USAGE "Usage: ota [status|stage |apply|abort|rollback]" + +static uint16_t le16(const uint8_t* p) { return (uint16_t)p[0] | ((uint16_t)p[1] << 8); } +static uint32_t le32(const uint8_t* p) { + return (uint32_t)p[0] | ((uint32_t)p[1] << 8) | ((uint32_t)p[2] << 16) | ((uint32_t)p[3] << 24); +} + +// ------------------------------------------------------------------ slot io + +#if defined(ESP32) + +// The only code in this file that knows about partitions. Wraps esp_ota_* and +// the Arduino FILESYSTEM-facing calls; everything else is flash-agnostic and +// host-tested against a fake. +class Esp32SlotIo : public OtaSlotIo { + const esp_partition_t* _inactive = esp_ota_get_next_update_partition(nullptr); + const esp_partition_t* _running = esp_ota_get_running_partition(); + esp_ota_handle_t _handle = 0; + bool _begun = false; + +public: + Esp32SlotIo() = default; // ctor is trivial; partitions are looked up statically + + uint32_t slotSize() const override { return _inactive ? _inactive->size : 0; } + uint32_t sourceSize() const override { return _running ? _running->size : 0; } + + bool beginWrite(uint32_t image_size) override { + _begun = false; + if (_inactive == nullptr) return false; + if (esp_ota_begin(_inactive, image_size, &_handle) != ESP_OK) { + _handle = 0; + return false; + } + _begun = true; + return true; + } + bool append(const uint8_t* data, size_t len) override { + return esp_ota_write(_handle, data, len) == ESP_OK; + } + bool readSource(uint32_t off, uint8_t* out, size_t len) override { + return _running != nullptr && esp_partition_read(_running, off, out, len) == ESP_OK; + } + bool readStaged(uint32_t off, uint8_t* out, size_t len) override { + return _inactive != nullptr && esp_partition_read(_inactive, off, out, len) == ESP_OK; + } + bool endWrite() override { + if (!_begun) return false; + bool ok = esp_ota_end(_handle) == ESP_OK; + _handle = 0; + _begun = false; + return ok; + } + void abortWrite() override { + if (_handle != 0) { + esp_ota_abort(_handle); + _handle = 0; + } + _begun = false; + } + bool setInactiveAsBoot() override { + return _inactive != nullptr && esp_ota_set_boot_partition(_inactive) == ESP_OK; + } +}; + +#endif // ESP32 + +// SHA-256 over `size` bytes of one slot, read in 1 KB slices. The layered +// helper is shared by OP_END verification and the boot health check. +static bool hashSlot(OtaSlotIo* io, bool staged, uint32_t size, uint8_t out[32]) { + SHA256 sha; + uint8_t buf[1024]; + uint32_t off = 0; + while (off < size) { + size_t n = size - off < sizeof(buf) ? size - off : sizeof(buf); + if (staged ? !io->readStaged(off, buf, n) : !io->readSource(off, buf, n)) return false; + sha.update(buf, n); + off += n; + } + sha.finalize(out, 32); + return true; +} + +// --------------------------------------------------------------- session + +OtaUpdate::OtaUpdate() = default; +OtaUpdate::~OtaUpdate() { resetSession(); } + +void OtaUpdate::begin(FILESYSTEM* fs, BatteryGate* gate, mesh::MainBoard* board, const char* firmware_version) { + _fs = fs; + _gate = gate; + _board = board; + _version = firmware_version ? firmware_version : ""; + +#if defined(ESP32) + if (_io == nullptr) _io = new Esp32SlotIo(); // lives for the board's lifetime +#endif + + uint8_t state; + uint32_t size; + uint8_t sha[32]; + if (readPend(&state, &size, sha)) { + if (state == OTA_PEND_PENDING) { + // A freshly-applied image is booting: verify + probe before declaring health. + _health_pending = true; + _health_size = size; + _health_nonce = ((uint32_t)sha[0] << 8) | sha[1]; + memcpy(_health_sha, sha, 32); + } else if (state == OTA_PEND_ROLLED) { + _rolledback = true; + } + } +} + +void OtaUpdate::loop() { + if (_health_checked) { + // wrap-safe deadline test: passed once elapsed millis lands in the positive u32 half + if (_health_pending && (uint32_t)(millis() - _health_deadline) < 0x80000000u) { + rollbackToPrevious("health timeout"); + } + return; + } + _health_checked = true; + if (!_health_pending) return; + + uint8_t sha[32]; + if (_io == nullptr || !hashSlot(_io, /*staged=*/false, _health_size, sha) || + memcmp(sha, _health_sha, 32) != 0) { + rollbackToPrevious("health slot digest mismatch"); + return; + } + if (sendHealthProbe()) { + _health_sent = true; + _health_deadline = millis() + kHealthTimeoutMs; + } else { + rollbackToPrevious("health probe not sent"); + } +} + +void OtaUpdate::onTxResult(const mesh::Packet* pkt, bool ok) { + if (!_health_pending || !_health_sent) return; + if (pkt == nullptr || pkt->payload_len != OTA_HEALTH_LEN) return; + if (pkt->payload[0] != OTA_MAGIC0 || pkt->payload[1] != OTA_MAGIC1 || pkt->payload[2] != OTA_OP_NOP) return; + if (le16(pkt->payload + 3) != (uint16_t)(_health_nonce & 0xFFFF)) return; + if (ok) { + deletePend(); + _health_pending = false; + } else { + rollbackToPrevious("health probe tx failed"); + } +} + +void OtaUpdate::resetSession() { + if (_io != nullptr) _io->abortWrite(); + delete[] _slots; + _slots = nullptr; + _state = State::Idle; + _err = OTA_ERR_NONE; + _size = 0; + _written = 0; + _expect = 1; + _arrived = 0; + _ret_path_len = 0; +} + +void OtaUpdate::abortStaging(uint8_t err) { + MESH_DEBUG_PRINTLN("ota: staging aborted (err=%u)", err); + resetSession(); + _state = State::Error; + _err = err; +} + +bool OtaUpdate::armSession(uint32_t size, const uint8_t sha[32], + const uint8_t* ret_path, uint8_t ret_path_len) { + if (_state != State::Idle) return false; // a busy session keeps its place + if (_io == nullptr) { _err = OTA_ERR_SLOT; return false; } + if (_gate != nullptr && _gate->isSuspended()) { + _err = OTA_ERR_BATTERY; + return false; + } + if (size == 0 || size > _io->slotSize()) { + _err = OTA_ERR_SLOT; + return false; + } + _slots = new (std::nothrow) WindowSlot[OTA_WINDOW]; + if (_slots == nullptr) { + _err = OTA_ERR_IO; + return false; + } + if (!_io->beginWrite(size)) { + delete[] _slots; + _slots = nullptr; + _err = OTA_ERR_IO; + return false; + } + _size = size; + _written = 0; + _expect = 1; + _arrived = 0; + memcpy(_expected_sha, sha, 32); + _ret_path_len = ret_path_len; + if (ret_path_len != 0 && ret_path != nullptr) { + memcpy(_ret_path, ret_path, (ret_path_len & 63) * ((ret_path_len >> 6) + 1)); + } + _state = State::Staging; + _err = OTA_ERR_NONE; + return true; +} + +uint32_t OtaUpdate::ownTargetId() const { +#if defined(OTA_PIO_ENV) + static uint32_t id = 0; + if (id == 0) { + uint8_t hash[4]; + mesh::Utils::sha256(hash, 4, (const uint8_t*)OTA_PIO_ENV, (int)strlen(OTA_PIO_ENV)); + id = le32(hash); + } + return id; +#else + return 0; +#endif +} + +void OtaUpdate::onPacket(const mesh::Packet* pkt) { + if (!otaIsOtaPacket(pkt)) return; + const uint8_t* payload = pkt->payload; + const size_t n = pkt->payload_len; + + uint16_t stored_crc = le16(payload + n - 2); + if (crc16_ccitt(payload, n - 2) != stored_crc) return; // bad CRC: drop + + const uint8_t op = payload[2]; + const uint16_t seq = le16(payload + 3); + const uint8_t* body = payload + 5; + const uint16_t body_len = (uint16_t)(n - OTA_FRAME_OVERHEAD); + + if (_io == nullptr) return; // not an ESP32 (or slot lookup failed): inert + + switch (op) { + case OTA_OP_NOP: + case OTA_OP_REPORT: + return; + case OTA_OP_START: + if (seq != 0) return; // OP_START is always seq 0 + handleStart(body, body_len); + return; + case OTA_OP_ASK: + if (stagingArmed()) sendReport(seq); + return; + default: + break; + } + if (!stagingArmed() || _slots == nullptr) return; + + int32_t d = (int32_t)(int16_t)(seq - _expect); // modular: handles the u16 wrap + if (d < 0) return; // already applied / future window overflow + if (d >= OTA_WINDOW) return; // beyond the window: drop + _slots[d].len = (uint16_t)(body_len + 1); + _slots[d].data[0] = op; + memcpy(_slots[d].data + 1, body, body_len); + _arrived |= (uint16_t)(1u << d); + drainWindow(); +} + +void OtaUpdate::handleStart(const uint8_t* body, uint16_t len) { + if (len < OTA_OP_START_MIN || len > OTA_OP_START_MIN + MAX_PATH_SIZE) { _err = OTA_ERR_BOUNDS; return; } + uint32_t size = le32(body); + const uint8_t* sha = body + 4; + uint32_t target_id = le32(body + 36); + uint8_t ret_path_len = body[44]; + if (ret_path_len != 0) { + if (!mesh::Packet::isValidPathLen(ret_path_len)) { _err = OTA_ERR_BOUNDS; return; } + uint16_t path_bytes = (uint16_t)((ret_path_len & 63) * ((ret_path_len >> 6) + 1)); + if (len != OTA_OP_START_MIN + path_bytes) { _err = OTA_ERR_BOUNDS; return; } + } else if (len != OTA_OP_START_MIN) { + _err = OTA_ERR_BOUNDS; + return; + } + if (target_id != ownTargetId()) { _err = OTA_ERR_TARGET; return; } + + // fw (body+40) is opaque to the node β€” carried for the app, not used here + armSession(size, sha, body + OTA_OP_START_MIN, ret_path_len); +} + +void OtaUpdate::drainWindow() { + while (_slots != nullptr && (_arrived & 1)) { + WindowSlot slot = _slots[0]; + applyOp(slot.data + 1, (uint16_t)(slot.len - 1), slot.data[0]); + if (_slots == nullptr) return; // session ended inside applyOp + _arrived >>= 1; + memmove(_slots, _slots + 1, (OTA_WINDOW - 1) * sizeof(WindowSlot)); + _expect++; + if (_state != State::Staging) return; + } +} + +void OtaUpdate::applyOp(const uint8_t* body, uint16_t body_len, uint8_t op) { + switch (op) { + case OTA_OP_COPY: + if (body_len != 6) { abortStaging(OTA_ERR_BOUNDS); return; } + applyCopy(le32(body), le16(body + 4)); + return; + case OTA_OP_LITERAL: { + if (body_len < 2) { abortStaging(OTA_ERR_BOUNDS); return; } + uint16_t dlen = le16(body); + if (body_len != (uint16_t)(2 + dlen)) { abortStaging(OTA_ERR_BOUNDS); return; } + applyLiteral(body + 2, dlen); + return; + } + case OTA_OP_END: + if (body_len != 0) { abortStaging(OTA_ERR_BOUNDS); return; } + if (_written != _size) { abortStaging(OTA_ERR_BOUNDS); return; } + { + uint8_t sha[32]; + if (!hashSlot(_io, /*staged=*/true, _size, sha) || memcmp(sha, _expected_sha, 32) != 0) { + abortStaging(OTA_ERR_SHA); + return; + } + if (!_io->endWrite()) { abortStaging(OTA_ERR_END); return; } + } + delete[] _slots; + _slots = nullptr; + _arrived = 0; + _state = State::Ready; + return; + default: + abortStaging(OTA_ERR_BOUNDS); // unknown op in a committed window + return; + } +} + +bool OtaUpdate::applyCopy(uint32_t base_off, uint16_t len) { + if ((uint64_t)base_off + len > _io->sourceSize() || (uint64_t)_written + len > _size) { + abortStaging(OTA_ERR_BOUNDS); + return false; + } + uint8_t buf[256]; + uint32_t off = 0; + while (off < len) { + size_t n = (size_t)(len - off) < sizeof(buf) ? (size_t)(len - off) : sizeof(buf); + if (!_io->readSource(base_off + off, buf, n)) { abortStaging(OTA_ERR_IO); return false; } + if (!_io->append(buf, n)) { abortStaging(OTA_ERR_IO); return false; } + off += (uint32_t)n; + } + _written += len; + return true; +} + +bool OtaUpdate::applyLiteral(const uint8_t* data, uint16_t len) { + if ((uint64_t)_written + len > _size) { abortStaging(OTA_ERR_BOUNDS); return false; } + if (!_io->append(data, len)) { abortStaging(OTA_ERR_IO); return false; } + _written += len; + return true; +} + +void OtaUpdate::sendReport(uint16_t ask_seq) { + uint8_t p[12]; + p[0] = OTA_MAGIC0; + p[1] = OTA_MAGIC1; + p[2] = OTA_OP_REPORT; + p[3] = (uint8_t)(ask_seq & 0xFF); + p[4] = (uint8_t)(ask_seq >> 8); + p[5] = (uint8_t)(_expect & 0xFF); + p[6] = (uint8_t)(_expect >> 8); + uint16_t gaps = (uint16_t)~_arrived; // bit i = seq expect+i never arrived + p[7] = (uint8_t)(gaps & 0xFF); + p[8] = (uint8_t)(gaps >> 8); + uint16_t crc = crc16_ccitt(p, 10); + p[10] = (uint8_t)(crc & 0xFF); + p[11] = (uint8_t)(crc >> 8); + if (_send != nullptr) { + _send(_send_ctx, p, sizeof(p), _ret_path_len != 0 ? _ret_path : nullptr, _ret_path_len); + } +} + +bool OtaUpdate::sendHealthProbe() { + uint8_t p[OTA_HEALTH_LEN] = {OTA_MAGIC0, OTA_MAGIC1, OTA_OP_NOP, + (uint8_t)(_health_nonce & 0xFF), (uint8_t)(_health_nonce >> 8)}; + uint16_t crc = crc16_ccitt(p, OTA_HEALTH_LEN - 2); + p[5] = (uint8_t)(crc & 0xFF); + p[6] = (uint8_t)(crc >> 8); + return _send != nullptr && _send(_send_ctx, p, sizeof(p), nullptr, 0); +} + +// ------------------------------------------------------------------ /ota_pend + +#define OTA_PEND_MAGIC "OTAP" +#define OTA_PEND_VERSION 1 +// magic(4) ver(1) state(1) size(4) sha256(32) crc16(2) +#define OTA_PEND_SIZE 44 + +bool OtaUpdate::writePendRecord(uint8_t state, uint32_t size, const uint8_t sha[32]) { + if (_fs == nullptr) return false; + uint8_t rec[OTA_PEND_SIZE]; + memcpy(rec, OTA_PEND_MAGIC, 4); + rec[4] = OTA_PEND_VERSION; + rec[5] = state; + for (int i = 0; i < 4; i++) rec[6 + i] = (uint8_t)(size >> (8 * i)); + memcpy(rec + 10, sha, 32); + uint16_t crc = crc16_ccitt(rec, OTA_PEND_SIZE - 2); + rec[42] = (uint8_t)(crc & 0xFF); + rec[43] = (uint8_t)(crc >> 8); + + File f = fsOpenWrite(_fs, OTA_PEND_FILE); + if (!f) return false; + size_t n = f.write(rec, sizeof(rec)); + f.flush(); + f.close(); + if (n != sizeof(rec)) { _fs->remove(OTA_PEND_FILE); return false; } + + + // read back before it is allowed to gate anything + uint8_t back_state; + uint32_t back_size; + uint8_t back_sha[32]; + if (!readPend(&back_state, &back_size, back_sha)) return false; + return back_state == state && back_size == size && memcmp(back_sha, sha, 32) == 0; +} + +bool OtaUpdate::readPend(uint8_t* state, uint32_t* size, uint8_t sha[32]) { + if (_fs == nullptr || !_fs->exists(OTA_PEND_FILE)) return false; + File f = fsOpenRead(_fs, OTA_PEND_FILE); + if (!f) return false; + uint8_t rec[OTA_PEND_SIZE]; + size_t n = f.read(rec, sizeof(rec)); + f.close(); + if (n != sizeof(rec)) return false; + if (memcmp(rec, OTA_PEND_MAGIC, 4) != 0) return false; + if (rec[4] != OTA_PEND_VERSION) return false; + uint16_t stored = (uint16_t)rec[42] | ((uint16_t)rec[43] << 8); + if (crc16_ccitt(rec, OTA_PEND_SIZE - 2) != stored) return false; + *state = rec[5]; + *size = le32(rec + 6); + memcpy(sha, rec + 10, 32); + return true; +} + +void OtaUpdate::deletePend() { + if (_fs != nullptr && _fs->exists(OTA_PEND_FILE)) _fs->remove(OTA_PEND_FILE); +} + +void OtaUpdate::rollbackToPrevious(const char* why) { + MESH_DEBUG_PRINTLN("ota: %s; rolling back", why); + writePendRecord(OTA_PEND_ROLLED, _health_size, _health_sha); // best-effort marker + _health_pending = false; + if (_io != nullptr && _io->setInactiveAsBoot() && _board != nullptr) { + _board->reboot(); + } +} + +// --------------------------------------------------------------------- CLI + +void OtaUpdate::formatStatus(char* reply, size_t reply_size) { + if (_io == nullptr) { + snprintf(reply, reply_size, "running=%s sha=0000000000000000 state=unsupported size=0 off=0 err=0 rolledback=%d", + _version, _rolledback ? 1 : 0); + return; + } + if (!_running_sha_valid) { + memset(_running_sha, 0, sizeof(_running_sha)); + hashSlot(_io, /*staged=*/false, _io->sourceSize(), _running_sha); + _running_sha_valid = true; + } + const char* state_name = _state == State::Staging ? "staging" + : _state == State::Ready ? "ready" + : _state == State::Error ? "error" : "idle"; + char sha16[17]; + for (int i = 0; i < 8; i++) snprintf(sha16 + i * 2, 3, "%02x", _running_sha[i]); + sha16[16] = 0; + snprintf(reply, reply_size, "running=%s sha=%s state=%s size=%lu off=%lu err=%u rolledback=%u", + _version, sha16, state_name, (unsigned long)_size, (unsigned long)_written, + (unsigned)_err, (unsigned)(_rolledback ? 1 : 0)); +} + +static bool parseFwVersion(const char* s, uint32_t* out) { + if (s == nullptr || *s == 0) return false; + if (*s == 'v') s++; + unsigned nums[3] = {0, 0, 0}; + unsigned pre = 0; + int idx = 0; + unsigned acc = 0; + int digits = 0; + for (const char* q = s;; q++) { + char c = *q; + if (c >= '0' && c <= '9') { + if (idx > 3 || digits >= 3) return false; + acc = acc * 10 + (unsigned)(c - '0'); + digits++; + continue; + } + if (c == '.' || c == '-' || c == 0) { + if (digits == 0 || acc > 255) return false; + if (c == '.') { + if (idx >= 2) return false; + nums[idx++] = acc; + } else if (c == '-') { + if (idx != 2) return false; // pre-release only as MAJOR.MINOR.PATCH-pre + nums[2] = acc; + idx = 3; + } else { + if (idx == 3) pre = acc; else nums[idx] = acc; + break; + } + acc = 0; + digits = 0; + continue; + } + return false; + } + *out = ((uint32_t)nums[0] << 24) | ((uint32_t)nums[1] << 16) | ((uint32_t)nums[2] << 8) | pre; + return true; +} + +bool OtaUpdate::stageCommand(const char* size_tok, const char* sha_tok, const char* ver_tok, char* reply) { + if (_io == nullptr) { + snprintf(reply, CLI_REPLY_MAX, "Err - OTA unsupported on this platform"); + return false; + } + if (_state != State::Idle) { + snprintf(reply, CLI_REPLY_MAX, "Err - staging in progress; abort it first"); + return false; + } + long size; + if (!parseIntRange(size_tok, 1, 0x7FFFFFFFL, &size)) { + snprintf(reply, CLI_REPLY_MAX, "Err - size must be 1..2147483647"); + return false; + } + uint8_t sha[32]; + if (sha_tok == nullptr || strlen(sha_tok) != 64 || !mesh::Utils::fromHex(sha, 32, sha_tok)) { + snprintf(reply, CLI_REPLY_MAX, "Err - sha256 must be 64 hex chars"); + return false; + } + uint32_t ignored_fw; + if (!parseFwVersion(ver_tok, &ignored_fw)) { + snprintf(reply, CLI_REPLY_MAX, "Err - ver must be MAJOR[.MINOR[.PATCH][-pre]]"); + return false; + } + if (!armSession((uint32_t)size, sha, nullptr, 0)) { + if (_err == OTA_ERR_BATTERY) { + snprintf(reply, CLI_REPLY_MAX, "Err - battery gate active; staging refused"); + } else { + snprintf(reply, CLI_REPLY_MAX, "Err - cannot stage (slot unavailable?)"); + } + return false; + } + snprintf(reply, CLI_REPLY_MAX, "OK - staging armed (size=%ld)", size); + return true; +} + +bool OtaUpdate::applyCommand(char* reply) { + if (_state != State::Ready) { + snprintf(reply, CLI_REPLY_MAX, "Err - no verified staging (see ota status)"); + return false; + } + if (!writePendRecord(OTA_PEND_PENDING, _size, _expected_sha)) { + snprintf(reply, CLI_REPLY_MAX, "Err - could not arm boot health record"); + return false; + } + if (!_io->setInactiveAsBoot()) { + snprintf(reply, CLI_REPLY_MAX, "Err - could not set boot partition"); + return false; + } + if (_board != nullptr) _board->reboot(); // does not return on-device + snprintf(reply, CLI_REPLY_MAX, "OK - applied; rebooting"); + return true; +} + +bool OtaUpdate::abortCommand(char* reply) { + resetSession(); + if (_rolledback) { + deletePend(); + _rolledback = false; + } + snprintf(reply, CLI_REPLY_MAX, "OK - aborted"); + return true; +} + +bool OtaUpdate::rollbackCommand(char* reply) { + uint8_t zero[32] = {0}; + writePendRecord(OTA_PEND_ROLLED, 0, zero); // best-effort marker for the old image + if (_io == nullptr || !_io->setInactiveAsBoot()) { + snprintf(reply, CLI_REPLY_MAX, "Err - could not set boot partition"); + return false; + } + if (_board != nullptr) _board->reboot(); // does not return on-device + snprintf(reply, CLI_REPLY_MAX, "OK - rolling back; rebooting"); + return true; +} + +void otaCLI(OtaUpdate& ota, const char* sub, char* reply) { + char scratch[MAX_PACKET_PAYLOAD + 1]; + if (!cliPrepare(sub, scratch, sizeof(scratch), reply)) return; + char* p = scratch; + char* cmd = nextToken(&p); + + if (cmd == nullptr) { + ota.formatStatus(reply, CLI_REPLY_MAX); + return; + } + if (strcmp(cmd, "status") == 0) { + if (!cliNoExtra(p, reply, OTA_USAGE)) return; + ota.formatStatus(reply, CLI_REPLY_MAX); + return; + } + if (strcmp(cmd, "stage") == 0) { + char* size_tok = nextToken(&p); + char* sha_tok = nextToken(&p); + char* ver_tok = nextToken(&p); + if (size_tok == nullptr || sha_tok == nullptr || ver_tok == nullptr || nextToken(&p) != nullptr) { + snprintf(reply, CLI_REPLY_MAX, "%s", OTA_USAGE); + return; + } + ota.stageCommand(size_tok, sha_tok, ver_tok, reply); + return; + } + if (strcmp(cmd, "apply") == 0) { if (!cliNoExtra(p, reply, OTA_USAGE)) return; ota.applyCommand(reply); return; } + if (strcmp(cmd, "abort") == 0) { if (!cliNoExtra(p, reply, OTA_USAGE)) return; ota.abortCommand(reply); return; } + if (strcmp(cmd, "rollback") == 0) { if (!cliNoExtra(p, reply, OTA_USAGE)) return; ota.rollbackCommand(reply); return; } + snprintf(reply, CLI_REPLY_MAX, "%s", OTA_USAGE); +} diff --git a/examples/simple_repeater/OtaUpdate.h b/examples/simple_repeater/OtaUpdate.h new file mode 100644 index 00000000..d3332127 --- /dev/null +++ b/examples/simple_repeater/OtaUpdate.h @@ -0,0 +1,259 @@ +// OtaUpdate.h β€” LoRa OTA (over-the-air firmware update) for the ESP32 +// simple_repeater firmware, from the lora-ota plan +// (plans/2026-11-15-lora-ota-fork-firmware.md). Personal fork feature; all +// fork-owned code lives in this file pair plus minimal hook lines in +// MyMesh.{h,cpp} and the `ota` CLI branch in handleCommand(). No changes to +// MeshCore core sources. +// +// The repeater is dumb; the phone app is smart. The app picks the target, +// computes the delta (or full image), paces the transfer and interprets +// `ota status`; this node only reassembles an op stream into its *inactive* +// app slot, verifies the SHA-256 of what actually landed in flash, and β€” +// only then β€” offers to flip the boot partition. Nothing here floods a +// single byte: every OTA packet is ROUTE_TYPE_DIRECT carrying +// PAYLOAD_TYPE_RAW_CUSTOM, zero-hop or along an explicit --via path, and +// DIRECT packets cannot flood. +// +// Wire format (frozen in M0): +// +// ch0 'O' 0x4F +// ch1 'T' 0x54 +// ch2 op +// ch3 seq (u16, little endian) β€” OP_START is 0; each later packet +1 +// ch4.. opcode-specific body +// last.. last-1 +// crc16 (u16, LE) β€” CRC-16/CCITT-FALSE over everything before it +// +// OP_START 0x01 size:u32 sha256[32] target:u32 fw:u32 ret_path_len:u8 [ret_path] +// size total byte length of the image to stage +// sha256 expected digest of the staged slot at OP_END +// target sha256(pio_env)[0..3] LE; mismatch = wrong node, reject +// fw MAJOR<<24 | MINOR<<16 | PATCH<<8 | pre (opaque here) +// ret_path_len / ret_path return itinerary in the repeaterβ†’app +// travel order, encoded exactly like a packet's path_len byte +// (count in the low 6 bits, hash-size-1 in the high 2). Empty +// (0) = the app is zero-hop and OP_REPORTs go back zero-hop. +// DIRECT paths are consumed hop by hop as they travel, so the +// final hop can never learn the reverse itinerary β€” without it +// OP_REPORT cannot cross a multi-hop path. The app knows the +// full route both ways and hands the return leg over; the +// repeater uses it verbatim for every reply in the session. +// +// OP_COPY 0x02 base_off:u32 len:u16 +// copy running-slot bytes [base_off, base_off+len) into the +// inactive slot at the current write offset +// OP_LITERAL 0x03 len:u16 data[len] +// write data into the inactive slot at the current write offset +// OP_END 0x04 finish; SHA-256 the staged slot; if OK, ready +// OP_ASK 0x05 request an OP_REPORT (after a window) +// OP_REPORT 0x06 next_expected:u16 gaps_mask:u16 (repeater β†’ app only) +// gaps_mask bit i = op at (next_expected + i) never arrived +// OP_NOP 0x00 health probe; never answered +// +// Ops are strictly ordered: an op is applied only when its seq equals +// next_expected; anything else is buffered (up to a 16-op window) or, if it +// falls outside the window, dropped. Unchanged bytes are never re-transmitted +// β€” a delta is OP_COPY + OP_LITERAL against the running slot; a full image is +// OP_LITERALs against nothing. Verify-then-apply is the only path to a +// reboot into new firmware: on any mismatch the staging is scrapped and the +// previous firmware keeps running. +// +// /ota_pend is a tiny record (magic "OTAP", version, state, size, sha256, +// CRC-16) written before an apply reboot and consumed by the boot health +// check: a freshly-applied image re-verifies the SHA-256 of the slot it is +// running from, then sends one zero-hop health packet as proof the radio +// path works. Success clears the record; failure flips the boot partition +// back to the previous slot and reboots. The record is kept in state +// ROLLED after a rollback so the old image can surface rolledback=1 in +// `ota status` until `ota abort` acknowledges it. +// +// CLI: "ota ..." commands, handled by otaCLI() (see OtaUpdate.cpp). `ota +// status` is the app's progress feed; the line format is frozen in M0: +// +// running= sha=<16hex> state= size= off= err= rolledback=<0|1> +// +// - sha is the running slot's SHA-256, truncated to its first 8 bytes +// - size/off are the staged contract's size and the write offset (0 when idle) +// - err is one of the OTA_ERR_* codes (0 = OK); state=error sticks until an +// explicit `ota abort` or a new `ota stage`/OP_START +// - rolledback=1 appears on the previous firmware after an automatic +// rollback; `ota abort` acknowledges it. state=unsupported on builds with +// no second app slot (and on non-ESP32), where every other key still prints. + +#ifndef _OTA_UPDATE_H +#define _OTA_UPDATE_H + +#include +#include +#include + +#include // mesh::Packet, mesh::MainBoard +#include // FILESYSTEM typedef +#include // PAYLOAD_TYPE_RAW_CUSTOM +#include "PersistUtil.h" // crc16_ccitt (the wire CRC) + +// --- wire format ------------------------------------------------------------ +#define OTA_OP_NOP 0x00 +#define OTA_OP_START 0x01 +#define OTA_OP_COPY 0x02 +#define OTA_OP_LITERAL 0x03 +#define OTA_OP_END 0x04 +#define OTA_OP_ASK 0x05 +#define OTA_OP_REPORT 0x06 + +#define OTA_MAGIC0 0x4F // 'O' +#define OTA_MAGIC1 0x54 // 'T' + +// every OTA frame: magic(2) + op(1) + seq(2) + body + crc16(2) +#define OTA_FRAME_OVERHEAD (2 + 1 + 2 + 2) +#define OTA_WINDOW 16 // ops buffered in flight, relative to expect +#define OTA_OP_START_MIN (4 + 32 + 4 + 4 + 1) // without ret_path +#define OTA_HEALTH_LEN 7 // NOP(3) seq(2) crc(2) + +// error codes reported as err= in `ota status` (0 = OK) +#define OTA_ERR_NONE 0 +#define OTA_ERR_TARGET 1 // wrong target_id for this node +#define OTA_ERR_BATTERY 2 // battery gate suspended: staging refused +#define OTA_ERR_SLOT 3 // size 0, too big, or no second slot +#define OTA_ERR_SHA 4 // OP_END digest mismatch: staging scrapped +#define OTA_ERR_IO 5 // flash read/write/begin/end failed +#define OTA_ERR_BOUNDS 6 // op out of bounds or past end of image +#define OTA_ERR_END 9 // esp_ota_end() failed after a clean verify + +// /ota_pend states +#define OTA_PEND_FILE "/ota_pend" +#define OTA_PEND_PENDING 1 // freshly applied; boot health check pending +#define OTA_PEND_ROLLED 2 // rolled back; visible as rolledback=1 until acked + +// true iff the packet is a well-formed OTA frame: RAW_CUSTOM payload, OTA +// magic, valid CRC. Used by the relay path (a fork filter rule must never +// drop an update in transit β€” and only frames the node would itself accept +// are exempt) and by the local receive path, on every platform. +inline bool otaIsOtaPacket(const mesh::Packet* pkt) { + if (pkt == nullptr) return false; + if (pkt->getPayloadType() != PAYLOAD_TYPE_RAW_CUSTOM) return false; + const size_t n = pkt->payload_len; + if (n < OTA_FRAME_OVERHEAD) return false; + if (pkt->payload[0] != OTA_MAGIC0 || pkt->payload[1] != OTA_MAGIC1) return false; + const uint16_t stored = (uint16_t)pkt->payload[n - 2] | ((uint16_t)pkt->payload[n - 1] << 8); + return crc16_ccitt(pkt->payload, n - 2) == stored; +} + +// The staging slot engine's only view of flash, so the session machine is +// host-testable. The ESP32 implementation (Esp32SlotIo, OtaUpdate.cpp) wraps +// esp_ota_*; host tests inject a RAM-backed fake. +class OtaSlotIo { +public: + virtual ~OtaSlotIo() {} + virtual uint32_t slotSize() const = 0; // inactive slot size, bytes + virtual uint32_t sourceSize() const = 0; // running slot size, bytes + virtual bool beginWrite(uint32_t image_size) = 0; // esp_ota_begin() + virtual bool append(const uint8_t* data, size_t len) = 0; // esp_ota_write() + virtual bool readSource(uint32_t off, uint8_t* out, size_t len) = 0; + virtual bool readStaged(uint32_t off, uint8_t* out, size_t len) = 0; + virtual bool endWrite() = 0; // esp_ota_end() + virtual void abortWrite() = 0; // esp_ota_abort() + // Point the bootloader at the inactive slot (esp_ota_set_boot_partition()). + // The engine calls this for apply (flip forward) and rollback (flip back). + virtual bool setInactiveAsBoot() = 0; +}; + +typedef bool (*OtaSendFn)(void* ctx, const uint8_t* payload, size_t len, + const uint8_t* ret_path, uint8_t ret_path_len); + +class BatteryGate; + +class OtaUpdate { +public: + enum class State : uint8_t { Idle, Staging, Ready, Error }; + + OtaUpdate(); + ~OtaUpdate(); + + // Wire the engine into the node: filesystem, the battery gate (staging is + // refused while it is suspended), and the board (apply/rollback reboot via + // board->reboot()). `firmware_version` is FIRMWARE_VERSION (shown in + // `ota status`). The sender dispatches replies: zero-hop, or DIRECT along + // the return path from the armed OP_START. + void begin(FILESYSTEM* fs, BatteryGate* gate, mesh::MainBoard* board, const char* firmware_version); + void setSender(OtaSendFn fn, void* ctx) { _send = fn; _send_ctx = ctx; } + + // Receive entry: RAW_CUSTOM payloads with the OTA magic are validated and + // applied here; anything else is inert. + void onPacket(const mesh::Packet* pkt); + + // Boot health check pump (first loop passes after a freshly-applied boot) + // plus the rollback deadline. Cheap once settled. + void loop(); + + // Feed TX completion for the health probe (from logTx / logTxFail). + void onTxResult(const mesh::Packet* pkt, bool ok); + + // CLI handler for everything after the "ota" verb (see otaCLI()). + void formatStatus(char* reply, size_t reply_size); + bool stageCommand(const char* size_tok, const char* sha_tok, const char* ver_tok, char* reply); + bool applyCommand(char* reply); + bool abortCommand(char* reply); + bool rollbackCommand(char* reply); + + State state() const { return _state; } + bool isUnsupported() const { return _io == nullptr; } + + // Test-only: inject a RAM-backed slot instead of the ESP32 partitions. + void setSlotIo(OtaSlotIo* io) { _io = io; } + +private: + struct WindowSlot { uint16_t len; uint8_t data[MAX_PACKET_PAYLOAD]; }; + + static constexpr uint32_t kHealthTimeoutMs = 15000; + + FILESYSTEM* _fs = nullptr; + BatteryGate* _gate = nullptr; + mesh::MainBoard* _board = nullptr; + const char* _version = ""; + OtaSlotIo* _io = nullptr; + OtaSendFn _send = nullptr; + void* _send_ctx = nullptr; + + State _state = State::Idle; + uint8_t _err = OTA_ERR_NONE; + WindowSlot* _slots = nullptr; // heap, sized OTA_WINDOW, armed only + uint16_t _expect = 1; // next seq to apply (OP_START = 0) + uint16_t _arrived = 0; // window bitmap, relative to _expect + uint32_t _size = 0, _written = 0; + uint8_t _expected_sha[32] = {0}; + uint8_t _ret_path_len = 0, _ret_path[MAX_PATH_SIZE] = {0}; + + bool _running_sha_valid = false; + uint8_t _running_sha[32] = {0}; + + bool _health_pending = false; // freshly-applied image booted + bool _health_sent = false; // health probe already dispatched + bool _health_checked = false; // boot pump settled + uint32_t _health_deadline = 0; + uint32_t _health_size = 0, _health_nonce = 0; + uint8_t _health_sha[32] = {0}; + bool _rolledback = false; // ROLLED record seen at boot + + bool stagingArmed() const { return _state == State::Staging || _state == State::Ready; } + void resetSession(); // back to Idle, window buffer freed + void abortStaging(uint8_t err); // scrap the staged slot on failure + bool armSession(uint32_t size, const uint8_t sha[32], const uint8_t* ret_path, uint8_t ret_path_len); + void handleStart(const uint8_t* body, uint16_t body_len); + void applyOp(const uint8_t* body, uint16_t body_len, uint8_t op); + bool applyCopy(uint32_t base_off, uint16_t len); + bool applyLiteral(const uint8_t* data, uint16_t len); + void drainWindow(); + uint32_t ownTargetId() const; + void sendReport(uint16_t ask_seq); + bool sendHealthProbe(); + void rollbackToPrevious(const char* why); + bool writePendRecord(uint8_t state, uint32_t size, const uint8_t sha[32]); + bool readPend(uint8_t* state, uint32_t* size, uint8_t sha[32]); + void deletePend(); +}; + +// CLI verb handler: everything after "ota" (see MyMesh::handleCommand). +void otaCLI(OtaUpdate& ota, const char* sub, char* reply); + +#endif // _OTA_UPDATE_H diff --git a/platformio.ini b/platformio.ini index 9d082f46..2fa9424d 100644 --- a/platformio.ini +++ b/platformio.ini @@ -60,7 +60,9 @@ build_src_filter = extends = arduino_base platform = platformio/espressif32@6.11.0 monitor_filters = esp32_exception_decoder -extra_scripts = merge-bin.py +extra_scripts = + pre:scripts/ota-pio-env.py + merge-bin.py build_flags = ${arduino_base.build_flags} -D ESP32_PLATFORM ; -D ESP32_CPU_FREQ=80 ; change it to your need diff --git a/scripts/ota-pio-env.py b/scripts/ota-pio-env.py new file mode 100755 index 00000000..05ba09b5 --- /dev/null +++ b/scripts/ota-pio-env.py @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +# Adds the pio_env name as OTA_PIO_ENV to every ESP32 build, so the firmware +# can compute its target_id (sha256(pio_env)[0..3]) at runtime β€” the same +# value the phone app derives from the release asset name (-...). +# OTA releases rely on it to refuse updates armed for a different board. + +Import("env") + +# StringifyMacro quotes the value for the toolchain so the macro expands to a +# string literal in C++ β€” plain embedded quotes do not survive the gcc +# command line on every platform. +env["CPPDEFINES"] = env.get("CPPDEFINES", []) + [("OTA_PIO_ENV", env.StringifyMacro(env["PIOENV"]))]