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

+14
View File
@@ -2021,9 +2021,23 @@ void MyMesh::handleCmdFrame(size_t len) {
result = sendCommandData(*recipient, msg_timestamp, attempt, text, est_timeout);
expected_ack = 0; // no Ack expected
} else {
const uint32_t app_timestamp = msg_timestamp;
const bool is_room_post = recipient->type == ADV_TYPE_ROOM;
if (is_room_post
&& !room_message_timestamps.find(text_fingerprint, app_timestamp,
&msg_timestamp)) {
// Room login/control packets already use the node's monotonic clock.
// Give a new post that same clock source, then preserve the mapping
// so application retries keep one logical server-side timestamp.
msg_timestamp = getRTCClock()->getCurrentTimeUnique();
}
result = sendMessage(*recipient, msg_timestamp, attempt, text, expected_ack, est_timeout,
packet_retry_key,
replacement_entry != NULL ? replacement_entry->retry_key : NULL);
if (result != MSG_SEND_FAILED && is_room_post) {
room_message_timestamps.remember(text_fingerprint, app_timestamp,
msg_timestamp);
}
}
if (result == MSG_SEND_FAILED) {
writeErrFrame(ERR_CODE_TABLE_FULL);
+6
View File
@@ -40,6 +40,7 @@
#include <helpers/ArduinoHelpers.h>
#include <helpers/BaseSerialInterface.h>
#include <helpers/IdentityStore.h>
#include <helpers/LogicalMessageCache.h>
#include <helpers/SimpleMeshTables.h>
#include <helpers/StaticPoolPacketManager.h>
#include <target.h>
@@ -73,6 +74,10 @@
#define OFFLINE_QUEUE_SIZE 16
#endif
#ifndef ROOM_MESSAGE_TIMESTAMP_CACHE_SIZE
#define ROOM_MESSAGE_TIMESTAMP_CACHE_SIZE 16
#endif
#ifndef BLE_NAME_PREFIX
#define BLE_NAME_PREFIX "MeshCore-"
#endif
@@ -324,6 +329,7 @@ private:
};
#define EXPECTED_ACK_TABLE_SIZE 8
AckTableEntry expected_ack_table[EXPECTED_ACK_TABLE_SIZE]; // circular table
mesh::LogicalMessageCache<ROOM_MESSAGE_TIMESTAMP_CACHE_SIZE> room_message_timestamps;
int next_ack_idx;
unsigned long next_ack_expiry;
bool has_next_ack_expiry;
File diff suppressed because it is too large. Load diff
+89 -37
View File
@@ -73,6 +73,7 @@
#include <helpers/ClientACL.h>
#include <helpers/CommonCLI.h>
#include <helpers/DeferredCliCommand.h>
#include <helpers/RemoteCliReplyCache.h>
#if defined(ESP32_PLATFORM) || defined(USER_GPIO_CONTROL)
#include <helpers/UserGpioReplyTracker.h>
#endif
@@ -138,8 +139,22 @@ struct NeighbourInfo {
#define MAX_SCHEDULED_RADIO_SETTINGS (MAX_SCHEDULED_RADIO_SETTINGS_PER_TYPE * 2)
#ifndef MESH_ENABLE_FLOOD_RULE_ENGINE
// STM32WL repeater images have only 240 KB of application flash. They keep
// the established dynamic flood.filter table unless a larger target profile
// explicitly opts into the generalized rule parser and persistence format.
#if defined(STM32_PLATFORM)
#define MESH_ENABLE_FLOOD_RULE_ENGINE 0
#else
#define MESH_ENABLE_FLOOD_RULE_ENGINE 1
#endif
#endif
#ifndef FLOOD_PACKET_FILTER_SLOTS
#define FLOOD_PACKET_FILTER_SLOTS 16
#if MESH_ENABLE_FLOOD_RULE_ENGINE
#define FLOOD_PACKET_FILTER_SLOTS 31
#else
#define FLOOD_PACKET_FILTER_SLOTS 16
#endif
#endif
#define FLOOD_PACKET_FILTER_ANY_TYPE 0xFF
#define FLOOD_PACKET_FILTER_MAX_HOPS 63
@@ -151,6 +166,9 @@ struct NeighbourInfo {
#endif
#define FLOOD_PACKET_FILTER_BLACKLIST_REPLACE_MAX 18
#define FLOOD_PACKET_FILTER_PATH_ID_SIZE 3
#define FLOOD_PACKET_FILTER_PATH_PREFIX_HOPS_MAX 3
#define FLOOD_PACKET_FILTER_PATH_PREFIX_BYTES_MAX \
(FLOOD_PACKET_FILTER_PATH_PREFIX_HOPS_MAX * 3)
#ifndef FLOOD_CHANNEL_SCOPE_SLOTS
#if defined(ESP32)
@@ -164,6 +182,18 @@ struct NeighbourInfo {
#define FLOOD_CHANNEL_SCOPE_TXT_ANY 0
#define FLOOD_CHANNEL_SCOPE_LOGIN_ANY 1
#define FLOOD_CHANNEL_SCOPE_OTHER_ANY 2
#ifndef FLOOD_CHANNEL_DIRECT_SCOPE_SLOTS
// STM32WL repeater images and RAM are both exceptionally tight. Keep one
// reusable regionless target there; other platforms scale with the rule
// table up to the region-map capacity.
#if defined(STM32_PLATFORM)
#define FLOOD_CHANNEL_DIRECT_SCOPE_SLOTS 1
#elif FLOOD_CHANNEL_SCOPE_SLOTS < MAX_REGION_ENTRIES
#define FLOOD_CHANNEL_DIRECT_SCOPE_SLOTS FLOOD_CHANNEL_SCOPE_SLOTS
#else
#define FLOOD_CHANNEL_DIRECT_SCOPE_SLOTS MAX_REGION_ENTRIES
#endif
#endif
#ifndef FLOOD_CHANNEL_SCOPE_REQUIRE_SLOTS
#define FLOOD_CHANNEL_SCOPE_REQUIRE_SLOTS FLOOD_CHANNEL_SCOPE_SLOTS
#endif
@@ -234,6 +264,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
uint64_t uptime_millis;
unsigned long next_local_advert, next_flood_advert;
mesh::DeferredCliCommand deferred_cli_command;
mesh::RemoteCliReplyCache remote_cli_reply_cache;
TransportKey deferred_cli_reply_scope;
bool deferred_cli_reply_scoped;
uint32_t pending_self_advert_delay;
@@ -259,7 +290,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
RegionMap region_map, temp_map;
RegionEntry* load_stack[8];
RegionEntry* recv_pkt_region;
bool recv_pkt_filter_scope_set;
bool recv_pkt_regionless_scope_set;
bool recv_pkt_channel_scope_bypass;
bool recv_pkt_channel_scope_rejected;
TransportKey default_scope;
@@ -277,14 +308,6 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
uint8_t prefix_len;
uint32_t last_heard_millis;
};
struct FloodChannelBlockEntry {
bool active;
uint8_t key_len;
uint8_t max_hops;
uint8_t hash_prefix[FLOOD_CHANNEL_BLOCK_PREFIX_LEN];
uint8_t secret[PUB_KEY_SIZE];
char name[FLOOD_CHANNEL_BLOCK_NAME_LEN];
};
struct FloodPacketFilterEntry {
bool active;
uint8_t payload_type;
@@ -293,12 +316,37 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
bool suspend_on_temp_radio;
char scope_name[FLOOD_PACKET_FILTER_SCOPE_NAME_LEN];
bool match_blacklisted_path;
#if !MESH_ENABLE_FLOOD_RULE_ENGINE
bool scope_requires_region_match;
#endif
bool scope_uses_slow_timing;
#if MESH_ENABLE_FLOOD_RULE_ENGINE
uint8_t incoming_scope_kind;
char incoming_scope_name[FLOOD_PACKET_FILTER_SCOPE_NAME_LEN];
uint8_t channel_key_len;
uint8_t channel_hash;
uint8_t channel_secret[PUB_KEY_SIZE];
char channel_name[FLOOD_GROUP_MODERATION_NAME_LEN];
uint8_t path_hash_size;
uint8_t path_hops;
uint8_t path[FLOOD_PACKET_FILTER_PATH_PREFIX_BYTES_MAX];
char target_region_name[FLOOD_PACKET_FILTER_SCOPE_NAME_LEN];
bool drop_on_match;
bool rate_limit_enabled;
uint16_t rate_per_minute;
uint8_t priority;
bool stop_on_match;
uint32_t rate_window_started;
uint16_t rate_window_count;
bool rate_window_active;
#endif
};
struct FloodChannelScopeEntry {
uint16_t region_id; // zero means unused
// Low bits select txt:*/login:*/other:* or an exact channel-key length.
// Zero means unused. Otherwise this is either a region ID or a one-based
// flood_channel_direct_scopes index, as selected by selector.
uint16_t target_id;
// Encodes txt:*/login:*/other:* or an exact key length, target kind,
// optional path selector, and fast/slow timing.
uint8_t selector;
uint8_t channel_hash;
uint8_t secret[PUB_KEY_SIZE];
@@ -311,7 +359,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
struct FloodGroupModerationEntry {
bool active;
uint8_t key_len;
uint8_t hash_prefix[FLOOD_CHANNEL_BLOCK_PREFIX_LEN];
uint8_t hash_prefix[FLOOD_CHANNEL_KEY_PREFIX_LEN];
uint8_t secret[PUB_KEY_SIZE];
char channel_name[FLOOD_GROUP_MODERATION_NAME_LEN];
char sender[FLOOD_GROUP_MODERATION_NAME_LEN];
@@ -334,15 +382,17 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
};
mutable FloodRetryBridgeState flood_retry_bridge_states[MAX_FLOOD_RETRY_SLOTS];
FloodRetryBridgeReachability flood_retry_bridge_reachability[FLOOD_RETRY_BRIDGE_BUCKETS + 1];
FloodChannelBlockEntry flood_channel_blocks[FLOOD_CHANNEL_BLOCK_SLOTS];
FloodPacketFilterEntry flood_packet_filters[FLOOD_PACKET_FILTER_SLOTS];
uint8_t flood_packet_filter_blacklist_count;
uint8_t flood_packet_filter_blacklist[FLOOD_PACKET_FILTER_BLACKLIST_MAX]
[FLOOD_PACKET_FILTER_PATH_ID_SIZE];
FloodChannelScopeEntry flood_channel_scopes[FLOOD_CHANNEL_SCOPE_SLOTS];
char flood_channel_direct_scopes[FLOOD_CHANNEL_DIRECT_SCOPE_SLOTS]
[FLOOD_PACKET_FILTER_SCOPE_NAME_LEN];
FloodChannelScopeRequireEntry
flood_channel_scope_requirements[FLOOD_CHANNEL_SCOPE_REQUIRE_SLOTS];
FloodGroupModerationEntry flood_group_moderation[FLOOD_GROUP_MODERATION_SLOTS];
uint32_t recv_pkt_filter_match_mask;
ClockSyncSample clock_sync_samples[CLOCK_SYNC_SAMPLE_SLOTS];
bool clock_sync_mesh_enabled;
bool clock_sync_mesh_edge_enabled;
@@ -530,32 +580,40 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
void refreshScheduledRadioState();
void processScheduledRadioSettings();
bool isMillisTimerDue(unsigned long timestamp) const;
void loadFloodChannelBlocks();
bool saveFloodChannelBlocks();
void seedDefaultFloodChannelBlocks();
void clearFloodChannelBlockEntry(FloodChannelBlockEntry& entry);
void deriveFloodChannelBlockPrefix(const uint8_t* secret, uint8_t key_len,
uint8_t prefix[FLOOD_CHANNEL_BLOCK_PREFIX_LEN]) const;
uint8_t resolveFloodChannelBlockHops(uint8_t max_hops) const;
bool floodChannelBlockHopApplies(const mesh::Packet* packet, uint8_t max_hops) const;
bool floodChannelDataHopApplies(const mesh::Packet* packet) const;
bool floodChannelBlockMatches(const FloodChannelBlockEntry& entry, const mesh::Packet* packet) const;
bool shouldBlockFloodChannelForward(const mesh::Packet* packet) const;
void loadFloodPacketFilters();
bool loadFloodPacketFilters();
bool saveFloodPacketFilters();
#if MESH_ENABLE_FLOOD_RULE_ENGINE
void migrateLegacyFloodChannelBlocks();
#endif
void loadFloodPacketFilterBlacklist();
bool saveFloodPacketFilterBlacklist();
void seedDefaultFloodPacketFilters();
bool floodPacketFilterBlacklistMatches(const mesh::Packet* packet) const;
bool floodPacketFilterMatches(const FloodPacketFilterEntry& entry,
const mesh::Packet* packet) const;
bool applyFloodPacketFilterScope(mesh::Packet* packet, bool incoming_region_allowed,
bool floodPacketFilterFieldsMatch(const FloodPacketFilterEntry& entry,
const mesh::Packet* packet,
bool incoming_is_scoped,
uint16_t incoming_transport_code,
bool incoming_region_allowed,
const RegionEntry* incoming_region) const;
bool authenticateFloodPacketFilterChannel(
const FloodPacketFilterEntry& entry,
const mesh::Packet* packet) const;
int nextFloodPacketFilterMatch(uint32_t match_mask,
uint32_t visited_mask) const;
uint32_t applyFloodPacketFilterStop(uint32_t match_mask) const;
uint32_t evaluateFloodPacketFilterMatches(
const mesh::Packet* packet, bool incoming_region_allowed,
const RegionEntry* incoming_region) const;
bool applyFloodPacketFilterScope(mesh::Packet* packet, uint32_t match_mask,
bool& scope_set, bool& fast_track,
bool log_change = true);
bool shouldBlockFloodPacketForward(const mesh::Packet* packet) const;
void commitFloodPacketFilterRates(const mesh::Packet* packet);
void formatFloodPacketFilters(const char* args, char* reply) const;
void formatFloodPacketFilterDetail(int index, char* reply, size_t reply_len) const;
void setFloodPacketFilter(const char* args, char* reply);
void setFloodPacketFilter(const char* args, char* reply,
bool require_explicit_action = false);
void deleteFloodPacketFilter(const char* args, char* reply);
void formatFloodPacketFilterBlacklist(const char* args, char* reply) const;
void setFloodPacketFilterBlacklist(const char* args, char* reply);
@@ -564,8 +622,10 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
bool saveFloodChannelScopes(bool empty_table = false);
bool applyFloodChannelScopeTarget(mesh::Packet* packet, const FloodChannelScopeEntry& entry,
bool& scope_changed, bool& fast_track,
bool& regionless_scope_set,
bool log_change = true);
bool applyFloodChannelScope(mesh::Packet* packet, bool& fast_track,
bool& regionless_scope_set,
bool log_change = true);
static uint8_t scoreFloodTransportScope(const mesh::Packet* packet, void* context);
uint8_t getFloodTransportScopeDepth(const mesh::Packet* packet);
@@ -609,9 +669,6 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
void formatClockSyncStatus(const char* args, char* reply, size_t reply_len) const;
void formatClockSyncTable(char* reply, size_t reply_len) const;
void formatClockSyncSampleDetail(int index, char* reply, size_t reply_len) const;
int findFloodChannelBlockBySelector(const char* selector) const;
int findFloodChannelBlockSlot(const uint8_t prefix[FLOOD_CHANNEL_BLOCK_PREFIX_LEN], const char* name) const;
void formatFloodChannelBlockDetail(char* reply, int idx) const;
bool hasScheduledRadioWorkDue() const;
uint32_t limitSleepToMillisTimer(unsigned long timestamp, uint32_t sleep_secs) const;
uint32_t limitSleepToScheduledRadioWork(uint32_t sleep_secs) const;
@@ -791,11 +848,6 @@ public:
void startRegionsLoad() override;
bool saveRegions() override;
void onDefaultRegionChanged(const RegionEntry* r) override;
void setFloodChannelBlock(int index, const uint8_t* secret, uint8_t key_len,
const char* name, uint8_t max_hops, char* reply) override;
void formatFloodChannelBlocks(const char* selector, char* reply) override;
void deleteFloodChannelBlock(const char* selector, char* reply) override;
mesh::LocalIdentity& getSelfId() override { return self_id; }
void saveIdentity(const mesh::LocalIdentity& new_id) override;
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,91 @@
#pragma once
#if defined(MESHCORE_ESP32_FULL_PROFILE)
#include <Arduino.h>
#include <Mesh.h>
#include <helpers/IdentityStore.h>
#include <helpers/RegionMap.h>
class FloodRuleEngine {
public:
static constexpr uint8_t RULE_SLOTS = 31;
static constexpr uint8_t ANY_TYPE = 0xFF;
static constexpr uint8_t MAX_HOPS = 63;
static constexpr uint8_t NAME_LEN = 32;
static constexpr uint8_t PATH_PREFIX_HOPS_MAX = 3;
static constexpr uint8_t PATH_PREFIX_BYTES_MAX = 9;
static constexpr uint16_t RATE_UNLIMITED = 0xFFFF;
FloodRuleEngine();
void begin(FILESYSTEM* fs, RegionMap* regions);
uint32_t evaluate(const mesh::Packet* packet, bool temp_radio_active,
bool incoming_region_allowed,
const RegionEntry* incoming_region) const;
bool applyScope(mesh::Packet* packet, uint32_t match_mask,
bool& scope_set, bool& fast_track,
bool log_change = true);
bool shouldBlock(const mesh::Packet* packet, uint32_t match_mask,
uint32_t now_millis) const;
void commitRates(const mesh::Packet* packet, uint32_t match_mask,
uint32_t now_millis);
bool handleCommand(const char* command, char* reply);
private:
struct Entry {
bool active;
uint8_t payload_type;
uint8_t min_hops;
uint8_t max_hops;
bool suspend_on_temp_radio;
char scope_name[NAME_LEN];
bool match_blacklisted_path;
bool scope_uses_slow_timing;
uint8_t incoming_scope_kind;
char incoming_scope_name[NAME_LEN];
uint8_t channel_key_len;
uint8_t channel_hash;
uint8_t channel_secret[PUB_KEY_SIZE];
char channel_name[NAME_LEN];
uint8_t path_hash_size;
uint8_t path_hops;
uint8_t path[PATH_PREFIX_BYTES_MAX];
char target_region_name[NAME_LEN];
bool drop_on_match;
bool rate_limit_enabled;
uint16_t rate_per_minute;
uint8_t priority;
bool stop_on_match;
uint32_t rate_window_started;
uint16_t rate_window_count;
bool rate_window_active;
};
FILESYSTEM* _fs;
RegionMap* _regions;
Entry _entries[RULE_SLOTS];
void seedDefaults();
void load();
bool save();
bool fieldsMatch(const Entry& entry, const mesh::Packet* packet,
bool temp_radio_active, bool incoming_is_scoped,
uint16_t incoming_transport_code,
bool incoming_region_allowed,
const RegionEntry* incoming_region) const;
bool authenticateChannel(const Entry& entry,
const mesh::Packet* packet) const;
int nextMatch(uint32_t match_mask, uint32_t visited_mask) const;
uint32_t applyStop(uint32_t match_mask) const;
void format(const char* args, char* reply) const;
void formatDetail(int index, char* reply, size_t reply_len) const;
void set(const char* args, char* reply,
bool require_explicit_action = false);
void remove(const char* args, char* reply);
};
#endif
+245 -80
View File
@@ -1,5 +1,8 @@
#include "MyMesh.h"
#include <helpers/CLICommandUtils.h>
#if defined(MESHCORE_ESP32_FULL_PROFILE)
#include <helpers/FloodFilterPolicy.h>
#endif
#include <helpers/radiolib/RXPowerSaving.h>
#include <algorithm>
#include <helpers/RxReservePacketManager.h>
@@ -317,6 +320,69 @@ int MyMesh::calcRxDelay(float score, uint32_t air_time) const {
return (int)((powf(_prefs.rx_delay_base, 0.85f - score) - 1.0f) * air_time);
}
#if defined(MESHCORE_ESP32_FULL_PROFILE)
bool MyMesh::evaluateFloodRuleTiming(const mesh::Packet* packet,
bool& fast_track) {
fast_track = false;
if (packet == NULL || !packet->isRouteFlood()) return false;
bool incoming_region_allowed = false;
RegionEntry* incoming_region = NULL;
if (packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
incoming_region = region_map.findMatch(packet, REGION_DENY_FLOOD);
incoming_region_allowed = incoming_region != NULL;
} else if (packet->getRouteType() == ROUTE_TYPE_FLOOD) {
incoming_region_allowed =
(region_map.getWildcard().flags & REGION_DENY_FLOOD) == 0;
}
mesh::Packet candidate = *packet;
uint32_t match_mask = flood_rules.evaluate(
packet, isTempRadioActive(), incoming_region_allowed, incoming_region);
bool scope_set = false;
return flood_rules.applyScope(&candidate, match_mask, scope_set,
fast_track, false);
}
static const uint8_t ROOM_MAX_LOOP_MINIMAL[] = { 0, 4, 2, 1 };
static const uint8_t ROOM_MAX_LOOP_MODERATE[] = { 0, 2, 1, 1 };
static const uint8_t ROOM_MAX_LOOP_STRICT[] = { 0, 1, 1, 1 };
bool MyMesh::isLooped(const mesh::Packet* packet,
const uint8_t max_counters[]) const {
uint8_t hash_size = packet->getPathHashSize();
uint8_t hash_count = packet->getPathHashCount();
uint8_t occurrences = 0;
const uint8_t* path = packet->path;
while (hash_count > 0) {
if (self_id.isHashMatch(path, hash_size)) occurrences++;
hash_count--;
path += hash_size;
}
return occurrences >= max_counters[hash_size];
}
int MyMesh::calcRxDelayForPacket(const mesh::Packet* packet, float score,
uint32_t air_time) {
bool fast_track = false;
if (!evaluateFloodRuleTiming(packet, fast_track)) {
return calcRxDelay(score, air_time);
}
if (fast_track) return 0;
float slow_base =
FloodFilterPolicy::slowScopeRxDelayBase(_prefs.rx_delay_base);
return (int)((powf(slow_base, 0.85f - score) - 1.0f) * air_time);
}
uint32_t MyMesh::getSlowFloodRuleRetransmitDelay(
const mesh::Packet* packet) {
uint32_t airtime = _radio->getEstAirtimeFor(
packet->getPathByteLen() + packet->payload_len + 2);
uint32_t max_delay = FloodFilterPolicy::slowScopeMaxDelay(airtime);
return getRNG()->nextInt(0, max_delay + 1);
}
#endif
const char *MyMesh::getLogDateTime() {
static char tmp[32];
uint32_t now = getRTCClock()->getCurrentTime();
@@ -409,11 +475,62 @@ bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
if (packet->getPathHashCount() >= _prefs.flood_max) return false;
if (packet->getRouteType() == ROUTE_TYPE_FLOOD && packet->getPathHashCount() >= _prefs.flood_max_unscoped) return false;
if (packet->getPayloadType() == PAYLOAD_TYPE_ADVERT && packet->getPathHashCount() >= _prefs.flood_max_advert) return false;
#if defined(MESHCORE_ESP32_FULL_PROFILE)
if (flood_rules.shouldBlock(packet, recv_pkt_rule_match_mask,
_ms->getMillis())) {
return false;
}
#endif
}
#if defined(MESHCORE_ESP32_FULL_PROFILE)
if (packet->isRouteFlood()) {
if (recv_pkt_region == NULL && !recv_pkt_regionless_scope_set) {
MESH_DEBUG_PRINTLN(
"allowPacketForward: unknown transport code, or wildcard not allowed for FLOOD packet");
return false;
}
if (_prefs.loop_detect != LOOP_DETECT_OFF) {
const uint8_t* maximums = _prefs.loop_detect == LOOP_DETECT_MINIMAL
? ROOM_MAX_LOOP_MINIMAL
: (_prefs.loop_detect == LOOP_DETECT_MODERATE
? ROOM_MAX_LOOP_MODERATE : ROOM_MAX_LOOP_STRICT);
if (isLooped(packet, maximums)) {
MESH_DEBUG_PRINTLN(
"allowPacketForward: FLOOD packet loop detected!");
return false;
}
}
flood_rules.commitRates(packet, recv_pkt_rule_match_mask,
_ms->getMillis());
}
#endif
return true;
}
mesh::DispatcherAction MyMesh::onRecvPacket(mesh::Packet* pkt) {
#if defined(MESHCORE_ESP32_FULL_PROFILE)
bool scope_changed = false;
bool fast_track_scope_change = false;
recv_pkt_regionless_scope_set = false;
recv_pkt_rule_match_mask = 0;
if (pkt->isRouteFlood()) {
bool incoming_region_allowed = false;
RegionEntry* incoming_region = NULL;
if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
incoming_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
incoming_region_allowed = incoming_region != NULL;
} else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
incoming_region_allowed =
(region_map.getWildcard().flags & REGION_DENY_FLOOD) == 0;
}
recv_pkt_rule_match_mask = flood_rules.evaluate(
pkt, isTempRadioActive(), incoming_region_allowed, incoming_region);
bool scope_set = false;
scope_changed = flood_rules.applyScope(
pkt, recv_pkt_rule_match_mask, scope_set, fast_track_scope_change);
recv_pkt_regionless_scope_set = scope_set;
}
#endif
if (pkt->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD) {
recv_pkt_region = region_map.findMatch(pkt, REGION_DENY_FLOOD);
} else if (pkt->getRouteType() == ROUTE_TYPE_FLOOD) {
@@ -425,7 +542,20 @@ mesh::DispatcherAction MyMesh::onRecvPacket(mesh::Packet* pkt) {
} else {
recv_pkt_region = NULL;
}
return Mesh::onRecvPacket(pkt);
mesh::DispatcherAction action = Mesh::onRecvPacket(pkt);
#if defined(MESHCORE_ESP32_FULL_PROFILE)
if (scope_changed && action != ACTION_RELEASE
&& action != ACTION_MANUAL_HOLD) {
if (fast_track_scope_change) {
action = ACTION_RETRANSMIT(0);
} else {
uint8_t priority = (action >> 24) - 1;
action = ACTION_RETRANSMIT_DELAYED(
priority, getSlowFloodRuleRetransmitDelay(pkt));
}
}
#endif
return action;
}
void MyMesh::onAnonDataRecv(mesh::Packet *packet, const uint8_t *secret, const mesh::Identity &sender,
@@ -602,96 +732,118 @@ void MyMesh::onPeerDataRecv(mesh::Packet *packet, uint8_t type, int sender_idx,
if (!(flags == TXT_TYPE_PLAIN || flags == TXT_TYPE_CLI_DATA)) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: unsupported command flags received: flags=%02x", (uint32_t)flags);
} else if (sender_timestamp >= client->last_timestamp) { // prevent replay attacks, but send Acks for retries
bool is_retry = (sender_timestamp == client->last_timestamp);
client->last_timestamp = sender_timestamp;
return;
}
uint32_t now = getRTCClock()->getCurrentTimeUnique();
client->last_activity = now;
client->extra.room.push_failures = 0; // reset so push can resume (if prev failed)
// len can be > original length, but 'text' will be padded with zeroes
data[len] = 0; // need to make a C string again, with null terminator
const char* text = (const char*)&data[5];
const size_t text_len = strlen(text);
// len can be > original length, but 'text' will be padded with zeroes
data[len] = 0; // need to make a C string again, with null terminator
uint8_t temp[166];
temp[5] = 0;
bool send_ack = false;
uint32_t ack_hash; // calc truncated hash of the message timestamp + text + sender pub_key, to prove to
// sender that we got it
mesh::Utils::sha256((uint8_t *)&ack_hash, 4, data, 5 + strlen((char *)&data[5]), client->id.pub_key,
PUB_KEY_SIZE);
uint8_t temp[166];
bool send_ack;
if (flags == TXT_TYPE_CLI_DATA) {
if (client->isAdmin()) {
if (is_retry) {
temp[5] = 0; // no reply
} else {
handleCommand(sender_timestamp, (char *)&data[5], (char *)&temp[5],
i, packet->getPathHashSize());
temp[4] = (TXT_TYPE_CLI_DATA << 2); // attempt and flags, (NOTE: legacy was: TXT_TYPE_PLAIN)
}
send_ack = false;
} else {
temp[5] = 0; // no reply
send_ack = false; // and no ACK... user shoudn't be sending these
}
} else { // TXT_TYPE_PLAIN
if ((client->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST) {
temp[5] = 0; // no reply
send_ack = false; // no ACK
} else {
if (!is_retry) {
addPost(client, (const char *)&data[5]);
}
temp[5] = 0; // no reply (ACK is enough)
send_ack = true;
}
}
uint32_t delay_millis;
if (send_ack) {
if (client->out_path_len == OUT_PATH_UNKNOWN) {
mesh::Packet *ack = createAck(ack_hash);
if (ack) sendFloodReply(ack, TXT_ACK_DELAY, packet->getPathHashSize());
delay_millis = TXT_ACK_DELAY + REPLY_DELAY_MILLIS;
} else {
uint32_t d = TXT_ACK_DELAY;
if (getExtraAckTransmitCount() > 0) {
mesh::Packet *a1 = createMultiAck(ack_hash, 1);
if (a1) sendDirect(a1, client->out_path, client->out_path_len, d);
d += 300;
}
mesh::Packet *a2 = createAck(ack_hash);
if (a2) sendDirect(a2, client->out_path, client->out_path_len, d);
delay_millis = d + REPLY_DELAY_MILLIS;
if (flags == TXT_TYPE_PLAIN) {
const bool is_guest =
(client->permissions & PERM_ACL_ROLE_MASK) == PERM_ACL_GUEST;
if (is_guest) {
if (sender_timestamp < client->extra.room.last_post_timestamp) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: stale room post detected");
return;
}
client->extra.room.last_post_timestamp = sender_timestamp;
} else {
delay_millis = 0;
uint8_t message_fingerprint[MAX_HASH_SIZE];
mesh::Utils::sha256(message_fingerprint, sizeof(message_fingerprint),
client->id.pub_key, PUB_KEY_SIZE,
(const uint8_t*)text, text_len);
const auto replay_decision = recent_room_posts.classifyAndRemember(
message_fingerprint, sender_timestamp,
client->extra.room.last_post_timestamp);
using ReplayDecision =
mesh::LogicalMessageCache<ROOM_MESSAGE_CACHE_SIZE>::ReplayDecision;
if (replay_decision == ReplayDecision::StaleOrMismatched) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: stale or mismatched room post detected");
return;
}
if (replay_decision == ReplayDecision::NewMessage) {
addPost(client, text);
}
// Exact retries are ACKed again regardless of whether newer posts have
// advanced this client's room-post replay timestamp.
send_ack = true;
}
} else { // TXT_TYPE_CLI_DATA
if (sender_timestamp < client->last_timestamp) {
MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
return;
}
int text_len = strlen((char *)&temp[5]);
if (text_len > 0) {
if (now == sender_timestamp) {
// WORKAROUND: the two timestamps need to be different, in the CLI view
now++;
}
memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
const bool is_retry = sender_timestamp == client->last_timestamp;
client->last_timestamp = sender_timestamp;
if (client->isAdmin() && !is_retry) {
handleCommand(sender_timestamp, (char*)text, (char*)&temp[5],
i, packet->getPathHashSize());
temp[4] = (TXT_TYPE_CLI_DATA << 2); // attempt and flags, (NOTE: legacy was: TXT_TYPE_PLAIN)
}
// CLI_DATA replies are the result signal; no separate ACK is expected.
}
// calc expected ACK reply
// mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + text_len, self_id.pub_key,
// PUB_KEY_SIZE);
uint32_t now = getRTCClock()->getCurrentTimeUnique();
client->last_activity = now;
client->extra.room.push_failures = 0; // reset so push can resume (if prev failed)
auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret, temp, 5 + text_len);
if (reply) {
if (client->out_path_len == OUT_PATH_UNKNOWN) {
sendFloodReply(reply, delay_millis + SERVER_RESPONSE_DELAY, packet->getPathHashSize());
} else {
sendDirect(reply, client->out_path, client->out_path_len, delay_millis + SERVER_RESPONSE_DELAY);
}
uint32_t delay_millis;
if (send_ack) {
uint32_t ack_hash; // prove receipt of this timestamp, attempt, text, and sender
mesh::Utils::sha256((uint8_t*)&ack_hash, 4, data, 5 + text_len,
client->id.pub_key, PUB_KEY_SIZE);
if (client->out_path_len == OUT_PATH_UNKNOWN) {
mesh::Packet *ack = createAck(ack_hash);
if (ack) sendFloodReply(ack, TXT_ACK_DELAY, packet->getPathHashSize());
delay_millis = TXT_ACK_DELAY + REPLY_DELAY_MILLIS;
} else {
uint32_t d = TXT_ACK_DELAY;
if (getExtraAckTransmitCount() > 0) {
mesh::Packet *a1 = createMultiAck(ack_hash, 1);
if (a1) sendDirect(a1, client->out_path, client->out_path_len, d);
d += 300;
}
mesh::Packet *a2 = createAck(ack_hash);
if (a2) sendDirect(a2, client->out_path, client->out_path_len, d);
delay_millis = d + REPLY_DELAY_MILLIS;
}
} else {
MESH_DEBUG_PRINTLN("onPeerDataRecv: possible replay attack detected");
delay_millis = 0;
}
int reply_text_len = strlen((char*)&temp[5]);
if (reply_text_len > 0) {
if (now == sender_timestamp) {
// WORKAROUND: the two timestamps need to be different, in the CLI view
now++;
}
memcpy(temp, &now, 4); // mostly an extra blob to help make packet_hash unique
// calc expected ACK reply
// mesh::Utils::sha256((uint8_t *)&expected_ack_crc, 4, temp, 5 + reply_text_len, self_id.pub_key,
// PUB_KEY_SIZE);
auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret,
temp, 5 + reply_text_len);
if (reply) {
if (client->out_path_len == OUT_PATH_UNKNOWN) {
sendFloodReply(reply, delay_millis + SERVER_RESPONSE_DELAY,
packet->getPathHashSize());
} else {
sendDirect(reply, client->out_path, client->out_path_len,
delay_millis + SERVER_RESPONSE_DELAY);
}
}
}
} else if (type == PAYLOAD_TYPE_REQ && len >= 5) {
uint32_t sender_timestamp;
@@ -909,6 +1061,10 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
radio_apply_retry_at = 0;
radio_apply_failures = 0;
recv_pkt_region = NULL;
#if defined(MESHCORE_ESP32_FULL_PROFILE)
recv_pkt_rule_match_mask = 0;
recv_pkt_regionless_scope_set = false;
#endif
// defaults
memset(&_prefs, 0, sizeof(_prefs));
@@ -998,6 +1154,9 @@ void MyMesh::begin(FILESYSTEM *fs) {
acl.load(_fs, self_id);
region_map.load(_fs);
#if defined(MESHCORE_ESP32_FULL_PROFILE)
flood_rules.begin(_fs, &region_map);
#endif
// establish default-scope
{
@@ -1818,7 +1977,13 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
addSystemPost(msg);
snprintf(reply, MAX_POST_TEXT_LEN, "OK");
}
} else{
}
#if defined(MESHCORE_ESP32_FULL_PROFILE)
else if (flood_rules.handleCommand(command, reply)) {
// handled by the FULL-profile persistent flood rule engine
}
#endif
else {
_cli.handleCommand(sender_timestamp, command, reply); // common CLI commands
}
}
+24
View File
@@ -24,7 +24,9 @@
#endif
#include <helpers/StatsFormatHelper.h>
#include <helpers/ClientACL.h>
#include <helpers/LogicalMessageCache.h>
#include <helpers/RegionMap.h>
#include "FloodRuleEngine.h"
#include <RTClib.h>
#include <target.h>
@@ -87,6 +89,10 @@
#define MAX_UNSYNCED_POSTS 32
#endif
#ifndef ROOM_MESSAGE_CACHE_SIZE
#define ROOM_MESSAGE_CACHE_SIZE 32
#endif
#ifndef SERVER_RESPONSE_DELAY
#define SERVER_RESPONSE_DELAY 300
#endif
@@ -128,7 +134,13 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
NodePrefs _prefs;
TransportKeyStore key_store;
RegionMap region_map, temp_map;
#if defined(MESHCORE_ESP32_FULL_PROFILE)
FloodRuleEngine flood_rules;
uint32_t recv_pkt_rule_match_mask;
bool recv_pkt_regionless_scope_set;
#endif
ClientACL acl;
mesh::LogicalMessageCache<ROOM_MESSAGE_CACHE_SIZE> recent_room_posts;
CommonCLI _cli;
#if defined(ESP32_PLATFORM) || defined(USER_GPIO_CONTROL)
UserGpioReplyTracker _gpio_reply_tracker;
@@ -218,6 +230,14 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
mesh::Packet* createSelfAdvert();
File openAppend(const char* fname);
int handleRequest(ClientInfo* sender, uint32_t sender_timestamp, uint8_t* payload, size_t payload_len);
#if defined(MESHCORE_ESP32_FULL_PROFILE)
bool evaluateFloodRuleTiming(const mesh::Packet* packet,
bool& fast_track);
bool isLooped(const mesh::Packet* packet,
const uint8_t max_counters[]) const;
uint32_t getSlowFloodRuleRetransmitDelay(
const mesh::Packet* packet);
#endif
protected:
bool isTempRadioActive() const override {
@@ -233,6 +253,10 @@ protected:
void logTxFail(mesh::Packet* pkt, int len) override;
int calcRxDelay(float score, uint32_t air_time) const override;
#if defined(MESHCORE_ESP32_FULL_PROFILE)
int calcRxDelayForPacket(const mesh::Packet* packet, float score,
uint32_t air_time) override;
#endif
const char* getLogDateTime() override;
uint32_t getRetransmitDelay(const mesh::Packet* packet) override;
uint32_t getDirectRetransmitDelay(const mesh::Packet* packet) override;