Extend flood policy and harden message retries

This commit is contained in:
mikecarper committed 2026-08-07 14:26:31 -07:00
1 parent 687e114828
commit 7f56da7a34
34 files changed
+5297 -1338

No files matched your search

+1
View File
@@ -28,6 +28,7 @@ struct ClientInfo {
union {
struct {
uint32_t sync_since; // sync messages SINCE this timestamp (by OUR clock)
uint32_t last_post_timestamp; // sender timestamp for room posts only (transient)
uint32_t pending_ack;
uint32_t push_post_timestamp;
unsigned long ack_timeout;
+21 -255
View File
@@ -497,92 +497,20 @@ static void formatFloodRetryPathGate(char* dest, uint8_t path_gate) {
}
}
static bool parseFloodChannelBlockHops(const char* value, uint8_t& max_hops) {
static bool parseFloodChannelHops(const char* value, uint8_t& max_hops) {
if (value == NULL) {
return false;
}
value = skipSpacesConst(value);
if (strcmp(value, "all") == 0) {
max_hops = FLOOD_CHANNEL_BLOCK_HOPS_ALL;
max_hops = FLOOD_CHANNEL_HOPS_ALL;
return true;
}
return parseUint8Strict(value, 1, 7, max_hops);
}
static bool parseFloodChannelBlockRowHops(const char* value, uint8_t& max_hops) {
if (value == NULL) {
return false;
}
value = skipSpacesConst(value);
if (strcmp(value, "default") == 0 || strcmp(value, "def") == 0 || strcmp(value, "inherit") == 0) {
max_hops = FLOOD_CHANNEL_BLOCK_HOPS_INHERIT;
return true;
}
return parseFloodChannelBlockHops(value, max_hops);
}
static bool parseFloodChannelBlockHopAssignment(const char* text, bool allow_bare, uint8_t& max_hops) {
char token[16];
text = skipSpacesConst(text);
if (text == NULL || *text == 0) {
return false;
}
size_t len = 0;
while (text[len] && text[len] != ' ' && len + 1 < sizeof(token)) {
token[len] = text[len];
len++;
}
token[len] = 0;
const char* value = NULL;
if (strncmp(token, "h=", 2) == 0) {
value = token + 2;
} else if (strncmp(token, "hops=", 5) == 0) {
value = token + 5;
} else if (allow_bare) {
value = token;
} else {
return false;
}
return parseFloodChannelBlockRowHops(value, max_hops);
}
static bool looksFloodChannelBlockHopAssignment(const char* text) {
text = skipSpacesConst(text);
if (text == NULL || *text == 0) {
return false;
}
return (*text >= '0' && *text <= '9')
|| strncmp(text, "h=", 2) == 0
|| strncmp(text, "hops=", 5) == 0
|| strncmp(text, "all", 3) == 0
|| strncmp(text, "def", 3) == 0
|| strncmp(text, "default", 7) == 0
|| strncmp(text, "inherit", 7) == 0;
}
static bool trimFloodChannelBlockHopSuffix(char* name, uint8_t& max_hops) {
size_t len = strlen(name);
while (len > 0 && name[len - 1] == ' ') {
name[--len] = 0;
}
char* token = strrchr(name, ' ');
if (token == NULL) {
return true;
}
if (strncmp(token + 1, "h=", 2) != 0 && strncmp(token + 1, "hops=", 5) != 0) {
return true;
}
if (!parseFloodChannelBlockHopAssignment(token + 1, false, max_hops)) {
return false;
}
*token = 0;
return strlen(name) > 0;
}
static void formatFloodChannelBlockHops(char* dest, uint8_t max_hops) {
if (max_hops == FLOOD_CHANNEL_BLOCK_HOPS_ALL) {
static void formatFloodChannelHops(char* dest, uint8_t max_hops) {
if (max_hops == FLOOD_CHANNEL_HOPS_ALL) {
strcpy(dest, "h=all");
} else {
sprintf(dest, "h>%u", (unsigned int)max_hops);
@@ -699,69 +627,6 @@ static bool formatFloodRetryBucketCollisionWarning(char* reply, const NodePrefs*
return true;
}
static bool parseFloodChannelBlockKey(const char* text, uint8_t secret[PUB_KEY_SIZE], uint8_t& key_len) {
if (text == NULL || text[0] == 0) {
return false;
}
memset(secret, 0, PUB_KEY_SIZE);
if (text[0] == '#') {
if (!isValidName(text)) {
return false;
}
mesh::Utils::sha256(secret, CIPHER_KEY_SIZE, (const uint8_t*)text, strlen(text));
key_len = CIPHER_KEY_SIZE;
return true;
}
size_t hex_len = strlen(text);
if (!(hex_len == CIPHER_KEY_SIZE * 2 || hex_len == PUB_KEY_SIZE * 2)) {
return false;
}
for (size_t i = 0; i < hex_len; i++) {
if (!mesh::Utils::isHexChar(text[i])) {
return false;
}
}
key_len = (uint8_t)(hex_len / 2);
return mesh::Utils::fromHex(secret, key_len, text);
}
static bool parseFloodChannelBlockDotIndex(const char*& cursor, int& index) {
if (*cursor != '.') {
index = 0;
return true;
}
cursor++;
if (*cursor < '0' || *cursor > '9') {
return false;
}
int value = 0;
while (*cursor >= '0' && *cursor <= '9') {
value = (value * 10) + (*cursor - '0');
if (value > FLOOD_CHANNEL_BLOCK_SLOTS) {
return false;
}
cursor++;
}
if (value < 1) {
return false;
}
index = value;
return true;
}
static void copyTrimmedFloodChannelBlockName(char* dest, size_t dest_len, const char* src) {
src = skipSpacesConst(src);
StrHelper::strncpy(dest, src, dest_len);
size_t len = strlen(dest);
while (len > 0 && dest[len - 1] == ' ') {
dest[--len] = 0;
}
}
static void applyDirectRetryPreset(NodePrefs* prefs, uint8_t preset) {
prefs->retry_preset = preset;
if (preset == RETRY_PRESET_INFRA) {
@@ -1208,8 +1073,8 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
memset(_prefs->battery_alert_region, 0, sizeof(_prefs->battery_alert_region));
_prefs->direct_retry_recent_enabled = DIRECT_RETRY_RECENT_DEFAULT;
_prefs->flood_channel_data_enabled = 1;
_prefs->flood_channel_block_max_hops = FLOOD_CHANNEL_BLOCK_HOPS_ALL;
_prefs->flood_channel_data_max_hops = FLOOD_CHANNEL_BLOCK_HOPS_ALL;
_prefs->legacy_flood_channel_block_max_hops = FLOOD_CHANNEL_HOPS_ALL;
_prefs->flood_channel_data_max_hops = FLOOD_CHANNEL_HOPS_ALL;
has_flood_retry_prefs = file.available() >= 2;
if (has_flood_retry_prefs) {
file.read((uint8_t *)&_prefs->flood_retry_attempts, sizeof(_prefs->flood_retry_attempts)); // 311
@@ -1244,8 +1109,9 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
if (file.available() >= (int)sizeof(_prefs->flood_channel_data_enabled)) {
file.read((uint8_t *)&_prefs->flood_channel_data_enabled, sizeof(_prefs->flood_channel_data_enabled));
}
if (file.available() >= (int)sizeof(_prefs->flood_channel_block_max_hops)) {
file.read((uint8_t *)&_prefs->flood_channel_block_max_hops, sizeof(_prefs->flood_channel_block_max_hops));
if (file.available() >= (int)sizeof(_prefs->legacy_flood_channel_block_max_hops)) {
file.read((uint8_t *)&_prefs->legacy_flood_channel_block_max_hops,
sizeof(_prefs->legacy_flood_channel_block_max_hops));
}
if (file.available() >= (int)sizeof(_prefs->flood_channel_data_max_hops)) {
file.read((uint8_t *)&_prefs->flood_channel_data_max_hops, sizeof(_prefs->flood_channel_data_max_hops));
@@ -1431,13 +1297,14 @@ void CommonCLI::loadPrefsInt(FILESYSTEM* fs, const char* filename) {
_prefs->direct_retry_recent_enabled = constrain(_prefs->direct_retry_recent_enabled, 0, 1);
_prefs->flood_channel_data_enabled = constrain(_prefs->flood_channel_data_enabled, 0, 1);
_prefs->telemetry_access = constrain(_prefs->telemetry_access, 0, 1);
if (_prefs->flood_channel_block_max_hops != FLOOD_CHANNEL_BLOCK_HOPS_ALL
&& (_prefs->flood_channel_block_max_hops < 1 || _prefs->flood_channel_block_max_hops > 7)) {
_prefs->flood_channel_block_max_hops = FLOOD_CHANNEL_BLOCK_HOPS_ALL;
if (_prefs->legacy_flood_channel_block_max_hops != FLOOD_CHANNEL_HOPS_ALL
&& (_prefs->legacy_flood_channel_block_max_hops < 1
|| _prefs->legacy_flood_channel_block_max_hops > 7)) {
_prefs->legacy_flood_channel_block_max_hops = FLOOD_CHANNEL_HOPS_ALL;
}
if (_prefs->flood_channel_data_max_hops != FLOOD_CHANNEL_BLOCK_HOPS_ALL
if (_prefs->flood_channel_data_max_hops != FLOOD_CHANNEL_HOPS_ALL
&& (_prefs->flood_channel_data_max_hops < 1 || _prefs->flood_channel_data_max_hops > 7)) {
_prefs->flood_channel_data_max_hops = FLOOD_CHANNEL_BLOCK_HOPS_ALL;
_prefs->flood_channel_data_max_hops = FLOOD_CHANNEL_HOPS_ALL;
}
if (_prefs->battery_alert_low_percent < 1
|| _prefs->battery_alert_low_percent > 100
@@ -1564,7 +1431,7 @@ static bool writeCommonPrefsImage(Writer& writer, NodePrefs* prefs) {
WRITE_COMMON_PREFS(&prefs->battery_alert_critical_percent);
WRITE_COMMON_PREFS(&prefs->direct_retry_recent_enabled);
WRITE_COMMON_PREFS(&prefs->flood_channel_data_enabled);
WRITE_COMMON_PREFS(&prefs->flood_channel_block_max_hops);
WRITE_COMMON_PREFS(&prefs->legacy_flood_channel_block_max_hops);
WRITE_COMMON_PREFS(&prefs->flood_channel_data_max_hops);
WRITE_COMMON_PREFS(&prefs->telemetry_access); // 674
#if defined(ENABLE_OTA)
@@ -1708,7 +1575,8 @@ void CommonCLI::savePrefs(FILESYSTEM* fs, PrefsSaveRouting::Scope scope) {
file.write((uint8_t *)&_prefs->battery_alert_critical_percent, sizeof(_prefs->battery_alert_critical_percent));
file.write((uint8_t *)&_prefs->direct_retry_recent_enabled, sizeof(_prefs->direct_retry_recent_enabled));
file.write((uint8_t *)&_prefs->flood_channel_data_enabled, sizeof(_prefs->flood_channel_data_enabled));
file.write((uint8_t *)&_prefs->flood_channel_block_max_hops, sizeof(_prefs->flood_channel_block_max_hops));
file.write((uint8_t *)&_prefs->legacy_flood_channel_block_max_hops,
sizeof(_prefs->legacy_flood_channel_block_max_hops));
file.write((uint8_t *)&_prefs->flood_channel_data_max_hops, sizeof(_prefs->flood_channel_data_max_hops));
file.write((uint8_t *)&_prefs->telemetry_access, sizeof(_prefs->telemetry_access)); // 674
#if defined(ENABLE_OTA)
@@ -3945,7 +3813,7 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
}
} else if (memcmp(config, "flood.channel.data.hops ", 24) == 0) {
uint8_t max_hops;
if (parseFloodChannelBlockHops(&config[24], max_hops)) {
if (parseFloodChannelHops(&config[24], max_hops)) {
_prefs->flood_channel_data_max_hops = max_hops;
savePrefs();
strcpy(reply, "OK");
@@ -3964,62 +3832,6 @@ void CommonCLI::handleSetCmd(uint32_t sender_timestamp, char* command, char* rep
} else {
strcpy(reply, "Error, must be on or off");
}
} else if (memcmp(config, "flood.channel.block.hops ", 25) == 0) {
uint8_t max_hops;
if (parseFloodChannelBlockHops(&config[25], max_hops)) {
_prefs->flood_channel_block_max_hops = max_hops;
savePrefs();
strcpy(reply, "OK");
} else {
strcpy(reply, "Error, must be all or 1-7");
}
} else if (memcmp(config, "flood.channel.block", 19) == 0
&& (config[19] == ' ' || config[19] == '.')) {
const char* cursor = &config[19];
int index = 0;
if (!parseFloodChannelBlockDotIndex(cursor, index)) {
sprintf(reply, "Error, index 1-%d", FLOOD_CHANNEL_BLOCK_SLOTS);
return;
}
cursor = skipSpacesConst(cursor);
const char* key_start = cursor;
while (*cursor && *cursor != ' ') cursor++;
size_t key_len_text = cursor - key_start;
char key_text[PUB_KEY_SIZE * 2 + 1];
if (key_len_text == 0 || key_len_text >= sizeof(key_text)) {
strcpy(reply, "Error, use: set flood.channel.block[.n] <hex-key> <name>|#channel");
return;
}
memcpy(key_text, key_start, key_len_text);
key_text[key_len_text] = 0;
char name[FLOOD_CHANNEL_BLOCK_NAME_LEN];
uint8_t block_hops = FLOOD_CHANNEL_BLOCK_HOPS_INHERIT;
if (key_text[0] == '#') {
StrHelper::strncpy(name, key_text, sizeof(name));
const char* extra = skipSpacesConst(cursor);
if (*extra && looksFloodChannelBlockHopAssignment(extra)
&& !parseFloodChannelBlockHopAssignment(extra, true, block_hops)) {
strcpy(reply, "Error, hops must be all, default, or 1-7");
return;
}
} else {
copyTrimmedFloodChannelBlockName(name, sizeof(name), cursor);
if (!trimFloodChannelBlockHopSuffix(name, block_hops)) {
strcpy(reply, "Error, bad name or hops");
return;
}
}
uint8_t secret[PUB_KEY_SIZE];
uint8_t decoded_key_len = 0;
if (!parseFloodChannelBlockKey(key_text, secret, decoded_key_len)) {
strcpy(reply, "Error, key must be 128/256-bit hex or #channel");
} else if (name[0] == 0 || !isValidName(name)) {
strcpy(reply, "Error, bad name");
} else {
_callbacks->setFloodChannelBlock(index, secret, decoded_key_len, name, block_hops, reply);
}
} else if (memcmp(config, "flood.retry.count ", 18) == 0) {
int attempts = looksUnsignedInteger(&config[18]) ? _atoi(&config[18]) : -1;
if (attempts >= 0 && attempts <= 15) {
@@ -4570,36 +4382,12 @@ void CommonCLI::handleGetCmd(uint32_t sender_timestamp, char* command, char* rep
sprintf(reply, "> %s", StrHelper::ftoa(_prefs->tx_delay_factor));
} else if (strcmp(config, "flood.channel.data.hops") == 0) {
char hops[8];
formatFloodChannelBlockHops(hops, _prefs->flood_channel_data_max_hops);
formatFloodChannelHops(hops, _prefs->flood_channel_data_max_hops);
sprintf(reply, "> %s", hops);
} else if (strcmp(config, "flood.channel.data") == 0) {
char hops[8];
formatFloodChannelBlockHops(hops, _prefs->flood_channel_data_max_hops);
formatFloodChannelHops(hops, _prefs->flood_channel_data_max_hops);
sprintf(reply, "> %s %s", _prefs->flood_channel_data_enabled ? "on" : "off", hops);
} else if (memcmp(config, "flood.channel.block.hops", 24) == 0) {
char hops[8];
formatFloodChannelBlockHops(hops, _prefs->flood_channel_block_max_hops);
sprintf(reply, "> %s", hops);
} else if (memcmp(config, "flood.channel.block", 19) == 0
&& (config[19] == 0 || config[19] == ' ' || config[19] == '.')) {
const char* cursor = &config[19];
int index = 0;
if (!parseFloodChannelBlockDotIndex(cursor, index)) {
sprintf(reply, "Error, index 1-%d", FLOOD_CHANNEL_BLOCK_SLOTS);
return;
}
cursor = skipSpacesConst(cursor);
char selector[8];
if (index > 0 && *cursor != 0) {
strcpy(reply, "Error, use index or selector");
return;
}
if (index > 0) {
snprintf(selector, sizeof(selector), "%d", index);
_callbacks->formatFloodChannelBlocks(selector, reply);
} else {
_callbacks->formatFloodChannelBlocks(cursor, reply);
}
} else if (memcmp(config, "flood.max.advert", 16) == 0) {
sprintf(reply, "> %d", (uint32_t)_prefs->flood_max_advert);
} else if (memcmp(config, "flood.max.unscoped", 18) == 0) {
@@ -4799,28 +4587,6 @@ void CommonCLI::handleDelCmd(char* command, char* reply) {
_callbacks->deleteScheduledRadioParams(true, skipSpacesConst(&config[11]), reply);
} else if (memcmp(config, "radioat", 7) == 0 && (config[7] == 0 || config[7] == ' ')) {
_callbacks->deleteScheduledRadioParams(false, skipSpacesConst(&config[7]), reply);
} else if (memcmp(config, "flood.channel.block", 19) == 0
&& (config[19] == ' ' || config[19] == '.')) {
const char* cursor = &config[19];
int index = 0;
if (!parseFloodChannelBlockDotIndex(cursor, index)) {
sprintf(reply, "Error, index 1-%d", FLOOD_CHANNEL_BLOCK_SLOTS);
return;
}
cursor = skipSpacesConst(cursor);
char selector[8];
if (index > 0 && *cursor != 0) {
strcpy(reply, "Error, use index or selector");
return;
}
if (index > 0) {
snprintf(selector, sizeof(selector), "%d", index);
_callbacks->deleteFloodChannelBlock(selector, reply);
} else if (*cursor != 0) {
_callbacks->deleteFloodChannelBlock(cursor, reply);
} else {
strcpy(reply, "Error, use: del flood.channel.block <index|name|prefix>");
}
} else {
strcpy(reply, "unknown del: ");
StrHelper::strncpy(&reply[13], config, 160 - 14);
+6 -29
View File
@@ -90,17 +90,10 @@
#define COMMON_CLI_TMP_LEN ((FLOOD_RETRY_LIST_TEXT_MAX > (PRV_KEY_SIZE * 2 + 4)) ? FLOOD_RETRY_LIST_TEXT_MAX : (PRV_KEY_SIZE * 2 + 4))
#endif
#ifndef FLOOD_CHANNEL_BLOCK_SLOTS
#define FLOOD_CHANNEL_BLOCK_SLOTS 15
#ifndef FLOOD_CHANNEL_KEY_PREFIX_LEN
#define FLOOD_CHANNEL_KEY_PREFIX_LEN 4
#endif
#ifndef FLOOD_CHANNEL_BLOCK_NAME_LEN
#define FLOOD_CHANNEL_BLOCK_NAME_LEN 32
#endif
#ifndef FLOOD_CHANNEL_BLOCK_PREFIX_LEN
#define FLOOD_CHANNEL_BLOCK_PREFIX_LEN 4
#endif
#define FLOOD_CHANNEL_BLOCK_HOPS_ALL 0xFF
#define FLOOD_CHANNEL_BLOCK_HOPS_INHERIT 0xFE
#define FLOOD_CHANNEL_HOPS_ALL 0xFF
#define DIRECT_RETRY_CR4_MIN_SNR_X4_DEFAULT 40
#define DIRECT_RETRY_CR5_MIN_SNR_X4_DEFAULT 30
@@ -191,7 +184,9 @@ struct NodePrefs { // persisted to file
uint8_t battery_alert_critical_percent;
uint8_t direct_retry_recent_enabled;
uint8_t flood_channel_data_enabled;
uint8_t flood_channel_block_max_hops;
// Retains the removed flood.channel.block byte at its established file
// offset so every following preference remains upgrade-compatible.
uint8_t legacy_flood_channel_block_max_hops;
uint8_t flood_channel_data_max_hops;
uint8_t telemetry_access;
@@ -334,24 +329,6 @@ public:
(void)selector;
strcpy(reply, "Error: unsupported");
}
virtual void setFloodChannelBlock(int index, const uint8_t* secret, uint8_t key_len,
const char* name, uint8_t max_hops, char* reply) {
(void)index;
(void)secret;
(void)key_len;
(void)name;
(void)max_hops;
strcpy(reply, "Error: unsupported");
}
virtual void formatFloodChannelBlocks(const char* selector, char* reply) {
(void)selector;
strcpy(reply, "Error: unsupported");
}
virtual void deleteFloodChannelBlock(const char* selector, char* reply) {
(void)selector;
strcpy(reply, "Error: unsupported");
}
virtual void startRegionsLoad() {
// no op by default
}
+87
View File
@@ -0,0 +1,87 @@
#pragma once
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
inline bool isCompanionPushFrame(const uint8_t* frame, size_t len) {
return frame != NULL && len > 0 && (frame[0] & 0x80) != 0;
}
/**
* Add a frame to a companion transport's contiguous outbound queue.
*
* Protocol responses use codes below 0x80 and complete an app command that is
* waiting for them. Push frames use codes at or above 0x80 and are
* asynchronous. Keep one slot available for a response, and if an older queue
* is already full of mixed traffic, let a response replace the newest push.
* Responses are inserted before pushes so packet-log traffic cannot delay a
* command indefinitely.
*/
template <typename Frame, typename QueueLength>
bool enqueueCompanionFrame(Frame queue[], QueueLength& queue_len, size_t capacity,
const uint8_t* src, size_t len) {
if (queue == NULL || src == NULL || len == 0 || capacity == 0) return false;
size_t count = static_cast<size_t>(queue_len);
if (count > capacity) return false;
const bool push = isCompanionPushFrame(src, len);
if (push && count >= capacity - 1) {
return false; // preserve one slot for the reply to an app command
}
if (count == capacity) {
// A response may displace best-effort asynchronous traffic, but never an
// earlier response that another command is already waiting for.
size_t evict = count;
while (evict > 0) {
--evict;
if (isCompanionPushFrame(queue[evict].buf, queue[evict].len)) break;
}
if (!isCompanionPushFrame(queue[evict].buf, queue[evict].len)) return false;
for (size_t i = evict; i + 1 < count; ++i) {
queue[i] = queue[i + 1];
}
--count;
}
size_t insert_at = count;
if (!push) {
// Keep responses FIFO with respect to one another, ahead of asynchronous
// pushes such as raw-packet logs and message-waiting notifications.
// The stable partition also repairs a queue populated by older admission
// behavior before this policy gets a chance to add the next response.
for (size_t i = 1; i < count; ++i) {
if (isCompanionPushFrame(queue[i].buf, queue[i].len)) continue;
Frame response = queue[i];
size_t j = i;
while (j > 0
&& isCompanionPushFrame(queue[j - 1].buf, queue[j - 1].len)) {
queue[j] = queue[j - 1];
--j;
}
queue[j] = response;
}
for (size_t i = 0; i < count; ++i) {
if (isCompanionPushFrame(queue[i].buf, queue[i].len)) {
insert_at = i;
break;
}
}
for (size_t i = count; i > insert_at; --i) {
queue[i] = queue[i - 1];
}
}
queue[insert_at].len = len;
memcpy(queue[insert_at].buf, src, len);
queue_len = static_cast<QueueLength>(count + 1);
return true;
}
} // namespace mesh
+139
View File
@@ -23,6 +23,16 @@ static constexpr uint8_t SCOPE_PATH_BRIDGE_BUCKET_BASE = 2;
static constexpr uint8_t SCOPE_PATH_BRIDGE_BUCKET_COUNT = 6;
static constexpr uint8_t SCOPE_PATH_INVALID_BUCKET = 0xFF;
enum RuleIncomingScope : uint8_t {
RULE_IN_ANY = 0,
RULE_IN_NONE = 1,
RULE_IN_SCOPED = 2,
RULE_IN_ALLOWED = 3,
RULE_IN_UNKNOWN = 4,
RULE_IN_SCOPE = 5,
RULE_IN_REGION = 6,
};
enum ChannelScopeGate {
CHANNEL_SCOPE_USE_GLOBAL,
CHANNEL_SCOPE_BYPASS,
@@ -66,6 +76,49 @@ inline uint8_t scopeSelectorValue(uint8_t stored_selector) {
& (uint8_t)~(SLOW_SCOPE_FLAG | SCOPE_PATH_MASK);
}
// Regionless channel-scope rows use alternate base selector values so the
// existing 16-bit target field can hold a one-based direct-scope table index.
// Region-backed rows retain their original on-disk selector values.
static constexpr uint8_t CHANNEL_SCOPE_DIRECT_KEY_128 = 17;
static constexpr uint8_t CHANNEL_SCOPE_DIRECT_KEY_256 = 18;
static constexpr uint8_t CHANNEL_SCOPE_DIRECT_TXT_ANY = 33;
static constexpr uint8_t CHANNEL_SCOPE_DIRECT_LOGIN_ANY = 34;
static constexpr uint8_t CHANNEL_SCOPE_DIRECT_OTHER_ANY = 35;
static constexpr uint8_t CHANNEL_SCOPE_INVALID_SELECTOR = 0xFF;
inline uint8_t encodeChannelScopeTargetSelector(uint8_t match_selector,
bool direct_target) {
if (!direct_target) return match_selector;
if (match_selector <= 2) {
return (uint8_t)(CHANNEL_SCOPE_DIRECT_TXT_ANY + match_selector);
}
if (match_selector == 16 || match_selector == 32) {
return (uint8_t)(16 + match_selector / 16);
}
return CHANNEL_SCOPE_INVALID_SELECTOR;
}
inline bool channelScopeUsesDirectTarget(uint8_t stored_selector) {
uint8_t selector = scopeSelectorValue(stored_selector);
return (selector >= CHANNEL_SCOPE_DIRECT_KEY_128
&& selector <= CHANNEL_SCOPE_DIRECT_KEY_256)
|| (selector >= CHANNEL_SCOPE_DIRECT_TXT_ANY
&& selector <= CHANNEL_SCOPE_DIRECT_OTHER_ANY);
}
inline uint8_t channelScopeMatchSelectorValue(uint8_t stored_selector) {
uint8_t selector = scopeSelectorValue(stored_selector);
if (selector >= CHANNEL_SCOPE_DIRECT_KEY_128
&& selector <= CHANNEL_SCOPE_DIRECT_KEY_256) {
return (uint8_t)((selector - 16) * 16);
}
if (selector >= CHANNEL_SCOPE_DIRECT_TXT_ANY
&& selector <= CHANNEL_SCOPE_DIRECT_OTHER_ANY) {
return (uint8_t)(selector - CHANNEL_SCOPE_DIRECT_TXT_ANY);
}
return selector;
}
inline bool scopeUsesSlowTiming(uint8_t stored_selector) {
return (stored_selector & SLOW_SCOPE_FLAG) != 0;
}
@@ -176,6 +229,92 @@ inline bool pathMatchesConfiguredIds(const mesh::Packet* packet,
packet, ids, configuredIdCount(ids, maximum_count));
}
inline bool pathStartsWith(const mesh::Packet* packet,
uint8_t hash_size,
uint8_t prefix_hops,
const uint8_t* prefix) {
if (prefix_hops == 0) return true;
if (packet == NULL || prefix == NULL || hash_size < 1 || hash_size > 3
|| packet->getPathHashSize() != hash_size
|| packet->getPathHashCount() < prefix_hops) {
return false;
}
return memcmp(packet->path, prefix, hash_size * prefix_hops) == 0;
}
inline bool ruleIncomingScopeMatches(uint8_t kind,
bool incoming_is_scoped,
uint16_t incoming_transport_code,
bool incoming_region_allowed,
uint16_t wanted_transport_code) {
switch (kind) {
case RULE_IN_ANY:
return true;
case RULE_IN_NONE:
return !incoming_is_scoped;
case RULE_IN_SCOPED:
return incoming_is_scoped;
case RULE_IN_ALLOWED:
return incoming_region_allowed;
case RULE_IN_UNKNOWN:
return incoming_is_scoped && !incoming_region_allowed;
case RULE_IN_SCOPE:
return incoming_is_scoped
&& incoming_transport_code == wanted_transport_code;
case RULE_IN_REGION:
// Region rules are name-bound and must be evaluated by the caller with
// RegionNameUtils. Numeric region IDs are deliberately not rule identity.
return false;
default:
return false;
}
}
inline bool rateLimitReached(bool window_active, uint32_t now,
uint32_t window_started, uint16_t window_count,
uint16_t rate_per_minute) {
uint16_t effective_count = (!window_active
|| now - window_started >= 60000UL)
? 0 : window_count;
return effective_count >= rate_per_minute;
}
inline bool sameChannelKey(uint8_t left_len, const uint8_t left[],
uint8_t right_len, const uint8_t right[]) {
return left != NULL && right != NULL && left_len != 0
&& left_len == right_len && memcmp(left, right, left_len) == 0;
}
inline int nextOrderedRule(uint32_t match_mask, uint32_t visited_mask,
const uint8_t priorities[], uint8_t count) {
if (priorities == NULL || count > 32) return -1;
int best = -1;
for (uint8_t i = 0; i < count; i++) {
uint32_t bit = (uint32_t)1U << i;
if ((match_mask & bit) == 0 || (visited_mask & bit) != 0) continue;
if (best < 0 || priorities[i] > priorities[best]) best = i;
}
return best;
}
inline uint32_t truncateRulesAtStop(uint32_t match_mask,
const uint8_t priorities[],
const uint8_t stop_flags[],
uint8_t count) {
if (stop_flags == NULL) return match_mask;
uint32_t effective = 0;
uint32_t visited = 0;
while (true) {
int index = nextOrderedRule(match_mask, visited, priorities, count);
if (index < 0) break;
uint32_t bit = (uint32_t)1U << index;
visited |= bit;
effective |= bit;
if (stop_flags[index] != 0) break;
}
return effective;
}
inline bool scopeRuleAllowed(bool requires_region_match,
bool incoming_region_allowed) {
return !requires_region_match || incoming_region_allowed;
+98
View File
@@ -0,0 +1,98 @@
#pragma once
#include <MeshCore.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
// Remembers a bounded set of logical messages independently of their on-air
// attempt byte. The fingerprint supplied by the caller must already identify
// the peer and message text.
template <size_t ENTRY_COUNT>
class LogicalMessageCache {
public:
enum class ReplayDecision : uint8_t {
NewMessage,
ExactRetry,
StaleOrMismatched
};
LogicalMessageCache() { clear(); }
bool find(const uint8_t fingerprint[MAX_HASH_SIZE], uint32_t source_timestamp,
uint32_t* mapped_timestamp = NULL) const {
if (fingerprint == NULL) return false;
for (size_t i = 0; i < ENTRY_COUNT; i++) {
const Entry& entry = entries_[i];
if (entry.valid && entry.source_timestamp == source_timestamp
&& memcmp(entry.fingerprint, fingerprint, MAX_HASH_SIZE) == 0) {
if (mapped_timestamp != NULL) {
*mapped_timestamp = entry.mapped_timestamp;
}
return true;
}
}
return false;
}
bool remember(const uint8_t fingerprint[MAX_HASH_SIZE], uint32_t source_timestamp,
uint32_t mapped_timestamp = 0) {
if (fingerprint == NULL) return false;
for (size_t i = 0; i < ENTRY_COUNT; i++) {
Entry& entry = entries_[i];
if (entry.valid && entry.source_timestamp == source_timestamp
&& memcmp(entry.fingerprint, fingerprint, MAX_HASH_SIZE) == 0) {
entry.mapped_timestamp = mapped_timestamp;
return true;
}
}
Entry& entry = entries_[next_entry_];
memcpy(entry.fingerprint, fingerprint, MAX_HASH_SIZE);
entry.source_timestamp = source_timestamp;
entry.mapped_timestamp = mapped_timestamp;
entry.valid = true;
next_entry_ = (next_entry_ + 1) % ENTRY_COUNT;
return true;
}
ReplayDecision classifyAndRemember(
const uint8_t fingerprint[MAX_HASH_SIZE], uint32_t source_timestamp,
uint32_t& latest_source_timestamp) {
if (fingerprint == NULL) return ReplayDecision::StaleOrMismatched;
if (find(fingerprint, source_timestamp)) {
return ReplayDecision::ExactRetry;
}
if (source_timestamp <= latest_source_timestamp) {
return ReplayDecision::StaleOrMismatched;
}
latest_source_timestamp = source_timestamp;
remember(fingerprint, source_timestamp);
return ReplayDecision::NewMessage;
}
void clear() {
memset(entries_, 0, sizeof(entries_));
next_entry_ = 0;
}
private:
static_assert(ENTRY_COUNT > 0, "LogicalMessageCache needs at least one entry");
struct Entry {
uint8_t fingerprint[MAX_HASH_SIZE];
uint32_t source_timestamp;
uint32_t mapped_timestamp;
bool valid;
};
Entry entries_[ENTRY_COUNT];
size_t next_entry_;
};
} // namespace mesh
+81
View File
@@ -0,0 +1,81 @@
#pragma once
#include <MeshCore.h>
#include <stddef.h>
#include <stdint.h>
#include <string.h>
namespace mesh {
// Keeps the most recently completed remote CLI reply so an exact request
// retry can recover a lost response without executing the command twice.
// This is deliberately a single bounded entry: remote CLI commands are
// serialized, and repeater builds on small MCUs cannot afford one reply-sized
// buffer for every ACL client.
class RemoteCliReplyCache {
public:
static constexpr size_t MAX_REPLY_TEXT =
MAX_PACKET_PAYLOAD - CIPHER_MAC_SIZE - (CIPHER_BLOCK_SIZE - 1) - 5;
RemoteCliReplyCache() { clear(); }
static uint32_t fingerprint(const char* command, size_t command_len) {
if (command == NULL) return 0;
// FNV-1a is only a compact request-mismatch guard. Authentication and the
// sender/timestamp tuple remain the replay-protection boundary.
uint32_t value = 2166136261UL;
for (size_t i = 0; i < command_len; i++) {
value ^= (uint8_t)command[i];
value *= 16777619UL;
}
return value;
}
bool remember(const uint8_t* sender_pub_key, uint32_t request_timestamp,
uint32_t command_fingerprint, const char* response) {
if (sender_pub_key == NULL || response == NULL) return false;
memcpy(sender_pub_key_, sender_pub_key, sizeof(sender_pub_key_));
request_timestamp_ = request_timestamp;
command_fingerprint_ = command_fingerprint;
size_t response_len = 0;
while (response_len < MAX_REPLY_TEXT && response[response_len] != 0) {
response_len++;
}
memcpy(response_, response, response_len);
response_[response_len] = 0;
valid_ = true;
return true;
}
bool matches(const uint8_t* sender_pub_key, uint32_t request_timestamp,
uint32_t command_fingerprint) const {
return valid_ && sender_pub_key != NULL
&& request_timestamp_ == request_timestamp
&& command_fingerprint_ == command_fingerprint
&& memcmp(sender_pub_key_, sender_pub_key, sizeof(sender_pub_key_)) == 0;
}
const char* response() const { return response_; }
bool hasResponse() const { return valid_ && response_[0] != 0; }
bool isValid() const { return valid_; }
void clear() {
valid_ = false;
memset(sender_pub_key_, 0, sizeof(sender_pub_key_));
request_timestamp_ = 0;
command_fingerprint_ = 0;
memset(response_, 0, sizeof(response_));
}
private:
bool valid_;
uint8_t sender_pub_key_[PUB_KEY_SIZE];
uint32_t request_timestamp_;
uint32_t command_fingerprint_;
char response_[MAX_REPLY_TEXT + 1];
};
} // namespace mesh
+3 -6
View File
@@ -1,4 +1,5 @@
#include "SerialBLEInterface.h"
#include "../CompanionFrameQueue.h"
#include "esp_mac.h"
#include "esp_gap_ble_api.h"
@@ -211,15 +212,11 @@ size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
}
if (deviceConnected && len > 0) {
if (send_queue_len >= FRAME_QUEUE_SIZE) {
if (!mesh::enqueueCompanionFrame(send_queue, send_queue_len, FRAME_QUEUE_SIZE,
src, len)) {
BLE_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
return 0;
}
send_queue[send_queue_len].len = len; // add to send queue
memcpy(send_queue[send_queue_len].buf, src, len);
send_queue_len++;
return len;
}
return 0;
+4 -7
View File
@@ -1,4 +1,5 @@
#include "SerialWifiInterface.h"
#include "../CompanionFrameQueue.h"
#include <WiFi.h>
void SerialWifiInterface::begin(int port) {
@@ -25,15 +26,11 @@ size_t SerialWifiInterface::writeFrame(const uint8_t src[], size_t len) {
}
if (deviceConnected && len > 0) {
if (send_queue_len >= FRAME_QUEUE_SIZE) {
if (!mesh::enqueueCompanionFrame(send_queue, send_queue_len, FRAME_QUEUE_SIZE,
src, len)) {
WIFI_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
return 0;
}
send_queue[send_queue_len].len = len; // add to send queue
memcpy(send_queue[send_queue_len].buf, src, len);
send_queue_len++;
return len;
}
return 0;
@@ -173,4 +170,4 @@ size_t SerialWifiInterface::checkRecvFrame(uint8_t dest[]) {
bool SerialWifiInterface::isConnected() const {
return deviceConnected; //pServer != NULL && pServer->getConnectedCount() > 0;
}
}
@@ -1,4 +1,5 @@
#include "SerialEthernetInterface.h"
#include "../CompanionFrameQueue.h"
#define RECV_STATE_IDLE 0
#define RECV_STATE_HDR_FOUND 1
@@ -27,15 +28,11 @@ size_t SerialEthernetInterface::writeFrame(const uint8_t src[], size_t len) {
}
if (isConnected() && len > 0) {
if (send_queue_len >= FRAME_QUEUE_SIZE) {
if (!mesh::enqueueCompanionFrame(send_queue, send_queue_len, FRAME_QUEUE_SIZE,
src, len)) {
ETHERNET_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
return 0;
}
send_queue[send_queue_len].len = len; // add to send queue
memcpy(send_queue[send_queue_len].buf, src, len);
send_queue_len++;
return len;
}
return 0;
+3 -6
View File
@@ -1,4 +1,5 @@
#include "SerialBLEInterface.h"
#include "../CompanionFrameQueue.h"
#include <stdio.h>
#include <string.h>
#include "ble_gap.h"
@@ -353,15 +354,11 @@ size_t SerialBLEInterface::writeFrame(const uint8_t src[], size_t len) {
bool connected = isConnected();
if (connected && len > 0) {
if (send_queue_len >= FRAME_QUEUE_SIZE) {
if (!mesh::enqueueCompanionFrame(send_queue, send_queue_len, FRAME_QUEUE_SIZE,
src, len)) {
BLE_DEBUG_PRINTLN("writeFrame(), send_queue is full!");
return 0;
}
send_queue[send_queue_len].len = len;
memcpy(send_queue[send_queue_len].buf, src, len);
send_queue_len++;
return len;
}
return 0;