Add per-profile TX routing and bridge filtering

Persist Companion TX preferences per contact and channel. Default repeater,
room, and sensor replies to both active TX profiles, with a reply-only force
option for an RX-only secondary profile. Track both reply copies before a
temporary-radio handoff and account for OTA copies under queue backpressure.

Add bridge/crossover filter modes and the third built-in wardriving filter,
plus compact filter CLI syntax, documentation, and CI coverage.

Fix quoted target names being interpreted as slot/key selectors, partial
recovery of invalid saved reply settings, filter suspension during tempradio2,
and unnecessary packet allocation while OTA traffic is throttled.

Validation: 1,477 native tests, 52 Python integration tests, 29 filter UI tests,
and five firmware builds covering ESP32, nRF52, and STM32 passed.
This commit is contained in:
mikecarper committed 2026-09-15 01:58:43 -07:00
1 parent 0e0aa8e014
commit 95aca52b4e
60 files changed
+3188 -362

No files matched your search

+8 -5
View File
@@ -942,12 +942,11 @@ bool DataStore::savePrefs(const CompanionNodePrefs& _prefs, double node_lat, dou
static bool serializeContactRecord(const ContactInfo& c,
uint8_t out[mesh::storage::CONTACT_RECORD_SIZE]) {
size_t offset = 0;
const uint8_t unused = 0;
memcpy(&out[offset], c.id.pub_key, 32); offset += 32;
memcpy(&out[offset], c.name, 32); offset += 32;
out[offset++] = c.type;
out[offset++] = c.flags;
out[offset++] = unused;
out[offset++] = mesh::encodeRadioTxPolicy(c.tx_radio);
memcpy(&out[offset], &c.sync_since, 4); offset += 4;
out[offset++] = c.out_path_len;
memcpy(&out[offset], &c.last_advert_timestamp, 4); offset += 4;
@@ -970,7 +969,7 @@ static bool deserializeContactRecord(
c.name[sizeof(c.name) - 1] = 0;
c.type = in[offset++];
c.flags = in[offset++];
offset++; // reserved
c.tx_radio = mesh::decodeRadioTxPolicy(in[offset++]);
memcpy(&c.sync_since, &in[offset], 4); offset += 4;
c.out_path_len = in[offset++];
memcpy(&c.last_advert_timestamp, &in[offset], 4); offset += 4;
@@ -1712,7 +1711,7 @@ bool DataStore::saveContacts(DataStoreHost* host, bool (*filter)(const ContactIn
if (file) {
uint32_t idx = 0;
ContactInfo c;
uint8_t unused = 0;
uint8_t tx_radio = 0;
while (host->getContactForSave(idx, c)) {
if (filter && !filter(c)) {
@@ -1723,7 +1722,8 @@ bool DataStore::saveContacts(DataStoreHost* host, bool (*filter)(const ContactIn
success = success && (file.write((uint8_t *)&c.name, 32) == 32);
success = success && (file.write(&c.type, 1) == 1);
success = success && (file.write(&c.flags, 1) == 1);
success = success && (file.write(&unused, 1) == 1);
tx_radio = mesh::encodeRadioTxPolicy(c.tx_radio);
success = success && (file.write(&tx_radio, 1) == 1);
success = success && (file.write((uint8_t *)&c.sync_since, 4) == 4);
success = success && (file.write((uint8_t *)&c.out_path_len, 1) == 1);
success = success && (file.write((uint8_t *)&c.last_advert_timestamp, 4) == 4);
@@ -1986,6 +1986,7 @@ void DataStore::loadChannels(DataStoreHost* host) {
sizeof(loaded[channel_idx].channel.secret))
== sizeof(loaded[channel_idx].channel.secret);
if (!success) break;
loaded[channel_idx].channel.tx_radio = mesh::decodeRadioTxPolicy(unused[0]);
}
file.close();
if (!success) {
@@ -2019,6 +2020,7 @@ void DataStore::loadChannels(DataStoreHost* host) {
if (!success) break; // EOF
ch.channel.tx_radio = mesh::decodeRadioTxPolicy(unused[0]);
if (host->onChannelLoaded(channel_idx, ch)) {
channel_idx++;
} else {
@@ -2047,6 +2049,7 @@ bool DataStore::saveChannels(DataStoreHost* host) {
memset(unused, 0, 4);
while (success && host->getChannelForSave(channel_idx, ch)) {
unused[0] = mesh::encodeRadioTxPolicy(ch.channel.tx_radio);
success = (file.write(unused, 4) == 4);
success = success && (file.write((uint8_t *)ch.name, 32) == 32);
success = success && (file.write((uint8_t *)ch.channel.secret, 32) == 32);
+102 -1
View File
@@ -1,5 +1,6 @@
#include <helpers/ui/DisplayPowerSettings.h>
#include "MyMesh.h"
#include <helpers/CompanionTxRoutingCLI.h>
#include "CompanionBluetooth.h"
#include "CompanionWireless.h"
#if defined(MESH_SOAK_DIAGNOSTICS)
@@ -2298,11 +2299,106 @@ bool MyMesh::handleCadCommand(const char* command, char* reply,
return true;
}
bool MyMesh::handleTxRoutingCommand(const char* command, char* reply, size_t reply_size) {
const auto parsed = mesh::companion::parseTxRouteCommand(command);
if (!parsed.matched) return false;
const char* kind = parsed.channel ? "channel" : "user";
if (!parsed.valid) {
snprintf(reply, reply_size, "Error: use get/set tx.%s <name|%s> [auto|radio|radio2|both|off]",
kind, parsed.channel ? "index" : "key:hex");
return true;
}
if (parsed.set && !canMutateContacts()) {
snprintf(reply, reply_size, "Error: contact/channel storage unavailable");
return true;
}
ContactInfo* contact = nullptr;
ChannelDetails channel;
int channel_index = -1;
unsigned matches = 0, overrides = 0;
if (parsed.channel) {
uint32_t index = 0;
const bool by_index = !parsed.quoted && mesh::cli::parseUnsignedIntegerStrict(parsed.target, index);
for (int i = 0; i < MAX_GROUP_CHANNELS; ++i) {
ChannelDetails candidate;
if (!getChannel(i, candidate) || !candidate.name[0]) continue;
if (candidate.channel.tx_radio != mesh::RADIO_TX_AUTO) ++overrides;
if (by_index ? index == (uint32_t)i : !strcmp(candidate.name, parsed.target)) {
channel = candidate; channel_index = i; ++matches;
}
}
} else {
uint8_t key[32]; size_t key_bytes = 0;
const bool by_key = !parsed.quoted && !strncmp(parsed.target, "key:", 4);
if (by_key && !mesh::companion::parseTxRouteKey(parsed.target + 4, key, key_bytes)) {
snprintf(reply, reply_size, "Error: key: needs 12-64 hexadecimal digits (whole bytes)");
return true;
}
for (int i = MAX_ANON_CONTACTS; i < getTotalContactSlots(); ++i) {
ContactInfo* candidate = getContactPtrByIdx(i);
if (!candidate || candidate->type == ADV_TYPE_NONE) continue;
if (candidate->tx_radio != mesh::RADIO_TX_AUTO) ++overrides;
if (by_key ? !memcmp(candidate->id.pub_key, key, key_bytes) : !strcmp(candidate->name, parsed.target)) {
contact = candidate; ++matches;
}
}
}
if (!parsed.target[0]) {
snprintf(reply, reply_size, "> tx.%s: %u overrides; use get tx.%s <name|%s>",
kind, overrides, kind, parsed.channel ? "index" : "key:hex");
return true;
}
if (matches != 1) {
snprintf(reply, reply_size, "Error: %s %s%s", kind, matches ? "is ambiguous" : "not found",
matches ? (parsed.channel ? "; use an index" : "; use a longer key: prefix") : "");
return true;
}
uint8_t policy = parsed.channel ? channel.channel.tx_radio : contact->tx_radio;
if (parsed.set && policy != parsed.policy) {
bool saved;
if (parsed.channel) {
const ChannelDetails previous = channel;
channel.channel.tx_radio = parsed.policy;
saved = setChannel(channel_index, channel) && saveChannels();
if (!saved) setChannel(channel_index, previous);
} else {
contact->tx_radio = parsed.policy;
saved = scheduleContactWrite(*contact) && flushContactsBeforeReboot();
if (!saved) {
contact->tx_radio = policy;
scheduleContactWrite(*contact);
}
}
if (!saved) {
snprintf(reply, reply_size, "Error: TX routing was not saved");
return true;
}
policy = parsed.policy;
}
const auto* profiles = _radio->profiles();
const uint8_t mask = policy == mesh::RADIO_TX_AUTO ? (profiles ? profiles->transmitMask(0) : 1)
: mesh::explicitRadioTxMask(policy, profiles && profiles->canTransmit(1));
const char* active = mask ? mesh::radioTxPolicyName(mask) : "off";
char label[80];
if (parsed.channel) snprintf(label, sizeof(label), "%d \"%s\"", channel_index, channel.name);
else {
char key_prefix[13]; mesh::Utils::toHex(key_prefix, contact->id.pub_key, 6);
snprintf(label, sizeof(label), "\"%s\" key:%s", contact->name, key_prefix);
}
snprintf(reply, reply_size, "%s tx.%s %s %s; active=%s%s",
parsed.set ? "OK -" : ">", kind, label, mesh::radioTxPolicyName(policy), active,
(policy == mesh::RADIO_TX_SECONDARY || policy == mesh::RADIO_TX_BOTH) && !(mask & 2)
? " (radio2 unavailable for TX)" : "");
return true;
}
bool MyMesh::handleLocalControlCommand(const char* command, char* reply,
size_t reply_size) {
if (!command || !reply || reply_size == 0) return false;
while (*command == ' ') command++;
if (handleTxRoutingCommand(command, reply, reply_size)) return true;
if (handleCompanionBluetoothCommand(command, reply, reply_size)) return true;
if (handleCompanionWirelessCommand(command, reply, reply_size)) return true;
@@ -5060,7 +5156,12 @@ void MyMesh::handleCmdFrame(size_t len) {
StrHelper::strncpy(channel.name, (char *)&cmd_frame[2], 32);
memset(channel.channel.secret, 0, sizeof(channel.channel.secret));
memcpy(channel.channel.secret, &cmd_frame[2 + 32], 16); // NOTE: only 128-bit supported
if (!getChannel(channel_idx, previous)
const bool have_previous = getChannel(channel_idx, previous);
if (have_previous && channel.name[0] != 0 && previous.name[0] != 0
&& !memcmp(channel.channel.secret, previous.channel.secret, sizeof(channel.channel.secret))) {
channel.channel.tx_radio = previous.channel.tx_radio;
}
if (!have_previous
|| !setChannel(channel_idx, channel)) {
writeErrFrame(ERR_CODE_NOT_FOUND); // bad channel_idx
} else if (saveChannels()) {
+1
View File
@@ -237,6 +237,7 @@ public:
// setup/status commands here; Full builds add TempRadio and OTA commands.
bool handleLocalControlCommand(const char* command, char* reply,
size_t reply_size);
bool handleTxRoutingCommand(const char* command, char* reply, size_t reply_size);
int getRecentlyHeard(AdvertPath dest[], int max_num);
+177 -128
View File
@@ -14,6 +14,7 @@
#include <helpers/ClientPathPersistence.h>
#include <helpers/DatagramPayloadLimits.h>
#include <helpers/FloodFilterPolicy.h>
#include <helpers/FloodRuleCLI.h>
#include <helpers/LazyPersistence.h>
#include <helpers/RegionNameUtils.h>
#if MESH_PACKET_LOGGING
@@ -1031,7 +1032,7 @@ bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
}
#endif
#if !defined(PORTABLE_MQTT_OBSERVER)
if (shouldBlockFloodPacketForward(packet)) return false;
if (shouldBlockFloodPacketForward(packet, recv_pkt_filter_match_mask)) return false;
#endif
}
if (packet->isRouteFlood() && recv_pkt_channel_scope_rejected) {
@@ -1066,7 +1067,7 @@ bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
#if MESH_ENABLE_FLOOD_GROUP_MODERATION
if (packet->isRouteFlood() && shouldBlockFloodGroupTextForward(packet)) return false;
#endif
if (packet->isRouteFlood()) commitFloodPacketFilterRates(packet);
if (packet->isRouteFlood()) commitFloodPacketFilterRates(packet, recv_pkt_filter_match_mask);
// Normal path mode accepts clock evidence only from packets this node would
// forward. Edge mode observes verified evidence on the receive path instead,
// so repeat off and other forwarding filters do not hide a single upstream
@@ -1087,6 +1088,29 @@ const char *MyMesh::getLogDateTime() {
return tmp;
}
#if MESH_ENABLE_FLOOD_RULE_ENGINE
bool MyMesh::allowTransportPacket(const mesh::Packet* packet, uint8_t context) {
if (!packet) return false;
RegionEntry* incoming_region = NULL;
bool scoped = packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD
|| packet->getRouteType() == ROUTE_TYPE_TRANSPORT_DIRECT;
bool incoming_allowed;
if (scoped) {
incoming_region = region_map.findMatch(packet, REGION_DENY_FLOOD);
incoming_allowed = incoming_region != NULL;
} else {
incoming_allowed = (region_map.getWildcard().flags & REGION_DENY_FLOOD) == 0;
}
// Use a local mask: bridge RX/TX callbacks can run inside mesh dispatch,
// where recv_pkt_* still belongs to the ordinary radio forwarding phase.
uint64_t matches = evaluateFloodPacketFilterMatches(
packet, incoming_allowed, incoming_region, context);
if (shouldBlockFloodPacketForward(packet, matches)) return false;
commitFloodPacketFilterRates(packet, matches);
return true;
}
#endif
void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
#if MESH_PACKET_LOGGING
if (mesh::isUsbLoggingEnabled()) {
@@ -2920,15 +2944,17 @@ bool MyMesh::sendRemoteCliReply(ClientInfo* client, const uint8_t* secret,
mesh::Packet* packet = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, secret,
reply_data, 5 + text_len);
// A caller which requests the exact queued packet is going to make a state
// transition depend on that packet's TX result. Keep one authoritative
// copy: an untracked alternate or retry could report success after primary
// failure cancelled the transition, or still be queued when primary success
// lets the radio tuple change. Ordinary replies retain redundant delivery.
if (packet) packet->radio_reply = true; // also covers delayed GPIO completion
// A state-changing reply tracks its first copy on each selected profile.
// Suppress alternate paths and retries, which could outlive the handoff.
// Prepare before admission so Dispatcher can register its second copy;
// the caller arms the barrier only after admission succeeds.
const bool allow_redundant_copies = queued_packet == NULL;
if (!allow_redundant_copies) temp_radio_reply_barrier.prepare(packet);
const bool queued = sendClientReplyWithFallbackScope(
client, packet, CLI_REPLY_DELAY_MILLIS, path_hash_size, fallback_scope,
allow_redundant_copies);
if (!queued && !allow_redundant_copies) temp_radio_reply_barrier.clear();
if (queued && queued_packet != NULL) *queued_packet = packet;
return queued;
}
@@ -3197,9 +3223,8 @@ void __attribute__((noinline)) MyMesh::processDeferredCliCommand() {
arms_temp_radio ? &queued_reply : NULL);
if (arms_temp_radio) {
if (reply_queued && queued_reply != NULL) {
// The old two-RTC-second delay could expire while this exact packet was
// still parked behind CAD/duty/queue work. Do not change modulation
// until Dispatcher confirms that the reply physically transmitted.
// A fixed delay can expire while either copy is parked behind queue
// work. Wait for both to drain and at least one to physically transmit.
temp_radio_reply_barrier.arm(queued_reply);
} else {
// A command which cannot queue its acknowledgement must never strand
@@ -3708,6 +3733,7 @@ void MyMesh::begin(FILESYSTEM *fs) {
#endif
#endif
configureBridgeFilter(active_bridge);
active_bridge->begin();
}
#endif
@@ -3939,10 +3965,16 @@ void MyMesh::onSendComplete(mesh::Packet* packet) {
}
}
void MyMesh::onRadioProfileCopyQueued(mesh::Packet* packet, const mesh::Packet* original,
uint8_t priority) {
temp_radio_reply_barrier.trackCopy(original, packet);
mesh::Mesh::onRadioProfileCopyQueued(packet, original, priority);
}
void MyMesh::onSendFail(mesh::Packet* packet) {
mesh::Mesh::onSendFail(packet);
if (temp_radio_reply_barrier.fail(packet)) {
// Failure of the exact acknowledgement packet cancels the unconfirmed
// Failure of every acknowledgement copy cancels the unconfirmed
// handoff. A later cached-command retry may replay the reply, but it does
// not re-run the mutation.
scheduleNormalRadio();
@@ -4530,7 +4562,7 @@ void MyMesh::processScheduledRadioSettings() {
}
if (temp_radio_reply_barrier.waiting() && !hard_temp_end_due) {
// The exact parameterized-TempRadio reply is queued or on air. Unlike a
// A parameterized-TempRadio reply copy is queued or on air. Unlike a
// fixed RTC delay, this remains correct under CAD, duty throttling, and
// unrelated queue pressure. TX completion/failure releases the barrier.
scheduled_radio_retry_at = futureMillis(RADIO_APPLY_RETRY_INTERVAL_MILLIS);
@@ -5296,7 +5328,7 @@ static bool parseFloodFilterPayloadType(const char* text, uint8_t& type) {
return true;
}
if (floodFilterAsciiStartsWith(text, "payload_type_")) text += strlen("payload_type_");
if (floodFilterAsciiEqual(text, "any")) type = FLOOD_PACKET_FILTER_ANY_TYPE;
if (floodFilterAsciiEqual(text, "any") || floodFilterAsciiEqual(text, "*")) type = FLOOD_PACKET_FILTER_ANY_TYPE;
else if (floodFilterAsciiEqual(text, "req")) type = PAYLOAD_TYPE_REQ;
else if (floodFilterAsciiEqual(text, "response") || floodFilterAsciiEqual(text, "resp")) type = PAYLOAD_TYPE_RESPONSE;
else if (floodFilterAsciiEqual(text, "txt_msg") || floodFilterAsciiEqual(text, "txt")) type = PAYLOAD_TYPE_TXT_MSG;
@@ -5317,7 +5349,7 @@ static bool parseFloodFilterPayloadType(const char* text, uint8_t& type) {
static bool parseFloodFilterHopSpec(const char* text, uint8_t& min_hops, uint8_t& max_hops) {
if (text == NULL || *text == 0) return false;
if (floodFilterAsciiEqual(text, "all")) {
if (floodFilterAsciiEqual(text, "all") || floodFilterAsciiEqual(text, "*")) {
min_hops = 0;
max_hops = FLOOD_PACKET_FILTER_MAX_HOPS;
return true;
@@ -5711,7 +5743,7 @@ static void formatFloodModerationPath(
const uint8_t path[FLOOD_GROUP_MODERATION_PATH_BYTES_MAX]);
void MyMesh::seedDefaultFloodPacketFilters() {
// Slots 0 and 1 carry the built-in defaults; without a table there is
// Slots 0, 1 and 2 carry the built-in defaults; without a table there is
// nothing to seed and the node forwards unfiltered.
if (flood_packet_filter_slots == 0) return;
auto& entry = flood_packet_filters[0];
@@ -5744,6 +5776,15 @@ void MyMesh::seedDefaultFloodPacketFilters() {
StrHelper::strncpy(wardriving.channel_name, DEFAULT_WARDRIVING_CHANNEL,
sizeof(wardriving.channel_name));
wardriving.drop_on_match = true;
// Bridge admission is independent of the ordinary LoRa hop limit. Use the
// same authenticated channel identity, including zero-hop/local messages.
if (flood_packet_filter_slots < 3) return;
auto& bridge_wardriving = flood_packet_filters[2];
bridge_wardriving = wardriving;
bridge_wardriving.min_hops = 0;
bridge_wardriving.transport_modes = FloodFilterPolicy::RULE_MODE_BRIDGE
| FloodFilterPolicy::RULE_MODE_CROSS;
#endif
}
@@ -5883,19 +5924,29 @@ bool MyMesh::loadFloodPacketFilters() {
} else {
loaded[i].retry_on_match = false;
}
loaded[i].active = active != 0;
if (version_7) {
success = success && FloodFilterPolicy::decodeStoredRuleActive(
active, loaded[i].active, loaded[i].transport_modes);
} else {
loaded[i].active = active != 0;
success = success && active <= 1;
}
loaded[i].suspend_on_temp_radio = suspend_on_temp_radio != 0;
loaded[i].match_blacklisted_path = match_blacklisted_path != 0;
loaded[i].scope_uses_slow_timing = scope_uses_slow_timing != 0;
loaded[i].drop_on_match = drop_on_match != 0;
loaded[i].rate_limit_enabled = rate_limit_enabled != 0;
loaded[i].stop_on_match = stop_on_match != 0;
if (success && (active > 1 || suspend_on_temp_radio > 1
if (success && (suspend_on_temp_radio > 1
|| match_blacklisted_path > 1 || scope_requires_region_match > 1
|| scope_uses_slow_timing > 1 || drop_on_match > 1
|| rate_limit_enabled > 1 || stop_on_match > 1)) {
success = false;
}
success = success && FloodFilterPolicy::transportActionsSupported(
loaded[i].transport_modes, loaded[i].scope_name[0] != 0
|| loaded[i].target_region_name[0] != 0,
loaded[i].retry_on_match, loaded[i].scope_uses_slow_timing);
if (!success) break;
if (!loaded[i].active) {
memset(&loaded[i], 0, sizeof(loaded[i]));
@@ -6204,6 +6255,7 @@ bool MyMesh::isFloodChannelDataRule(
bool valid_hops = entry.min_hops == 0
|| (entry.min_hops >= 2 && entry.min_hops <= 8);
return entry.active
&& entry.transport_modes == FloodFilterPolicy::RULE_MODE_RADIO
&& entry.payload_type == PAYLOAD_TYPE_GRP_DATA
&& valid_hops
&& entry.max_hops == FLOOD_PACKET_FILTER_MAX_HOPS
@@ -6493,6 +6545,7 @@ bool MyMesh::migrateLegacyFloodChannelBlocks() {
continue;
}
duplicate = entry.payload_type == FLOOD_PACKET_FILTER_ANY_TYPE
&& entry.transport_modes == FloodFilterPolicy::RULE_MODE_RADIO
&& entry.min_hops == min_hops
&& entry.max_hops == FLOOD_PACKET_FILTER_MAX_HOPS
&& !entry.suspend_on_temp_radio
@@ -6578,7 +6631,8 @@ bool MyMesh::saveFloodPacketFilters(bool empty_scope_phase,
&& writeExact(&count, sizeof(count));
for (int i = 0; success && i < count; i++) {
const auto& entry = flood_packet_filters[i];
uint8_t active = entry.active ? 1 : 0;
uint8_t active = FloodFilterPolicy::encodeStoredRuleActive(
entry.active, entry.transport_modes);
uint8_t suspend_on_temp_radio = entry.suspend_on_temp_radio ? 1 : 0;
uint8_t match_blacklisted_path = entry.match_blacklisted_path ? 1 : 0;
uint8_t scope_requires_region_match =
@@ -6846,11 +6900,12 @@ bool MyMesh::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 {
if (!entry.active || packet == NULL || !packet->isRouteFlood()) return false;
const RegionEntry* incoming_region, uint8_t context) const {
if (!entry.active || !FloodFilterPolicy::ruleModeMatches(
entry.transport_modes, context, packet)) return false;
if (!FloodFilterPolicy::channelKeyLengthSupported(
entry.channel_key_len)) return false;
if (entry.suspend_on_temp_radio && isTempRadioActive()) return false;
if (entry.suspend_on_temp_radio && isAnyTempRadioActive()) return false;
if (entry.match_blacklisted_path && !floodPacketFilterBlacklistMatches(packet)) {
return false;
}
@@ -6988,12 +7043,13 @@ uint64_t MyMesh::applyFloodPacketFilterStop(uint64_t match_mask) {
uint64_t MyMesh::evaluateFloodPacketFilterMatches(
const mesh::Packet* packet, bool incoming_region_allowed,
const RegionEntry* incoming_region) {
const RegionEntry* incoming_region, uint8_t context) {
static_assert(FLOOD_PACKET_FILTER_SLOTS <= 64,
"flood filter match mask supports at most 64 slots");
if (packet == NULL || !packet->isRouteFlood()) return 0;
if (packet == NULL || (context == FloodFilterPolicy::RULE_MODE_RADIO && !packet->isRouteFlood())) return 0;
bool incoming_is_scoped =
packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD;
packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD
|| packet->getRouteType() == ROUTE_TYPE_TRANSPORT_DIRECT;
uint16_t incoming_transport_code = incoming_is_scoped
? packet->transport_codes[0] : 0;
bool channel_auth_checked[FLOOD_PACKET_FILTER_SLOTS] = { false };
@@ -7003,7 +7059,7 @@ uint64_t MyMesh::evaluateFloodPacketFilterMatches(
const auto& entry = flood_packet_filters[i];
if (!floodPacketFilterFieldsMatch(
entry, packet, incoming_is_scoped, incoming_transport_code,
incoming_region_allowed, incoming_region)) {
incoming_region_allowed, incoming_region, context)) {
continue;
}
bool authenticated = true;
@@ -7079,14 +7135,15 @@ bool MyMesh::applyFloodPacketFilterScope(mesh::Packet* packet,
return false;
}
bool MyMesh::shouldBlockFloodPacketForward(const mesh::Packet* packet) const {
if (packet == NULL || !packet->isRouteFlood()) return false;
bool MyMesh::shouldBlockFloodPacketForward(const mesh::Packet* packet,
uint64_t match_mask) const {
if (packet == NULL) return false;
uint8_t type = packet->getPayloadType();
uint8_t hops = packet->getPathHashCount();
uint64_t visited = 0;
while (true) {
int i = nextFloodPacketFilterMatch(recv_pkt_filter_match_mask, visited);
int i = nextFloodPacketFilterMatch(match_mask, visited);
if (i < 0) break;
visited |= (uint64_t)1U << i;
const auto& entry = flood_packet_filters[i];
@@ -7108,12 +7165,13 @@ bool MyMesh::shouldBlockFloodPacketForward(const mesh::Packet* packet) const {
return false;
}
void MyMesh::commitFloodPacketFilterRates(const mesh::Packet* packet) {
if (packet == NULL || !packet->isRouteFlood()) return;
void MyMesh::commitFloodPacketFilterRates(const mesh::Packet* packet,
uint64_t match_mask) {
if (packet == NULL) return;
uint32_t now = _ms->getMillis();
for (int i = 0; i < flood_packet_filter_slots; i++) {
auto& entry = flood_packet_filters[i];
if ((recv_pkt_filter_match_mask & ((uint64_t)1U << i)) == 0
if ((match_mask & ((uint64_t)1U << i)) == 0
|| !entry.rate_limit_enabled) {
continue;
}
@@ -7131,13 +7189,14 @@ bool MyMesh::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 {
const RegionEntry* incoming_region, uint8_t context) const {
(void)context;
(void)incoming_is_scoped;
(void)incoming_transport_code;
(void)incoming_region_allowed;
(void)incoming_region;
if (!entry.active || packet == NULL || !packet->isRouteFlood()) return false;
if (entry.suspend_on_temp_radio && isTempRadioActive()) return false;
if (entry.suspend_on_temp_radio && isAnyTempRadioActive()) return false;
if (entry.match_blacklisted_path
&& !floodPacketFilterBlacklistMatches(packet)) return false;
@@ -7150,7 +7209,8 @@ bool MyMesh::floodPacketFilterFieldsMatch(
uint64_t MyMesh::evaluateFloodPacketFilterMatches(
const mesh::Packet* packet, bool incoming_region_allowed,
const RegionEntry* incoming_region) {
const RegionEntry* incoming_region, uint8_t context) {
(void)context;
(void)incoming_region;
uint64_t matches = 0;
for (int i = 0; i < flood_packet_filter_slots; i++) {
@@ -7196,13 +7256,14 @@ bool MyMesh::applyFloodPacketFilterScope(mesh::Packet* packet,
return false;
}
bool MyMesh::shouldBlockFloodPacketForward(const mesh::Packet* packet) const {
bool MyMesh::shouldBlockFloodPacketForward(const mesh::Packet* packet,
uint64_t match_mask) const {
if (packet == NULL || !packet->isRouteFlood()) return false;
uint8_t type = packet->getPayloadType();
uint8_t hops = packet->getPathHashCount();
for (int i = 0; i < flood_packet_filter_slots; i++) {
const auto& entry = flood_packet_filters[i];
if ((recv_pkt_filter_match_mask & ((uint64_t)1U << i)) != 0
if ((match_mask & ((uint64_t)1U << i)) != 0
&& entry.scope_name[0] == 0) {
MESH_DEBUG_PRINTLN("allowPacketForward: flood.filter matched slot=%d type=%d hops=%d range=%d-%d",
i + 1, type, hops, entry.min_hops,
@@ -7213,7 +7274,9 @@ bool MyMesh::shouldBlockFloodPacketForward(const mesh::Packet* packet) const {
return false;
}
void MyMesh::commitFloodPacketFilterRates(const mesh::Packet* packet) {
void MyMesh::commitFloodPacketFilterRates(const mesh::Packet* packet,
uint64_t match_mask) {
(void)match_mask;
(void)packet;
}
#endif
@@ -7229,12 +7292,16 @@ static bool floodRuleRegionNamePresent(const RegionMap& map,
return false;
}
void MyMesh::formatFloodPacketFilterDetail(int index, char* reply, size_t reply_len) const {
void MyMesh::formatFloodPacketFilterDetail(int index, char* reply, size_t reply_len, bool compact) const {
if (index < 0 || index >= flood_packet_filter_slots || !flood_packet_filters[index].active) {
snprintf(reply, reply_len, "Err - empty filter slot");
return;
}
const auto& entry = flood_packet_filters[index];
if (compact) {
FloodRuleCLI::formatCompact(reply, reply_len, index + 1, entry);
return;
}
char hops[12];
char prefix[32];
char incoming[48];
@@ -7302,8 +7369,9 @@ void MyMesh::formatFloodPacketFilterDetail(int index, char* reply, size_t reply_
}
int written = snprintf(
reply, reply_len,
"> %d type=%s hops=%s channel=%s prefix=%s in=%s %s%s%s priority=%u%s%s%s",
index + 1, floodFilterPayloadTypeName(entry.payload_type), hops,
"> %d type=%s mode=%s hops=%s channel=%s prefix=%s in=%s %s%s%s priority=%u%s%s%s",
index + 1, floodFilterPayloadTypeName(entry.payload_type),
FloodFilterPolicy::ruleModeName(entry.transport_modes), hops,
entry.channel_key_len == 0 ? "*" : entry.channel_name,
prefix, incoming, action, rate, retry,
(unsigned int)entry.priority,
@@ -7312,81 +7380,10 @@ void MyMesh::formatFloodPacketFilterDetail(int index, char* reply, size_t reply_
entry.suspend_on_temp_radio ? " suspend=tempradio" : "");
if (written >= 0 && (size_t)written < reply_len) return;
// A fully populated row can exceed the 160-byte CLI reply. Fall back to a
// compact, accepted-by-set spelling instead of silently hiding tail fields.
char compact_type[4];
if (entry.payload_type == FLOOD_PACKET_FILTER_ANY_TYPE) {
strcpy(compact_type, "any");
} else {
snprintf(compact_type, sizeof(compact_type), "%u",
(unsigned int)entry.payload_type);
}
char compact_incoming[40];
switch (entry.incoming_scope_kind) {
case FloodFilterPolicy::RULE_IN_NONE:
strcpy(compact_incoming, "n");
break;
case FloodFilterPolicy::RULE_IN_SCOPED:
strcpy(compact_incoming, "s");
break;
case FloodFilterPolicy::RULE_IN_ALLOWED:
strcpy(compact_incoming, "a");
break;
case FloodFilterPolicy::RULE_IN_UNKNOWN:
strcpy(compact_incoming, "u");
break;
case FloodFilterPolicy::RULE_IN_SCOPE:
snprintf(compact_incoming, sizeof(compact_incoming), "s:%s",
entry.incoming_scope_name);
break;
case FloodFilterPolicy::RULE_IN_REGION: {
snprintf(compact_incoming, sizeof(compact_incoming), "r:%s",
entry.incoming_scope_name);
break;
}
default:
strcpy(compact_incoming, "*");
break;
}
char compact_action[40];
if (entry.drop_on_match) {
strcpy(compact_action, " drop");
} else if (entry.scope_name[0] != 0) {
snprintf(compact_action, sizeof(compact_action), " scope=%s",
entry.scope_name);
} else if (entry.target_region_name[0] != 0) {
snprintf(compact_action, sizeof(compact_action), " region=%s",
entry.target_region_name);
} else {
compact_action[0] = 0;
}
char compact_rate[12];
compact_rate[0] = 0;
if (entry.rate_limit_enabled) {
snprintf(compact_rate, sizeof(compact_rate), " q=%u",
(unsigned int)entry.rate_per_minute);
}
char compact_flags[8];
compact_flags[0] = 0;
if (entry.scope_uses_slow_timing || entry.suspend_on_temp_radio
|| entry.retry_on_match) {
snprintf(compact_flags, sizeof(compact_flags), " f=%s%s%s",
entry.scope_uses_slow_timing ? "s" : "",
entry.suspend_on_temp_radio ? "t" : "",
entry.retry_on_match ? "r" : "");
}
snprintf(reply, reply_len,
">%d %s %s c=%s p=%s i=%s%s%s pri=%u%s%s",
index + 1, compact_type, hops,
entry.channel_key_len == 0 ? "*" : entry.channel_name,
prefix, compact_incoming, compact_action, compact_rate,
(unsigned int)entry.priority,
entry.stop_on_match ? " stop" : "",
compact_flags);
FloodRuleCLI::formatCompact(reply, reply_len, index + 1, entry);
}
void MyMesh::formatFloodPacketFilters(const char* args, char* reply) const {
void MyMesh::formatFloodPacketFilters(const char* args, char* reply, bool compact) const {
const char* selector = skipFloodFilterSpaces(args);
if (*selector == '.') selector = skipFloodFilterSpaces(selector + 1);
if (*selector != 0) {
@@ -7395,7 +7392,7 @@ void MyMesh::formatFloodPacketFilters(const char* args, char* reply) const {
snprintf(reply, 160, "Err - filter slot must be 1-%d", flood_packet_filter_slots);
return;
}
formatFloodPacketFilterDetail(slot - 1, reply, 160);
formatFloodPacketFilterDetail(slot - 1, reply, 160, compact);
return;
}
@@ -7426,8 +7423,9 @@ void MyMesh::formatFloodPacketFilters(const char* args, char* reply) const {
snprintf(priority, sizeof(priority), "^%u",
(unsigned int)entry.priority);
}
snprintf(item, sizeof(item), " %d=%s@%s%s%s%s%s%s%s%s%s%s",
i + 1, floodFilterPayloadTypeName(entry.payload_type), hops,
snprintf(item, sizeof(item), " %d=%s~%s@%s%s%s%s%s%s%s%s%s%s",
i + 1, floodFilterPayloadTypeName(entry.payload_type),
FloodFilterPolicy::ruleModeName(entry.transport_modes), hops,
entry.match_blacklisted_path ? "?blacklist" : "",
target, priority,
entry.stop_on_match ? "~stop" : "",
@@ -7508,7 +7506,8 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
uint8_t payload_type;
const char* type_text = floodFilterAsciiStartsWith(tokens[0], "type=")
? tokens[0] + strlen("type=") : tokens[0];
? tokens[0] + strlen("type=")
: floodFilterAsciiStartsWith(tokens[0], "t=") ? tokens[0] + 2 : tokens[0];
if (!parseFloodFilterPayloadType(type_text, payload_type)) {
strcpy(reply, "Err - packet type must be name, any, 0-15, or 0x00-0x0F");
return;
@@ -7550,8 +7549,22 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
bool priority_set = false;
bool stop_on_match = false;
bool retry_on_match = false;
uint8_t transport_modes = FloodFilterPolicy::RULE_MODE_RADIO;
bool mode_set = false;
for (int i = 1; i < token_count; i++) {
if (floodFilterAsciiEqual(tokens[i], "suspend=tempradio")) {
if (floodFilterAsciiStartsWith(tokens[i], "mode=")
|| floodFilterAsciiStartsWith(tokens[i], "m=")) {
if (mode_set) {
strcpy(reply, FLOOD_PACKET_FILTER_DUPLICATE);
return;
}
const char* value = strchr(tokens[i], '=') + 1;
if (!FloodFilterPolicy::parseRuleModes(value, transport_modes)) {
strcpy(reply, "Err - mode is radio, bridge, cross, or bridge,cross");
return;
}
mode_set = true;
} else if (floodFilterAsciiEqual(tokens[i], "suspend=tempradio")) {
if (suspend_on_temp_radio) {
strcpy(reply, FLOOD_PACKET_FILTER_DUPLICATE);
return;
@@ -7589,7 +7602,9 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
}
flags++;
}
} else if (floodFilterAsciiEqual(tokens[i], "path=blacklist")) {
} else if (floodFilterAsciiEqual(tokens[i], "path=blacklist")
|| floodFilterAsciiEqual(tokens[i], "p=blacklist")
|| floodFilterAsciiEqual(tokens[i], "p=bl")) {
if (path_set) {
strcpy(reply, FLOOD_PACKET_FILTER_DUPLICATE);
return;
@@ -7671,6 +7686,7 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
priority = (uint8_t)parsed;
priority_set = true;
} else if (floodFilterAsciiEqual(tokens[i], "stop")
|| floodFilterAsciiEqual(tokens[i], "s")
|| floodFilterAsciiEqual(tokens[i], "action=stop")) {
if (stop_on_match) {
strcpy(reply, FLOOD_PACKET_FILTER_DUPLICATE);
@@ -7678,6 +7694,7 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
}
stop_on_match = true;
} else if (floodFilterAsciiEqual(tokens[i], "retry")
|| floodFilterAsciiEqual(tokens[i], "r")
|| floodFilterAsciiEqual(tokens[i], "retry=on")
|| floodFilterAsciiEqual(tokens[i], "retry=allow")
|| floodFilterAsciiEqual(tokens[i], "action=retry")) {
@@ -7698,24 +7715,26 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
return;
}
scope_timing_set = true;
} else if (floodFilterAsciiStartsWith(tokens[i], "scope=")) {
} else if (floodFilterAsciiStartsWith(tokens[i], "scope=")
|| floodFilterAsciiStartsWith(tokens[i], "s=")) {
if (target_set || drop_set) {
strcpy(reply, FLOOD_PACKET_FILTER_DUPLICATE);
return;
}
if (!normalizeFloodFilterScopeName(tokens[i] + strlen("scope="),
if (!normalizeFloodFilterScopeName(strchr(tokens[i], '=') + 1,
scope_name, sizeof(scope_name))) {
strcpy(reply, "Err - scope must be a public name of at most 30 characters");
return;
}
target_set = true;
} else if (floodFilterAsciiStartsWith(tokens[i], "region=")) {
} else if (floodFilterAsciiStartsWith(tokens[i], "region=")
|| floodFilterAsciiStartsWith(tokens[i], "r=")) {
if (target_set || drop_set) {
strcpy(reply, FLOOD_PACKET_FILTER_DUPLICATE);
return;
}
RegionEntry* region = region_map.findByNamePrefix(
tokens[i] + strlen("region="));
strchr(tokens[i], '=') + 1);
TransportKey target_scope;
if (region == NULL || region->isWildcard()
|| (region->flags & REGION_DENY_FLOOD) != 0
@@ -7728,6 +7747,7 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
sizeof(target_region_name));
target_set = true;
} else if (floodFilterAsciiEqual(tokens[i], "drop")
|| floodFilterAsciiEqual(tokens[i], "d")
|| floodFilterAsciiEqual(tokens[i], "action=drop")) {
if (drop_set || target_set) {
strcpy(reply, FLOOD_PACKET_FILTER_DUPLICATE);
@@ -7773,7 +7793,14 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
const char* value = tokens[i]
+ (floodFilterAsciiStartsWith(tokens[i], "c=")
? 2 : strlen("channel="));
if (!floodFilterAsciiEqual(value, "*")) {
if (FloodRuleCLI::isChannelReference(value)) {
if (!FloodRuleCLI::copyChannelReference(value, flood_packet_filters,
flood_packet_filter_slots, channel_key_len, channel_hash,
channel_secret, channel_name, sizeof(channel_name))) {
strcpy(reply, "Err - unknown or ambiguous channel key reference; use the original key");
return;
}
} else if (!floodFilterAsciiEqual(value, "*")) {
if (value[0] == '#'
&& strlen(value) >= sizeof(channel_name)) {
strcpy(reply, "Err - channel name is too long");
@@ -7806,9 +7833,10 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
return;
}
path_set = true;
} else if (floodFilterAsciiStartsWith(tokens[i], "hops=")) {
} else if (floodFilterAsciiStartsWith(tokens[i], "hops=")
|| floodFilterAsciiStartsWith(tokens[i], "h=")) {
if (hops_set || !parseFloodFilterHopSpec(
tokens[i] + strlen("hops="), min_hops, max_hops)) {
strchr(tokens[i], '=') + 1, min_hops, max_hops)) {
strcpy(reply, "Err - hops must be all, N, N+, or N-M (0-63)");
return;
}
@@ -7839,6 +7867,11 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
strcpy(reply, "Err - channel matcher requires type=any|grp_txt|grp_data");
return;
}
if (!FloodFilterPolicy::transportActionsSupported(
transport_modes, target_set, retry_on_match, scope_uses_slow_timing)) {
strcpy(reply, "Err - bridge/cross supports drop, rate=, priority=, stop only");
return;
}
bool action_set = drop_set || target_set || rate_limit_enabled
|| stop_on_match || retry_on_match;
if (require_explicit_action && !action_set) {
@@ -7879,6 +7912,7 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
candidate.priority = priority;
candidate.stop_on_match = stop_on_match;
candidate.retry_on_match = retry_on_match;
candidate.transport_modes = transport_modes;
StrHelper::strzcpy(candidate.scope_name, scope_name,
sizeof(candidate.scope_name));
@@ -7927,10 +7961,15 @@ void MyMesh::setFloodPacketFilter(const char* args, char* reply,
char detail[160];
formatFloodPacketFilterDetail(slot, detail, sizeof(detail));
if (strncmp(detail, "Err - compact", 13) == 0) {
snprintf(reply, 160, "OK - rule %d saved (details exceed reply size)", slot + 1);
return;
}
snprintf(reply, 160, "OK - %s", detail[0] == '>' ? skipFloodFilterSpaces(detail + 1) : detail);
}
#else
void MyMesh::formatFloodPacketFilterDetail(int index, char* reply, size_t reply_len) const {
void MyMesh::formatFloodPacketFilterDetail(int index, char* reply, size_t reply_len, bool compact) const {
(void)compact;
if (index < 0 || index >= flood_packet_filter_slots || !flood_packet_filters[index].active) {
snprintf(reply, reply_len, "Err - empty filter slot");
return;
@@ -7959,7 +7998,8 @@ void MyMesh::formatFloodPacketFilterDetail(int index, char* reply, size_t reply_
}
}
void MyMesh::formatFloodPacketFilters(const char* args, char* reply) const {
void MyMesh::formatFloodPacketFilters(const char* args, char* reply, bool compact) const {
(void)compact;
const char* selector = skipFloodFilterSpaces(args);
if (*selector == '.') selector = skipFloodFilterSpaces(selector + 1);
if (*selector != 0) {
@@ -11046,6 +11086,7 @@ static bool isFilterMgrAllowed(const char* cmd) {
|| commandFamilyMatches(cmd, "get flood.filter")
#if MESH_ENABLE_FLOOD_RULE_ENGINE
|| commandFamilyMatches(cmd, "get flood.rule")
|| commandFamilyMatches(cmd, "get fr")
#endif
|| commandFamilyMatches(cmd, "get flood.moderation")) return true;
// General payload/hop filters plus the remaining flood-hop gates.
@@ -11053,7 +11094,9 @@ static bool isFilterMgrAllowed(const char* cmd) {
|| commandFamilyMatches(cmd, "del flood.filter")
#if MESH_ENABLE_FLOOD_RULE_ENGINE
|| commandFamilyMatches(cmd, "set flood.rule")
|| commandFamilyMatches(cmd, "set fr")
|| commandFamilyMatches(cmd, "del flood.rule")
|| commandFamilyMatches(cmd, "del fr")
#endif
|| commandFamilyMatches(cmd, "set flood.moderation")
|| commandFamilyMatches(cmd, "del flood.moderation")
@@ -11684,6 +11727,12 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, ClientInfo* sender, char *
} else if (commandFamilyMatches(command, "del flood.filter")) {
deleteFloodPacketFilter(command + strlen("del flood.filter"), reply);
#if MESH_ENABLE_FLOOD_RULE_ENGINE
} else if (commandFamilyMatches(command, "get fr")) {
formatFloodPacketFilters(command + strlen("get fr"), reply, true);
} else if (commandFamilyMatches(command, "set fr")) {
setFloodPacketFilter(command + strlen("set fr"), reply, true);
} else if (commandFamilyMatches(command, "del fr")) {
deleteFloodPacketFilter(command + strlen("del fr"), reply);
} else if (commandFamilyMatches(command, "get flood.rule")) {
formatFloodPacketFilters(command + strlen("get flood.rule"), reply);
} else if (commandFamilyMatches(command, "set flood.rule")) {
+32 -6
View File
@@ -422,6 +422,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
uint8_t priority;
bool stop_on_match;
bool retry_on_match;
uint8_t transport_modes;
uint32_t rate_window_started;
uint16_t rate_window_count;
bool rate_window_active;
@@ -763,7 +764,7 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
bool incoming_is_scoped,
uint16_t incoming_transport_code,
bool incoming_region_allowed,
const RegionEntry* incoming_region) const;
const RegionEntry* incoming_region, uint8_t context = 0) const;
bool authenticateFloodPacketFilterChannel(
const FloodPacketFilterEntry& entry,
const mesh::Packet* packet) const;
@@ -777,14 +778,16 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks
uint64_t applyFloodPacketFilterStop(uint64_t match_mask);
uint64_t evaluateFloodPacketFilterMatches(
const mesh::Packet* packet, bool incoming_region_allowed,
const RegionEntry* incoming_region);
const RegionEntry* incoming_region, uint8_t context = 0);
bool applyFloodPacketFilterScope(mesh::Packet* packet, uint64_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;
bool shouldBlockFloodPacketForward(const mesh::Packet* packet,
uint64_t match_mask) const;
void commitFloodPacketFilterRates(const mesh::Packet* packet,
uint64_t match_mask);
void formatFloodPacketFilters(const char* args, char* reply, bool compact = false) const;
void formatFloodPacketFilterDetail(int index, char* reply, size_t reply_len, bool compact = false) const;
void setFloodPacketFilter(const char* args, char* reply,
bool require_explicit_action = false);
void deleteFloodPacketFilter(const char* args, char* reply);
@@ -940,6 +943,8 @@ protected:
mesh::DispatcherAction onRecvPacket(mesh::Packet* pkt) override;
void onSendComplete(mesh::Packet* packet) override;
void onRadioProfileCopyQueued(mesh::Packet* packet, const mesh::Packet* original,
uint8_t priority) override;
void onSendFail(mesh::Packet* packet) override;
void onAnonDataRecv(mesh::Packet* packet, const uint8_t* secret, const mesh::Identity& sender, uint8_t* data, size_t len) override;
@@ -1100,9 +1105,27 @@ public:
bool handleHostCliSerialReply(const char* command, char* reply);
#endif
void loop();
#if MESH_ENABLE_FLOOD_RULE_ENGINE
bool allowTransportPacket(const mesh::Packet* packet, uint8_t context);
bool allowRadioProfileCross(const mesh::Packet* packet) override {
return allowTransportPacket(packet, 4); // RULE_MODE_CROSS
}
#endif
uint32_t getPowerSaveSleepSeconds(uint32_t max_secs) const;
#if defined(WITH_BRIDGE)
void configureBridgeFilter(AbstractBridge* active_bridge) {
#if MESH_ENABLE_FLOOD_RULE_ENGINE
active_bridge->setPacketFilter([](void* context, const mesh::Packet* packet) {
return static_cast<MyMesh*>(context)->allowTransportPacket(packet, 2); // RULE_MODE_BRIDGE
}, this);
#else
(void)active_bridge;
#endif
}
#ifdef WITH_RS232_BRIDGE
RS232Bridge* createRS232Bridge() {
#ifdef WITH_RS232_BRIDGE_ALT
@@ -1137,6 +1160,7 @@ public:
active_rs232_bridge_uart = selected_uart;
}
#endif
configureBridgeFilter(bridge);
bridge->begin();
if (!bridge->isRunning()) {
#if ENV_INCLUDE_GPS == 1
@@ -1239,6 +1263,7 @@ public:
#ifdef WITH_RS232_BRIDGE
const bool started = beginRS232Bridge();
#else
configureBridgeFilter(active_bridge);
active_bridge->begin();
const bool started = active_bridge->isRunning();
#endif
@@ -1297,6 +1322,7 @@ public:
mqtt_bridge->setBuildDate(getBuildDate());
mqtt_bridge->setStatsSources(this, _radio, _cli.getBoard(), _ms);
#endif
configureBridgeFilter(active_bridge);
active_bridge->begin();
return active_bridge->isRunning();
#endif
+103 -95
View File
@@ -6,6 +6,7 @@
#include <string.h>
#include <helpers/FloodFilterPolicy.h>
#include <helpers/FloodRuleCLI.h>
#include <helpers/FileRead.h>
#include <helpers/RegionNameUtils.h>
@@ -127,7 +128,7 @@ static bool parsePayloadType(const char* text, uint8_t& type) {
return true;
}
if (asciiStartsWith(text, "payload_type_")) text += strlen("payload_type_");
if (asciiEqual(text, "any")) type = FloodRuleEngine::ANY_TYPE;
if (asciiEqual(text, "any") || asciiEqual(text, "*")) type = FloodRuleEngine::ANY_TYPE;
else if (asciiEqual(text, "req")) type = PAYLOAD_TYPE_REQ;
else if (asciiEqual(text, "response") || asciiEqual(text, "resp")) type = PAYLOAD_TYPE_RESPONSE;
else if (asciiEqual(text, "txt_msg") || asciiEqual(text, "txt")) type = PAYLOAD_TYPE_TXT_MSG;
@@ -149,7 +150,7 @@ static bool parsePayloadType(const char* text, uint8_t& type) {
static bool parseHopSpec(const char* text, uint8_t& min_hops,
uint8_t& max_hops) {
if (text == NULL || *text == 0) return false;
if (asciiEqual(text, "all")) {
if (asciiEqual(text, "all") || asciiEqual(text, "*")) {
min_hops = 0;
max_hops = FloodRuleEngine::MAX_HOPS;
return true;
@@ -503,19 +504,29 @@ void FloodRuleEngine::load() {
loaded[i].retry_on_match = false;
}
loaded[i].active = active != 0;
if (version_7) {
success = success && FloodFilterPolicy::decodeStoredRuleActive(
active, loaded[i].active, loaded[i].transport_modes);
} else {
loaded[i].active = active != 0;
success = success && active <= 1;
}
loaded[i].suspend_on_temp_radio = suspend_on_temp_radio != 0;
loaded[i].match_blacklisted_path = match_blacklisted_path != 0;
loaded[i].scope_uses_slow_timing = scope_uses_slow_timing != 0;
loaded[i].drop_on_match = drop_on_match != 0;
loaded[i].rate_limit_enabled = rate_limit_enabled != 0;
loaded[i].stop_on_match = stop_on_match != 0;
if (success && (active > 1 || suspend_on_temp_radio > 1
if (success && (suspend_on_temp_radio > 1
|| match_blacklisted_path > 1 || scope_requires_region_match > 1
|| scope_uses_slow_timing > 1 || drop_on_match > 1
|| rate_limit_enabled > 1 || stop_on_match > 1)) {
success = false;
}
success = success && FloodFilterPolicy::transportActionsSupported(
loaded[i].transport_modes, loaded[i].scope_name[0] != 0
|| loaded[i].target_region_name[0] != 0,
loaded[i].retry_on_match, loaded[i].scope_uses_slow_timing);
if (!success) break;
if (!loaded[i].active) {
memset(&loaded[i], 0, sizeof(loaded[i]));
@@ -717,7 +728,8 @@ bool FloodRuleEngine::save() {
&& writeExact(&count, sizeof(count));
for (int i = 0; success && i < RULE_SLOTS; i++) {
const Entry& entry = _entries[i];
uint8_t active = entry.active ? 1 : 0;
uint8_t active = FloodFilterPolicy::encodeStoredRuleActive(
entry.active, entry.transport_modes);
uint8_t suspend_on_temp_radio = entry.suspend_on_temp_radio ? 1 : 0;
uint8_t match_blacklisted_path = entry.match_blacklisted_path ? 1 : 0;
uint8_t scope_requires_region_match =
@@ -797,8 +809,9 @@ bool FloodRuleEngine::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 {
if (!entry.active || packet == NULL || !packet->isRouteFlood()) return false;
const RegionEntry* incoming_region, uint8_t context) const {
if (!entry.active || !FloodFilterPolicy::ruleModeMatches(
entry.transport_modes, context, packet)) return false;
if (!FloodFilterPolicy::channelKeyLengthSupported(
entry.channel_key_len)) return false;
if (entry.suspend_on_temp_radio && temp_radio_active) return false;
@@ -920,12 +933,13 @@ uint32_t FloodRuleEngine::applyStop(uint32_t match_mask) {
uint32_t FloodRuleEngine::evaluate(
const mesh::Packet* packet, bool temp_radio_active,
bool incoming_region_allowed,
const RegionEntry* incoming_region) {
const RegionEntry* incoming_region, uint8_t context) {
static_assert(RULE_SLOTS <= 32,
"flood rule match mask supports at most 32 slots");
if (packet == NULL || !packet->isRouteFlood()) return 0;
if (packet == NULL || (context == FloodFilterPolicy::RULE_MODE_RADIO && !packet->isRouteFlood())) return 0;
bool incoming_is_scoped =
packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD;
packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD
|| packet->getRouteType() == ROUTE_TYPE_TRANSPORT_DIRECT;
uint16_t incoming_transport_code = incoming_is_scoped
? packet->transport_codes[0] : 0;
bool channel_auth_checked[RULE_SLOTS] = { false };
@@ -935,7 +949,7 @@ uint32_t FloodRuleEngine::evaluate(
const Entry& entry = _entries[i];
if (!fieldsMatch(entry, packet, temp_radio_active, incoming_is_scoped,
incoming_transport_code, incoming_region_allowed,
incoming_region)) {
incoming_region, context)) {
continue;
}
bool authenticated = true;
@@ -1025,7 +1039,7 @@ bool FloodRuleEngine::applyScope(mesh::Packet* packet, uint32_t match_mask,
bool FloodRuleEngine::shouldBlock(const mesh::Packet* packet,
uint32_t match_mask,
uint32_t now_millis) const {
if (packet == NULL || !packet->isRouteFlood()) return false;
if (packet == NULL) return false;
uint8_t type = packet->getPayloadType();
uint8_t hops = packet->getPathHashCount();
@@ -1056,7 +1070,7 @@ bool FloodRuleEngine::shouldBlock(const mesh::Packet* packet,
void FloodRuleEngine::commitRates(const mesh::Packet* packet,
uint32_t match_mask,
uint32_t now_millis) {
if (packet == NULL || !packet->isRouteFlood()) return;
if (packet == NULL) return;
for (int i = 0; i < RULE_SLOTS; i++) {
Entry& entry = _entries[i];
if ((match_mask & ((uint32_t)1U << i)) == 0
@@ -1074,12 +1088,16 @@ void FloodRuleEngine::commitRates(const mesh::Packet* packet,
}
void FloodRuleEngine::formatDetail(int index, char* reply,
size_t reply_len) const {
size_t reply_len, bool compact) const {
if (index < 0 || index >= RULE_SLOTS || !_entries[index].active) {
snprintf(reply, reply_len, "Err - empty filter slot");
return;
}
const Entry& entry = _entries[index];
if (compact) {
FloodRuleCLI::formatCompact(reply, reply_len, index + 1, entry);
return;
}
char hops[12];
char prefix[32];
char incoming[48];
@@ -1145,8 +1163,9 @@ void FloodRuleEngine::formatDetail(int index, char* reply,
int written = snprintf(
reply, reply_len,
"> %d type=%s hops=%s channel=%s prefix=%s in=%s %s%s%s priority=%u%s%s%s",
index + 1, payloadTypeName(entry.payload_type), hops,
"> %d type=%s mode=%s hops=%s channel=%s prefix=%s in=%s %s%s%s priority=%u%s%s%s",
index + 1, payloadTypeName(entry.payload_type),
FloodFilterPolicy::ruleModeName(entry.transport_modes), hops,
entry.channel_key_len == 0 ? "*" : entry.channel_name,
prefix, incoming, action, rate, retry,
(unsigned int)entry.priority,
@@ -1155,74 +1174,10 @@ void FloodRuleEngine::formatDetail(int index, char* reply,
entry.suspend_on_temp_radio ? " suspend=tempradio" : "");
if (written >= 0 && (size_t)written < reply_len) return;
char compact_type[4];
if (entry.payload_type == ANY_TYPE) copyString(compact_type, "any", sizeof(compact_type));
else snprintf(compact_type, sizeof(compact_type), "%u",
(unsigned int)entry.payload_type);
char compact_incoming[44];
switch (entry.incoming_scope_kind) {
case FloodFilterPolicy::RULE_IN_NONE:
copyString(compact_incoming, "n", sizeof(compact_incoming));
break;
case FloodFilterPolicy::RULE_IN_SCOPED:
copyString(compact_incoming, "s", sizeof(compact_incoming));
break;
case FloodFilterPolicy::RULE_IN_ALLOWED:
copyString(compact_incoming, "a", sizeof(compact_incoming));
break;
case FloodFilterPolicy::RULE_IN_UNKNOWN:
copyString(compact_incoming, "u", sizeof(compact_incoming));
break;
case FloodFilterPolicy::RULE_IN_SCOPE:
snprintf(compact_incoming, sizeof(compact_incoming), "s:%s",
entry.incoming_scope_name);
break;
case FloodFilterPolicy::RULE_IN_REGION:
snprintf(compact_incoming, sizeof(compact_incoming), "r:%s",
entry.incoming_scope_name);
break;
default:
copyString(compact_incoming, "*", sizeof(compact_incoming));
break;
}
char compact_action[44];
if (entry.drop_on_match) {
copyString(compact_action, " drop", sizeof(compact_action));
} else if (entry.scope_name[0] != 0) {
snprintf(compact_action, sizeof(compact_action), " scope=%s",
entry.scope_name);
} else if (entry.target_region_name[0] != 0) {
snprintf(compact_action, sizeof(compact_action), " region=%s",
entry.target_region_name);
} else {
compact_action[0] = 0;
}
char compact_rate[12];
compact_rate[0] = 0;
if (entry.rate_limit_enabled) {
snprintf(compact_rate, sizeof(compact_rate), " q=%u",
(unsigned int)entry.rate_per_minute);
}
char compact_flags[8];
compact_flags[0] = 0;
if (entry.scope_uses_slow_timing || entry.suspend_on_temp_radio
|| entry.retry_on_match) {
snprintf(compact_flags, sizeof(compact_flags), " f=%s%s%s",
entry.scope_uses_slow_timing ? "s" : "",
entry.suspend_on_temp_radio ? "t" : "",
entry.retry_on_match ? "r" : "");
}
snprintf(reply, reply_len,
">%d %s %s c=%s p=%s i=%s%s%s pri=%u%s%s",
index + 1, compact_type, hops,
entry.channel_key_len == 0 ? "*" : entry.channel_name,
prefix, compact_incoming, compact_action, compact_rate,
(unsigned int)entry.priority,
entry.stop_on_match ? " stop" : "",
compact_flags);
FloodRuleCLI::formatCompact(reply, reply_len, index + 1, entry);
}
void FloodRuleEngine::format(const char* args, char* reply) const {
void FloodRuleEngine::format(const char* args, char* reply, bool compact) const {
const char* selector = skipSpaces(args);
if (*selector == '.') selector = skipSpaces(selector + 1);
if (*selector != 0) {
@@ -1232,7 +1187,7 @@ void FloodRuleEngine::format(const char* args, char* reply) const {
(unsigned int)RULE_SLOTS);
return;
}
formatDetail((int)slot - 1, reply, 160);
formatDetail((int)slot - 1, reply, 160, compact);
return;
}
@@ -1263,8 +1218,9 @@ void FloodRuleEngine::format(const char* args, char* reply) const {
snprintf(priority, sizeof(priority), "^%u",
(unsigned int)entry.priority);
}
snprintf(item, sizeof(item), " %d=%s@%s%s%s%s%s%s%s%s%s",
i + 1, payloadTypeName(entry.payload_type), hops,
snprintf(item, sizeof(item), " %d=%s~%s@%s%s%s%s%s%s%s%s%s",
i + 1, payloadTypeName(entry.payload_type),
FloodFilterPolicy::ruleModeName(entry.transport_modes), hops,
entry.match_blacklisted_path ? "?blacklist" : "", target,
priority, entry.stop_on_match ? "~stop" : "",
entry.rate_limit_enabled ? "~rate" : "",
@@ -1342,7 +1298,8 @@ void FloodRuleEngine::set(const char* args, char* reply,
uint8_t payload_type = 0;
const char* type_text = asciiStartsWith(tokens[0], "type=")
? tokens[0] + strlen("type=") : tokens[0];
? tokens[0] + strlen("type=")
: asciiStartsWith(tokens[0], "t=") ? tokens[0] + 2 : tokens[0];
if (!parsePayloadType(type_text, payload_type)) {
copyString(reply,
"Err - packet type must be name, any, 0-15, or 0x00-0x0F",
@@ -1385,9 +1342,23 @@ void FloodRuleEngine::set(const char* args, char* reply,
bool priority_set = false;
bool stop_on_match = false;
bool retry_on_match = false;
uint8_t transport_modes = FloodFilterPolicy::RULE_MODE_RADIO;
bool mode_set = false;
for (int i = 1; i < token_count; i++) {
if (asciiEqual(tokens[i], "suspend=tempradio")) {
if (asciiStartsWith(tokens[i], "mode=")
|| asciiStartsWith(tokens[i], "m=")) {
if (mode_set) {
strcpy(reply, DUPLICATE_OPTION);
return;
}
const char* value = strchr(tokens[i], '=') + 1;
if (!FloodFilterPolicy::parseRuleModes(value, transport_modes)) {
strcpy(reply, "Err - mode is radio, bridge, cross, or bridge,cross");
return;
}
mode_set = true;
} else if (asciiEqual(tokens[i], "suspend=tempradio")) {
if (suspend_on_temp_radio) {
copyString(reply, DUPLICATE_OPTION, 160);
return;
@@ -1425,7 +1396,9 @@ void FloodRuleEngine::set(const char* args, char* reply,
}
flags++;
}
} else if (asciiEqual(tokens[i], "path=blacklist")) {
} else if (asciiEqual(tokens[i], "path=blacklist")
|| asciiEqual(tokens[i], "p=blacklist")
|| asciiEqual(tokens[i], "p=bl")) {
copyString(reply,
"Err - path=blacklist is repeater-only; use prefix= on rooms",
160);
@@ -1504,6 +1477,7 @@ void FloodRuleEngine::set(const char* args, char* reply,
priority = (uint8_t)parsed;
priority_set = true;
} else if (asciiEqual(tokens[i], "stop")
|| asciiEqual(tokens[i], "s")
|| asciiEqual(tokens[i], "action=stop")) {
if (stop_on_match) {
copyString(reply, DUPLICATE_OPTION, 160);
@@ -1511,6 +1485,7 @@ void FloodRuleEngine::set(const char* args, char* reply,
}
stop_on_match = true;
} else if (asciiEqual(tokens[i], "retry")
|| asciiEqual(tokens[i], "r")
|| asciiEqual(tokens[i], "retry=on")
|| asciiEqual(tokens[i], "retry=allow")
|| asciiEqual(tokens[i], "action=retry")) {
@@ -1531,12 +1506,13 @@ void FloodRuleEngine::set(const char* args, char* reply,
return;
}
scope_timing_set = true;
} else if (asciiStartsWith(tokens[i], "scope=")) {
} else if (asciiStartsWith(tokens[i], "scope=")
|| asciiStartsWith(tokens[i], "s=")) {
if (target_set || drop_set) {
copyString(reply, DUPLICATE_OPTION, 160);
return;
}
if (!normalizeScopeName(tokens[i] + strlen("scope="), scope_name,
if (!normalizeScopeName(strchr(tokens[i], '=') + 1, scope_name,
sizeof(scope_name))) {
copyString(reply,
"Err - scope must be a public name of at most 30 characters",
@@ -1544,13 +1520,14 @@ void FloodRuleEngine::set(const char* args, char* reply,
return;
}
target_set = true;
} else if (asciiStartsWith(tokens[i], "region=")) {
} else if (asciiStartsWith(tokens[i], "region=")
|| asciiStartsWith(tokens[i], "r=")) {
if (target_set || drop_set) {
copyString(reply, DUPLICATE_OPTION, 160);
return;
}
RegionEntry* region = _regions == NULL ? NULL
: _regions->findByNamePrefix(tokens[i] + strlen("region="));
: _regions->findByNamePrefix(strchr(tokens[i], '=') + 1);
TransportKey target_scope;
if (region == NULL || region->isWildcard()
|| (region->flags & REGION_DENY_FLOOD) != 0
@@ -1563,6 +1540,7 @@ void FloodRuleEngine::set(const char* args, char* reply,
sizeof(target_region_name));
target_set = true;
} else if (asciiEqual(tokens[i], "drop")
|| asciiEqual(tokens[i], "d")
|| asciiEqual(tokens[i], "action=drop")) {
if (drop_set || target_set) {
copyString(reply, DUPLICATE_OPTION, 160);
@@ -1605,7 +1583,14 @@ void FloodRuleEngine::set(const char* args, char* reply,
channel_set = true;
const char* value = tokens[i] + (asciiStartsWith(tokens[i], "c=")
? 2 : strlen("channel="));
if (!asciiEqual(value, "*")) {
if (FloodRuleCLI::isChannelReference(value)) {
if (!FloodRuleCLI::copyChannelReference(value, _entries, RULE_SLOTS,
channel_key_len, channel_hash, channel_secret, channel_name,
sizeof(channel_name))) {
copyString(reply, "Err - unknown or ambiguous channel key reference; use the original key", 160);
return;
}
} else if (!asciiEqual(value, "*")) {
if (!parseChannel(value, channel_secret, channel_key_len,
channel_hash, channel_name,
sizeof(channel_name))) {
@@ -1630,8 +1615,9 @@ void FloodRuleEngine::set(const char* args, char* reply,
return;
}
path_set = true;
} else if (asciiStartsWith(tokens[i], "hops=")) {
if (hops_set || !parseHopSpec(tokens[i] + strlen("hops="),
} else if (asciiStartsWith(tokens[i], "hops=")
|| asciiStartsWith(tokens[i], "h=")) {
if (hops_set || !parseHopSpec(strchr(tokens[i], '=') + 1,
min_hops, max_hops)) {
copyString(reply,
"Err - hops must be all, N, N+, or N-M (0-63)", 160);
@@ -1667,6 +1653,11 @@ void FloodRuleEngine::set(const char* args, char* reply,
160);
return;
}
if (!FloodFilterPolicy::transportActionsSupported(
transport_modes, target_set, retry_on_match, scope_uses_slow_timing)) {
strcpy(reply, "Err - bridge/cross supports drop, rate=, priority=, stop only");
return;
}
bool action_set = drop_set || target_set || rate_limit_enabled
|| stop_on_match || retry_on_match;
if (require_explicit_action && !action_set) {
@@ -1706,6 +1697,7 @@ void FloodRuleEngine::set(const char* args, char* reply,
candidate.priority = priority;
candidate.stop_on_match = stop_on_match;
candidate.retry_on_match = retry_on_match;
candidate.transport_modes = transport_modes;
int slot = requested_slot;
if (slot < 0) {
@@ -1740,6 +1732,10 @@ void FloodRuleEngine::set(const char* args, char* reply,
}
char detail[160];
formatDetail(slot, detail, sizeof(detail));
if (strncmp(detail, "Err - compact", 13) == 0) {
snprintf(reply, 160, "OK - rule %d saved (details exceed reply size)", slot + 1);
return;
}
const char* text = detail[0] == '>' ? skipSpaces(detail + 1) : detail;
snprintf(reply, 160, "OK - %s", text);
}
@@ -1791,6 +1787,18 @@ bool FloodRuleEngine::handleCommand(const char* command, char* reply) {
160);
return true;
}
if (commandMatches(command, "get fr")) {
format(command + strlen("get fr"), reply, true);
return true;
}
if (commandMatches(command, "set fr")) {
set(command + strlen("set fr"), reply, true);
return true;
}
if (commandMatches(command, "del fr")) {
remove(command + strlen("del fr"), reply);
return true;
}
if (commandMatches(command, "get flood.rule")) {
format(command + strlen("get flood.rule"), reply);
return true;
@@ -26,7 +26,7 @@ public:
uint32_t evaluate(const mesh::Packet* packet, bool temp_radio_active,
bool incoming_region_allowed,
const RegionEntry* incoming_region);
const RegionEntry* incoming_region, uint8_t context = 0);
bool applyScope(mesh::Packet* packet, uint32_t match_mask,
bool& scope_set, bool& fast_track,
bool log_change = true);
@@ -65,6 +65,7 @@ private:
uint8_t priority;
bool stop_on_match;
bool retry_on_match;
uint8_t transport_modes;
uint32_t rate_window_started;
uint16_t rate_window_count;
bool rate_window_active;
@@ -81,15 +82,15 @@ private:
bool temp_radio_active, bool incoming_is_scoped,
uint16_t incoming_transport_code,
bool incoming_region_allowed,
const RegionEntry* incoming_region) const;
const RegionEntry* incoming_region, uint8_t context) const;
bool authenticateChannel(const Entry& entry,
const mesh::Packet* packet) const;
int nextMatch(uint32_t match_mask, uint32_t visited_mask) const;
bool resolveTargetRegion(const char* name, TransportKey& scope,
const char*& canonical_name);
uint32_t applyStop(uint32_t match_mask);
void format(const char* args, char* reply) const;
void formatDetail(int index, char* reply, size_t reply_len) const;
void format(const char* args, char* reply, bool compact = false) const;
void formatDetail(int index, char* reply, size_t reply_len, bool compact = false) const;
void set(const char* args, char* reply,
bool require_explicit_action = false);
void remove(const char* args, char* reply);
+28 -2
View File
@@ -142,6 +142,7 @@ void MyMesh::pushPostToClient(ClientInfo *client, PostInfo &post) {
auto reply = createDatagram(PAYLOAD_TYPE_TXT_MSG, client->id, client->shared_secret, reply_data, len);
bool sent = false;
if (reply) {
reply->radio_reply = true; // asynchronous response to the room subscription
if (client->out_path_len == OUT_PATH_UNKNOWN) {
unsigned long delay_millis = 0;
sent = sendFloodScoped(default_scope, reply, delay_millis,
@@ -278,6 +279,29 @@ int MyMesh::handleRequest(ClientInfo *sender, uint32_t sender_timestamp, uint8_t
return 0; // unknown command
}
#if MESH_ENABLE_ROOM_FLOOD_RULE_ENGINE
bool MyMesh::allowTransportPacket(const mesh::Packet* packet, uint8_t context) {
if (!packet) return false;
RegionEntry* incoming_region = NULL;
bool scoped = packet->getRouteType() == ROUTE_TYPE_TRANSPORT_FLOOD
|| packet->getRouteType() == ROUTE_TYPE_TRANSPORT_DIRECT;
bool incoming_allowed;
if (scoped) {
incoming_region = region_map.findMatch(packet, REGION_DENY_FLOOD);
incoming_allowed = incoming_region != NULL;
} else {
incoming_allowed = (region_map.getWildcard().flags & REGION_DENY_FLOOD) == 0;
}
// Use a local mask: bridge RX/TX callbacks can run inside mesh dispatch,
// where recv_pkt_* still belongs to the ordinary radio forwarding phase.
uint32_t matches = flood_rules.evaluate(packet, isAnyTempRadioActive(),
incoming_allowed, incoming_region, context);
if (flood_rules.shouldBlock(packet, matches, _ms->getMillis())) return false;
flood_rules.commitRates(packet, matches, _ms->getMillis());
return true;
}
#endif
void MyMesh::logRxRaw(float snr, float rssi, const uint8_t raw[], int len) {
#if MESH_PACKET_LOGGING
if (mesh::isUsbLoggingEnabled()) {
@@ -411,7 +435,7 @@ bool MyMesh::evaluateFloodRuleTiming(const mesh::Packet* packet,
mesh::Packet candidate = *packet;
uint32_t match_mask = flood_rules.evaluate(
packet, isTempRadioActive(), incoming_region_allowed, incoming_region);
packet, isAnyTempRadioActive(), incoming_region_allowed, incoming_region);
bool scope_set = false;
return flood_rules.applyScope(&candidate, match_mask, scope_set,
fast_track, false);
@@ -607,7 +631,7 @@ mesh::DispatcherAction MyMesh::onRecvPacket(mesh::Packet* pkt) {
(region_map.getWildcard().flags & REGION_DENY_FLOOD) == 0;
}
recv_pkt_rule_match_mask = flood_rules.evaluate(
pkt, isTempRadioActive(), incoming_region_allowed, incoming_region);
pkt, isAnyTempRadioActive(), incoming_region_allowed, incoming_region);
if (flood_rules.hasRetryRules()) {
pkt->flood_retry_policy = flood_rules.allowsRetry(
recv_pkt_rule_match_mask)
@@ -1410,6 +1434,7 @@ void MyMesh::begin(FILESYSTEM *fs) {
// Set stats sources for automatic stats collection
bridge->setStatsSources(this, _radio, _cli.getBoard(), _ms);
configureBridgeFilter(bridge);
bridge->begin();
}
}
@@ -2161,6 +2186,7 @@ void MyMesh::onUserGpioTimerCompleted(uint8_t pin, uint8_t state,
client->shared_secret, data,
5 + (size_t)text_len);
if (!packet) return;
packet->radio_reply = true; // delayed GPIO command completion
if (client->out_path_len == OUT_PATH_UNKNOWN) {
sendFlood(packet, SERVER_RESPONSE_DELAY, path_hash_size);
} else {
+20
View File
@@ -540,12 +540,30 @@ public:
return mesh::wireless::WiFi;
}
void loop();
#if MESH_ENABLE_ROOM_FLOOD_RULE_ENGINE
bool allowTransportPacket(const mesh::Packet* packet, uint8_t context);
bool allowRadioProfileCross(const mesh::Packet* packet) override {
return allowTransportPacket(packet, 4); // RULE_MODE_CROSS
}
#endif
#if defined(WITH_BRIDGE)
bool isBridgeRunning() const override {
return bridge != nullptr && bridge->isRunning();
}
void configureBridgeFilter(AbstractBridge* active_bridge) {
#if MESH_ENABLE_ROOM_FLOOD_RULE_ENGINE
active_bridge->setPacketFilter([](void* context, const mesh::Packet* packet) {
return static_cast<MyMesh*>(context)->allowTransportPacket(packet, 2); // RULE_MODE_BRIDGE
}, this);
#else
(void)active_bridge;
#endif
}
bool setBridgeState(bool enable) override {
// An absent MQTT bridge is already stopped. Do not allocate one solely to
// satisfy an idempotent disable request.
@@ -585,6 +603,7 @@ public:
}
#endif
#endif
configureBridgeFilter(bridge);
bridge->begin();
#ifdef WITH_MQTT_BRIDGE
_alerter.setBridge(bridge);
@@ -619,6 +638,7 @@ public:
#ifdef WITH_MQTT_BRIDGE
bridge->setStatsSources(this, _radio, _cli.getBoard(), _ms);
#endif
configureBridgeFilter(bridge);
bridge->begin();
return bridge->isRunning();
}
+1
View File
@@ -577,6 +577,7 @@ void SensorMesh::onUserGpioTimerCompleted(uint8_t pin, uint8_t state,
client->shared_secret, data,
5 + (size_t)text_len);
if (!packet) return;
packet->radio_reply = true; // delayed GPIO command completion
if (client->out_path_len == OUT_PATH_UNKNOWN) {
sendFlood(packet, CLI_REPLY_DELAY_MILLIS, path_hash_size);
} else {