From 2b6607fe2e38bcaeb0469fb554477c5659d7c554 Mon Sep 17 00:00:00 2001 From: "github-actions[bot]" <41898282+github-actions[bot]@users.noreply.github.com> Date: Mon, 16 Nov 2026 12:43:57 -0600 Subject: [PATCH] feat(ota): add OP_INFO negotiation handshake MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit OP_INFO (0x07) is answered in every state — idle, staging, ready, error, and on builds without a second app slot. OP_INFO_REPORT (0x08) carries the frame-format version, the board target id, the usable slot size, the largest accepted OP_LITERAL, the feature mask (delta/apply), and the running image's firmware version (32 bytes, NUL-padded) and full SHA-256 — everything an app needs to pick a delta base by exact-image match and refuse a board mismatch *before* registering an arm. Unknown ops are dropped silently; a stray unknown op inside a staged stream still aborts staging (deliberate fail-safe). --- examples/simple_repeater/MyMesh.cpp | 2 +- examples/simple_repeater/OtaUpdate.cpp | 55 +++++++++++- examples/simple_repeater/OtaUpdate.h | 114 +++++++++++++++++-------- test/test_ota/test_ota.cpp | 88 ++++++++++++++++++- 4 files changed, 217 insertions(+), 42 deletions(-) diff --git a/examples/simple_repeater/MyMesh.cpp b/examples/simple_repeater/MyMesh.cpp index 9564654f..abeb9185 100644 --- a/examples/simple_repeater/MyMesh.cpp +++ b/examples/simple_repeater/MyMesh.cpp @@ -221,7 +221,7 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t // after frame_len bytes of frame is padding. const uint8_t flen = payload[1]; if (payload_len < (size_t)2 + flen) return 0; // truncated: no reply - uint8_t report[7]; + uint8_t report[OTA_REPORT_MAX]; size_t rlen = ota.onFrame(payload + 2, flen, report, sizeof(report)); if (rlen == 0) return 0; // non-ask op (or nothing accepted): no response, like any unknown REQ memcpy(&reply_data[4], report, rlen); diff --git a/examples/simple_repeater/OtaUpdate.cpp b/examples/simple_repeater/OtaUpdate.cpp index cab167a8..d8b415a2 100644 --- a/examples/simple_repeater/OtaUpdate.cpp +++ b/examples/simple_repeater/OtaUpdate.cpp @@ -227,6 +227,51 @@ uint32_t OtaUpdate::ownTargetId() const { #endif } +size_t OtaUpdate::buildInfoReport(uint8_t* out) { + uint32_t features = 0; + uint32_t slot = 0; + if (_io != nullptr) { + slot = _io->slotSize(); + features |= OTA_FEAT_DELTA; // OP_COPY is implemented everywhere with flash + features |= OTA_FEAT_APPLY; // dual app slot (ESP32) + } + + // OP_INFO_REPORT body: wire_ver(1) target(4) slot(4) max_literal(2) features(4) + // ver[32] sha256[32] + uint8_t p[OTA_INFO_BODY]; + memset(p, 0, sizeof(p)); + size_t i = 0; + p[i++] = OTA_WIRE_VERSION; + uint32_t target = ownTargetId(); + for (int k = 0; k < 4; k++) p[i++] = (uint8_t)(target >> (8 * k)); + for (int k = 0; k < 4; k++) p[i++] = (uint8_t)(slot >> (8 * k)); + p[i++] = (uint8_t)(OTA_MAX_LITERAL & 0xFF); + p[i++] = (uint8_t)(OTA_MAX_LITERAL >> 8); + for (int k = 0; k < 4; k++) p[i++] = (uint8_t)(features >> (8 * k)); + if (_version != nullptr) { + size_t n = strlen(_version); + if (n > 31) n = 31; + memcpy(&p[OTA_INFO_RUNNING_VER_OFF], _version, n); // NUL-padded by memset + } + if (_io != nullptr) { + if (!_running_sha_valid) { + memset(_running_sha, 0, sizeof(_running_sha)); + hashSlot(_io, /*staged=*/false, _io->sourceSize(), _running_sha); + _running_sha_valid = true; + } + memcpy(&p[OTA_INFO_RUNNING_SHA_OFF], _running_sha, 32); + } + + out[0] = OTA_MAGIC0; + out[1] = OTA_MAGIC1; + out[2] = OTA_OP_INFO_REPORT; + memcpy(out + 3, p, sizeof(p)); + uint16_t crc = crc16_ccitt(out, 3 + sizeof(p)); + out[3 + sizeof(p)] = (uint8_t)(crc & 0xFF); + out[3 + sizeof(p) + 1] = (uint8_t)(crc >> 8); + return 3 + sizeof(p) + 2; +} + size_t OtaUpdate::onFrame(const uint8_t* frame, size_t n, uint8_t* report_out, size_t report_cap) { if (frame == nullptr || n < 5) return 0; // magic(2) + op(1) + crc(2); ops carry a seq if (frame[0] != OTA_MAGIC0 || frame[1] != OTA_MAGIC1) return 0; @@ -234,9 +279,17 @@ size_t OtaUpdate::onFrame(const uint8_t* frame, size_t n, uint8_t* report_out, s const uint8_t op = frame[2]; + // OP_INFO is the negotiation handshake: answered in every state, no arm + // required, tolerant of a body (for forward-compatible query extensions). + // It does not touch flash and does not create or consume a session. + if (op == OTA_OP_INFO) { + if (report_out == nullptr || report_cap < OTA_INFO_REPORT_LEN) return 0; + return buildInfoReport(report_out); + } + if (_io == nullptr) return 0; // not an ESP32 (or slot lookup failed): inert - if (op == OTA_OP_NOP || op == OTA_OP_REPORT) return 0; + if (op == OTA_OP_NOP || op == OTA_OP_REPORT || op == OTA_OP_INFO_REPORT) return 0; if (op == OTA_OP_ASK) { if (!stagingArmed()) return 0; diff --git a/examples/simple_repeater/OtaUpdate.h b/examples/simple_repeater/OtaUpdate.h index ddb89788..8d5746ba 100644 --- a/examples/simple_repeater/OtaUpdate.h +++ b/examples/simple_repeater/OtaUpdate.h @@ -22,22 +22,16 @@ // boot health check (radio init + one zero-hop packet TX) and flips // back automatically on failure. // -// The CLI exchange carrying the token is encrypted end-to-end (same TXT_MSG -// path as every admin command); OP_START itself is cleartext by nature, and -// that is safe by (2) — see the plan's threat model. DIRECT packets only, -// never flooded. SHA-256 gate on the staged slot is the only integrity -// decision; the op stream itself is trustless once armed. +// The CLI exchange carrying the token and every op ride in encrypted +// admin REQ/RESPONSE datagrams (same trust path as every admin command); +// relays forward ciphertext. SHA-256 gate on the staged slot is the only +// integrity decision; the op stream itself is trustless once armed. // -// Wire format (v2): carried inside an admin client's REQ, answered by a -// RESPONSE, so intermediate nodes only ever forward ordinary mesh traffic. +// Wire format: carried inside an admin client's REQ, answered by a RESPONSE, +// so intermediate nodes only ever forward ordinary mesh traffic. // // REQ plaintext: [tag(4)][REQ_TYPE_OTA (1)][frame_len(1)][OTA frame] -// RESPONSE plaintext (only for OP_ASK): [tag(4)][OP_REPORT frame] -// The plaintext is padded by the crypto layer to a 16-byte block, so the -// OTA frame inside an OP_ASK request carries its own length and the padding -// after it is ignored by the node; on the response side the OTA frame is -// validated by its magic and CRC, and padding may follow it. -// +// RESPONSE plaintext (only for OP_ASK / OP_INFO): [tag(4)][report frame] // The plaintext is padded by the crypto layer to a 16-byte block, so the // OTA frame inside carries its own length — the padding after it is ignored. // @@ -46,34 +40,59 @@ // ch1 'T' 0x54 // ch2 op // ch3 seq (u16, little endian) — op packets only: OP_START/OP_COPY/ -// OP_LITERAL/OP_END. OP_ASK, OP_REPORT and OP_NOP carry no seq. +// OP_LITERAL/OP_END. OP_ASK, OP_INFO, OP_REPORT, +// OP_INFO_REPORT and OP_NOP carry no seq. // 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 token:u32 -// OP_COPY 0x02 base_off:u32 len:u16 copy running-slot bytes into the staged image -// OP_LITERAL 0x03 len:u16 data[len] write data into the staged image -// OP_END 0x04 finish; SHA-256 the slot; if OK, ready -// OP_ASK 0x05 request an OP_REPORT (after a window) -// OP_REPORT 0x06 next_expected:u16 (repeater → app, inside RESPONSE) -// OP_NOP 0x00 boot health probe; never answered +// OP_NOP 0x00 boot health probe; never answered +// OP_START 0x01 size:u32 sha256[32] target:u32 token:u32 +// OP_COPY 0x02 base_off:u32 len:u16 copy running-slot bytes into the staged image +// OP_LITERAL 0x03 len:u16 data[len] write data into the staged image +// OP_END 0x04 finish; SHA-256 the slot; if OK, ready +// OP_ASK 0x05 request an OP_REPORT (after a window) +// OP_REPORT 0x06 next_expected:u16 (repeater → app, inside RESPONSE) +// OP_INFO 0x07 query node capabilities (any state) +// OP_INFO_REPORT 0x08 wire_ver:u8 target:u32 slot:u32 max_literal:u16 features:u32 +// ver[32] sha256[32] (repeater → app, inside RESPONSE) +// +// Stability contract (this is what lets the format live for years): +// - Unknown ops and unknown OP_INFO bodies are dropped silently. +// - A stray unknown op *inside a staged stream* aborts staging — the node +// will never apply a half-understood update. +// - OP_INFO is always answered, in every state (idle/staging/ready/error, +// and on builds with no second app slot, with slot_size = 0). +// - OP_INFO_REPORT is the negotiation handshake: it is how an app detects +// the wire version, the board's target id (before arming), the usable +// slot size, the largest accepted OP_LITERAL, and the feature mask +// (bit0 = OP_COPY delta, bit1 = apply/rollback), plus the RUNNING +// image's firmware version (32 bytes, NUL-padded) and full SHA-256 — +// which is what an app uses to pick a delta base by exact-image match. +// New features are only ever added as new bits or new report fields +// appended at the end. +// - New ops get new op codes; existing ops never change meaning, field +// order or size. The CRC algorithm, the magic bytes and the SEQ rules +// are frozen. +// - The `frame_len` byte in the REQ says the exact OTA frame length that +// follows; the node requires frame_len <= payload_len - 2 and ignores +// any trailing padding. +// Any hard break of these rules is a NEW protocol (new REQ code), never a +// silent redefinition of these ones. // // The tag the companion prepends to every request keeps each REQ's packet hash -// unique, so a re-sent op is never swallowed by the duplicate filter — the -// idempotency rule the raw-custom transport needed (and its -// allowRawDataDuplicate() hook) is not required here. The inner CRC stays on -// the OP_* frames: it costs two bytes and lets the engine reject a mangled -// frame before touching flash, without trusting the carrier. +// unique, so a re-sent op is never swallowed by the duplicate filter. +// The inner CRC stays on the OP_* frames: it lets the engine reject a +// mangled frame before touching flash, without trusting the carrier. // // Ops are strictly in order: an op applies only when seq == next_expected; // anything else is dropped. DIRECT routing delivers in order per path, so // this costs nothing on the wire and no reassembly buffer is needed. The // app's recovery from a lost op is "re-send from next_expected". // -// The OP_REPORT comes back through the stock REQ reply routing (the client's +// The report frame comes back through the stock REQ reply routing (the client's // stored out_path, or a flood when none is known), exactly like a status -// response — the ask carries no return itinerary and nothing is stored. +// response — the ask/info carries no return itinerary and nothing is stored. // // /ota_pend is an 8-byte marker (magic "OTAP", a random nonce, CRC-16): its mere presence means an apply just booted and the boot health // check owes the board a verdict. Success deletes the marker; failure flips @@ -103,20 +122,40 @@ #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_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_OP_INFO 0x07 +#define OTA_OP_INFO_REPORT 0x08 #define OTA_MAGIC0 0x4F // 'O' #define OTA_MAGIC1 0x54 // 'T' +// The frame-format version OP_INFO_REPORT reports. New reports keep all +// previously-defined fields in the same positions. +#define OTA_WIRE_VERSION 1 + +// feature bits reported in OP_INFO_REPORT.features (rest reserved, must be 0) +#define OTA_FEAT_DELTA 0x00000001 // OP_COPY is implemented +#define OTA_FEAT_APPLY 0x00000002 // apply/rollback is implemented (dual app slot) + +// OP_INFO_REPORT body size (before the OTA frame envelope: magic + op + crc) +#define OTA_INFO_BODY 79 // wire_ver(1) + target(4) + slot(4) + max_literal(2) + features(4) + ver[32] + running sha256[32] +#define OTA_INFO_RUNNING_VER_OFF 15 // body offset of the 32-byte running version string +#define OTA_INFO_RUNNING_SHA_OFF 47 // body offset of the 32-byte running SHA-256 +#define OTA_INFO_REPORT_LEN (3 + OTA_INFO_BODY + 2) +// largest report frame the engine ever returns (OP_INFO_REPORT is the biggest) +#define OTA_REPORT_MAX OTA_INFO_REPORT_LEN + // OTA frames carrying an op: magic(2) + op(1) + seq(2) + body + crc16(2). -// ASK/REPORT/NOP carry no seq. +// ASK/REPORT/INFO*/NOP carry no seq. #define OTA_FRAME_OVERHEAD (2 + 1 + 2 + 2) +// largest OP_LITERAL the node accepts (fits one MAX_PACKET_PAYLOAD op frame) +#define OTA_MAX_LITERAL (MAX_PACKET_PAYLOAD - OTA_FRAME_OVERHEAD - 2) #define OTA_OP_START_MIN (4 + 32 + 4 + 4) // size + sha256 + target + token #define OTA_HEALTH_LEN 7 // NOP(3) nonce(2) crc(2) #define OTA_HEALTH_MAX_ATTEMPTS 3 // boots of a new image before it is rejected @@ -240,6 +279,9 @@ private: uint16_t _health_nonce = 0; // sha-free marker nonce bool stagingArmed() const { return _state == State::Staging || _state == State::Ready; } + // Build the OP_INFO_REPORT frame (magic..CRC) into `out`. Works in every + // state — it is the negotiation handshake an app performs before arming. + size_t buildInfoReport(uint8_t* out); public: /// Boot-time verdict before the radio or mesh start: count this boot of a /// freshly-applied image and roll back once the attempts run out. Covers the diff --git a/test/test_ota/test_ota.cpp b/test/test_ota/test_ota.cpp index 86d40889..064d6fe4 100644 --- a/test/test_ota/test_ota.cpp +++ b/test/test_ota/test_ota.cpp @@ -124,6 +124,17 @@ static std::vector askFrame() { return p; } +static std::vector bodyFrame(uint8_t op, const std::vector& body) { + std::vector p = {OTA_MAGIC0, OTA_MAGIC1, op}; + p.insert(p.end(), body.begin(), body.end()); + uint16_t crc = crc16_ccitt(p.data(), p.size()); + p.push_back((uint8_t)(crc & 0xFF)); + p.push_back((uint8_t)(crc >> 8)); + return p; +} + +static std::vector infoFrame() { return bodyFrame(OTA_OP_INFO, {}); } + static void mockSha256(const std::vector& data, uint8_t out[32]) { SHA256 sha; sha.update(data.data(), data.size()); @@ -183,10 +194,10 @@ protected: } // Feed one frame to the engine, exactly as handleRequest() does from an - // admin client's REQ. Returns the OP_REPORT frame when the frame was an - // OP_ASK (7 bytes), else an empty vector. + // admin client's REQ. Returns the OP_REPORT/INFO_REPORT frame the op asks + // for (or an empty vector). std::vector feed(const std::vector& f) { - std::vector report(7, 0); + std::vector report(OTA_REPORT_MAX, 0); size_t n = ota.onFrame(f.data(), f.size(), report.data(), report.size()); report.resize(n); return report; @@ -521,7 +532,7 @@ TEST_F(OtaTest, AskWithStrayBodyGetsNoReply) { auto image = testImage(); arm(image); ASSERT_EQ(ota.state(), OtaUpdate::State::Staging); - // OP_ASK carries no body since v2; a stray byte is not an ask. + // OP_ASK carries no body; a stray byte is not an ask. std::vector p = {OTA_MAGIC0, OTA_MAGIC1, OTA_OP_ASK, 0x00}; uint16_t crc = crc16_ccitt(p.data(), p.size()); p.push_back((uint8_t)(crc & 0xFF)); @@ -530,6 +541,75 @@ TEST_F(OtaTest, AskWithStrayBodyGetsNoReply) { EXPECT_TRUE(report.empty()); } +// ============================================================ +// OP_INFO — the negotiation handshake (answered in any state) +// ============================================================ + +TEST_F(OtaTest, InfoReportAnswersWhenIdle) { + auto report = feed(infoFrame()); + ASSERT_EQ(report.size(), OTA_INFO_REPORT_LEN); + EXPECT_EQ(report[0], OTA_MAGIC0); + EXPECT_EQ(report[1], OTA_MAGIC1); + EXPECT_EQ(report[2], OTA_OP_INFO_REPORT); + // frame CRC is valid + uint16_t stored = (uint16_t)report[report.size() - 2] | ((uint16_t)report[report.size() - 1] << 8); + EXPECT_EQ(crc16_ccitt(report.data(), report.size() - 2), stored); + const uint8_t* body = report.data() + 3; + EXPECT_EQ(body[0], OTA_WIRE_VERSION); + EXPECT_EQ(le32From(body + 1), testTargetId()); + EXPECT_EQ(le32From(body + 5), 0x200000u); // FakeSlotIo slot size + EXPECT_EQ(body[9] | (body[10] << 8), (uint16_t)OTA_MAX_LITERAL); + EXPECT_EQ(le32From(body + 11), (uint32_t)(OTA_FEAT_DELTA | OTA_FEAT_APPLY)); + // running slot is all zeroes in the fake + uint8_t expect_sha[32]; + mockSha256(std::vector(slot.source.begin(), slot.source.end()), expect_sha); + EXPECT_EQ(memcmp(body + OTA_INFO_RUNNING_SHA_OFF, expect_sha, 32), 0); + EXPECT_STREQ((const char*)(body + OTA_INFO_RUNNING_VER_OFF), "test-fw-1.0.0"); +} + +TEST_F(OtaTest, InfoReportAnswersDuringStaging) { + auto image = testImage(); + arm(image); + ASSERT_EQ(ota.state(), OtaUpdate::State::Staging); + auto report = feed(infoFrame()); + ASSERT_EQ(report.size(), OTA_INFO_REPORT_LEN); + EXPECT_EQ(report[2], OTA_OP_INFO_REPORT); +} + +TEST_F(OtaTest, InfoReportAnswersAfterStagingError) { + auto image = testImage(16); + arm(image); + sendLiteral(1, std::vector(16, 0xFF)); // wrong bytes for the contract + sendEnd(2); // sha mismatch → err=4 + ASSERT_EQ(ota.state(), OtaUpdate::State::Error); + auto report = feed(infoFrame()); + ASSERT_EQ(report.size(), OTA_INFO_REPORT_LEN); + EXPECT_EQ(report[2], OTA_OP_INFO_REPORT); +} + +TEST_F(OtaTest, InfoReportToleratesStrayBody) { + auto report = feed(bodyFrame(OTA_OP_INFO, {0xDE, 0xAD, 0xBE, 0xEF})); + ASSERT_EQ(report.size(), OTA_INFO_REPORT_LEN); + EXPECT_EQ(report[2], OTA_OP_INFO_REPORT); +} + +TEST_F(OtaTest, InfoReportOnUnwiredEngineAnswersWithZeros) { + OtaUpdate fresh; // never wired: no fs, slot io, rng, or firmware version + std::vector f = infoFrame(); + std::vector report(OTA_REPORT_MAX, 0); + size_t n = fresh.onFrame(f.data(), f.size(), report.data(), report.size()); + report.resize(n); + ASSERT_EQ(report.size(), OTA_INFO_REPORT_LEN); + const uint8_t* body = report.data() + 3; + EXPECT_EQ(body[0], OTA_WIRE_VERSION); + EXPECT_EQ(le32From(body + 1), testTargetId()); // OTA_PIO_ENV is fixed at compile time + EXPECT_EQ(le32From(body + 5), 0u); // no slot size without a slot io + EXPECT_EQ(le32From(body + 11), 0u); // no features without flash + for (size_t i = OTA_INFO_RUNNING_VER_OFF; i < OTA_INFO_BODY; i++) { + EXPECT_EQ(body[i], 0u); // running version and sha are zero + } +} + // ============================================================ // IN-ORDER OP APPLICATION // ============================================================