Receive an update in chunks
Write update chunks to the spare slot in order, ignore resends, refuse gaps and overruns, and check the CRC at the end. A medium embedded C problem (OTA…
medium · OTA updates and rollback · ota · flash · crc · robustness
An update arrives over a network that can lose acknowledgements, so the server sometimes resends a chunk you already have, and a buggy proxy can skip one. Write:
ota_begin(o, total): start an update oftotalbytes. ReturnOTA_TOO_BIGif it is 0 or does not fit in the slot, otherwiseOTA_OK.ota_chunk(o, offset, data, n): in this order,OTA_BAD_CHUNKifnis 0 or more thanCHUNK_MAX;OTA_DUPif the whole chunk is already written (offset + n <= next). Acknowledge it again, but do not write it;OTA_GAPifoffsetis notnext;OTA_TOO_BIGif it would go pasttotal;- otherwise copy it into
slotatoffset, update the CRC, advancenext, and returnOTA_OK. ota_finish(o, crc):OTA_INCOMPLETEif not alltotalbytes arrived,OTA_BAD_CRCif the image's CRC-32 is notcrc, otherwiseOTA_DONE.
Starter code
int ota_begin(ota_t *o, uint32_t total) {
o->total = total;
o->next = 0;
return OTA_OK;
}
int ota_chunk(ota_t *o, uint32_t offset, const uint8_t *data, uint32_t n) {
memcpy(&slot[offset], data, n);
o->next = offset + n;
return OTA_OK;
}
int ota_finish(ota_t *o, uint32_t crc) {
(void)o; (void)crc;
return OTA_DONE;
}Example tests
A clean transfer, with one resent chunk
make_image(150);
begin(150);
chunk(0, 64);
chunk(64, 64);
chunk(64, 64);
chunk(128, 22);
finish(image_crc);Expected output:
begin 150: ok
chunk 0+64: ok
chunk 64+64: ok
chunk 64+64: duplicate
chunk 128+22: ok
finish: done, slot matchesA skipped chunk, an early finish and a wrong CRC
make_image(150);
begin(150);
chunk(0, 64);
chunk(128, 22);
finish(image_crc);
chunk(64, 64);
chunk(128, 22);
finish(image_crc ^ 1u);Expected output:
begin 150: ok
chunk 0+64: ok
chunk 128+22: gap
finish: incomplete, slot differs
chunk 64+64: ok
chunk 128+22: ok
finish: bad crc, slot matchesLearn it first
- OTA updates and rollback · A/B slots, delta updates, rollback and signing.
More OTA updates and rollback problems
- Pick the slot to boot · Boot a new update on trial, and roll back if it never confirms itself.
- Is this image safe to jump to? · Check a firmware image's header, bounds, CRC and vector table before a bootloader starts it.
- Resume an update after a power cut · Keep download progress in an append-only flash journal, and find where to resume even after a torn write.
- Anti-rollback with one-time fuses · Refuse old, vulnerable firmware by its security version, counted in one-time-programmable fuses.
- Thermostat fleet: boot the update or roll back · Decide which firmware slot to boot, trying a new update a few times before rolling back.