// Compiled only into the experimental -ota images (-D FW_OTA=1); a classic // image has no firmware update at all (helpers/NodeMaintenance.h). #ifdef FW_OTA #include "FwUpdate.h" #include "FwPatch.h" #if defined(NRF52_PLATFORM) #include #include #include #include #include #ifndef FW_OTA_PUBKEY #error "FW_OTA_PUBKEY (64 hex chars) must be defined for FwUpdate" #endif #ifndef FW_OTA_TARGET #error "FW_OTA_TARGET (the env name) must be defined, tools/build_version.py does it" #endif // Roles with a console (repeater, room server, sensor) never mount ExtraFS, so // the whole space up to InternalFS is free. The companion would need 0xD4000. #ifndef FW_OTA_STAGE_END #define FW_OTA_STAGE_END 0xED000 #endif #define APP_START 0x27000 // S140 7.x, all our nRF52840 boards #define PATCH_LO (FW_OTA_STAGE_END - FW_OTA_PATCH_AREA) // delta packages live here #define PAGE 4096u #define BL_SETTINGS 0xFF000u // sdk11 bootloader_settings_t, nRF52840 #define RING_BITS 15 #define RING_SIZE (1u << RING_BITS) #define RING_MASK (RING_SIZE - 1) extern "C" uint32_t __etext, __data_start__, __data_end__; // --- manifest (tools/ota_pack.py writes the same layout) ---------------------- struct __attribute__((packed)) Manifest { char magic[4]; // "MCFW" uint8_t format; // 1 = deflate full image, 2 = in-place delta (FwPatch) uint8_t layout; // MANIFEST_LAYOUT; was a reserved 0 in the first layout uint8_t reserved0[2]; uint32_t raw_size; uint32_t comp_size; uint8_t raw_sha[32]; uint8_t comp_sha[32]; char target[48]; // env + image variant, e.g. "SenseCap_Solar_repeater-observer-ota" char version[28]; // FIRMWARE_VERSION, at most 19 chars (tools/build_version.py) uint32_t build_epoch; // FIRMWARE_BUILD_EPOCH of the new image: no downgrade over the mesh uint8_t base_sha[32]; // format 2: sha256 of the image the delta applies to uint8_t signature[64]; // Ed25519 over bytes 0..191 }; #define MANIFEST_LAYOUT 2 // What a package for THIS image must carry, read by tools/ota_pack.py from the // ELF -- the target string and the epoch come from the build, never from a // command line that could disagree with it. `fw ver` prints it (and keeps it // in the image: an unreferenced string would fall to --gc-sections). #define FWU_STR2(x) #x #define FWU_STR(x) FWU_STR2(x) static const char FW_OTA_TAGS[] = "MCFW-TAGS target=" FW_OTA_TARGET " epoch=" FWU_STR(FIRMWARE_BUILD_EPOCH); static_assert(sizeof(Manifest) == FW_OTA_MANIFEST_SIZE, "manifest layout"); static_assert(offsetof(Manifest, target) == 80 && offsetof(Manifest, version) == 128 && offsetof(Manifest, build_epoch) == 156 && offsetof(Manifest, base_sha) == 160 && offsetof(Manifest, signature) == 192, "manifest offsets shared with tools/ota_pack.py"); // --- inflate ------------------------------------------------------------------ // A small RFC 1951 decoder in the style of zlib's contrib/puff. EVERYTHING it // touches during the copy must live in RAM, because the copy erases the flash // the firmware runs from: the functions are placed in .data (copied to RAM by // the startup code), the tables are non-const for the same reason, and no // library call (memset, memcpy) may be emitted -- `fw verify` runs the very same // code, and tools/ota_check_ramfunc.sh checks the disassembly for calls out. #define RAMFUNC \ __attribute__((section(".data.ramfunc"), noinline, long_call, optimize("no-tree-loop-distribute-patterns"))) // GCC moves a never-written static table to .rodata, i.e. flash, even when it // is not const (seen: lbase..clorder at 0x7b9fc). Pin the tables to RAM. #define RAMDATA __attribute__((section(".data.ramtab"))) typedef int (*FlushFn)(void *ctx, const uint8_t *data, uint32_t off, uint32_t len, uint32_t in_used); struct Inflate { const uint8_t *in; uint32_t inlen, incnt; uint32_t bitbuf, bitcnt; uint8_t *ring; uint32_t outcnt, outmax; FlushFn flush; void *ctx; }; struct Huff { int16_t count[16]; int16_t symbol[288]; }; RAMDATA static uint16_t lbase[29] = { 3, 4, 5, 6, 7, 8, 9, 10, 11, 13, 15, 17, 19, 23, 27, 31, 35, 43, 51, 59, 67, 83, 99, 115, 131, 163, 195, 227, 258 }; RAMDATA static uint16_t lext[29] = { 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3, 4, 4, 4, 4, 5, 5, 5, 5, 0 }; RAMDATA static uint16_t dbase[30] = { 1, 2, 3, 4, 5, 7, 9, 13, 17, 25, 33, 49, 65, 97, 129, 193, 257, 385, 513, 769, 1025, 1537, 2049, 3073, 4097, 6145, 8193, 12289, 16385, 24577 }; RAMDATA static uint16_t dext[30] = { 0, 0, 0, 0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10, 11, 11, 12, 12, 13, 13 }; RAMDATA static uint8_t clorder[19] = { 16, 17, 18, 0, 8, 7, 9, 6, 10, 5, 11, 4, 12, 3, 13, 2, 14, 1, 15 }; static Huff g_lencode, g_distcode; // .bss is RAM; static so the stack stays small static int16_t g_lengths[320]; RAMFUNC static int inf_bits(Inflate *s, int need, uint32_t *out) { uint32_t val = s->bitbuf; while (s->bitcnt < (uint32_t)need) { if (s->incnt == s->inlen) return -1; val |= (uint32_t)s->in[s->incnt++] << s->bitcnt; s->bitcnt += 8; } s->bitbuf = val >> need; s->bitcnt -= need; *out = val & ((1u << need) - 1); return 0; } RAMFUNC static int inf_put(Inflate *s, uint8_t b) { if (s->outcnt >= s->outmax) return -2; s->ring[s->outcnt & RING_MASK] = b; s->outcnt++; if ((s->outcnt % PAGE) == 0) { uint32_t off = s->outcnt - PAGE; return s->flush(s->ctx, &s->ring[off & RING_MASK], off, PAGE, s->incnt); } return 0; } RAMFUNC static int inf_decode(Inflate *s, const Huff *h, int *sym) { int code = 0, first = 0, index = 0; for (int len = 1; len < 16; len++) { uint32_t b; if (inf_bits(s, 1, &b)) return -1; code |= (int)b; int count = h->count[len]; if (code - count < first) { *sym = h->symbol[index + (code - first)]; return 0; } index += count; first += count; first <<= 1; code <<= 1; } return -3; } RAMFUNC static int inf_construct(Huff *h, const int16_t *length, int n) { int16_t offs[16]; for (int len = 0; len < 16; len++) h->count[len] = 0; for (int sym = 0; sym < n; sym++) h->count[length[sym]]++; if (h->count[0] == n) return 0; int left = 1; for (int len = 1; len < 16; len++) { left <<= 1; left -= h->count[len]; if (left < 0) return left; } offs[1] = 0; for (int len = 1; len < 15; len++) offs[len + 1] = offs[len] + h->count[len]; for (int sym = 0; sym < n; sym++) if (length[sym] != 0) h->symbol[offs[length[sym]]++] = sym; return left; } RAMFUNC static int inf_codes(Inflate *s, const Huff *lc, const Huff *dc) { int sym; do { if (inf_decode(s, lc, &sym)) return -4; if (sym < 256) { if (inf_put(s, (uint8_t)sym)) return -5; } else if (sym > 256) { sym -= 257; if (sym >= 29) return -6; uint32_t e; if (inf_bits(s, lext[sym], &e)) return -1; uint32_t len = lbase[sym] + e; if (inf_decode(s, dc, &sym)) return -4; if (sym >= 30) return -6; if (inf_bits(s, dext[sym], &e)) return -1; uint32_t dist = dbase[sym] + e; if (dist > s->outcnt || dist > RING_SIZE) return -7; while (len--) { if (inf_put(s, s->ring[(s->outcnt - dist) & RING_MASK])) return -5; } } } while (sym != 256); return 0; } RAMFUNC static int inf_stored(Inflate *s) { s->bitbuf = 0; s->bitcnt = 0; if (s->incnt + 4 > s->inlen) return -1; uint32_t len = s->in[s->incnt] | ((uint32_t)s->in[s->incnt + 1] << 8); uint32_t nlen = s->in[s->incnt + 2] | ((uint32_t)s->in[s->incnt + 3] << 8); s->incnt += 4; if (len != (~nlen & 0xffff)) return -8; if (s->incnt + len > s->inlen) return -1; while (len--) if (inf_put(s, s->in[s->incnt++])) return -5; return 0; } RAMFUNC static int inf_fixed(Inflate *s) { int sym = 0; for (; sym < 144; sym++) g_lengths[sym] = 8; for (; sym < 256; sym++) g_lengths[sym] = 9; for (; sym < 280; sym++) g_lengths[sym] = 7; for (; sym < 288; sym++) g_lengths[sym] = 8; inf_construct(&g_lencode, g_lengths, 288); for (sym = 0; sym < 30; sym++) g_lengths[sym] = 5; inf_construct(&g_distcode, g_lengths, 30); return inf_codes(s, &g_lencode, &g_distcode); } RAMFUNC static int inf_dynamic(Inflate *s) { uint32_t nlen, ndist, ncode, v; if (inf_bits(s, 5, &nlen)) return -1; nlen += 257; if (inf_bits(s, 5, &ndist)) return -1; ndist += 1; if (inf_bits(s, 4, &ncode)) return -1; ncode += 4; if (nlen > 286 || ndist > 30) return -9; uint32_t index; for (index = 0; index < ncode; index++) { if (inf_bits(s, 3, &v)) return -1; g_lengths[clorder[index]] = (int16_t)v; } for (; index < 19; index++) g_lengths[clorder[index]] = 0; if (inf_construct(&g_lencode, g_lengths, 19) != 0) return -10; index = 0; while (index < nlen + ndist) { int sym; if (inf_decode(s, &g_lencode, &sym)) return -4; if (sym < 16) { g_lengths[index++] = (int16_t)sym; } else { int16_t len = 0; uint32_t rep; if (sym == 16) { if (index == 0) return -11; len = g_lengths[index - 1]; if (inf_bits(s, 2, &rep)) return -1; rep += 3; } else if (sym == 17) { if (inf_bits(s, 3, &rep)) return -1; rep += 3; } else { if (inf_bits(s, 7, &rep)) return -1; rep += 11; } if (index + rep > nlen + ndist) return -12; while (rep--) g_lengths[index++] = len; } } if (g_lengths[256] == 0) return -13; int err = inf_construct(&g_lencode, g_lengths, nlen); if (err && (err < 0 || nlen != (uint32_t)(g_lencode.count[0] + g_lencode.count[1]))) return -14; err = inf_construct(&g_distcode, g_lengths + nlen, ndist); if (err && (err < 0 || ndist != (uint32_t)(g_distcode.count[0] + g_distcode.count[1]))) return -15; return inf_codes(s, &g_lencode, &g_distcode); } // Raw deflate stream -> flush() per 4 KB page, the last page short. RAMFUNC static int inf_run(Inflate *s) { uint32_t last, type; int err; do { if (inf_bits(s, 1, &last)) return -1; if (inf_bits(s, 2, &type)) return -1; if (type == 0) err = inf_stored(s); else if (type == 1) err = inf_fixed(s); else if (type == 2) err = inf_dynamic(s); else err = -16; if (err) return err; } while (!last); uint32_t tail = s->outcnt % PAGE; if (tail) { uint32_t off = s->outcnt - tail; return s->flush(s->ctx, &s->ring[off & RING_MASK], off, tail, s->incnt); } return 0; } // --- the copy, RAM only --------------------------------------------------------- struct CopyCtx { uint32_t stage_blob; // flash address of the compressed stream const uint32_t *settings; // RAM copy of the bootloader settings page }; RAMFUNC static void nvmc_wait() { while (NRF_NVMC->READY == NVMC_READY_READY_Busy) { } } RAMFUNC static void nvmc_erase(uint32_t addr) { NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Een; nvmc_wait(); NRF_NVMC->ERASEPAGE = addr; nvmc_wait(); NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren; nvmc_wait(); } RAMFUNC static void nvmc_write(uint32_t addr, const uint8_t *src, uint32_t len) { NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Wen; nvmc_wait(); for (uint32_t i = 0; i < len; i += 4) { uint32_t w = 0xFFFFFFFFu; for (uint32_t b = 0; b < 4 && i + b < len; b++) { w &= ~((uint32_t)0xFF << (8 * b)); w |= (uint32_t)src[i + b] << (8 * b); } *(volatile uint32_t *)(addr + i) = w; nvmc_wait(); } NRF_NVMC->CONFIG = NVMC_CONFIG_WEN_Ren; nvmc_wait(); } RAMFUNC static void wdt_feed() { if (NRF_WDT->RUNSTATUS) NRF_WDT->RR[0] = WDT_RR_RR_Reload; } RAMFUNC static int copy_flush(void *vctx, const uint8_t *data, uint32_t off, uint32_t len, uint32_t in_used) { CopyCtx *c = (CopyCtx *)vctx; uint32_t addr = APP_START + off; // never overwrite compressed input that has not been read yet if (addr + PAGE > c->stage_blob + in_used) return -20; wdt_feed(); nvmc_erase(addr); nvmc_write(addr, data, len); return 0; } RAMFUNC static void copy_and_reset(Inflate *s, CopyCtx *c) { // 1) the bootloader learns the new CRC before a single app byte changes wdt_feed(); nvmc_erase(BL_SETTINGS); nvmc_write(BL_SETTINGS, (const uint8_t *)c->settings, PAGE); // 2) inflate over the running image inf_run(s); // 3) whatever happened, reset; a CRC mismatch keeps the node in the bootloader wdt_feed(); __DSB(); SCB->AIRCR = (0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk; __DSB(); for (;;) { } } // --- delta apply (format 2) ------------------------------------------------------ // The applier itself (FwPatch.cpp, detools) is moved to RAM by tools/ota_ramlib.py; // these are its flash callbacks and the entry point, all RAM as well. RAMFUNC static void fwp_erase_page(uintptr_t a) { wdt_feed(); nvmc_erase((uint32_t)a); } RAMFUNC static void fwp_write_page(uintptr_t a, const uint8_t *src, uint32_t n) { nvmc_write((uint32_t)a, src, n); } RAMFUNC static void fwp_tick() { wdt_feed(); } RAMFUNC static void patch_and_reset(fwp_job *j, const uint32_t *settings) { // 1) the bootloader learns the new CRC before a single app byte changes wdt_feed(); nvmc_erase(BL_SETTINGS); nvmc_write(BL_SETTINGS, (const uint8_t *)settings, PAGE); // 2) patch the running image in place fwp_run(j); // 3) whatever happened, reset; a CRC mismatch keeps the node in the bootloader wdt_feed(); __DSB(); SCB->AIRCR = (0x5FAUL << SCB_AIRCR_VECTKEY_Pos) | SCB_AIRCR_SYSRESETREQ_Msk; __DSB(); for (;;) { } } // An env without tools/ota_ramlib.py would leave the applier in flash, which the // real run erases under itself. Refuse delta packages there. static bool deltaInRam() { return (uintptr_t)&fwp_run >= 0x20000000u; } // --- helpers -------------------------------------------------------------------- static uint16_t crc16_update(uint16_t crc, const uint8_t *p, uint32_t len) { // Nordic crc16_compute (CRC-16-CCITT, init 0xFFFF), as the bootloader checks it for (uint32_t i = 0; i < len; i++) { crc = (uint16_t)((crc >> 8) | (crc << 8)); crc ^= p[i]; crc ^= (uint16_t)((crc & 0xFF) >> 4); crc ^= (uint16_t)((crc << 8) << 4); crc ^= (uint16_t)(((crc & 0xFF) << 4) << 1); } return crc; } static int hexval(char c) { if (c >= '0' && c <= '9') return c - '0'; if (c >= 'a' && c <= 'f') return c - 'a' + 10; if (c >= 'A' && c <= 'F') return c - 'A' + 10; return -1; } static bool pubkey(uint8_t out[32]) { const char *hex = FW_OTA_PUBKEY; if (strlen(hex) != 64) return false; for (int i = 0; i < 32; i++) { int hi = hexval(hex[2 * i]), lo = hexval(hex[2 * i + 1]); if (hi < 0 || lo < 0) return false; out[i] = (uint8_t)(hi << 4 | lo); } return true; } static int b64val(char c) { if (c >= 'A' && c <= 'Z') return c - 'A'; if (c >= 'a' && c <= 'z') return c - 'a' + 26; if (c >= '0' && c <= '9') return c - '0' + 52; if (c == '+') return 62; if (c == '/') return 63; return -1; } static int b64decode(const char *in, uint8_t *out, int max) { int n = 0, bits = 0; uint32_t acc = 0; for (; *in && *in != '='; in++) { int v = b64val(*in); if (v < 0) return -1; acc = (acc << 6) | (uint32_t)v; bits += 6; if (bits >= 8) { bits -= 8; if (n >= max) return -1; out[n++] = (uint8_t)(acc >> bits); } } return n; } static uint32_t imageEnd() { uint32_t data_len = (uint32_t)&__data_end__ - (uint32_t)&__data_start__; return (uint32_t)&__etext + data_len; } struct VerifyCtx { SHA256 sha; uint16_t crc; uint32_t stage_blob; bool overlap; }; static void delta_sink(void *vctx, const uint8_t *data, uint32_t len) { VerifyCtx *v = (VerifyCtx *)vctx; v->sha.update(data, len); v->crc = crc16_update(v->crc, data, len); } static int verify_flush(void *vctx, const uint8_t *data, uint32_t off, uint32_t len, uint32_t in_used) { VerifyCtx *v = (VerifyCtx *)vctx; v->sha.update(data, len); v->crc = crc16_update(v->crc, data, len); if (APP_START + off + PAGE > v->stage_blob + in_used) v->overlap = true; return 0; } // --- commands ------------------------------------------------------------------- uint32_t FwUpdate::received() const { uint32_t n = units(), have = 0; for (uint32_t i = 0; i < n; i++) if (haveUnit(i)) have++; return have; } // One chunk from either transport. Offsets on unit boundaries, lengths whole // units except at the end of the package. Rewriting a chunk is harmless. const char *FwUpdate::writeAt(uint32_t off, const uint8_t *buf, int len) { if (_state == FAILED) return _err; if (_state != RECEIVING) return "not receiving"; // never `off + len > _total`: off comes from the sender, 0xFFFFFFE0 + 32 wraps to // 0 and the write would land below the stage, in the running image if (len <= 0 || off % FW_OTA_UNIT || off > _total || (uint32_t)len > _total - off || (len % FW_OTA_UNIT && off + len != _total)) return "bad chunk"; uint32_t u0 = off / FW_OTA_UNIT, u1 = (off + len + FW_OTA_UNIT - 1) / FW_OTA_UNIT; bool all = true; for (uint32_t u = u0; u < u1; u++) if (!haveUnit(u)) all = false; if (off < FW_OTA_MANIFEST_SIZE) { _mani_off = off; uint32_t n = (uint32_t)len; if (off + n > FW_OTA_MANIFEST_SIZE) n = FW_OTA_MANIFEST_SIZE - off; memcpy(&_mani[off], buf, n); } if (!all) { flash_nrf5x_write(_stage + off, buf, len); for (uint32_t u = u0; u < u1; u++) _have[u >> 3] |= (1 << (u & 7)); } if (!_manifest_ok && _job == JOB_NONE) { // as soon as the manifest is complete: refuse a package for another board or // another base before the rest of it is sent (loop() checks it) bool m = true; for (uint32_t u = 0; u * FW_OTA_UNIT < FW_OTA_MANIFEST_SIZE; u++) if (!haveUnit(u)) m = false; if (m) _job = JOB_MANIFEST; } return NULL; } int FwUpdate::handleBinary(const uint8_t *req, int len, uint8_t *reply, int reply_max) { if (len >= 11 && req[1] == 'w') { // the payload arrives padded to the AES block: trust the length byte, not len uint16_t sid; uint32_t off; memcpy(&sid, &req[2], 2); memcpy(&off, &req[4], 4); int n = req[8]; uint16_t crc; memcpy(&crc, &req[9], 2); if (_state != RECEIVING || sid != _sid) { // another (stale) transfer _w_drop++; return 0; } // crc over sid, offset, length AND data: seen on the bench, a fresh header // with the previous transfer's chunk (data and its crc) behind it uint16_t want = crc16_update(crc16_update(0xFFFF, &req[2], 7), &req[11], 11 + n <= len ? n : 0); if (11 + n > len || want != crc) { // the data got mangled on the way (seen: a fresh header with the previous // chunk's data behind it) -- drop it, the bitmap asks for it again _w_bad++; return 0; } _w_bin++; _remote = true; // binary chunks are the mesh protocol (`fw bin` replays it on the bench) _mani_src = 'b'; writeAt(off, &req[11], n); // errors show in the next 'm' return 0; } if (len >= 2 && req[1] == 'm' && reply_max >= 5) { uint8_t st = _state == IDLE ? 0 : _state == READY ? 2 : _state == FAILED ? 3 : 1; if (_job != JOB_NONE) st = 4; uint16_t n = (uint16_t)units(), cnt = 0; reply[0] = st; memcpy(&reply[1], &n, 2); int pos = 5; if (_state == RECEIVING) { for (uint32_t u = 0; u < n && pos + 2 <= reply_max; u++) { if (!haveUnit(u)) { uint16_t v = (uint16_t)u; memcpy(&reply[pos], &v, 2); pos += 2; cnt++; } } } memcpy(&reply[3], &cnt, 2); return pos; } return 0; } // USB VBUS present: the copy cannot run out of power, and a board without // a cell reads only ~3.7 V on VBAT (x4 on the bench), so the gate would // refuse a perfectly safe apply. const char *FwUpdate::battGate(uint16_t mv, bool force) { static char why[40]; if (force || _board.isExternalPowered()) return NULL; if (mv < 2000) { sprintf(why, "battery unknown (%umV)", mv); return why; } if (mv < FW_OTA_MIN_MV) { sprintf(why, "batt %umV < %u", mv, FW_OTA_MIN_MV); return why; } return NULL; } uint16_t FwUpdate::battMinMv() { uint16_t mv = 0xFFFF; for (int i = 0; i < 5; i++) { uint16_t v = _board.getBattMilliVolts(); if (v < mv) mv = v; delay(100); } return mv; } const uint8_t *FwUpdate::baseSha() { if (!_base_known) { SHA256 sha; sha.update((const uint8_t *)APP_START, imageEnd() - APP_START); sha.finalize(_base_sha, 32); _base_known = true; } return _base_sha; } bool FwUpdate::checkManifest() { const Manifest *m = (const Manifest *)_mani; uint8_t key[32]; if (memcmp(m->magic, "MCFW", 4) != 0 || (m->format != 1 && m->format != 2)) { strcpy(_err, "not a package"); return false; } if (!pubkey(key)) { strcpy(_err, "bad FW_OTA_PUBKEY"); return false; } if (!ed25519_verify(m->signature, (const uint8_t *)m, offsetof(Manifest, signature), key)) { strcpy(_err, "bad signature"); return false; } if (m->layout != MANIFEST_LAYOUT) { strcpy(_err, "old package layout, repack it (tools/ota_pack.py)"); return false; } // Not newer than what runs (an older build, or this very one): never over the // mesh -- a bad release is undone by a revert and a NEW release. Locally it // takes `fw apply downgrade`. _older = m->build_epoch <= (uint32_t)FIRMWARE_BUILD_EPOCH; if (_older && _remote) { sprintf(_err, "not newer than this image (pkg %lu, node %lu)", (unsigned long)m->build_epoch, (unsigned long)FIRMWARE_BUILD_EPOCH); return false; } if (strncmp(m->target, FW_OTA_TARGET, sizeof(m->target)) != 0) { strcpy(_err, "wrong target"); return false; } if (FW_OTA_MANIFEST_SIZE + m->comp_size != _total) { strcpy(_err, "size mismatch"); return false; } if (_remote && m->format != 2) { strcpy(_err, "full image not over the mesh (USB or BLE)"); return false; } if (m->format == 2) { if (!deltaInRam()) { strcpy(_err, "no delta support in this build"); return false; } if (_stage != PATCH_LO) { strcpy(_err, "delta too big for the patch area"); return false; } if (memcmp(m->base_sha, baseSha(), 32) != 0) { const uint8_t *b = baseSha(); sprintf(_err, "wrong base image (pkg %02x%02x%02x%02x, node %02x%02x%02x%02x)", m->base_sha[0], m->base_sha[1], m->base_sha[2], m->base_sha[3], b[0], b[1], b[2], b[3]); return false; } } _format = m->format; return true; } void FwUpdate::cmdStatus(char *reply) { uint16_t mv = _board.getBattMilliVolts(); uint32_t n = units(); switch (_state) { case IDLE: { const uint8_t *b = baseSha(); sprintf(reply, "> idle, batt %umV (min %u), free %lu B, base %lu %02x%02x%02x%02x%s", mv, FW_OTA_MIN_MV, (unsigned long)(FW_OTA_STAGE_END - ((imageEnd() + PAGE - 1) & ~(PAGE - 1))), (unsigned long)(imageEnd() - APP_START), b[0], b[1], b[2], b[3], deltaInRam() ? ", delta" : ""); } break; case RECEIVING: if (_job == JOB_VERIFY) { strcpy(reply, "> verifying"); break; } sprintf(reply, "> rx %lu/%lu units, batt %umV%s [b%u d%u x%u t%u]", (unsigned long)received(), (unsigned long)n, mv, _flash_diff ? ", flash!" : "", _w_bin, _w_drop, _w_bad, _w_txt); break; case READY: if (_apply_err[0]) { sprintf(reply, "> ready %s%s, apply refused: %s", _version, _format == 2 ? " (delta)" : "", _apply_err); break; } sprintf(reply, "> ready %s%s, %lu B, crc %04X, batt %umV [b%u d%u x%u t%u]", _version, _format == 2 ? " (delta)" : "", (unsigned long)_raw_size, _crc, mv, _w_bin, _w_drop, _w_bad, _w_txt); break; case FAILED: sprintf(reply, "> failed: %s%s [b%u d%u x%u t%u last %c@%lu sid %u]", _err, _flash_diff ? " flash!" : "", _w_bin, _w_drop, _w_bad, _w_txt, _mani_src, (unsigned long)_mani_off, _sid); break; } } void FwUpdate::cmdBegin(uint32_t sender_timestamp, const char *arg, char *reply) { char *rest; uint32_t total = strtoul(arg, &rest, 10); uint32_t sid = strtoul(rest, NULL, 10); // optional transfer session (binary chunks) if (sender_timestamp != 0 && total > FW_OTA_PATCH_AREA) { sprintf(reply, "ERR: over the mesh only a delta (<= %u B); a full image goes over USB or BLE", (unsigned)FW_OTA_PATCH_AREA); return; } // small = delta: top of the free flash, out of reach of the in-place shift; // big = full image: right above the running one, as before uint32_t stage = total <= FW_OTA_PATCH_AREA ? PATCH_LO : (imageEnd() + PAGE - 1) & ~(PAGE - 1); if (total <= FW_OTA_MANIFEST_SIZE) { strcpy(reply, "ERR: fw begin "); return; } if (stage + total > FW_OTA_STAGE_END) { sprintf(reply, "ERR: %lu B does not fit, %lu free", (unsigned long)total, (unsigned long)(FW_OTA_STAGE_END - stage)); return; } _stage = stage; _total = total; _remote = sender_timestamp != 0; _older = false; memset(_have, 0, sizeof(_have)); _state = RECEIVING; _manifest_ok = false; _format = 0; _job = JOB_NONE; _flash_diff = false; memset(_mani, 0xFF, sizeof(_mani)); _sid = (uint16_t)sid; _w_bin = _w_drop = _w_bad = _w_txt = 0; _mani_src = '-'; _apply_at = 0; _apply_err[0] = 0; sprintf(reply, "OK %lu chunks of %u at %05lX", (unsigned long)((total + FW_OTA_CHUNK - 1) / FW_OTA_CHUNK), FW_OTA_CHUNK, (unsigned long)stage); } void FwUpdate::cmdWrite(uint32_t sender_timestamp, const char *arg, char *reply) { if (sender_timestamp != 0) _remote = true; if (_state == FAILED) { sprintf(reply, "ERR: %s", _err); return; } if (_state != RECEIVING) { strcpy(reply, "ERR: not receiving"); return; } char *end; uint32_t off = strtoul(arg, &end, 10); while (*end == ' ') end++; uint8_t buf[FW_OTA_CHUNK]; int len = b64decode(end, buf, sizeof(buf)); _w_txt++; _mani_src = 't'; const char *err = writeAt(off, buf, len); if (err) sprintf(reply, "ERR: %s", err); else strcpy(reply, "ok"); } void FwUpdate::cmdMissing(char *reply) { if (_state != RECEIVING) { strcpy(reply, "ERR: not receiving"); return; } uint32_t n = (_total + FW_OTA_CHUNK - 1) / FW_OTA_CHUNK; int pos = sprintf(reply, ">"); int listed = 0; const uint32_t per = FW_OTA_CHUNK / FW_OTA_UNIT; for (uint32_t i = 0; i < n && pos < 140; i++) { bool have = true; for (uint32_t u = i * per; u < (i + 1) * per && u < units(); u++) if (!haveUnit(u)) have = false; if (!have) { pos += sprintf(reply + pos, " %lu", (unsigned long)(i * FW_OTA_CHUNK)); listed++; } } if (!listed) strcpy(reply, "> none"); } void FwUpdate::cmdVerify(char *reply) { if (_state == READY || _state == FAILED || _job == JOB_VERIFY) { cmdStatus(reply); return; } if (_state != RECEIVING) { strcpy(reply, "ERR: nothing staged"); return; } if (received() != units()) { strcpy(reply, "ERR: incomplete, see fw missing"); return; } _job = JOB_VERIFY; // loop() runs it; poll `fw status` strcpy(reply, "> verifying"); } void FwUpdate::doVerify() { flash_nrf5x_flush(); _state = FAILED; const Manifest *m = (const Manifest *)_mani; if (!checkManifest()) goto fail; if (APP_START + m->raw_size > (m->format == 2 ? PATCH_LO : FW_OTA_STAGE_END)) { strcpy(_err, "image too big"); goto fail; } { uint8_t h[32]; SHA256 sha; sha.update((const uint8_t *)(_stage + FW_OTA_MANIFEST_SIZE), m->comp_size); sha.finalize(h, 32); if (memcmp(h, m->comp_sha, 32) != 0) { strcpy(_err, "blob hash"); goto fail; } } if (m->format == 2) { // dry run of the very code `fw apply` runs: no flash touched, the new image // streamed through sha256 + the bootloader's CRC16 VerifyCtx *v = new VerifyCtx(); if (!v) { strcpy(_err, "no RAM"); goto fail; } v->crc = 0xFFFF; fwp_job j; memset(&j, 0, sizeof(j)); j.mem_base = APP_START; j.mem_size = PATCH_LO - APP_START; j.from_size = imageEnd() - APP_START; j.patch = (const uint8_t *)(_stage + FW_OTA_MANIFEST_SIZE); j.patch_size = m->comp_size; j.dry = 1; j.sink = delta_sink; j.sink_ctx = v; int err = fwp_run(&j); uint8_t h[32]; v->sha.finalize(h, 32); _crc = v->crc; delete v; if (err) { sprintf(_err, "delta %d/%d", err, j.detools_err); goto fail; } if (j.to_size != m->raw_size || memcmp(h, m->raw_sha, 32) != 0) { strcpy(_err, "image hash"); goto fail; } } else { uint8_t *ring = (uint8_t *)malloc(RING_SIZE); VerifyCtx *v = new VerifyCtx(); if (!ring || !v) { free(ring); delete v; strcpy(_err, "no RAM"); goto fail; } v->crc = 0xFFFF; v->stage_blob = _stage + FW_OTA_MANIFEST_SIZE; v->overlap = false; Inflate s = {}; s.in = (const uint8_t *)v->stage_blob; s.inlen = m->comp_size; s.ring = ring; s.outmax = m->raw_size; s.flush = verify_flush; s.ctx = v; int err = inf_run(&s); uint8_t h[32]; v->sha.finalize(h, 32); _crc = v->crc; bool overlap = v->overlap; free(ring); delete v; if (err) { sprintf(_err, "inflate %d", err); goto fail; } if (s.outcnt != m->raw_size || memcmp(h, m->raw_sha, 32) != 0) { strcpy(_err, "image hash"); goto fail; } if (overlap) { strcpy(_err, "image would overrun the package"); goto fail; } } _raw_size = m->raw_size; memcpy(_version, m->version, sizeof(m->version)); // may fill all 28 bytes, no NUL _version[sizeof(m->version)] = 0; _state = READY; return; fail: _state = FAILED; } void FwUpdate::cmdBootloader(char *reply) { const volatile uint16_t *s16 = (const volatile uint16_t *)BL_SETTINGS; const volatile uint32_t *s32 = (const volatile uint32_t *)BL_SETTINGS; sprintf(reply, "> bank0=%04X crc=%04X bank1=%04X size=%lu", s16[0], s16[1], s16[2], (unsigned long)s32[2]); } void FwUpdate::cmdApply(uint32_t sender_timestamp, const char *arg, char *reply) { if (_state != READY) { strcpy(reply, "ERR: nothing verified, fw verify first"); return; } // arguments: `force` (skip the battery gate) and/or `downgrade`, both local only bool force = strstr(arg, "force") != NULL; bool downgrade = strstr(arg, "downgrade") != NULL; if ((force || downgrade) && sender_timestamp != 0) { strcpy(reply, "ERR: force / downgrade are local-only"); return; } if (_older && !downgrade) { strcpy(reply, "ERR: not newer than this image: fw apply downgrade (local only)"); return; } uint16_t bank0 = *(const volatile uint16_t *)BL_SETTINGS; if (bank0 != 0x0001 && bank0 != 0xFFFF) { sprintf(reply, "ERR: unknown bootloader settings (bank0=%04X)", bank0); return; } // The bootloader skips its CRC check when the stored crc is 0 -- a power cut // mid-copy would then boot half an image. One build in 65536; rebuild it. if (_crc == 0) { strcpy(reply, "ERR: image crc is 0000 (disables the bootloader check), rebuild"); return; } // One quick read for the reply; loop() repeats the gate with the slow min of 5 // reads right before the rewrite (500 ms of delay() has no place in the packet path). uint16_t mv = _board.getBattMilliVolts(); const char *why = battGate(mv, force); if (why) { sprintf(reply, "ERR: %s%s", why, mv < 2000 ? ", fw apply force (local)" : ""); return; } _apply_force = force; _apply_err[0] = 0; _apply_at = millis() + 2000; // let the reply go out first sprintf(reply, "OK applying %s in 2 s (batt %umV%s), back in ~20 s", _version, mv, _board.isExternalPowered() ? ", USB" : ""); } void FwUpdate::loop() { // sha256 of ~400 kB takes a few hundred ms: once here, right after boot, so // `fw status` (the first command of every transfer) never runs it in a handler if (!_base_known) baseSha(); if (_job == JOB_MANIFEST) { _job = JOB_NONE; flash_nrf5x_flush(); if (memcmp((const void *)_stage, _mani, FW_OTA_MANIFEST_SIZE) != 0) _flash_diff = true; if (checkManifest()) { _manifest_ok = true; } else { _state = FAILED; } } else if (_job == JOB_VERIFY) { _job = JOB_NONE; if (!_manifest_ok && !checkManifest()) { _state = FAILED; } else { doVerify(); } } if (_apply_at == 0 || (long)(millis() - _apply_at) < 0) return; _apply_at = 0; if (_state != READY) return; const char *why = battGate(battMinMv(), _apply_force); if (why) { strncpy(_apply_err, why, sizeof(_apply_err) - 1); // `fw status` shows it return; } uint32_t *settings = (uint32_t *)malloc(PAGE); uint8_t *ring = _format == 2 ? (uint8_t *)1 : (uint8_t *)malloc(RING_SIZE); // delta needs no ring static Inflate s; static CopyCtx c; if (!settings || !ring) { free(settings); if (_format != 2) free(ring); _state = FAILED; strcpy(_err, "no RAM for apply"); return; } memcpy(settings, (const void *)BL_SETTINGS, PAGE); uint16_t *s16 = (uint16_t *)settings; s16[0] = 0x0001; // BANK_VALID_APP s16[1] = _crc; // bank_0_crc s16[2] = 0x00FF; // bank_1 = BANK_INVALID_APP settings[2] = _raw_size; // bank_0_size static fwp_job j; if (_format == 2) { memset(&j, 0, sizeof(j)); j.mem_base = APP_START; j.mem_size = PATCH_LO - APP_START; j.from_size = imageEnd() - APP_START; j.patch = (const uint8_t *)(_stage + FW_OTA_MANIFEST_SIZE); j.patch_size = ((const Manifest *)_mani)->comp_size; j.erase = fwp_erase_page; j.write = fwp_write_page; j.tick = fwp_tick; } c.stage_blob = _stage + FW_OTA_MANIFEST_SIZE; c.settings = settings; memset(&s, 0, sizeof(s)); s.in = (const uint8_t *)c.stage_blob; s.inlen = ((const Manifest *)_mani)->comp_size; s.ring = ring; s.outmax = _raw_size; s.flush = copy_flush; s.ctx = &c; Serial.flush(); NRF_USBD->USBPULLUP = 0; // a clean disconnect, see NodeMaintenance::dfuTick delay(100); uint8_t sd = 0; sd_softdevice_is_enabled(&sd); if (sd) sd_softdevice_disable(); __disable_irq(); if (_format == 2) patch_and_reset(&j, settings); copy_and_reset(&s, &c); } bool FwUpdate::handleCommand(uint32_t sender_timestamp, const char *command, char *reply) { if (memcmp(command, "fw", 2) != 0 || (command[2] != 0 && command[2] != ' ')) return false; const char *arg = command[2] ? &command[3] : ""; while (*arg == ' ') arg++; if (strncmp(arg, "w ", 2) == 0) cmdWrite(sender_timestamp, arg + 2, reply); else if (strcmp(arg, "status") == 0 || !*arg) cmdStatus(reply); else if (strncmp(arg, "begin ", 6) == 0) cmdBegin(sender_timestamp, arg + 6, reply); else if (strcmp(arg, "missing") == 0) cmdMissing(reply); else if (strcmp(arg, "verify") == 0) cmdVerify(reply); else if (strncmp(arg, "apply", 5) == 0) { const char *a = arg + 5; while (*a == ' ') a++; cmdApply(sender_timestamp, a, reply); } else if (strcmp(arg, "abort") == 0) { _state = IDLE; _job = JOB_NONE; // a queued verify would turn IDLE back into READY _apply_at = 0; strcpy(reply, "OK"); } else if (strcmp(arg, "bl") == 0) cmdBootloader(reply); else if (strcmp(arg, "ver") == 0) sprintf(reply, "> %s", FW_OTA_TAGS + 10); // "target=... epoch=..." else if (strncmp(arg, "bin ", 4) == 0) { // Bench: feed a binary REQ_TYPE_FW_OTA payload (base64) through the same // handler the mesh uses -- padded to the AES block exactly as the node sees // a decrypted request -- and print the reply. Local console only. if (sender_timestamp != 0) { strcpy(reply, "ERR: local only"); return true; } uint8_t req[176], out[150]; memset(req, 0, sizeof(req)); int n = b64decode(arg + 4, req, 160); if (n <= 0) { strcpy(reply, "ERR: fw bin "); return true; } int padded = ((4 + n + 15) / 16) * 16 - 4; // timestamp + payload, AES-padded int r = handleBinary(req, padded, out, sizeof(out)); if (r <= 0) { strcpy(reply, "> -"); return true; } int pos = sprintf(reply, "> "); for (int i = 0; i < r && pos < 150; i++) pos += sprintf(reply + pos, "%02x", out[i]); } else if (strcmp(arg, "base") == 0) { // full sha256 of the running image: the cached value, and on the local // console also a fresh one (not over the mesh: hundreds of ms in the handler) const uint8_t *c = baseSha(); int pos = sprintf(reply, "> "); for (int i = 0; i < 32; i++) pos += sprintf(reply + pos, "%02x", c[i]); if (sender_timestamp == 0) { uint8_t fresh[32]; SHA256 sha; sha.update((const uint8_t *)APP_START, imageEnd() - APP_START); sha.finalize(fresh, 32); sprintf(reply + pos, " %s", memcmp(c, fresh, 32) == 0 ? "ok" : "CACHE DIFFERS"); } } else strcpy(reply, "ERR: fw status|begin|w|missing|verify|apply|abort|bl|base|ver"); return true; } #else bool FwUpdate::handleCommand(uint32_t, const char *command, char *reply) { if (memcmp(command, "fw", 2) != 0 || (command[2] != 0 && command[2] != ' ')) return false; strcpy(reply, "ERR: not an nRF52 board"); return true; } void FwUpdate::loop() {} #endif #endif // FW_OTA