Add compressed self-serve OTA and resilient native USB sleep
Use a bounded uzlib-derived block encoder with the existing strict tinf decoder, qualify infrastructure roles, budget temporary RAM, and cache running-image metadata. Add self-serve CLI and policy, USB host-loss sleep grace, hardware test harnesses, regression tests, and CI coverage.
This commit is contained in:
1 parent
29de7820e5
commit
5833ac2f1f
34 files changed
+5437
-40
No files matched your search
+4
-3
@@ -521,10 +521,11 @@ void __attribute__((noinline)) Mesh::serviceLoopMaintenance() {
|
||||
bool in_burst = _ota_announce_count < OTA_ANNOUNCE_BURST;
|
||||
uint32_t mins = oc.manager.advert_mins(); // periodic cadence in minutes; 0 = disabled (boot burst only)
|
||||
if (in_burst || mins != 0) {
|
||||
// Install-capable nodes add their running firmware to the served set.
|
||||
// Seeder-only nodes advertise only host-provided folder entries.
|
||||
// Full-image platforms offer the running app directly from flash. Keep a
|
||||
// manually staged primary source intact; host folder entries coexist.
|
||||
// Internal-only nRF52 diagnostic exports remain explicitly selectable.
|
||||
#if !defined(OTA_SEEDER_ONLY)
|
||||
if (!oc.serving) oc.serving = ota::ota_serve_self(oc, 0);
|
||||
if (oc.self_serve_supported && !oc.serving) oc.serving = ota::ota_serve_self(oc, 0);
|
||||
#endif
|
||||
oc.manager.announce();
|
||||
if (_ota_announce_count < 250) _ota_announce_count++;
|
||||
|
||||
@@ -17,6 +17,13 @@
|
||||
#include <driver/rtc_io.h>
|
||||
#include "ESP32TrueRandom.h"
|
||||
#include "UsbLogging.h"
|
||||
#include "UsbHostSleepPolicy.h"
|
||||
|
||||
#ifndef MESH_ESP32_USB_HOST_LOSS_SLEEP_GRACE_MS
|
||||
#define MESH_ESP32_USB_HOST_LOSS_SLEEP_GRACE_MS 120000UL
|
||||
#endif
|
||||
static_assert(MESH_ESP32_USB_HOST_LOSS_SLEEP_GRACE_MS <= 0x7fffffffUL,
|
||||
"USB host-loss sleep grace must fit a bounded millis interval");
|
||||
|
||||
#if defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT && \
|
||||
(!defined(ARDUINO_USB_MODE) || !ARDUINO_USB_MODE)
|
||||
@@ -32,6 +39,9 @@ class ESP32Board : public mesh::MainBoard {
|
||||
protected:
|
||||
uint8_t startup_reason;
|
||||
bool inhibit_sleep = false;
|
||||
#if MESH_ESP32_USB_CONSOLE_COOPERATIVE
|
||||
mesh::UsbHostSleepPolicy usb_host_sleep_policy;
|
||||
#endif
|
||||
#if defined(LIGHTWEIGHT_WIFI_OTA)
|
||||
void* ota_server = nullptr;
|
||||
#else
|
||||
@@ -104,7 +114,17 @@ public:
|
||||
// Native USB loses its connection in light sleep. An enumerated host
|
||||
// still needs USB serviced when no terminal asserts CDC DTR (for example,
|
||||
// after a Pi closes its serial port). Guard every caller here.
|
||||
bool keep_awake = inhibit_sleep || isUsbHostConnected() || isRadioTestActive();
|
||||
// Sample even when another blocker is active, so an open console/OTA does
|
||||
// not leave the last positive native USB host signal stale.
|
||||
const bool usb_host_connected = isUsbHostConnected();
|
||||
bool keep_awake = inhibit_sleep || usb_host_connected || isRadioTestActive();
|
||||
#if MESH_ESP32_USB_CONSOLE_COOPERATIVE
|
||||
// HWCDC loses its SOF host signal after about 5 ms. A warm Pi reboot,
|
||||
// especially on a USB 1.1 bus, must not put us in a 30-second light sleep
|
||||
// while the host is returning and trying to enumerate this same radio.
|
||||
keep_awake = keep_awake || usb_host_sleep_policy.shouldKeepAwake(
|
||||
millis(), MESH_ESP32_USB_HOST_LOSS_SLEEP_GRACE_MS);
|
||||
#endif
|
||||
#if MESH_USB_LOGGING_AVAILABLE
|
||||
// A live logging stream must also remain available before a host opens
|
||||
// it and across host disconnects. Compiled-out logging is not a blocker.
|
||||
@@ -234,6 +254,11 @@ public:
|
||||
|
||||
bool isUsbDataConnected() override {
|
||||
#if defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT
|
||||
#if MESH_ESP32_USB_CONSOLE_COOPERATIVE
|
||||
// Role loops may never call sleep() while a CDC client is open. Keep the
|
||||
// native-host signal history current here too; host detection never calls us.
|
||||
(void)isUsbHostConnected();
|
||||
#endif
|
||||
return (bool)Serial;
|
||||
#else
|
||||
return false;
|
||||
@@ -241,17 +266,21 @@ public:
|
||||
}
|
||||
|
||||
bool isUsbHostConnected() override {
|
||||
bool host_connected = false;
|
||||
#if defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT
|
||||
#if defined(ARDUINO_USB_MODE) && ARDUINO_USB_MODE
|
||||
return Serial.isPlugged();
|
||||
host_connected = Serial.isPlugged();
|
||||
#elif defined(CONFIG_TINYUSB_ENABLED) && CONFIG_TINYUSB_ENABLED
|
||||
return (bool)USB;
|
||||
host_connected = (bool)USB;
|
||||
#else
|
||||
return (bool)Serial;
|
||||
host_connected = (bool)Serial;
|
||||
#endif
|
||||
#else
|
||||
return false;
|
||||
#endif
|
||||
#if MESH_ESP32_USB_CONSOLE_COOPERATIVE
|
||||
usb_host_sleep_policy.observe(host_connected, millis());
|
||||
#endif
|
||||
// The grace is a sleep policy, not proof that a USB host is still present.
|
||||
return host_connected;
|
||||
}
|
||||
|
||||
void setInhibitSleep(bool inhibit) {
|
||||
|
||||
@@ -0,0 +1,37 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
|
||||
namespace mesh {
|
||||
|
||||
// Keep a native USB radio awake through a short host reboot after a positive
|
||||
// native USB host signal. No reported host means no grace. Some cores initially
|
||||
// report a host before their first SOF check; that can arm only this bounded
|
||||
// window, never an indefinite charger-only/battery sleep inhibitor.
|
||||
class UsbHostSleepPolicy {
|
||||
uint32_t _last_host_seen_ms = 0;
|
||||
bool _host_present = false;
|
||||
bool _loss_grace_armed = false;
|
||||
|
||||
public:
|
||||
void observe(bool host_present, uint32_t now) {
|
||||
_host_present = host_present;
|
||||
if (host_present) {
|
||||
_last_host_seen_ms = now;
|
||||
_loss_grace_armed = true;
|
||||
}
|
||||
}
|
||||
|
||||
bool shouldKeepAwake(uint32_t now, uint32_t grace_ms) {
|
||||
if (_host_present) return true;
|
||||
if (!_loss_grace_armed) return false;
|
||||
if (static_cast<uint32_t>(now - _last_host_seen_ms) < grace_ms) {
|
||||
return true;
|
||||
}
|
||||
// Disarm after expiry so another millis() cycle cannot revive an old signal.
|
||||
_loss_grace_armed = false;
|
||||
return false;
|
||||
}
|
||||
};
|
||||
|
||||
} // namespace mesh
|
||||
@@ -4,6 +4,7 @@
|
||||
#include "FolderMotaStore.h" // `ota pull <id> folder` destination (set_mid on the connected folder store)
|
||||
#include "OtaVerify.h"
|
||||
#include "OtaSelf.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include "OtaTargets.h" // ota_target_env_name(): human-readable name for a target_id (no string on the wire)
|
||||
#if defined(NRF52_PLATFORM)
|
||||
#include "OtaBlInfo.h" // installed bootloader application/update capability views
|
||||
@@ -183,30 +184,30 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
|
||||
#endif
|
||||
#elif defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
|
||||
strcpy(reply,
|
||||
"OTA: status | stats | ls | get <id> flash | install | bootloader | cancel | announce | self | storage | folder | config | key");
|
||||
"OTA: status | stats | ls | get <id> flash | install | bootloader | cancel | announce | self | serve | storage | folder | config | key");
|
||||
#elif defined(NRF52_PLATFORM) && defined(OTA_QSPI_STORE)
|
||||
#if defined(OTA_QSPI_BOOTLOADER_UPDATE)
|
||||
strcpy(reply,
|
||||
"OTA: status | stats | ls | get <id> flash | install | bootloader | cancel | announce | self | "
|
||||
"OTA: status | stats | ls | get <id> flash | install | bootloader | cancel | announce | self | serve | "
|
||||
"qspi | folder | config | key");
|
||||
#else
|
||||
strcpy(reply,
|
||||
"OTA: status | stats | ls | get <id> flash | install | cancel | announce | self | qspi | "
|
||||
"OTA: status | stats | ls | get <id> flash | install | cancel | announce | self | serve | qspi | "
|
||||
"folder | config | key");
|
||||
#endif
|
||||
#elif defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
|
||||
#if defined(OTA_SD_BOOTLOADER_UPDATE)
|
||||
strcpy(reply,
|
||||
"OTA: status | stats | ls | get <id> flash | install | bootloader | cancel | announce | self | "
|
||||
"OTA: status | stats | ls | get <id> flash | install | bootloader | cancel | announce | self | serve | "
|
||||
"folder | cache | config | key");
|
||||
#else
|
||||
strcpy(reply,
|
||||
"OTA: status | stats | ls | get <id> flash | install | cancel | announce | self | folder | "
|
||||
"OTA: status | stats | ls | get <id> flash | install | cancel | announce | self | serve | folder | "
|
||||
"cache | config | key");
|
||||
#endif
|
||||
#else
|
||||
snprintf(reply, 160,
|
||||
"OTA: status | stats | ls | get <id> flash | install | cancel | announce | self | folder | "
|
||||
"OTA: status | stats | ls | get <id> flash | install | cancel | announce | self | serve | folder | "
|
||||
"cache | config | key. `ota ls [page]`; folder [validate].");
|
||||
#endif
|
||||
|
||||
@@ -731,6 +732,28 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
|
||||
fstate_char(fs), midhx);
|
||||
}
|
||||
|
||||
// ---- public own-image source: reads the app, never saved identity/settings ----
|
||||
} else if (is_cmd(a, "serve", &rest)) {
|
||||
if (*rest == 0 || strcmp(rest, "status") == 0) {
|
||||
const bool own_image = c.manager.servingPrimaryManifest(c.serve_self_manifest);
|
||||
snprintf(reply, 160,
|
||||
"Own firmware: default:%s serving:%s | full unsigned | transfers require TempRadio",
|
||||
c.self_serve_supported ? "on" : "off", own_image ? "on" : "off");
|
||||
} else if (strcmp(rest, "self") != 0) {
|
||||
strcpy(reply, "ERR usage: ota serve [self|status]");
|
||||
} else if (!c.self_serve_supported) {
|
||||
strcpy(reply, "ERR self serve requires ESP32 or external-storage nRF52; host sources use ota folder");
|
||||
} else if (!ota_serve_self(c, 0)) {
|
||||
strcpy(reply, "ERR serve self (invalid running image or insufficient RAM)");
|
||||
} else {
|
||||
char midhx[9]; mesh::Utils::toHex(midhx, c.serve_self_manifest + 20, 4);
|
||||
uint32_t image = rd_u32le(c.serve_self_manifest + 11);
|
||||
c.manager.announce();
|
||||
snprintf(reply, 160,
|
||||
"OK serving own fw mid=%s (%u B, flash-backed, unsigned); transfers require TempRadio",
|
||||
midhx, (unsigned)image);
|
||||
}
|
||||
|
||||
// ---- broadcast our tiny beacon so peers discover us. If not already serving, set up flash-backed
|
||||
// self-serve first (so we're a real, fetchable source of our own running firmware). ----
|
||||
} else if (is_cmd(a, "announce|adv", &rest)) {
|
||||
@@ -739,7 +762,7 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
|
||||
snprintf(reply, 160, "OK beacon sent (serving=%u host mOTA)",
|
||||
(unsigned)c.manager.servedCount());
|
||||
#else
|
||||
if (!c.serving) c.serving = ota_serve_self(c, 0);
|
||||
if (c.self_serve_supported && !c.serving) c.serving = ota_serve_self(c, 0);
|
||||
c.manager.announce();
|
||||
sprintf(reply, "OK beacon sent (serving=%s)", c.serving ? "self fw" : "nothing");
|
||||
#endif
|
||||
@@ -957,7 +980,7 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
|
||||
if (strcmp(p, "on") == 0) {
|
||||
#if defined(OTA_FOLDER_SERIAL)
|
||||
#if !defined(OTA_SEEDER_ONLY)
|
||||
if (!c.serving) c.serving = ota_serve_self(c, 0); // keep serving our own fw alongside the folder
|
||||
if (c.self_serve_supported && !c.serving) c.serving = ota_serve_self(c, 0);
|
||||
#endif
|
||||
char m2[120]; c.attach_folder(m2, sizeof(m2)); c.manager.announce();
|
||||
strncpy(reply, m2, 159); reply[159] = 0;
|
||||
@@ -969,7 +992,8 @@ bool handle_ota_command(const char* command, char* reply, mesh::MainBoard& board
|
||||
#if defined(OTA_SEEDER_ONLY)
|
||||
strcpy(reply, "OK folder detached (serving nothing)");
|
||||
#else
|
||||
strcpy(reply, "OK folder detached (still serving own fw)");
|
||||
strcpy(reply, c.serving ? "OK folder detached (primary source retained)"
|
||||
: "OK folder detached (no primary source)");
|
||||
#endif
|
||||
} else if (*p == 0) { // status + list served entries (* = our own fw)
|
||||
uint16_t offered = 0, advertised = 0;
|
||||
|
||||
@@ -12,6 +12,7 @@
|
||||
#include "OtaFormat.h"
|
||||
#include "OtaByteIO.h"
|
||||
#include "OtaSelf.h" // ota_self_firmware() - prefer self-describing EndF identity at begin()
|
||||
#include "OtaSelfServePolicy.h"
|
||||
#include "OtaBlInfo.h" // bootloader OTA-apply capability marker (nRF52); cached after first read
|
||||
|
||||
// Storage policy for the mOTA context. A "dynamic" context is created on demand
|
||||
@@ -144,6 +145,10 @@ struct OtaContext {
|
||||
#endif
|
||||
uint32_t serve_expected = 0; // size declared by `ota stage`
|
||||
bool serving = false; // manager.serve() succeeded
|
||||
// Capture application-storage eligibility once. An adaptive nRF52 may later
|
||||
// switch to internal flash to stage a bootloader without changing its normal
|
||||
// ability to offer its running application.
|
||||
bool self_serve_supported = false;
|
||||
// flash-backed self-serve: cached merkle leaves (heap, freed on re-serve) + assembled manifest of our
|
||||
// own running firmware. The payload is read from flash per block; only the metadata is held in RAM.
|
||||
// serve_self_proof is the proof-gen working buffer (>= block_count*4) - sized to OUR image's block
|
||||
@@ -713,6 +718,17 @@ struct OtaContext {
|
||||
manager.set_accept_bootloader(false);
|
||||
#endif
|
||||
manager.set_fetch_store(&fetch_store);
|
||||
#if defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE) && !defined(OTA_SEEDER_ONLY)
|
||||
self_serve_supported = ota_self_serve_supported(fetch_store.usesExternal());
|
||||
#else
|
||||
self_serve_supported = ota_self_serve_supported();
|
||||
#endif
|
||||
#if MESHCORE_OTA_DEVICE_DEFLATE
|
||||
// Register only on qualified full-image nodes (adaptive RAK eligibility
|
||||
// is the application backend latched above). Host precompressed blocks
|
||||
// still take precedence in OtaManager; receiver checks are unchanged.
|
||||
manager.set_transport_deflate_encoder(self_serve_supported ? ota_transport_deflate : nullptr);
|
||||
#endif
|
||||
#if defined(NRF52_PLATFORM) && defined(OTA_SD_STORE)
|
||||
sd_cache.attach(fetch_store);
|
||||
manager.set_archive_interest(true); // default on; the SD marker can turn it off at first mount
|
||||
|
||||
@@ -4,6 +4,9 @@
|
||||
|
||||
extern "C" {
|
||||
#include "tinf/tinf.h"
|
||||
#if MESHCORE_OTA_DEVICE_DEFLATE
|
||||
#include "tinydeflate/deflate.h"
|
||||
#endif
|
||||
}
|
||||
|
||||
namespace mesh {
|
||||
@@ -22,6 +25,29 @@ bool ota_transport_inflate(void* context, const uint8_t* src, uint16_t src_len,
|
||||
return true;
|
||||
}
|
||||
|
||||
#if MESHCORE_OTA_DEVICE_DEFLATE
|
||||
bool ota_transport_deflate(void* context, const uint8_t* src, uint16_t src_len,
|
||||
uint8_t* dst, uint16_t dst_cap, uint16_t* dst_len) {
|
||||
(void)context;
|
||||
if (dst_len) *dst_len = 0;
|
||||
if (!src || src_len < 3 || src_len > MESHCORE_OTA_DEFLATE_BLOCK_MAX ||
|
||||
!dst || !dst_cap || !dst_len) return false;
|
||||
// Proof/output scratch is disjoint from the manager's raw input. Reject
|
||||
// accidental aliases without overflowing a pointer-range endpoint.
|
||||
const uintptr_t source = reinterpret_cast<uintptr_t>(src);
|
||||
const uintptr_t output = reinterpret_cast<uintptr_t>(dst);
|
||||
if ((output >= source && output - source < src_len) ||
|
||||
(source > output && source - output < dst_cap)) return false;
|
||||
// Abort as soon as the stream cannot save a byte. Never need a worst-case
|
||||
// expanded-output buffer, and leave the original raw input intact on failure.
|
||||
const uint16_t limit = dst_cap < src_len ? dst_cap : (uint16_t)(src_len - 1);
|
||||
const uint16_t produced = meshcore_deflate_raw(src, src_len, dst, limit);
|
||||
if (!produced || produced >= src_len) return false;
|
||||
*dst_len = produced;
|
||||
return true;
|
||||
}
|
||||
#endif
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
#pragma once
|
||||
|
||||
#include <stdint.h>
|
||||
#include "OtaDeflateConfig.h"
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
@@ -12,5 +13,15 @@ namespace ota {
|
||||
bool ota_transport_inflate(void* context, const uint8_t* src, uint16_t src_len,
|
||||
uint8_t* dst, uint16_t dst_cap, uint16_t* dst_len);
|
||||
|
||||
#if MESHCORE_OTA_DEVICE_DEFLATE
|
||||
// Compact fixed-Huffman raw RFC1951 encoder; independent blocks of at most
|
||||
// 2048 bytes, with disjoint input/output. Returns false/zero length on invalid
|
||||
// arguments, OOM, output overflow, or no size saving, selecting raw OTA DATA.
|
||||
// 512 uint16_t hash offsets (1024 bytes) are allocated only during the call.
|
||||
// No shared state: repeated/reordered/concurrent blocks encode identically.
|
||||
bool ota_transport_deflate(void* context, const uint8_t* src, uint16_t src_len,
|
||||
uint8_t* dst, uint16_t dst_cap, uint16_t* dst_len);
|
||||
#endif
|
||||
|
||||
} // namespace ota
|
||||
} // namespace mesh
|
||||
@@ -0,0 +1,27 @@
|
||||
#pragma once
|
||||
|
||||
// Device-side compression is useful only where peers can install full own-images.
|
||||
// Source-only Companions retain the host's stronger precompressed-block path;
|
||||
// internal-only nRF52 receivers do not pay the encoder's flash or RAM cost.
|
||||
#ifndef MESHCORE_OTA_DEVICE_DEFLATE
|
||||
#if defined(OTA_TRANSPORT_DEFLATE_TEST)
|
||||
#define MESHCORE_OTA_DEVICE_DEFLATE 1
|
||||
#else
|
||||
#define MESHCORE_OTA_DEVICE_DEFLATE 0
|
||||
#endif
|
||||
#endif
|
||||
|
||||
// Production's shared pre-script positively qualifies the effective source
|
||||
// filter and platform/storage, and supplies this flag to EVERY translation
|
||||
// unit. Without qualification the default stays off, including Companions,
|
||||
// receiver-only targets, unknown roles and custom recipes missing the hook.
|
||||
|
||||
// Independent 2 KiB blocks need only 16-bit input offsets. 512 entries use
|
||||
// 1024 bytes, allocated for one encode call and released before radio TX.
|
||||
#ifndef MESHCORE_OTA_DEFLATE_HASH_BITS
|
||||
#define MESHCORE_OTA_DEFLATE_HASH_BITS 9
|
||||
#endif
|
||||
#if MESHCORE_OTA_DEFLATE_HASH_BITS < 7 || MESHCORE_OTA_DEFLATE_HASH_BITS > 10
|
||||
#error "Device DEFLATE hash must have 128..1024 entries"
|
||||
#endif
|
||||
#define MESHCORE_OTA_DEFLATE_BLOCK_MAX 2048u
|
||||
@@ -333,6 +333,11 @@ public:
|
||||
// Stop serving the primary caller-owned image while preserving attached sources.
|
||||
// Call this before releasing or overwriting the primary image's backing buffer.
|
||||
void clear_primary();
|
||||
// Identify the actual primary backing manifest, not just the view0 catalog
|
||||
// slot: that slot can also contain a manually staged image of another build.
|
||||
bool servingPrimaryManifest(const uint8_t* manifest) const {
|
||||
return _view0.valid && _view0.m.manifest_start == manifest;
|
||||
}
|
||||
uint8_t servedCount() const { return _n_serve; } // total mOTAs we offer (own fw + folder)
|
||||
// Per-source enumeration accounting. `offered` is what the attached host/source reported; `advertised`
|
||||
// is what fit in this build's serve registry after validation/deduplication/capacity limits.
|
||||
|
||||
+40
-13
@@ -27,10 +27,25 @@ namespace ota {
|
||||
// Scan the running app partition for the firmware's EndF trailer using esp_partition_read (stable
|
||||
// across IDF versions - no mmap). Same rule as find_self_firmware(): the marker's absolute offset
|
||||
// must equal its stored body_len, which uniquely identifies the running firmware's own trailer.
|
||||
// The active app is immutable until reboot: OTA writes its inactive peer. Cache only a successful
|
||||
// read, keyed to the current running partition's geometry, so status polling never rescans the app.
|
||||
bool ota_self_firmware(SelfFwInfo& out) {
|
||||
struct MetadataCache {
|
||||
bool valid = false;
|
||||
uint32_t address = 0;
|
||||
uint32_t size = 0;
|
||||
SelfFwInfo info;
|
||||
};
|
||||
static MetadataCache cache;
|
||||
out = SelfFwInfo();
|
||||
const esp_partition_t* p = esp_ota_get_running_partition();
|
||||
if (!p) return false;
|
||||
if (!p) { cache.valid = false; return false; }
|
||||
if (cache.valid && cache.address == p->address && cache.size == p->size) {
|
||||
out = cache.info;
|
||||
return true;
|
||||
}
|
||||
// Missing/changed partitions and failed scans must not resurrect a previous app's metadata.
|
||||
cache.valid = false;
|
||||
|
||||
const uint32_t CH = 512;
|
||||
uint8_t buf[CH + ENDF_LEN]; // overlap so a marker spanning a chunk edge is still seen
|
||||
@@ -43,20 +58,24 @@ bool ota_self_firmware(SelfFwInfo& out) {
|
||||
if (memcmp(buf + i, ENDF_MAGIC, 4) != 0) continue;
|
||||
uint32_t body_len = rd_u32le(buf + i + 4);
|
||||
if (body_len != base + i) continue; // must sit immediately after a body of that length
|
||||
// Read the complete fixed trailer before publishing or caching ANY metadata. A transient
|
||||
// failure here must remain retryable, not become a valid entry with missing identity fields.
|
||||
uint8_t tr[ENDF_LEN];
|
||||
if (body_len > p->size - ENDF_LEN ||
|
||||
esp_partition_read(p, body_len, tr, ENDF_LEN) != ESP_OK) return false;
|
||||
if (memcmp(tr, ENDF_MAGIC, 4) != 0 || rd_u32le(tr + 4) != body_len) return false;
|
||||
out.valid = true;
|
||||
out.endf_offset = body_len;
|
||||
out.body_len = body_len;
|
||||
out.image_len = body_len + ENDF_LEN;
|
||||
memcpy(out.body_hash, buf + i + 8, 8);
|
||||
// Fixed 56-byte trailer: re-read it whole at the marker (it may straddle the chunk window, so the
|
||||
// identity fields aren't reliably in `buf`) and pull identity from constant offsets (docs Section 2).
|
||||
uint8_t tr[ENDF_LEN];
|
||||
if (body_len + ENDF_LEN <= p->size &&
|
||||
esp_partition_read(p, body_len, tr, ENDF_LEN) == ESP_OK) {
|
||||
out.fw_version = (uint32_t)tr[16] | ((uint32_t)tr[17]<<8) | ((uint32_t)tr[18]<<16) | ((uint32_t)tr[19]<<24);
|
||||
out.target_id = (uint32_t)tr[20] | ((uint32_t)tr[21]<<8) | ((uint32_t)tr[22]<<16) | ((uint32_t)tr[23]<<24);
|
||||
memcpy(out.hw_id, tr + 24, 32); out.hw_id[32] = 0;
|
||||
}
|
||||
memcpy(out.body_hash, tr + 8, 8);
|
||||
out.fw_version = rd_u32le(tr + 16);
|
||||
out.target_id = rd_u32le(tr + 20);
|
||||
memcpy(out.hw_id, tr + 24, 32); out.hw_id[32] = 0;
|
||||
cache.address = p->address;
|
||||
cache.size = p->size;
|
||||
cache.info = out;
|
||||
cache.valid = true;
|
||||
return true;
|
||||
}
|
||||
}
|
||||
@@ -159,7 +178,15 @@ bool ota_serve_self(OtaContext& c, uint32_t fw_version) {
|
||||
c.serving = false;
|
||||
free(c.serve_self_leaves); free(c.serve_self_proof);
|
||||
c.serve_self_leaves = (uint8_t*)malloc((size_t)bc * 4);
|
||||
c.serve_self_proof = (uint8_t*)malloc((size_t)bc * 4); // proof-gen working buffer (sized to OUR image)
|
||||
size_t proof_size = (size_t)bc * 4;
|
||||
#if MESHCORE_OTA_DEVICE_DEFLATE
|
||||
// Proof generation and transport encoding use this buffer at different
|
||||
// times. Small nRF52 images can have <2 KiB of leaves: keep enough room for
|
||||
// a whole encoded block without allocating a second input/output buffer.
|
||||
// Receiver-only/Companion diagnostic raw exports retain the old allocation.
|
||||
if (proof_size < BS) proof_size = BS;
|
||||
#endif
|
||||
c.serve_self_proof = (uint8_t*)malloc(proof_size);
|
||||
if (!c.serve_self_leaves || !c.serve_self_proof) {
|
||||
free(c.serve_self_leaves); free(c.serve_self_proof);
|
||||
c.serve_self_leaves = c.serve_self_proof = nullptr;
|
||||
@@ -200,7 +227,7 @@ bool ota_serve_self(OtaContext& c, uint32_t fw_version) {
|
||||
memcpy(m + 57, out_hw, strlen(out_hw) < 32 ? strlen(out_hw) : 32); // hw_id[32] (NUL-padded by memset)
|
||||
memcpy(m + MOTA_OFF_APPROVAL, APPROVAL_NOT, 4); // approval (fetching device's apply-gate handles it)
|
||||
c.serving = c.manager.serve_self(m, MOTA_MFL, c.serve_self_leaves, bc,
|
||||
c.serve_self_proof, (size_t)bc * 4, self_read_cb, nullptr);
|
||||
c.serve_self_proof, proof_size, self_read_cb, nullptr);
|
||||
return c.serving;
|
||||
}
|
||||
#endif
|
||||
|
||||
@@ -3,15 +3,16 @@
|
||||
#include "FirmwareInfo.h"
|
||||
|
||||
// Device-side accessor for the running firmware's own image (to read its EndF trailer).
|
||||
// Per-platform: ESP32 memory-maps the running app partition; other platforms TBD (nRF52 uses the
|
||||
// bootloader-apply path, so its app-region wiring lands with that work). Not compiled on the native
|
||||
// host - the portable scan logic in FirmwareInfo.{h,cpp} is what gets unit-tested there.
|
||||
// ESP32 reads the running A/B app partition; nRF52 reads its memory-mapped app
|
||||
// region. The portable scan logic in FirmwareInfo.{h,cpp} is host-testable.
|
||||
|
||||
namespace mesh {
|
||||
namespace ota {
|
||||
|
||||
// Locate this firmware's EndF trailer in its own flash image. Returns false if unsupported on this
|
||||
// platform or no valid EndF is present (e.g. firmware built without the EndF build hook).
|
||||
// ESP32 caches successful metadata for this boot while the running partition address/size match;
|
||||
// missing partitions, changed geometry and read failures are never cached. OTA writes inactive flash.
|
||||
bool ota_self_firmware(SelfFwInfo& out);
|
||||
|
||||
// Read `len` bytes of the running firmware image at offset `off` (ESP32: running partition via
|
||||
|
||||
@@ -0,0 +1,28 @@
|
||||
#pragma once
|
||||
|
||||
namespace mesh { namespace ota {
|
||||
|
||||
// Default own-image offering is for full-image platforms. Internal-only nRF52
|
||||
// nodes retain the explicit diagnostic export used to capture delta bases, but
|
||||
// do not automatically offer a full image their ordinary peers cannot install.
|
||||
// Adaptive RAK builds must use the qualified application backend, not merely
|
||||
// the presence of a NOR chip (or the temporary bootloader staging backend).
|
||||
inline bool ota_self_serve_supported(bool external_application_storage = false) {
|
||||
#if defined(OTA_SEEDER_ONLY)
|
||||
(void)external_application_storage;
|
||||
return false; // Companion sources offer host packages
|
||||
#elif defined(ESP32_PLATFORM)
|
||||
(void)external_application_storage;
|
||||
return true;
|
||||
#elif defined(NRF52_PLATFORM) && defined(OTA_RAK_AUTO_STORE)
|
||||
return external_application_storage;
|
||||
#elif defined(NRF52_PLATFORM) && (defined(OTA_QSPI_STORE) || defined(OTA_SD_STORE))
|
||||
(void)external_application_storage;
|
||||
return true;
|
||||
#else
|
||||
(void)external_application_storage;
|
||||
return false;
|
||||
#endif
|
||||
}
|
||||
|
||||
} }
|
||||
@@ -4,6 +4,7 @@
|
||||
*/
|
||||
#include "../CompanionReaderConfig.h"
|
||||
#include "../ui/Nrf52FontConfig.h"
|
||||
#include "OtaDeflateConfig.h"
|
||||
#if defined(ENABLE_OTA) || defined(OTA_TRANSPORT_DEFLATE_TEST) || COMPANION_FEATURE_READER \
|
||||
|| MESHCORE_FONT_DEFLATE
|
||||
#if defined(__GNUC__) && !defined(__clang__)
|
||||
@@ -14,6 +15,11 @@
|
||||
#endif
|
||||
#define MESHCORE_TINF_IMPLEMENTATION 1
|
||||
#include "tinf/tinflate.c"
|
||||
#if MESHCORE_OTA_DEVICE_DEFLATE
|
||||
// One true-C translation unit for the existing strict decoder and the small
|
||||
// bounded encoder. Do not bring uzlib's second decoder or wrapper sources in.
|
||||
#include "tinydeflate/deflate.c"
|
||||
#endif
|
||||
#if defined(__GNUC__) && !defined(__clang__)
|
||||
#pragma GCC pop_options
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,65 @@
|
||||
Introduction
|
||||
------------
|
||||
|
||||
uzlib as a whole is licensed under the terms of Zlib license, listed in
|
||||
the next section. It consists of substantial works of individuals whose
|
||||
copyrights listed in the next session. Some portions of the uzlib codebase
|
||||
originally were licensed under different license(s), however compatible
|
||||
with the Zlib license. Such license(s) are listed at the end of this file.
|
||||
|
||||
License
|
||||
-------
|
||||
|
||||
uzlib - Deflate/Zlib-compatible LZ77 compression/decompression library
|
||||
|
||||
Copyright (c) 2003 Joergen Ibsen
|
||||
Copyright (c) 1997-2014 Simon Tatham
|
||||
Copyright (c) 2014-2020 Paul Sokolovsky
|
||||
|
||||
This software is provided 'as-is', without any express or implied
|
||||
warranty. In no event will the authors be held liable for any damages
|
||||
arising from the use of this software.
|
||||
|
||||
Permission is granted to anyone to use this software for any purpose,
|
||||
including commercial applications, and to alter it and redistribute it
|
||||
freely, subject to the following restrictions:
|
||||
|
||||
1. The origin of this software must not be misrepresented; you must
|
||||
not claim that you wrote the original software. If you use this
|
||||
software in a product, an acknowledgment in the product
|
||||
documentation would be appreciated but is not required.
|
||||
|
||||
2. Altered source versions must be plainly marked as such, and must
|
||||
not be misrepresented as being the original software.
|
||||
|
||||
3. This notice may not be removed or altered from any source
|
||||
distribution.
|
||||
|
||||
-------
|
||||
Original license for src/defl_static.c:
|
||||
|
||||
PuTTY is copyright 1997-2014 Simon Tatham.
|
||||
|
||||
Portions copyright Robert de Bath, Joris van Rantwijk, Delian
|
||||
Delchev, Andreas Schultz, Jeroen Massar, Wez Furlong, Nicolas Barry,
|
||||
Justin Bradford, Ben Harris, Malcolm Smith, Ahmad Khalifa, Markus
|
||||
Kuhn, Colin Watson, and CORE SDI S.A.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation files
|
||||
(the "Software"), to deal in the Software without restriction,
|
||||
including without limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of the Software,
|
||||
and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
|
||||
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
|
||||
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
@@ -0,0 +1,30 @@
|
||||
Compact bounded device raw-DEFLATE encoder
|
||||
=========================================
|
||||
|
||||
Derived from https://github.com/pfalcon/uzlib
|
||||
Revision: 6d60d651a4499a64f2e5b21b4cc08d98cb84b5c1
|
||||
Original files: src/genlz77.c, src/defl_static.c
|
||||
|
||||
Only the greedy single-probe LZ77/fixed-Huffman encoder is integrated. The
|
||||
existing strict tinf decoder is reused; no second decoder, zlib/gzip wrapper,
|
||||
checksum, or dynamic-Huffman implementation is added. The compressor is
|
||||
compiled as C through ../OtaTinf.c with the existing local size optimization.
|
||||
|
||||
MeshCore modifications are marked in deflate.c. Hash buckets hold 16-bit
|
||||
offsets+1 into the current <=2048-byte input instead of pointers. 512 buckets
|
||||
need 1024 bytes, calloc'ed for one call then freed (OOM falls back to raw).
|
||||
Hash bits may be 7..10; any override is also counted by the runtime RAM gate.
|
||||
There is no persistent dictionary, no shared mutable state, and no input copy.
|
||||
Output uses the caller's disjoint proof scratch, bounded at every byte write;
|
||||
overflow/incompressible blocks return failure and the untouched raw input is
|
||||
sent instead. The state is small on the stack (24 bytes on 32-bit targets),
|
||||
with no recursion. Match searches stop at 258 bytes; all tail reads are bounded.
|
||||
Repeated/reordered blocks produce identical bytes, independent of addresses.
|
||||
|
||||
Only eligible non-seeder ESP32/external-storage nRF52 targets compile the
|
||||
encoder. Runtime qualification also gates adaptive RAK boards. Host supplied
|
||||
precompressed blocks retain priority, and source-only Companions/internal-only
|
||||
nRF52 receivers retain their existing decoder and raw path without this code.
|
||||
|
||||
The original Zlib and PuTTY MIT-compatible licenses are preserved in LICENSE
|
||||
and the source notices. Modified source is not represented as upstream.
|
||||
@@ -0,0 +1,384 @@
|
||||
/*
|
||||
|
||||
Routines in this file are based on:
|
||||
Zlib (RFC1950 / RFC1951) compression for PuTTY.
|
||||
|
||||
PuTTY is copyright 1997-2014 Simon Tatham.
|
||||
|
||||
Portions copyright Robert de Bath, Joris van Rantwijk, Delian
|
||||
Delchev, Andreas Schultz, Jeroen Massar, Wez Furlong, Nicolas Barry,
|
||||
Justin Bradford, Ben Harris, Malcolm Smith, Ahmad Khalifa, Markus
|
||||
Kuhn, Colin Watson, and CORE SDI S.A.
|
||||
|
||||
Permission is hereby granted, free of charge, to any person
|
||||
obtaining a copy of this software and associated documentation files
|
||||
(the "Software"), to deal in the Software without restriction,
|
||||
including without limitation the rights to use, copy, modify, merge,
|
||||
publish, distribute, sublicense, and/or sell copies of the Software,
|
||||
and to permit persons to whom the Software is furnished to do so,
|
||||
subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be
|
||||
included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
|
||||
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
|
||||
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
|
||||
NONINFRINGEMENT. IN NO EVENT SHALL THE COPYRIGHT HOLDERS BE LIABLE
|
||||
FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF
|
||||
CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
|
||||
#include <stdlib.h>
|
||||
#include <stdint.h>
|
||||
#include <string.h>
|
||||
#include <assert.h>
|
||||
#include "deflate.h"
|
||||
#include "../OtaDeflateConfig.h"
|
||||
|
||||
/* MeshCore modifications (not unmodified upstream):
|
||||
* Only the genlz77 + fixed-Huffman encoder is retained. Output is bounded,
|
||||
* no realloc is used, and hash buckets are 16-bit offsets into ONE <=2KiB
|
||||
* input block. The hash table is calloc'ed for one call and freed afterwards.
|
||||
* No mutable global state, wrapper/checksum, or second decoder is included.
|
||||
*/
|
||||
struct meshcore_deflate {
|
||||
uint8_t *outbuf;
|
||||
uint16_t outlen, outsize;
|
||||
uint32_t outbits;
|
||||
unsigned noutbits;
|
||||
int failed;
|
||||
uint16_t *hash_table; /* input offset + 1; zero is the empty sentinel */
|
||||
};
|
||||
|
||||
/* ----------------------------------------------------------------------
|
||||
* Zlib compression. We always use the static Huffman tree option.
|
||||
* Mostly this is because it's hard to scan a block in advance to
|
||||
* work out better trees; dynamic trees are great when you're
|
||||
* compressing a large file under no significant time constraint,
|
||||
* but when you're compressing little bits in real time, things get
|
||||
* hairier.
|
||||
*
|
||||
* I suppose it's possible that I could compute Huffman trees based
|
||||
* on the frequencies in the _previous_ block, as a sort of
|
||||
* heuristic, but I'm not confident that the gain would balance out
|
||||
* having to transmit the trees.
|
||||
*/
|
||||
|
||||
static void outbits(struct meshcore_deflate *out, uint32_t bits, unsigned nbits)
|
||||
{
|
||||
if (out->failed) return;
|
||||
assert(out->noutbits + nbits <= 32);
|
||||
out->outbits |= bits << out->noutbits;
|
||||
out->noutbits += nbits;
|
||||
while (out->noutbits >= 8) {
|
||||
if (out->outlen >= out->outsize) {
|
||||
out->failed = 1;
|
||||
return;
|
||||
}
|
||||
out->outbuf[out->outlen++] = (unsigned char) (out->outbits & 0xFF);
|
||||
out->outbits >>= 8;
|
||||
out->noutbits -= 8;
|
||||
}
|
||||
}
|
||||
|
||||
static const unsigned char mirrorbytes[256] = {
|
||||
0x00, 0x80, 0x40, 0xc0, 0x20, 0xa0, 0x60, 0xe0,
|
||||
0x10, 0x90, 0x50, 0xd0, 0x30, 0xb0, 0x70, 0xf0,
|
||||
0x08, 0x88, 0x48, 0xc8, 0x28, 0xa8, 0x68, 0xe8,
|
||||
0x18, 0x98, 0x58, 0xd8, 0x38, 0xb8, 0x78, 0xf8,
|
||||
0x04, 0x84, 0x44, 0xc4, 0x24, 0xa4, 0x64, 0xe4,
|
||||
0x14, 0x94, 0x54, 0xd4, 0x34, 0xb4, 0x74, 0xf4,
|
||||
0x0c, 0x8c, 0x4c, 0xcc, 0x2c, 0xac, 0x6c, 0xec,
|
||||
0x1c, 0x9c, 0x5c, 0xdc, 0x3c, 0xbc, 0x7c, 0xfc,
|
||||
0x02, 0x82, 0x42, 0xc2, 0x22, 0xa2, 0x62, 0xe2,
|
||||
0x12, 0x92, 0x52, 0xd2, 0x32, 0xb2, 0x72, 0xf2,
|
||||
0x0a, 0x8a, 0x4a, 0xca, 0x2a, 0xaa, 0x6a, 0xea,
|
||||
0x1a, 0x9a, 0x5a, 0xda, 0x3a, 0xba, 0x7a, 0xfa,
|
||||
0x06, 0x86, 0x46, 0xc6, 0x26, 0xa6, 0x66, 0xe6,
|
||||
0x16, 0x96, 0x56, 0xd6, 0x36, 0xb6, 0x76, 0xf6,
|
||||
0x0e, 0x8e, 0x4e, 0xce, 0x2e, 0xae, 0x6e, 0xee,
|
||||
0x1e, 0x9e, 0x5e, 0xde, 0x3e, 0xbe, 0x7e, 0xfe,
|
||||
0x01, 0x81, 0x41, 0xc1, 0x21, 0xa1, 0x61, 0xe1,
|
||||
0x11, 0x91, 0x51, 0xd1, 0x31, 0xb1, 0x71, 0xf1,
|
||||
0x09, 0x89, 0x49, 0xc9, 0x29, 0xa9, 0x69, 0xe9,
|
||||
0x19, 0x99, 0x59, 0xd9, 0x39, 0xb9, 0x79, 0xf9,
|
||||
0x05, 0x85, 0x45, 0xc5, 0x25, 0xa5, 0x65, 0xe5,
|
||||
0x15, 0x95, 0x55, 0xd5, 0x35, 0xb5, 0x75, 0xf5,
|
||||
0x0d, 0x8d, 0x4d, 0xcd, 0x2d, 0xad, 0x6d, 0xed,
|
||||
0x1d, 0x9d, 0x5d, 0xdd, 0x3d, 0xbd, 0x7d, 0xfd,
|
||||
0x03, 0x83, 0x43, 0xc3, 0x23, 0xa3, 0x63, 0xe3,
|
||||
0x13, 0x93, 0x53, 0xd3, 0x33, 0xb3, 0x73, 0xf3,
|
||||
0x0b, 0x8b, 0x4b, 0xcb, 0x2b, 0xab, 0x6b, 0xeb,
|
||||
0x1b, 0x9b, 0x5b, 0xdb, 0x3b, 0xbb, 0x7b, 0xfb,
|
||||
0x07, 0x87, 0x47, 0xc7, 0x27, 0xa7, 0x67, 0xe7,
|
||||
0x17, 0x97, 0x57, 0xd7, 0x37, 0xb7, 0x77, 0xf7,
|
||||
0x0f, 0x8f, 0x4f, 0xcf, 0x2f, 0xaf, 0x6f, 0xef,
|
||||
0x1f, 0x9f, 0x5f, 0xdf, 0x3f, 0xbf, 0x7f, 0xff,
|
||||
};
|
||||
|
||||
typedef struct {
|
||||
uint8_t extrabits;
|
||||
uint8_t min, max;
|
||||
} len_coderecord;
|
||||
|
||||
typedef struct {
|
||||
uint8_t code, extrabits;
|
||||
uint16_t min, max;
|
||||
} dist_coderecord;
|
||||
|
||||
#define TO_LCODE(x, y) x - 3, y - 3
|
||||
#define FROM_LCODE(x) (x + 3)
|
||||
|
||||
static const len_coderecord lencodes[] = {
|
||||
{0, TO_LCODE(3, 3)},
|
||||
{0, TO_LCODE(4, 4)},
|
||||
{0, TO_LCODE(5, 5)},
|
||||
{0, TO_LCODE(6, 6)},
|
||||
{0, TO_LCODE(7, 7)},
|
||||
{0, TO_LCODE(8, 8)},
|
||||
{0, TO_LCODE(9, 9)},
|
||||
{0, TO_LCODE(10, 10)},
|
||||
{1, TO_LCODE(11, 12)},
|
||||
{1, TO_LCODE(13, 14)},
|
||||
{1, TO_LCODE(15, 16)},
|
||||
{1, TO_LCODE(17, 18)},
|
||||
{2, TO_LCODE(19, 22)},
|
||||
{2, TO_LCODE(23, 26)},
|
||||
{2, TO_LCODE(27, 30)},
|
||||
{2, TO_LCODE(31, 34)},
|
||||
{3, TO_LCODE(35, 42)},
|
||||
{3, TO_LCODE(43, 50)},
|
||||
{3, TO_LCODE(51, 58)},
|
||||
{3, TO_LCODE(59, 66)},
|
||||
{4, TO_LCODE(67, 82)},
|
||||
{4, TO_LCODE(83, 98)},
|
||||
{4, TO_LCODE(99, 114)},
|
||||
{4, TO_LCODE(115, 130)},
|
||||
{5, TO_LCODE(131, 162)},
|
||||
{5, TO_LCODE(163, 194)},
|
||||
{5, TO_LCODE(195, 226)},
|
||||
{5, TO_LCODE(227, 257)},
|
||||
{0, TO_LCODE(258, 258)},
|
||||
};
|
||||
|
||||
static const dist_coderecord distcodes[] = {
|
||||
{0, 0, 1, 1},
|
||||
{1, 0, 2, 2},
|
||||
{2, 0, 3, 3},
|
||||
{3, 0, 4, 4},
|
||||
{4, 1, 5, 6},
|
||||
{5, 1, 7, 8},
|
||||
{6, 2, 9, 12},
|
||||
{7, 2, 13, 16},
|
||||
{8, 3, 17, 24},
|
||||
{9, 3, 25, 32},
|
||||
{10, 4, 33, 48},
|
||||
{11, 4, 49, 64},
|
||||
{12, 5, 65, 96},
|
||||
{13, 5, 97, 128},
|
||||
{14, 6, 129, 192},
|
||||
{15, 6, 193, 256},
|
||||
{16, 7, 257, 384},
|
||||
{17, 7, 385, 512},
|
||||
{18, 8, 513, 768},
|
||||
{19, 8, 769, 1024},
|
||||
{20, 9, 1025, 1536},
|
||||
{21, 9, 1537, 2048},
|
||||
};
|
||||
|
||||
static void deflate_literal(struct meshcore_deflate *out, unsigned char c)
|
||||
{
|
||||
if (c <= 143) {
|
||||
/* 0 through 143 are 8 bits long starting at 00110000. */
|
||||
outbits(out, mirrorbytes[0x30 + c], 8);
|
||||
} else {
|
||||
/* 144 through 255 are 9 bits long starting at 110010000. */
|
||||
outbits(out, 1 + 2 * mirrorbytes[0x90 - 144 + c], 9);
|
||||
}
|
||||
}
|
||||
|
||||
static void deflate_match(struct meshcore_deflate *out, int distance, int len)
|
||||
{
|
||||
const dist_coderecord *d;
|
||||
const len_coderecord *l;
|
||||
int i, j, k;
|
||||
int lcode;
|
||||
|
||||
while (len > 0) {
|
||||
int thislen;
|
||||
|
||||
/*
|
||||
* We can transmit matches of lengths 3 through 258
|
||||
* inclusive. So if len exceeds 258, we must transmit in
|
||||
* several steps, with 258 or less in each step.
|
||||
*
|
||||
* Specifically: if len >= 261, we can transmit 258 and be
|
||||
* sure of having at least 3 left for the next step. And if
|
||||
* len <= 258, we can just transmit len. But if len == 259
|
||||
* or 260, we must transmit len-3.
|
||||
*/
|
||||
thislen = (len > 260 ? 258 : len <= 258 ? len : len - 3);
|
||||
len -= thislen;
|
||||
|
||||
/*
|
||||
* Binary-search to find which length code we're
|
||||
* transmitting.
|
||||
*/
|
||||
i = -1;
|
||||
j = sizeof(lencodes) / sizeof(*lencodes);
|
||||
while (1) {
|
||||
assert(j - i >= 2);
|
||||
k = (j + i) / 2;
|
||||
if (thislen < FROM_LCODE(lencodes[k].min))
|
||||
j = k;
|
||||
else if (thislen > FROM_LCODE(lencodes[k].max))
|
||||
i = k;
|
||||
else {
|
||||
l = &lencodes[k];
|
||||
break; /* found it! */
|
||||
}
|
||||
}
|
||||
|
||||
lcode = l - lencodes + 257;
|
||||
|
||||
/*
|
||||
* Transmit the length code. 256-279 are seven bits
|
||||
* starting at 0000000; 280-287 are eight bits starting at
|
||||
* 11000000.
|
||||
*/
|
||||
if (lcode <= 279) {
|
||||
outbits(out, mirrorbytes[(lcode - 256) * 2], 7);
|
||||
} else {
|
||||
outbits(out, mirrorbytes[0xc0 - 280 + lcode], 8);
|
||||
}
|
||||
|
||||
/*
|
||||
* Transmit the extra bits.
|
||||
*/
|
||||
if (l->extrabits)
|
||||
outbits(out, thislen - FROM_LCODE(l->min), l->extrabits);
|
||||
|
||||
/*
|
||||
* Binary-search to find which distance code we're
|
||||
* transmitting.
|
||||
*/
|
||||
i = -1;
|
||||
j = sizeof(distcodes) / sizeof(*distcodes);
|
||||
while (1) {
|
||||
assert(j - i >= 2);
|
||||
k = (j + i) / 2;
|
||||
if (distance < distcodes[k].min)
|
||||
j = k;
|
||||
else if (distance > distcodes[k].max)
|
||||
i = k;
|
||||
else {
|
||||
d = &distcodes[k];
|
||||
break; /* found it! */
|
||||
}
|
||||
}
|
||||
|
||||
/*
|
||||
* Transmit the distance code. Five bits starting at 00000.
|
||||
*/
|
||||
outbits(out, mirrorbytes[d->code * 8], 5);
|
||||
|
||||
/*
|
||||
* Transmit the extra bits.
|
||||
*/
|
||||
if (d->extrabits)
|
||||
outbits(out, distance - d->min, d->extrabits);
|
||||
}
|
||||
}
|
||||
|
||||
static void deflate_start_block(struct meshcore_deflate *out)
|
||||
{
|
||||
outbits(out, 1, 1); /* Final block */
|
||||
outbits(out, 1, 2); /* Static huffman block */
|
||||
}
|
||||
|
||||
static void deflate_finish_block(struct meshcore_deflate *out)
|
||||
{
|
||||
outbits(out, 0, 7); /* close block */
|
||||
outbits(out, 0, 7); /* Make sure all bits are flushed */
|
||||
}
|
||||
|
||||
/*
|
||||
* genlz77 - Generic LZ77 compressor
|
||||
*
|
||||
* Copyright (c) 2014 by Paul Sokolovsky
|
||||
*
|
||||
* This software is provided 'as-is', without any express
|
||||
* or implied warranty. In no event will the authors be
|
||||
* held liable for any damages arising from the use of
|
||||
* this software.
|
||||
*
|
||||
* Permission is granted to anyone to use this software
|
||||
* for any purpose, including commercial applications,
|
||||
* and to alter it and redistribute it freely, subject to
|
||||
* the following restrictions:
|
||||
*
|
||||
* 1. The origin of this software must not be
|
||||
* misrepresented; you must not claim that you
|
||||
* wrote the original software. If you use this
|
||||
* software in a product, an acknowledgment in the
|
||||
* product documentation would be appreciated
|
||||
* but is not required.
|
||||
*
|
||||
* 2. Altered source versions must be plainly marked
|
||||
* as such, and must not be misrepresented as being
|
||||
* the original software.
|
||||
*
|
||||
* 3. This notice may not be removed or altered from
|
||||
* any source distribution.
|
||||
*/
|
||||
/*
|
||||
* Match finder derived from uzlib src/genlz77.c.
|
||||
* MeshCore modification: offsets replace pointers, reset for every block.
|
||||
* Compare only inside the current input, including safe 0..2-byte handling.
|
||||
*/
|
||||
#define DEFLATE_HASH_SIZE (1u << MESHCORE_OTA_DEFLATE_HASH_BITS)
|
||||
static unsigned deflate_hash(const uint8_t *p) {
|
||||
const uint32_t v = ((uint32_t)p[0] << 16) | ((uint32_t)p[1] << 8) | p[2];
|
||||
return ((v >> (24 - MESHCORE_OTA_DEFLATE_HASH_BITS)) - v) & (DEFLATE_HASH_SIZE - 1u);
|
||||
}
|
||||
|
||||
uint16_t meshcore_deflate_raw(const uint8_t *src, uint16_t src_len,
|
||||
uint8_t *dst, uint16_t dst_cap) {
|
||||
struct meshcore_deflate out = {0};
|
||||
const uint8_t *base = src, *top;
|
||||
if (!src || src_len < 3 || src_len > MESHCORE_OTA_DEFLATE_BLOCK_MAX ||
|
||||
!dst || !dst_cap) return 0;
|
||||
out.hash_table = (uint16_t *)calloc(DEFLATE_HASH_SIZE, sizeof(uint16_t));
|
||||
if (!out.hash_table) return 0;
|
||||
out.outbuf = dst;
|
||||
out.outsize = dst_cap;
|
||||
deflate_start_block(&out);
|
||||
top = base + src_len - 3; /* length checked before any backwards pointer */
|
||||
while (src < top && !out.failed) {
|
||||
const unsigned hash = deflate_hash(src);
|
||||
const unsigned offset = (unsigned)(src - base);
|
||||
const uint16_t stored = out.hash_table[hash];
|
||||
out.hash_table[hash] = (uint16_t)(offset + 1u);
|
||||
if (stored && (unsigned)(stored - 1u) < offset &&
|
||||
!memcmp(src, base + stored - 1u, 3)) {
|
||||
const uint8_t *subs = base + stored - 1u;
|
||||
const unsigned distance = (unsigned)(src - subs);
|
||||
const uint8_t *match = subs + 3;
|
||||
int len = 3;
|
||||
src += 3;
|
||||
while (src < top && len < 258 && *src == *match) {
|
||||
++src; ++match; ++len;
|
||||
}
|
||||
deflate_match(&out, (int)distance, len);
|
||||
} else {
|
||||
deflate_literal(&out, *src++);
|
||||
}
|
||||
}
|
||||
top = base + src_len;
|
||||
while (src < top && !out.failed) deflate_literal(&out, *src++);
|
||||
if (!out.failed) deflate_finish_block(&out);
|
||||
free(out.hash_table);
|
||||
return out.failed ? 0 : out.outlen;
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
#ifndef MESHCORE_TINY_DEFLATE_H
|
||||
#define MESHCORE_TINY_DEFLATE_H
|
||||
|
||||
#include <stdint.h>
|
||||
#ifdef __cplusplus
|
||||
extern "C" {
|
||||
#endif
|
||||
|
||||
// Modified uzlib compressor: bounded caller-owned raw RFC1951 output only.
|
||||
// Returns zero on OOM/output overflow/invalid parameters. No decoder, container
|
||||
// headers, checksum, persistent dictionary, or dynamic-Huffman tree is included.
|
||||
uint16_t meshcore_deflate_raw(const uint8_t* src, uint16_t src_len,
|
||||
uint8_t* dst, uint16_t dst_cap);
|
||||
|
||||
#ifdef __cplusplus
|
||||
}
|
||||
#endif
|
||||
#endif
|
||||
Reference in new issue
Block a user