Add secure management reports and honor GPS off

This commit is contained in:
mikecarper committed 2026-09-16 20:42:30 -07:00
1 parent ad0ea545d3
commit 4ba26ff4af
30 files changed
+2109 -76

No files matched your search

+50
View File
@@ -1,4 +1,6 @@
#include "Mesh.h"
#include <helpers/ManagementReport.h>
#include <SHA256.h>
#include "helpers/ota/OtaFormat.h" // request types used by TempRadio relay-pressure tracking
//#include <Arduino.h>
#if defined(ENABLE_OTA)
@@ -1146,6 +1148,18 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
break;
}
// MGR1 is a plaintext management extension, not an encrypted channel
// datagram. Keep the legacy group payload length shape for opaque relay
// compatibility. Recognize it before any channel decryption/delivery.
if (pkt->getPayloadType() == PAYLOAD_TYPE_GRP_DATA &&
management::validPage(pkt->payload, pkt->payload_len, true)) {
if (!_tables->wasSeen(pkt)) {
_tables->markSeen(pkt);
action = routeRecvPacket(pkt);
}
break;
}
int i = 0;
uint8_t channel_hash = pkt->payload[i++];
@@ -2964,6 +2978,42 @@ bool Mesh::sendOtaFlood(Packet* packet, uint32_t delay_millis) {
}
#endif
bool Mesh::sendManagementData(Packet* packet, bool flood, const uint8_t* path,
uint8_t path_len, uint8_t flood_hash_size,
const uint8_t* scope_key) {
if (!packet) return false;
bool scope_valid = false;
if (scope_key) {
for (unsigned i = 0; i < 16; ++i) scope_valid |= scope_key[i] != 0;
}
if (isAnyTempRadioActive() || packet->getPayloadType() != PAYLOAD_TYPE_RAW_CUSTOM ||
!management::validPage(packet->payload, packet->payload_len) ||
(flood && !scope_valid) ||
(!flood && (!Packet::isValidPathLen(path_len) || ((path_len & 63) && !path)))) {
releasePacket(packet); return false;
}
packet->header = (PAYLOAD_TYPE_GRP_DATA << PH_TYPE_SHIFT)
| (flood ? ROUTE_TYPE_TRANSPORT_FLOOD : ROUTE_TYPE_DIRECT);
const size_t padded = management::floodSize(packet->payload_len);
memset(packet->payload + packet->payload_len, 0, padded - packet->payload_len);
packet->payload_len = padded;
if (flood) {
SHA256 sha;
sha.resetHMAC(scope_key, 16);
const uint8_t type = packet->getPayloadType();
sha.update(&type, 1); sha.update(packet->payload, packet->payload_len);
sha.finalizeHMAC(scope_key, 16,
reinterpret_cast<uint8_t*>(&packet->transport_codes[0]), 2);
if (packet->transport_codes[0] == 0) ++packet->transport_codes[0];
else if (packet->transport_codes[0] == 0xffff) --packet->transport_codes[0];
packet->transport_codes[1] = 0;
packet->setPathHashSizeAndCount(flood_hash_size >= 1 && flood_hash_size <= 3 ? flood_hash_size : 1, 0);
}
else packet->path_len = Packet::copyPath(packet->path, path, path_len);
_tables->markSent(packet);
return sendPacket(packet, 3, 1000);
}
bool Mesh::sendFlood(Packet* packet, uint32_t delay_millis, uint8_t path_hash_size) {
if (packet->getPayloadType() == PAYLOAD_TYPE_TRACE) {
MESH_DEBUG_PRINTLN("%s Mesh::sendFlood(): TRACE type not suspported", getLogDateTime());
+5
View File
@@ -607,6 +607,11 @@ public:
Packet* createPathReturn(const uint8_t* dest_hash, const uint8_t* secret, const uint8_t* path, uint8_t path_len, uint8_t extra_type, const uint8_t*extra, size_t extra_len);
Packet* createPathReturn(const Identity& dest, const uint8_t* secret, const uint8_t* path, uint8_t path_len, uint8_t extra_type, const uint8_t*extra, size_t extra_len);
Packet* createRawData(const uint8_t* data, size_t len);
// Background management traffic, without direct/flood automatic retries.
// Takes ownership on success AND failure, like sendDirect/sendFlood.
bool sendManagementData(Packet* packet, bool flood, const uint8_t* path,
uint8_t path_len, uint8_t flood_hash_size = 1,
const uint8_t* scope_key = nullptr);
#if defined(ENABLE_OTA)
// Build a PAYLOAD_TYPE_OTA packet from raw OTA message bytes (route set by sendOtaFlood).
+2
View File
@@ -149,6 +149,7 @@ static bool isGpioConfig(const char* config) {
void CommonCLI::loop() {
_radio_profiles.loop();
loopManagement();
#if defined(ESP32_PLATFORM) || defined(USER_GPIO_CONTROL)
_user_gpio.loop();
UserGpio::Completion completion;
@@ -2559,6 +2560,7 @@ uint8_t CommonCLI::buildAdvertData(uint8_t node_type, uint8_t* app_data) {
void CommonCLI::handleCommand(uint32_t sender_timestamp, char* command, char* reply) {
PrefsSaveReplyGuard save_reply(_prefs_save_failures, reply);
mesh::cli::normalizeCommandVerb(command);
if (handleManagementCommand(command, reply)) return;
if (mesh::wireless::control().handle(command, reply, 160, millis(),
_callbacks->wirelessCommandSource(sender_timestamp))) return;
if (_radio_profiles.handle(command, reply, 160, sender_timestamp != 0)) return;
+25
View File
@@ -453,6 +453,8 @@ struct LegacyObserverTail {
class CommonCLICallbacks {
public:
// True only after an actual NTP response this boot, not a plausible RTC.
virtual bool managementNtpSynced() const { return false; }
virtual mesh::Radio* getProfileRadio() { return nullptr; }
virtual mesh::FloodAdvertLimiter* getFloodAdvertLimiter() { return nullptr; }
// Ordinary CommonCLI setters mutate NodePrefs and therefore save only the
@@ -729,7 +731,19 @@ class LegacyUpgradeGate;
}
#endif
namespace mesh {
class ManagementReporter;
struct DataRouteState;
}
class CommonCLI {
mesh::ManagementReporter* _management = nullptr;
mesh::DataRouteState* _data_route = nullptr;
mesh::Mesh* _management_mesh = nullptr;
FILESYSTEM* _management_fs = nullptr;
uint64_t _management_uptime_ms = 0;
uint32_t _management_last_ms = 0;
bool handleManagementCommand(char* command, char* reply);
bool handleDataTxCommand(char* command, char* reply);
mesh::RTCClock* _rtc;
NodePrefs* _prefs;
CommonCLICallbacks* _callbacks;
@@ -802,6 +816,17 @@ class CommonCLI {
bool handleObserverCommand(uint32_t sender_timestamp, char* command, char* reply);
public:
void beginManagement(mesh::Mesh& mesh, FILESYSTEM* fs);
void loopManagement();
// Shared delivery configuration for scheduled/background data producers.
// Fresh installs use a zero-hop direct path and automatic region scope;
// producers retain independent disabled-by-default schedules.
bool getDataTxPath(const uint8_t*& path, uint8_t& path_len) const;
bool resolveDataTxScope(TransportKey& scope, char* resolved_name = nullptr,
size_t resolved_name_size = 0,
bool* ambiguous = nullptr) const;
bool adoptLegacyDataTxPath(const uint8_t* path, uint8_t path_len);
bool setDataTxPath(const char* spec, char* reply, size_t reply_size);
bool saveCommonPrefs();
bool savePrimaryRadioParams(float freq, float bw, uint8_t sf, uint8_t cr,
uint16_t preamble);
+389
View File
@@ -0,0 +1,389 @@
#include "CommonCLI.h"
#include "ManagementReporter.h"
#include "FileRead.h"
#include "PersistentStoreFormat.h"
#include <new>
#include <stdlib.h>
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#include "AtomicFileWriter.h"
#else
#include "ContactFileTransaction.h"
#endif
namespace mesh {
static constexpr char DATA_ROUTE_FILE[] = "/data_tx";
static constexpr size_t DATA_ROUTE_SIZE = 108;
enum DataRegionMode : uint8_t {
DATA_REGION_AUTO = 0,
DATA_REGION_DEFAULT = 1,
DATA_REGION_NAMED = 2,
DATA_REGION_NONE = 3,
};
struct DataRouteState {
FILESYSTEM* fs = nullptr;
RegionMap* regions = nullptr;
uint8_t path[MAX_PATH_SIZE] = {};
uint8_t path_len = 0; // safe fresh-install default: zero-hop direct
uint8_t region_mode = DATA_REGION_AUTO;
char region[31] = {};
bool persisted = false;
bool healthy = true;
};
static uint32_t readRoute32(const uint8_t* p) {
return uint32_t(p[0]) | (uint32_t(p[1]) << 8)
| (uint32_t(p[2]) << 16) | (uint32_t(p[3]) << 24);
}
static void writeRoute32(uint8_t* p, uint32_t value) {
p[0] = uint8_t(value); p[1] = uint8_t(value >> 8);
p[2] = uint8_t(value >> 16); p[3] = uint8_t(value >> 24);
}
static uint8_t nibble(char c) {
if (c >= '0' && c <= '9') return uint8_t(c - '0');
if (c >= 'a' && c <= 'f') return uint8_t(c - 'a' + 10);
if (c >= 'A' && c <= 'F') return uint8_t(c - 'A' + 10);
return 0xff;
}
static char* trimDataRoute(char* text) {
while (*text == ' ') ++text;
char* end = text + strlen(text);
while (end > text && end[-1] == ' ') --end;
*end = 0;
return text;
}
static bool parseDataPath(char* raw, uint8_t path[MAX_PATH_SIZE],
uint8_t& path_len, const char*& error) {
char* spec = trimDataRoute(raw);
memset(path, 0, MAX_PATH_SIZE);
if (!strcmp(spec, "direct")) { path_len = 0; return true; }
if (!strcmp(spec, "none") || !strcmp(spec, "clear") || !strcmp(spec, "-")) {
path_len = OUT_PATH_UNKNOWN; return true;
}
// Accept the compact management form (2:12abcd34) as well as the normal
// telemetry/outpath comma form (12ab,cd34).
if (spec[0] >= '1' && spec[0] <= '3' && spec[1] == ':') {
const uint8_t width = uint8_t(spec[0] - '0');
const char* hex = spec + 2;
const size_t chars = strlen(hex);
if (!chars || chars % (width * 2) || chars / 2 > MAX_PATH_SIZE) {
error = "Err - path must be direct, none, or 1|2|3:hex"; return false;
}
const size_t bytes = chars / 2, hops = bytes / width;
if (!hops || hops > 63) { error = "Err - path too long"; return false; }
for (size_t i = 0; i < bytes; ++i) {
const uint8_t hi = nibble(hex[i * 2]), lo = nibble(hex[i * 2 + 1]);
if (hi > 15 || lo > 15) { error = "Err - invalid path hex"; return false; }
path[i] = uint8_t((hi << 4) | lo);
}
path_len = uint8_t(((width - 1) << 6) | hops);
return Packet::isValidPathLen(path_len);
}
uint8_t width = 0, hops = 0;
char* token = spec;
while (token && *token) {
char* comma = strchr(token, ',');
if (comma) *comma = 0;
token = trimDataRoute(token);
const size_t chars = strlen(token);
const uint8_t token_width = uint8_t(chars / 2);
if ((chars != 2 && chars != 4 && chars != 6)
|| (width && width != token_width) || hops >= 63
|| size_t(hops + 1) * token_width > MAX_PATH_SIZE) {
error = "Err - path hashes must have one consistent 1-3 byte width";
return false;
}
if (!width) width = token_width;
for (uint8_t i = 0; i < width; ++i) {
const uint8_t hi = nibble(token[i * 2]), lo = nibble(token[i * 2 + 1]);
if (hi > 15 || lo > 15) { error = "Err - invalid path hex"; return false; }
path[hops * width + i] = uint8_t((hi << 4) | lo);
}
++hops; token = comma ? comma + 1 : nullptr;
}
if (!width || !hops) { error = "Err - missing path"; return false; }
path_len = uint8_t(((width - 1) << 6) | hops);
return Packet::isValidPathLen(path_len);
}
static void formatDataPath(const DataRouteState& route, char* out, size_t size) {
if (route.path_len == OUT_PATH_UNKNOWN) { snprintf(out, size, "none"); return; }
if (!Packet::isValidPathLen(route.path_len)) { snprintf(out, size, "invalid"); return; }
const uint8_t hops = route.path_len & 63;
if (!hops) { snprintf(out, size, "direct"); return; }
const uint8_t width = (route.path_len >> 6) + 1;
size_t used = snprintf(out, size, "%u:", unsigned(width));
for (unsigned i = 0; i < unsigned(hops) * width && used + 2 < size; ++i) {
used += snprintf(out + used, size - used, "%02x", route.path[i]);
}
}
static bool dataRouteSave(DataRouteState& route) {
if (!route.fs) return false;
uint8_t data[DATA_ROUTE_SIZE] = {};
memcpy(data, "DTX1", 4); data[4] = route.path_len; data[5] = route.region_mode;
memcpy(data + 8, route.path, MAX_PATH_SIZE);
memcpy(data + 72, route.region, sizeof(route.region));
writeRoute32(data + 104, storage::updateCRC32(0xffffffff, data, 104));
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
AtomicFileWriter writer(route.fs, DATA_ROUTE_FILE);
#else
ContactFileTransaction writer(route.fs, DATA_ROUTE_FILE);
#endif
const bool ok = writer && writer.write(data, sizeof(data)) == sizeof(data)
&& writer.commit();
if (ok) route.persisted = true;
return ok;
}
static bool dataRouteLoad(DataRouteState& route) {
#if defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
if (!ContactFileTransaction::recover(route.fs, DATA_ROUTE_FILE)) return false;
#endif
if (!route.fs->exists(DATA_ROUTE_FILE)) return true;
uint8_t data[DATA_ROUTE_SIZE] = {};
for (unsigned retry = 0; retry < 3; ++retry) {
auto file = openFileRead(route.fs, DATA_ROUTE_FILE);
const bool read = file && file.size() == sizeof(data)
&& file.read(data, sizeof(data)) == sizeof(data);
if (file) file.close();
const bool named = data[5] == DATA_REGION_NAMED;
if (!read || memcmp(data, "DTX1", 4)
|| (data[4] != OUT_PATH_UNKNOWN && !Packet::isValidPathLen(data[4]))
|| data[5] > DATA_REGION_NONE || (named && !data[72])
|| data[102] != 0
|| readRoute32(data + 104)
!= storage::updateCRC32(0xffffffff, data, 104)) continue;
route.path_len = data[4]; route.region_mode = data[5];
memcpy(route.path, data + 8, MAX_PATH_SIZE);
memcpy(route.region, data + 72, sizeof(route.region));
route.region[sizeof(route.region) - 1] = 0;
route.persisted = true;
return true;
}
return false;
}
static uint8_t regionDepth(const RegionMap& regions, const RegionEntry* region) {
if (!region || region->isWildcard()) return 0;
uint8_t depth = 1;
uint16_t parent = region->parent;
for (int walked = 0; parent; ++walked) {
if (walked >= regions.getCount()) return 0;
const RegionEntry* entry = const_cast<RegionMap&>(regions).findById(parent);
if (!entry || entry->isWildcard()) return 0;
++depth; parent = entry->parent;
}
return depth;
}
static bool usableScope(DataRouteState& route, const RegionEntry* region,
TransportKey& scope) {
return region && !region->isWildcard() && !(region->flags & REGION_DENY_FLOOD)
&& route.regions->getTransportKeysFor(*region, &scope, 1) > 0
&& !scope.isNull();
}
static bool resolveDataScope(DataRouteState& route, TransportKey& scope,
char* resolved, size_t resolved_size,
bool* ambiguity) {
if (resolved && resolved_size) resolved[0] = 0;
if (ambiguity) *ambiguity = false;
const RegionEntry* selected = nullptr;
if (route.region_mode == DATA_REGION_NONE) return false;
if (route.region_mode == DATA_REGION_DEFAULT) {
selected = route.regions->getDefaultRegion();
} else if (route.region_mode == DATA_REGION_NAMED) {
selected = route.regions->findByName(route.region);
} else {
// Auto follows an explicit radio default when it is usable. Radios
// without one fall back to the single narrowest usable region in the
// definition, which keeps fresh installs deterministic without silently
// choosing between equally specific scopes.
selected = route.regions->getDefaultRegion();
TransportKey default_scope;
if (usableScope(route, selected, default_scope)) {
scope = default_scope;
if (resolved && resolved_size) {
strncpy(resolved, selected->name, resolved_size - 1);
resolved[resolved_size - 1] = 0;
}
return true;
}
selected = nullptr;
uint8_t best_depth = 0;
bool tied = false;
for (int i = 0; i < route.regions->getCount(); ++i) {
const RegionEntry* candidate = route.regions->getByIdx(i);
TransportKey candidate_scope;
if (!usableScope(route, candidate, candidate_scope)) continue;
const uint8_t depth = regionDepth(*route.regions, candidate);
if (depth > best_depth) { selected = candidate; best_depth = depth; tied = false; }
else if (depth && depth == best_depth) tied = true;
}
if (tied) { if (ambiguity) *ambiguity = true; return false; }
}
if (!usableScope(route, selected, scope)) return false;
if (resolved && resolved_size) {
strncpy(resolved, selected->name, resolved_size - 1);
resolved[resolved_size - 1] = 0;
}
return true;
}
} // namespace mesh
void CommonCLI::beginManagement(mesh::Mesh& mesh, FILESYSTEM* fs) {
_management_mesh = &mesh; _management_fs = fs;
_management_last_ms = millis(); _management_uptime_ms = _management_last_ms;
if (!_data_route) {
_data_route = new (std::nothrow) mesh::DataRouteState;
if (_data_route) {
_data_route->fs = fs; _data_route->regions = _region_map;
_data_route->healthy = mesh::dataRouteLoad(*_data_route);
}
}
// No reporter/history allocation for the default unconfigured installation.
if (fs->exists("/management") || fs->exists("/management.bak")) {
_management = new (std::nothrow) mesh::ManagementReporter(
mesh, *_board, *_sensors, *_acl, *_prefs, *_callbacks, *this, fs);
}
}
void CommonCLI::loopManagement() {
const uint32_t now = millis();
_management_uptime_ms += uint32_t(now - _management_last_ms); _management_last_ms = now;
if (_management) _management->loop(_management_uptime_ms / 1000);
}
bool CommonCLI::getDataTxPath(const uint8_t*& path, uint8_t& path_len) const {
static const uint8_t direct[MAX_PATH_SIZE] = {};
if (!_data_route || !_data_route->healthy) { path = direct; path_len = OUT_PATH_UNKNOWN; return false; }
path = _data_route->path; path_len = _data_route->path_len;
return path_len != OUT_PATH_UNKNOWN && mesh::Packet::isValidPathLen(path_len);
}
bool CommonCLI::resolveDataTxScope(TransportKey& scope, char* name,
size_t name_size, bool* ambiguous) const {
return _data_route && _data_route->healthy
&& mesh::resolveDataScope(*_data_route, scope, name, name_size, ambiguous);
}
bool CommonCLI::adoptLegacyDataTxPath(const uint8_t* path, uint8_t path_len) {
if (!_data_route || !_data_route->healthy || _data_route->persisted
|| path_len == OUT_PATH_UNKNOWN || !mesh::Packet::isValidPathLen(path_len)
|| ((path_len & 63) && !path)) return false;
const uint8_t previous_len = _data_route->path_len;
uint8_t previous[MAX_PATH_SIZE]; memcpy(previous, _data_route->path, sizeof(previous));
_data_route->path_len = path_len; memset(_data_route->path, 0, sizeof(_data_route->path));
if (path_len & 63) mesh::Packet::copyPath(_data_route->path, path, path_len);
if (mesh::dataRouteSave(*_data_route)) return true;
_data_route->path_len = previous_len; memcpy(_data_route->path, previous, sizeof(previous));
return false;
}
bool CommonCLI::setDataTxPath(const char* spec, char* reply, size_t reply_size) {
if (!spec || strlen(spec) > 140) {
snprintf(reply, reply_size, "Err - invalid data.tx path"); return false;
}
char command[160];
snprintf(command, sizeof(command), "set data.tx path %s", spec);
char result[160] = {};
const bool handled = handleDataTxCommand(command, result);
snprintf(reply, reply_size, "%s", result);
return handled && !strncmp(result, "OK", 2);
}
bool CommonCLI::handleDataTxCommand(char* command, char* reply) {
const bool get_all = !strcmp(command, "get data.tx");
const bool get_path = !strcmp(command, "get data.tx path") || !strcmp(command, "get data.tx.path");
const bool get_region = !strcmp(command, "get data.tx region") || !strcmp(command, "get data.tx.region");
const char* path_prefix = !strncmp(command, "set data.tx path ", 17) ? "set data.tx path "
: (!strncmp(command, "set data.tx.path ", 17) ? "set data.tx.path " : nullptr);
const char* region_prefix = !strncmp(command, "set data.tx region ", 19) ? "set data.tx region "
: (!strncmp(command, "set data.tx.region ", 19) ? "set data.tx.region " : nullptr);
if (!get_all && !get_path && !get_region && !path_prefix && !region_prefix) return false;
if (!_data_route) { strcpy(reply, "Err - data.tx unavailable"); return true; }
if (!_data_route->healthy) { strcpy(reply, "Err - data.tx storage fault"); return true; }
char path_text[132]; mesh::formatDataPath(*_data_route, path_text, sizeof(path_text));
if (get_path) { snprintf(reply, 160, "> %s", path_text); return true; }
if (get_region) {
if (_data_route->region_mode == mesh::DATA_REGION_AUTO) {
char resolved[31]; bool ambiguous = false; TransportKey scope;
const bool ok = resolveDataTxScope(scope, resolved, sizeof(resolved), &ambiguous);
snprintf(reply, 160, "> auto (%s)", ok ? resolved : ambiguous ? "ambiguous" : "unresolved");
} else if (_data_route->region_mode == mesh::DATA_REGION_DEFAULT) strcpy(reply, "> default");
else if (_data_route->region_mode == mesh::DATA_REGION_NONE) strcpy(reply, "> none");
else snprintf(reply, 160, "> %s", _data_route->region);
return true;
}
if (get_all) {
char resolved[31]; bool ambiguous = false; TransportKey scope;
const bool scoped = resolveDataTxScope(scope, resolved, sizeof(resolved), &ambiguous);
const char* mode = _data_route->region_mode == mesh::DATA_REGION_AUTO ? "auto"
: _data_route->region_mode == mesh::DATA_REGION_DEFAULT ? "default"
: _data_route->region_mode == mesh::DATA_REGION_NONE ? "none" : _data_route->region;
snprintf(reply, 160, "> path=%s region=%s resolved=%s", path_text, mode,
scoped ? resolved : ambiguous ? "ambiguous" : "none");
return true;
}
const mesh::DataRouteState previous = *_data_route;
if (path_prefix) {
char* value = command + strlen(path_prefix); const char* error = nullptr;
uint8_t candidate[MAX_PATH_SIZE], encoded = OUT_PATH_UNKNOWN;
if (!mesh::parseDataPath(value, candidate, encoded, error)) {
snprintf(reply, 160, "%s", error ? error : "Err - invalid path"); return true;
}
_data_route->path_len = encoded; memcpy(_data_route->path, candidate, sizeof(candidate));
} else {
char* value = mesh::trimDataRoute(command + strlen(region_prefix));
if (!strcmp(value, "auto")) { _data_route->region_mode = mesh::DATA_REGION_AUTO; _data_route->region[0] = 0; }
else if (!strcmp(value, "default")) { _data_route->region_mode = mesh::DATA_REGION_DEFAULT; _data_route->region[0] = 0; }
else if (!strcmp(value, "none") || !strcmp(value, "clear") || !strcmp(value, "-")) {
_data_route->region_mode = mesh::DATA_REGION_NONE; _data_route->region[0] = 0;
} else {
RegionEntry* region = _region_map->findByNamePrefix(value);
TransportKey scope;
if (!region || !mesh::usableScope(*_data_route, region, scope)) {
strcpy(reply, "Err - unknown, ambiguous, denied, or unusable region"); return true;
}
_data_route->region_mode = mesh::DATA_REGION_NAMED;
strncpy(_data_route->region, region->name, sizeof(_data_route->region) - 1);
_data_route->region[sizeof(_data_route->region) - 1] = 0;
}
}
if (!mesh::dataRouteSave(*_data_route)) {
*_data_route = previous; strcpy(reply, "Err - unable to save data.tx"); return true;
}
strcpy(reply, "OK"); return true;
}
bool CommonCLI::handleManagementCommand(char* command, char* reply) {
if (handleDataTxCommand(command, reply)) return true;
if (!strcmp(command, "get mgmt.path")) {
char alias[] = "get data.tx path";
return handleDataTxCommand(alias, reply);
}
if (!strncmp(command, "set mgmt.path ", 14)) {
char alias[160];
snprintf(alias, sizeof(alias), "set data.tx path %s", command + 14);
return handleDataTxCommand(alias, reply);
}
if (strcmp(command, "get mgmt") && strncmp(command, "get mgmt.", 9)
&& strncmp(command, "set mgmt.", 9)) return false;
if (!_management && _management_mesh && _management_fs) {
_management = new (std::nothrow) mesh::ManagementReporter(
*_management_mesh, *_board, *_sensors, *_acl, *_prefs, *_callbacks, *this,
_management_fs);
}
if (!_management) { strcpy(reply, "ERR: management unavailable"); return true; }
if (!_management->command(command, reply, 160)) strcpy(reply, "ERR: unknown management setting");
return true;
}
+82
View File
@@ -0,0 +1,82 @@
#include "ManagementReport.h"
#include <AES.h>
#include <SHA256.h>
namespace mesh { namespace management {
void passwordKey(const char* password, uint8_t key[32]) {
SHA256 hash; hash.reset(); hash.update("#", 1);
hash.update(password, strlen(password)); hash.finalize(key, 32);
}
void deriveKey(const uint8_t key[32], const char* domain, const uint8_t radio[16], uint8_t out[32]) {
SHA256 hash; hash.resetHMAC(key, 32); hash.update(domain, strlen(domain));
hash.update(radio, 16); hash.finalizeHMAC(key, 32, out, 32);
}
void fingerprint(const uint8_t key[32], const uint8_t radio[16], const uint8_t admin[32], uint8_t out[12]) {
uint8_t derived[32]; deriveKey(key, "MeshCore-MGR1-ACL", radio, derived);
SHA256 hash; hash.resetHMAC(derived, 32); hash.update(radio, 16); hash.update(admin, 32);
hash.finalizeHMAC(derived, 32, out, 12); erase(derived, sizeof(derived));
}
bool equal(const uint8_t* a, const uint8_t* b, size_t size) {
uint8_t d = 0; while (size--) d |= *a++ ^ *b++; return d == 0;
}
static void dbl(uint8_t b[16]) {
const uint8_t carry = b[0] >> 7;
for (unsigned i = 0; i < 15; ++i) b[i] = (b[i] << 1) | (b[i + 1] >> 7);
b[15] = (b[15] << 1) ^ (carry ? 0x87 : 0);
}
// NIST SP 800-38B CMAC, using the existing rweather AES implementation.
static void cmac(AES128& aes, const uint8_t* data, size_t len, uint8_t out[16]) {
uint8_t subkey[16] = {}, block[16] = {};
aes.encryptBlock(subkey, subkey); dbl(subkey);
while (len > 16) {
for (unsigned i = 0; i < 16; ++i) block[i] ^= data[i];
aes.encryptBlock(block, block); data += 16; len -= 16;
}
for (size_t i = 0; i < len; ++i) block[i] ^= data[i];
if (len < 16) { dbl(subkey); block[len] ^= 0x80; }
for (unsigned i = 0; i < 16; ++i) block[i] ^= subkey[i];
aes.encryptBlock(out, block); erase(subkey, 16); erase(block, 16);
}
static void s2v(const uint8_t key[32], const uint8_t* aad, size_t aad_len,
const uint8_t* data, size_t len, uint8_t tag[16]) {
AES128 aes; aes.setKey(key, 16);
uint8_t d[16] = {}, t[16], buf[MAX_PAYLOAD] = {};
cmac(aes, d, 16, d); dbl(d); cmac(aes, aad, aad_len, t);
for (unsigned i = 0; i < 16; ++i) d[i] ^= t[i];
if (len >= 16) {
memcpy(buf, data, len);
for (unsigned i = 0; i < 16; ++i) buf[len - 16 + i] ^= d[i];
cmac(aes, buf, len, tag);
} else {
dbl(d); memcpy(buf, data, len); buf[len] = 0x80;
for (unsigned i = 0; i < 16; ++i) buf[i] ^= d[i];
cmac(aes, buf, 16, tag);
}
erase(buf, sizeof(buf)); erase(d, 16); erase(t, 16);
}
static void ctr(const uint8_t key[32], uint8_t* data, size_t len, const uint8_t tag[16]) {
AES128 aes; aes.setKey(key + 16, 16);
uint8_t counter[16], stream[16]; memcpy(counter, tag, 16);
counter[8] &= 0x7f; counter[12] &= 0x7f;
while (len) {
aes.encryptBlock(stream, counter); const size_t n = len < 16 ? len : 16;
for (size_t i = 0; i < n; ++i) data[i] ^= stream[i];
data += n; len -= n;
for (int i = 15; i >= 0 && ++counter[i] == 0; --i) {}
}
erase(counter, 16); erase(stream, 16);
}
bool seal(const uint8_t key[32], const uint8_t* aad, size_t aad_len,
uint8_t* data, size_t len, uint8_t tag[16]) {
if (len > MAX_PAYLOAD || aad_len > MAX_PAYLOAD) return false;
s2v(key, aad, aad_len, data, len, tag); ctr(key, data, len, tag); return true;
}
bool open(const uint8_t key[32], const uint8_t* aad, size_t aad_len,
uint8_t* data, size_t len, const uint8_t tag[16]) {
if (len > MAX_PAYLOAD || aad_len > MAX_PAYLOAD) return false;
uint8_t expected[16]; ctr(key, data, len, tag); s2v(key, aad, aad_len, data, len, expected);
const bool ok = equal(expected, tag, 16); erase(expected, 16);
if (!ok) erase(data, len);
return ok;
}
} }
+125
View File
@@ -0,0 +1,125 @@
#pragma once
#include <stdint.h>
#include <stddef.h>
#include <string.h>
#include <math.h>
// Portable management wire format. No update authorization is granted by this
// protocol. See docs/management_reports.md for the byte layout and trust model.
namespace mesh { namespace management {
constexpr size_t HEADER = 83, TAG = 16, ENTRY = 13, PER_PAGE = 6;
constexpr size_t MAX_KEYS = 36, MAX_PAGES = 6, MAX_PAYLOAD = HEADER + TAG + PER_PAGE * ENTRY;
constexpr uint32_t DAY = 86400, FLOOD_INTERVAL = 21 * DAY;
enum Feature : uint8_t { WIFI = 1, GPS = 2, NTP = 4, USB = 8, OTA = 16 };
enum Valid : uint16_t { FIRMWARE = 1, BOOTLOADER = 2, BASE = 4, STORE = 8,
PARTIAL_WEEK = 16, PARTIAL_PERIOD = 32, MCU_TEMPERATURE = 64 };
enum Permission : uint8_t { ADMIN = 1, OTA_SIGNER = 2 };
inline uint16_t read16(const uint8_t* p) { return p[0] | (uint16_t(p[1]) << 8); }
inline uint32_t read32(const uint8_t* p) { return read16(p) | (uint32_t(read16(p + 2)) << 16); }
inline void write16(uint8_t* p, uint16_t n) { p[0] = n; p[1] = n >> 8; }
inline void write32(uint8_t* p, uint32_t n) { write16(p, n); write16(p + 2, n >> 16); }
inline void erase(void* p, size_t n) { volatile uint8_t* b = static_cast<volatile uint8_t*>(p); while (n--) *b++ = 0; }
// 0 missing, 1..251 = -50..200 C, 252 below range, 253 above range.
inline uint8_t temperature(float c) {
if (!isfinite(c)) return 0;
if (c < -50) return 252;
if (c > 200) return 253;
return uint8_t(lroundf(c) + 51);
}
inline int tempOrder(uint8_t t) { return t == 252 ? -1 : t == 253 ? 252 : t; }
struct Extrema {
uint16_t voltage = 0;
uint8_t low = 0, high = 0;
void add(uint16_t v, uint8_t t) {
if (v && (!voltage || v < voltage)) voltage = v;
if (t && (!low || tempOrder(t) < tempOrder(low))) low = t;
if (t && (!high || tempOrder(t) > tempOrder(high))) high = t;
}
void merge(const Extrema& e) { add(e.voltage, e.low); add(0, e.high); }
void encode(uint8_t* p) const { write16(p, voltage); p[2] = low; p[3] = high; }
};
// Hourly extrema, retaining at least seven days, at most seven days + one
// hour. Sampling once a minute includes all samples, not only the first one
// in each bucket. No RTC dependence and no claim of pre-boot history.
class History {
Extrema hours[169] = {};
uint32_t hour = 0;
bool started = false;
public:
Extrema period;
void advance(uint32_t seconds) {
const uint32_t h = seconds / 3600;
if (!started || h < hour || h - hour >= 169) memset(hours, 0, sizeof(hours));
else for (uint32_t i = hour + 1; i <= h; ++i) hours[i % 169] = Extrema();
started = true; hour = h;
}
void sample(uint32_t seconds, uint16_t v, float c) {
advance(seconds); const uint8_t t = temperature(c);
hours[hour % 169].add(v, t); period.add(v, t);
}
Extrema week() const { Extrema result; for (const auto& h : hours) result.merge(h); return result; }
};
// Countdown seconds survive reboot via conservative hourly checkpoints.
// Wall-clock changes never accelerate reporting. Offline time is not credited.
struct Schedule {
uint32_t direct = 5 * DAY, flood = 21 * DAY;
static uint32_t sub(uint32_t n, uint32_t elapsed) { return elapsed < n ? n - elapsed : 0; }
void advance(uint32_t elapsed) { direct = sub(direct, elapsed); flood = sub(flood, elapsed); }
static bool validDirect(unsigned days) { return days >= 5 && days <= 90; }
static bool validFlood(unsigned days) { return days >= 21 && days <= 90; }
void reserve(bool is_flood, unsigned direct_days, unsigned flood_days,
uint32_t jitter) {
if (is_flood) {
flood = flood_days * DAY + jitter;
// A flood replaces a direct copy only when that copy is already due.
// Otherwise the independent direct cadence is left untouched.
if (!direct && direct_days) direct = direct_days * DAY + jitter;
} else {
direct = direct_days * DAY + jitter;
}
}
};
void passwordKey(const char* password, uint8_t key[32]);
void deriveKey(const uint8_t key[32], const char* domain, const uint8_t radio[16], uint8_t out[32]);
void fingerprint(const uint8_t key[32], const uint8_t radio[16], const uint8_t admin[32], uint8_t out[12]);
// RFC 5297 AES-SIV with one associated-data string. Tag is stored separately.
// Bound to packet-sized data; decrypt erases plaintext on authentication failure.
bool seal(const uint8_t key[32], const uint8_t* aad, size_t aad_len,
uint8_t* data, size_t len, uint8_t tag[16]);
bool open(const uint8_t key[32], const uint8_t* aad, size_t aad_len,
uint8_t* data, size_t len, const uint8_t tag[16]);
bool equal(const uint8_t* a, const uint8_t* b, size_t size);
inline size_t pageSize(const uint8_t* p) { return HEADER + p[82] * ENTRY + TAG; }
inline size_t floodSize(size_t canonical) { return 3 + ((canonical - 3 + 15) / 16) * 16; }
inline bool validPage(const uint8_t* p, size_t size, bool flood_padding = false) {
if (!p || size < HEADER + TAG || size > (flood_padding ? 179 : MAX_PAYLOAD) || memcmp(p, "MGR1", 4)) return false;
const unsigned page = p[78], pages = p[79], total = p[80], first = p[81], count = p[82];
const unsigned expected_pages = total ? (total + PER_PAGE - 1) / PER_PAGE : 1;
if (total > MAX_KEYS || pages != expected_pages || page >= pages || first != page * PER_PAGE || first > total) return false;
const unsigned remaining = total - first;
if (count != (remaining < PER_PAGE ? remaining : PER_PAGE)) return false;
const size_t canonical = pageSize(p);
if (size != (flood_padding ? floodSize(canonical) : canonical)) return false;
for (size_t i = canonical; i < size; ++i) if (p[i]) return false;
return true;
}
struct AclList {
uint8_t entries[MAX_KEYS][ENTRY] = {};
uint8_t count = 0;
bool add(const uint8_t token[12], uint8_t permissions) {
for (uint8_t i = 0; i < count; ++i) {
if (!memcmp(entries[i], token, 12)) { entries[i][12] |= permissions; return true; }
}
if (count == MAX_KEYS) return false;
memcpy(entries[count], token, 12); entries[count++][12] = permissions; return true;
}
uint8_t pages() const { return count ? (count + PER_PAGE - 1) / PER_PAGE : 1; }
};
} }
+386
View File
@@ -0,0 +1,386 @@
#include "ManagementReporter.h"
#include "CommonCLI.h"
#include "FileRead.h"
#include "PersistentStoreFormat.h"
#include <new>
#include <stdlib.h>
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
#include "AtomicFileWriter.h"
#else
#include "ContactFileTransaction.h"
#endif
#if defined(ESP32_PLATFORM)
#include <WiFi.h>
#include <esp_ota_ops.h>
#endif
#if defined(ENABLE_OTA)
#include "ota/OtaContext.h"
#include "ota/OtaDeflate.h"
#endif
namespace mesh {
using namespace management;
static constexpr char STATE_FILE[] = "/management";
static constexpr size_t STATE_SIZE = 120;
struct ManagementReporter::Working {
History history;
Extrema during_report;
AclList acl;
uint8_t header[HEADER] = {};
TransportKey scope;
uint8_t route_path[MAX_PATH_SIZE] = {};
uint8_t route_path_len = OUT_PATH_UNKNOWN;
uint32_t sample_in = 0, page_in = 0, lifetime = 0, history_seconds = 0;
uint8_t page = 0;
bool sending = false, flood = false, partial_period = true;
};
ManagementReporter::ManagementReporter(Mesh& mesh, MainBoard& board, SensorManager& sensors,
ClientACL& acl, NodePrefs& prefs, CommonCLICallbacks& callbacks,
CommonCLI& cli, FILESYSTEM* fs)
: mesh(mesh), board(board), sensors(sensors), acl(acl), prefs(prefs),
callbacks(callbacks), cli(cli), fs(fs) {
last_ms = millis(); healthy = load();
if (healthy && enabled && !allocate()) healthy = false;
}
ManagementReporter::~ManagementReporter() { delete work; erase(key, sizeof(key)); }
bool ManagementReporter::allocate() {
static_assert(sizeof(Working) <= 1536, "Keep opt-in management working RAM bounded");
if (!work) work = new (std::nothrow) Working;
return work != nullptr;
}
bool ManagementReporter::load() {
#if defined(ESP32_PLATFORM) || defined(RP2040_PLATFORM)
if (!ContactFileTransaction::recover(fs, STATE_FILE)) return false;
#endif
if (!fs->exists(STATE_FILE)) return true; // fresh install remains off
uint8_t b[STATE_SIZE] = {};
for (unsigned retry = 0; retry < 3; ++retry) {
auto f = openFileRead(fs, STATE_FILE);
const bool read = f && f.size() == sizeof(b) && f.read(b, sizeof(b)) == sizeof(b);
if (f) f.close();
const bool legacy = read && !memcmp(b, "MGC1", 4);
const bool current = read && !memcmp(b, "MGC2", 4);
const bool direct_valid = legacy ? Schedule::validDirect(b[5])
: (b[5] == 0 || Schedule::validDirect(b[5]));
const bool flood_valid = legacy
? (b[7] == OUT_PATH_UNKNOWN || Packet::isValidPathLen(b[7]))
: (b[7] == 0 || Schedule::validFlood(b[7]));
if ((!legacy && !current) || b[4] > 1 || b[6] > 1 ||
!direct_valid || !flood_valid || (b[4] && (!b[6] || (!b[5] && !b[7]))) ||
read32(b + 116) != storage::updateCRC32(0xffffffff, b, 116) ||
read32(b + 104) > 90 * DAY + 3600 || read32(b + 108) > 90 * DAY + 3600) continue;
enabled = b[4]; direct_days = b[5]; keyed = b[6];
flood_days = legacy ? (direct_days < 21 ? 21 : direct_days) : b[7];
if (legacy && b[7] != OUT_PATH_UNKNOWN) cli.adoptLegacyDataTxPath(b + 8, b[7]);
memcpy(key, b + 72, 32);
schedule.direct = read32(b + 104); schedule.flood = read32(b + 108);
if (!direct_days) schedule.direct = 0;
if (!flood_days) schedule.flood = 0;
sequence = read32(b + 112); erase(b, sizeof(b)); return true;
}
erase(b, sizeof(b)); return false; // unreadable/corrupt state never transmits
}
bool ManagementReporter::save() {
uint8_t b[STATE_SIZE] = {};
memcpy(b, "MGC2", 4); b[4] = enabled; b[5] = direct_days; b[6] = keyed;
b[7] = flood_days; memcpy(b + 72, key, 32);
write32(b + 104, schedule.direct); write32(b + 108, schedule.flood); write32(b + 112, sequence);
write32(b + 116, storage::updateCRC32(0xffffffff, b, 116));
#if defined(NRF52_PLATFORM) || defined(STM32_PLATFORM)
AtomicFileWriter writer(fs, STATE_FILE);
#else
ContactFileTransaction writer(fs, STATE_FILE);
#endif
const bool ok = writer && writer.write(b, sizeof(b)) == sizeof(b) && writer.commit();
erase(b, sizeof(b)); if (ok) checkpoint = 0; return ok;
}
void ManagementReporter::cancel() {
if (work) work->sending = false;
}
uint32_t ManagementReporter::jitter() const {
return (read32(mesh.self_id.pub_key) ^ (sequence * 2654435761UL)) % 3600;
}
void ManagementReporter::snapshot() {
auto& w = *work; memset(w.header, 0, sizeof(w.header)); w.acl = AclList();
auto* p = w.header; memcpy(p, "MGR1", 4); memcpy(p + 4, mesh.self_id.pub_key, 16);
write32(p + 20, sequence); write32(p + 24, mesh.getRTCClock()->getCurrentTime());
const uint64_t hours = uptime / 3600; write16(p + 60, hours > 65535 ? 65535 : hours);
w.history.week().encode(p + 62); w.history.period.encode(p + 66);
const uint32_t history_hours = w.history_seconds / 3600;
p[70] = history_hours > 168 ? 168 : history_hours;
p[71] = w.flood ? flood_days : direct_days;
p[72] = !strcmp(callbacks.getRole(), "repeater") ? 1 : !strcmp(callbacks.getRole(), "room_server") ? 2 : 3;
uint16_t valid = MCU_TEMPERATURE | (history_hours < 168 ? PARTIAL_WEEK : 0) | (w.partial_period ? PARTIAL_PERIOD : 0);
p[75] = GPS | OTA; // known active-state bits; unknown is not confused with off
if (sensors.isGPSDetected()) p[73] |= GPS;
auto* gps = sensors.getLocationProvider();
if (gps && gps->isEnabled()) p[74] |= GPS;
#if defined(ESP32_PLATFORM)
p[73] |= WIFI; p[75] |= WIFI;
if (WiFi.status() == WL_CONNECTED) p[74] |= WIFI;
#endif
#if defined(NRF52_PLATFORM) || (defined(ARDUINO_USB_CDC_ON_BOOT) && ARDUINO_USB_CDC_ON_BOOT)
p[73] |= USB; p[75] |= USB;
if (board.isUsbDataConnected()) p[74] |= USB;
#endif
#ifdef WITH_MQTT_BRIDGE
p[73] |= NTP; p[75] |= NTP;
if (callbacks.managementNtpSynced()) p[74] |= NTP;
#endif
#if defined(ENABLE_OTA)
p[73] |= OTA;
ota::SelfFwInfo info;
if (ota::ota_self_firmware(info) && info.valid) {
write32(p + 28, info.fw_version); write32(p + 36, info.target_id);
memcpy(p + 40, info.body_hash, 8); write32(p + 48, info.image_len);
valid |= BASE; if (info.fw_version) valid |= FIRMWARE;
}
uint32_t caps = 1; // compiled OTA protocol
// bits 8..23 apply codecs; transfer capabilities are separate low bits.
caps |= 2; // OTA transport decoder is installed in all ENABLE_OTA builds
caps |= 4; // 2 KiB application transfer blocks
#if defined(ESP32_PLATFORM)
const esp_partition_t* running = esp_ota_get_running_partition();
const esp_partition_t* next = esp_ota_get_next_update_partition(nullptr);
if (running && next && running->address != next->address) {
write32(p + 52, next->size); valid |= STORE; p[74] |= OTA;
caps |= 7UL << 8; // full + detools sequential + in-place
}
#elif defined(NRF52_PLATFORM)
const auto bl = ota::ota_bootloader_app_caps();
#if defined(OTA_SD_STORE) || defined(OTA_QSPI_STORE)
const uint16_t codecs = bl.codec_mask & 5u; // full + in-place
#else
const uint16_t codecs = bl.codec_mask & 4u; // internal app path accepts deltas only
#endif
if (bl.present && bl.apply_abi >= 2) caps |= uint32_t(codecs) << 8;
ota::OtaBootloaderIdentity identity;
if (ota::ota_installed_bootloader_identity(identity) && identity.boot_version) {
write32(p + 32, identity.boot_version); valid |= BOOTLOADER;
}
// Never allocate an OTA workspace or wake external media just for a report.
if (auto* context = ota::ota_context_if_active()) {
const uint32_t capacity = context->fetch_store.capacity();
write32(p + 52, capacity); valid |= STORE;
if (capacity && bl.present && bl.apply_abi >= 2 && codecs) p[74] |= OTA;
} else {
p[75] &= ~OTA; // compiled support, readiness not established
}
#else
p[75] &= ~OTA;
#endif
#if defined(OTA_SEEDER_ONLY)
caps &= 0xff; p[74] &= ~OTA;
#endif
write32(p + 56, caps);
#endif
// If EndF is absent, only publish a version we can parse unambiguously.
if (!(valid & FIRMWARE)) {
unsigned major = 0, minor = 0, patch = 0, pre = 0;
const char* version = callbacks.getFirmwareVer(); if (*version == 'v') ++version;
const int n = sscanf(version, "%u.%u.%u.%u", &major, &minor, &patch, &pre);
if (n >= 3 && major <= 255 && minor <= 255 && patch <= 255 && pre <= 255) {
write32(p + 28, major << 24 | minor << 16 | patch << 8 | pre); valid |= FIRMWARE;
}
}
write16(p + 76, valid);
uint8_t token[12]; bool complete = true;
for (int i = 0; i < acl.getNumClients(); ++i) {
const auto* client = acl.getClientByIdx(i);
if (!client->isAdmin()) continue;
fingerprint(key, p + 4, client->id.pub_key, token); complete &= w.acl.add(token, ADMIN);
}
#if defined(ENABLE_OTA)
if (prefs.ota_signer_count > 4) complete = false;
for (unsigned i = 0; i < prefs.ota_signer_count && i < 4; ++i) {
fingerprint(key, p + 4, prefs.ota_signers[i], token); complete &= w.acl.add(token, OTA_SIGNER);
}
#endif
erase(token, sizeof(token));
if (!complete) healthy = false; // never silently truncate an ACL
}
void ManagementReporter::start(bool flood) {
if (sequence == UINT32_MAX) { healthy = false; return; }
auto& w = *work;
w.route_path_len = OUT_PATH_UNKNOWN;
memset(w.route_path, 0, sizeof(w.route_path));
if (flood) {
if (!cli.resolveDataTxScope(w.scope)) return;
} else {
const uint8_t* configured = nullptr;
if (!cli.getDataTxPath(configured, w.route_path_len)) return;
if (w.route_path_len & 63) {
Packet::copyPath(w.route_path, configured, w.route_path_len);
}
}
++sequence; schedule.reserve(flood, direct_days, flood_days, jitter());
if (!save()) { healthy = false; return; } // reserve BEFORE any packet leaves
w.flood = flood;
snapshot(); if (!healthy) return;
w.page = 0; w.page_in = 0;
w.during_report = Extrema();
w.sending = true; w.lifetime = 3600;
}
void ManagementReporter::sendPage() {
auto& w = *work;
uint8_t packet[MAX_PAYLOAD], enc[32]; memcpy(packet, w.header, HEADER);
const uint8_t first = w.page * PER_PAGE;
const uint8_t count = w.acl.count - first < PER_PAGE ? w.acl.count - first : PER_PAGE;
packet[78] = w.page; packet[79] = w.acl.pages(); packet[80] = w.acl.count;
packet[81] = first; packet[82] = count;
const size_t private_len = count * ENTRY, size = HEADER + private_len + TAG;
memcpy(packet + HEADER, w.acl.entries + first, private_len);
deriveKey(key, "MeshCore-MGR1-SIV", packet + 4, enc);
seal(enc, packet, HEADER, packet + HEADER, private_len, packet + HEADER + private_len);
erase(enc, sizeof(enc));
Packet* pkt = mesh.createRawData(packet, size);
if (!pkt) { w.page_in = 60; return; }
// Dedicated background admission avoids normal direct-message priority and
// automatic retries. Dispatcher still enforces normal channel/duty limits.
if (!mesh.sendManagementData(pkt, w.flood, w.route_path, w.route_path_len,
prefs.path_hash_mode + 1,
w.flood ? w.scope.key : nullptr)) {
w.page_in = 60; return;
}
++w.page; w.page_in = 60;
if (w.page == w.acl.pages()) {
w.sending = false;
// Readings gathered while the frozen snapshot was being paged belong to
// the next report. Never discard that interval on completion.
w.history.period = w.during_report; w.partial_period = false;
}
}
void ManagementReporter::loop(uint64_t node_uptime_seconds) {
const uint32_t now = millis(), delta = now - last_ms; last_ms = now;
const uint64_t accumulated = uint64_t(fraction_ms) + delta;
const uint32_t elapsed = accumulated / 1000; fraction_ms = accumulated % 1000;
uptime = node_uptime_seconds == UINT64_MAX ? uptime + elapsed : node_uptime_seconds;
if (!healthy || !enabled || !keyed || !work) return;
auto& w = *work; schedule.advance(elapsed); checkpoint += elapsed;
w.history_seconds += elapsed;
w.sample_in = Schedule::sub(w.sample_in, elapsed);
w.page_in = Schedule::sub(w.page_in, elapsed);
w.lifetime = Schedule::sub(w.lifetime, elapsed);
if (w.sending && !w.lifetime) { w.sending = false; w.partial_period = true; }
if (!w.sample_in) {
const uint16_t voltage = board.getBattMilliVolts();
const float celsius = board.getMCUTemperature();
w.history.sample(w.history_seconds, voltage, celsius);
if (w.sending) w.during_report.add(voltage, temperature(celsius));
w.sample_in = 60;
}
if (checkpoint >= 3600 && !save()) { healthy = false; return; }
if (mesh.isAnyTempRadioActive() || mesh.hasOutbound() || !mesh.getRemainingTxBudget()) return;
if (!w.sending) {
const uint8_t* route_path = nullptr; uint8_t route_path_len = OUT_PATH_UNKNOWN;
// Flood has its own conservative schedule. MQTT upload has no deployed
// return path, so a direct transmission never postpones it. When both are
// due, the scoped flood replaces the redundant direct transmission.
if (flood_days && !schedule.flood) start(true);
if (!w.sending && direct_days
&& cli.getDataTxPath(route_path, route_path_len) && !schedule.direct) {
start(false);
}
}
if (healthy && w.sending && !w.page_in) sendPage();
}
bool ManagementReporter::command(char* command, char* reply, size_t size) {
if (!strcmp(command, "get mgmt")) {
const uint8_t* route_path = nullptr; uint8_t route_path_len = OUT_PATH_UNKNOWN;
TransportKey scope;
const bool routed = cli.getDataTxPath(route_path, route_path_len);
const bool scoped = cli.resolveDataTxScope(scope);
char direct[12], flood[12];
if (direct_days) snprintf(direct, sizeof(direct), "%ud", direct_days);
else strcpy(direct, "off");
if (flood_days) snprintf(flood, sizeof(flood), "%ud", flood_days);
else strcpy(flood, "off");
snprintf(reply, size, "> %s key=%s direct=%s/%luh flood=%s/%luh path=%s region=%s%s",
enabled ? "on" : "off", keyed ? "set" : "unset", direct,
(unsigned long)(schedule.direct / 3600), flood,
(unsigned long)(schedule.flood / 3600),
routed ? "set" : "missing", scoped ? "set" : "missing",
healthy ? "" : " FAULT(no TX)");
return true;
}
if (strncmp(command, "set mgmt.", 9)) return false;
char* value = strchr(command + 9, ' ');
if (!value) {
snprintf(reply, size, "ERR: mgmt.enabled/direct/flood/interval/password value");
return true;
}
++value;
if (!healthy) { snprintf(reply, size, "ERR: management state fault; repair storage/reboot first"); return true; }
// Failed persistence stops reporting; no uncommitted state is transmitted.
cancel();
if (!strncmp(command, "set mgmt.password ", 18)) {
const size_t len = strlen(value);
if (len < 12 || len > 96) { snprintf(reply, size, "ERR: password must be 12..96 bytes"); erase(value, len); return true; }
passwordKey(value, key); erase(value, len); keyed = true;
} else if (!strncmp(command, "set mgmt.enabled ", 17)) {
if (strcmp(value, "on") && strcmp(value, "off")) { snprintf(reply, size, "ERR: use on/off"); return true; }
const bool on = !strcmp(value, "on");
const uint8_t* route_path = nullptr; uint8_t route_path_len = OUT_PATH_UNKNOWN;
TransportKey scope;
const bool direct_ready = !direct_days
|| cli.getDataTxPath(route_path, route_path_len);
const bool flood_ready = !flood_days || cli.resolveDataTxScope(scope);
if (on && (!keyed || (!direct_days && !flood_days) || !direct_ready
|| !flood_ready || !allocate())) {
snprintf(reply, size, "ERR: password, enabled route(s), data.tx path/region and free RAM required");
return true;
}
if (on && !enabled && sequence == 0) {
if (direct_days && schedule.direct == direct_days * DAY) schedule.direct += jitter();
if (flood_days && schedule.flood == flood_days * DAY) schedule.flood += jitter();
}
enabled = on;
} else if (!strncmp(command, "set mgmt.direct ", 16)) {
if (!strcmp(value, "off")) {
if (enabled && !flood_days) {
snprintf(reply, size, "ERR: disable management or leave flood enabled"); return true;
}
direct_days = 0; schedule.direct = 0;
} else {
char* end; const unsigned long n = strtoul(value, &end, 10);
const uint8_t* route_path = nullptr; uint8_t route_path_len = OUT_PATH_UNKNOWN;
if (!*value || *end || !Schedule::validDirect(n)
|| !cli.getDataTxPath(route_path, route_path_len)) {
snprintf(reply, size, "ERR: direct needs data.tx path and 5..90 days"); return true;
}
direct_days = n; schedule.direct = direct_days * DAY;
}
} else if (!strncmp(command, "set mgmt.flood ", 15)) {
if (!strcmp(value, "off")) {
if (enabled && !direct_days) {
snprintf(reply, size, "ERR: disable management or leave direct enabled"); return true;
}
flood_days = 0; schedule.flood = 0;
} else {
char* end; const unsigned long n = strtoul(value, &end, 10);
TransportKey scope;
if (!*value || *end || !Schedule::validFlood(n)
|| !cli.resolveDataTxScope(scope)) {
snprintf(reply, size, "ERR: flood needs data.tx region and 21..90 days"); return true;
}
flood_days = n; schedule.flood = flood_days * DAY;
}
} else if (!strncmp(command, "set mgmt.interval ", 18)) {
char* end; const unsigned long n = strtoul(value, &end, 10);
const uint8_t* route_path = nullptr; uint8_t route_path_len = OUT_PATH_UNKNOWN;
TransportKey scope;
if (!*value || *end || !Schedule::validDirect(n)
|| !cli.getDataTxPath(route_path, route_path_len)
|| !cli.resolveDataTxScope(scope)) {
snprintf(reply, size, "ERR: interval needs path, region and 5..90 days"); return true;
}
// Compatibility shorthand: configure both schedules together.
direct_days = n; flood_days = n < 21 ? 21 : n;
schedule.direct = direct_days * DAY; schedule.flood = flood_days * DAY;
} else { snprintf(reply, size, "ERR: unknown management setting"); return true; }
if (!save()) { healthy = false; snprintf(reply, size, "ERR: save failed; reporting stopped"); return true; }
if (!enabled) { delete work; work = nullptr; }
snprintf(reply, size, "OK"); return true;
}
}
+48
View File
@@ -0,0 +1,48 @@
#pragma once
#include "ManagementReport.h"
#include "IdentityStore.h"
#include <Mesh.h>
class NodePrefs;
class CommonCLI;
class CommonCLICallbacks;
class ClientACL;
class SensorManager;
namespace mesh {
class ManagementReporter {
struct Working;
Mesh& mesh;
MainBoard& board;
SensorManager& sensors;
ClientACL& acl;
NodePrefs& prefs;
CommonCLICallbacks& callbacks;
CommonCLI& cli;
FILESYSTEM* fs;
Working* work = nullptr;
uint8_t key[32] = {};
uint8_t direct_days = 5, flood_days = 21;
bool enabled = false, keyed = false, healthy = true;
management::Schedule schedule;
uint32_t sequence = 0, last_ms = 0, fraction_ms = 0, checkpoint = 0;
uint64_t uptime = 0;
bool save();
bool load();
bool allocate();
void cancel();
void snapshot();
void start(bool flood);
void sendPage();
uint32_t jitter() const;
public:
ManagementReporter(Mesh& mesh, MainBoard& board, SensorManager& sensors,
ClientACL& acl, NodePrefs& prefs,
CommonCLICallbacks& callbacks, CommonCLI& cli,
FILESYSTEM* fs);
~ManagementReporter();
void loop(uint64_t node_uptime_seconds = UINT64_MAX);
bool command(char* command, char* reply, size_t size);
};
}
+19
View File
@@ -56,6 +56,24 @@ void SensorManager::maybeStopGpsForTelemetry(unsigned long now) {
}
}
void SensorManager::cancelGpsTelemetryDemand(unsigned long now) {
// An explicit user-off request must win over work started by an earlier
// telemetry query. Otherwise the acquisition/hold state can keep a GPS
// powered for up to two hours after the user turned it off.
gps_acquiring = false;
gps_acquire_has_fix = false;
gps_hold_until = 0;
gps_acquire_started_at = 0;
gps_stable_started_at = 0;
gps_weighted_lat = 0;
gps_weighted_lon = 0;
gps_weighted_altitude = 0;
gps_weight_sum = 0;
gps_weight_count = 0;
// Do not let the background cache refresh immediately undo the command.
gps_next_cache_update_at = now + GPS_TELEMETRY_CACHE_INTERVAL_SEC * 1000UL;
}
void SensorManager::beginGpsTelemetryAcquisition(unsigned long now) {
if (!gps_transport_available || !telemetryGpsDetected() || gps_acquiring) return;
@@ -162,6 +180,7 @@ void SensorManager::setGpsTelemetryUserEnabled(bool enabled) {
if (gps_transport_available && telemetryGpsDetected()
&& !telemetryGpsActive()) telemetryGpsStart();
} else {
cancelGpsTelemetryDemand(now);
maybeStopGpsForTelemetry(now);
}
}
+1
View File
@@ -43,6 +43,7 @@ class SensorManager {
void finishGpsTelemetryAcquisition(unsigned long now, bool use_weighted_average);
void updateGpsTelemetryCache(float lat, float lon, float altitude, unsigned long now);
void maybeStopGpsForTelemetry(unsigned long now);
void cancelGpsTelemetryDemand(unsigned long now);
protected:
virtual bool telemetryGpsDetected() const { return false; }