feat(repeater): antispam — FairnessLimiter (port #1502) + kanálový deny list

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
tthandClaude Fable 5 committed 2026-09-05 21:35:36 +02:00
1 parent de5bd52bd9
commit 6f90c80dcc
15 files changed
+1098 -112

No files matched your search

+109
View File
@@ -0,0 +1,109 @@
#pragma once
// CUSTOM (TeTeHacko): pure string helpers for the channel modules
// (ChannelCommon.h, ChannelFilter.h, ChannelBot.h). No MyMesh, no Arduino --
// deliberately, so test/test_chan_list can compile them on the native env.
#include <ctype.h>
#include <string.h>
// Longest node name an entry may hold. MeshCore node names are 32 bytes
// (NodePrefs.node_name), the margin is for UTF-8 names people paste with
// trailing decoration.
#define CHAN_NAME_MAX 40
#define CHAN_LIST_OK 0
#define CHAN_LIST_BAD_NAME -1 // empty, too long, or contains the ',' separator
#define CHAN_LIST_DUP -2
#define CHAN_LIST_FULL -3
static int chan_hex_nibble(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
// Exact, case-insensitive membership in a comma-separated list. Deliberately
// NOT a substring search: an ignore/deny list matching on substrings would be
// a trap (a node called "TTH" silencing "tracker"). Entries are trimmed of
// surrounding spaces; case folding is ASCII-only, so UTF-8 names match
// byte-exactly (good enough -- nobody case-shifts emoji).
static bool chan_list_has(const char* list, const char* word) {
const char* seg = list;
while (*seg) {
const char* comma = strchr(seg, ',');
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
while (len > 0 && *seg == ' ') { seg++; len--; }
while (len > 0 && seg[len - 1] == ' ') len--;
if (len > 0 && (int)strlen(word) == len) {
int i = 0;
while (i < len && tolower((unsigned char)word[i]) == tolower((unsigned char)seg[i])) i++;
if (i == len) return true;
}
if (!comma) break;
seg = comma + 1;
}
return false;
}
// Append name[0..name_len) to the comma-separated `list` (buffer of `cap`
// bytes, NUL-terminated). Leading/trailing spaces are trimmed off the name
// first (RF-padded commands happen).
static int chan_list_add(char* list, int cap, const char* name, int name_len) {
while (name_len > 0 && *name == ' ') { name++; name_len--; }
while (name_len > 0 && name[name_len - 1] == ' ') name_len--;
if (name_len <= 0 || name_len >= CHAN_NAME_MAX) return CHAN_LIST_BAD_NAME;
if (memchr(name, ',', name_len) != NULL) return CHAN_LIST_BAD_NAME; // ',' is the separator
char tmp[CHAN_NAME_MAX];
memcpy(tmp, name, name_len);
tmp[name_len] = 0;
if (chan_list_has(list, tmp)) return CHAN_LIST_DUP;
int cur = strlen(list);
if (cur + (cur > 0 ? 1 : 0) + name_len + 1 > cap) return CHAN_LIST_FULL;
if (cur > 0) list[cur++] = ',';
memcpy(&list[cur], tmp, name_len + 1);
return CHAN_LIST_OK;
}
// Remove the (case-insensitively) matching entry. Returns false when absent.
static bool chan_list_del(char* list, const char* name) {
while (*name == ' ') name++;
char out[512]; // callers' lists are far smaller (filter_deny is 128 B)
int out_len = 0;
bool removed = false;
const char* seg = list;
int list_len = strlen(list);
if (list_len >= (int)sizeof(out)) return false; // defensive, never expected
while (*seg) {
const char* comma = strchr(seg, ',');
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
const char* e = seg;
int elen = len;
while (elen > 0 && *e == ' ') { e++; elen--; }
while (elen > 0 && e[elen - 1] == ' ') elen--;
bool match = false;
if ((int)strlen(name) == elen) {
int i = 0;
while (i < elen && tolower((unsigned char)name[i]) == tolower((unsigned char)e[i])) i++;
match = (i == elen);
}
if (match) {
removed = true;
} else if (len > 0) {
if (out_len > 0) out[out_len++] = ',';
memcpy(&out[out_len], seg, len);
out_len += len;
}
if (!comma) break;
seg = comma + 1;
}
if (removed) {
out[out_len] = 0;
memcpy(list, out, out_len + 1);
}
return removed;
}
+25 -97
View File
@@ -1,7 +1,9 @@
#pragma once
// CUSTOM (TeTeHacko): channel bot -- not part of upstream simple_repeater.
// Included at the bottom of MyMesh.cpp, after all class definitions, so these
// Included at the bottom of MyMesh.cpp, after ChannelCommon.h (which owns the
// channel registry, the PSK parsing, searchChannelsByHash() and the
// onGroupDataRecv() dispatcher that calls botOnChannelText() here), so these
// are plain MyMesh methods with full access to the analyzer state.
//
// WHY THIS LIVES IN THE REPEATER/ANALYZER BUILD
@@ -67,7 +69,6 @@
#endif
#define BOT_REPLY_LEN 120 // well under the 184 B packet payload
#define BOT_TEXT_LEN 160 // inbound text, after the "<sender>: " prefix
#define BOT_PATH_STR_LEN 64 // "3f:a1:c8..." -- caps how many hops we print
// One !command's answer. Sized for the WORST CASE of !link, which is the longest:
// botFormatPath() caps the path string at 62 chars (21 hops x 1 B, or 9 x 3 B, or
@@ -81,59 +82,18 @@
// the command exists to report ("... 209f:34fa:ed9c, SNR 4.0 ").
#define BOT_FRAG_LEN 100
static int bot_hex_nibble(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return c - 'a' + 10;
if (c >= 'A' && c <= 'F') return c - 'A' + 10;
return -1;
}
// The PSK is given as HEX, which is exactly the form `meshcore-cli get_channel
// <n>` prints -- no base64 round trip by hand, and no base64.hpp dependency in
// this build (only companion_radio pulls that in). 32 hex chars = 128-bit key
// (what the phone app generates), 64 = 256-bit.
// Registers the bot channel in the shared registry (ChannelCommon.h does the
// hex parse and hash derivation) and resets bot state. Called by channelsInit().
void MyMesh::botInit() {
bot_channel_valid = false;
bot_next_reply_at = 0;
bot_replies_sent = 0;
bot_ignored = 0;
bot_throttled = 0;
memset(bot_peers, 0, sizeof(bot_peers));
bot_last_reply_secs = 0;
memset(&bot_channel, 0, sizeof(bot_channel));
const char* psk = BOT_CHANNEL_PSK;
int n = strlen(psk);
if (n != 32 && n != 64) {
MESH_DEBUG_PRINTLN("botInit: BOT_CHANNEL_PSK must be 32 or 64 hex chars, got %d", n);
return;
}
int key_len = n / 2;
for (int i = 0; i < key_len; i++) {
int hi = bot_hex_nibble(psk[i * 2]);
int lo = bot_hex_nibble(psk[i * 2 + 1]);
if (hi < 0 || lo < 0) {
MESH_DEBUG_PRINTLN("botInit: BOT_CHANNEL_PSK is not hex");
return;
}
bot_channel.secret[i] = (uint8_t)((hi << 4) | lo);
}
// Same derivation as BaseChatMesh::addChannel() (BaseChatMesh.cpp:875), so the
// hash matches what every other node computes for this channel. Cross-checked
// against a live node: the 128-bit #tth-test key hashes to 0x75, which is what
// `get_channel 1` reports as channel_hash.
mesh::Utils::sha256(bot_channel.hash, sizeof(bot_channel.hash), bot_channel.secret, key_len);
bot_channel_valid = true;
}
// Mirrors BaseChatMesh::searchChannelsByHash() for our single channel. Matching
// on hash[0] alone is upstream's design: PATH_HASH_SIZE is 1, so collisions are
// expected and resolved by MACThenDecrypt() failing in the caller.
int MyMesh::searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel channels[], int max_matches) {
if (!bot_channel_valid || max_matches < 1) return 0;
if (bot_channel.hash[0] != hash[0]) return 0;
channels[0] = bot_channel;
return 1;
bot_channel_idx = (int8_t)channelAddFromPsk(psk, strlen(psk), CHAN_FLAG_BOT);
}
// Colon-separated per-hop hashes, the same self-describing convention the
@@ -160,34 +120,17 @@ void MyMesh::botFormatPath(char* out, const mesh::Packet* pkt) const {
*p = 0;
}
// Exact, case-insensitive membership in a comma-separated list. Distinct from
// botTriggerMatches(), which is a SUBSTRING search: an ignore list or a command
// whitelist matching on substrings would be a trap ("path" enabling "!pathx",
// a node called "TTH" silencing "tracker").
static bool bot_list_has(const char* list, const char* word) {
const char* seg = list;
while (*seg) {
const char* comma = strchr(seg, ',');
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
while (len > 0 && *seg == ' ') { seg++; len--; }
while (len > 0 && seg[len - 1] == ' ') len--;
if (len > 0 && (int)strlen(word) == len) {
int i = 0;
while (i < len && tolower((unsigned char)word[i]) == tolower((unsigned char)seg[i])) i++;
if (i == len) return true;
}
if (!comma) break;
seg = comma + 1;
}
return false;
}
// NOTE: exact-membership matching lives in chan_list_has() (ChannelCommon.h);
// it is distinct from botTriggerMatches(), which is a SUBSTRING search -- an
// ignore list or a command whitelist matching on substrings would be a trap
// ("path" enabling "!pathx", a node called "TTH" silencing "tracker").
// One `!command` -> one text fragment. Returns chars written, 0 for unknown.
// The interesting ones are the analyzer's: a companion bot cannot answer these
// at all, because it has no rxlog and no heard registry.
int MyMesh::botCommandReply(char* out, int max_len, const char* cmd, const mesh::Packet* pkt) {
// An empty BOT_COMMANDS means "all"; otherwise only what is listed.
if (BOT_COMMANDS[0] != 0 && !bot_list_has(BOT_COMMANDS, cmd)) return 0;
if (BOT_COMMANDS[0] != 0 && !chan_list_has(BOT_COMMANDS, cmd)) return 0;
if (strcmp(cmd, "noise") == 0) {
// Noise floor is the analyzer's own measurement -- a companion bot has no
@@ -315,7 +258,7 @@ void MyMesh::botSendReply(const mesh::Packet* pkt, const char* text) {
if (n < 0) return;
if (n > BOT_REPLY_LEN - 1) n = BOT_REPLY_LEN - 1; // snprintf reports untruncated length
auto reply = createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, bot_channel, temp, 5 + n);
auto reply = createGroupDatagram(PAYLOAD_TYPE_GRP_TXT, known_channels[bot_channel_idx], temp, 5 + n);
if (reply == NULL) {
MESH_DEBUG_PRINTLN("botSendReply: packet pool empty");
return;
@@ -351,38 +294,23 @@ bool MyMesh::botPeerAllowed(const char* name) {
return true;
}
void MyMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel,
uint8_t* data, size_t len) {
if (type != PAYLOAD_TYPE_GRP_TXT) return; // GRP_DATA (telemetry etc.) is not ours
if (len < 5) return;
if ((data[4] >> 2) != 0) return; // only plain text, per BaseChatMesh.cpp:374
// Work on a bounded copy. Upstream NUL-terminates the caller's buffer in place
// (data[len] = 0), which is fine there but relies on headroom this function
// cannot verify -- and every other parse in this fork is bounds-checked.
char text[BOT_TEXT_LEN];
size_t body = len - 5;
if (body >= sizeof(text)) body = sizeof(text) - 1;
memcpy(text, &data[5], body);
text[body] = 0;
// "<sender>: <msg>". Bail out if the sender is us: our own reply comes back
// through the mesh and would otherwise ping-pong forever. The cooldown alone
// would not stop that, it would only slow it down.
const char* msg = text;
char* sep = strstr(text, ": ");
if (sep) {
*sep = 0;
if (strcmp(text, _prefs.node_name) == 0) return;
// Called from onChannelText() (ChannelCommon.h) for messages on the bot
// channel only -- the "<sender>: <msg>" split already happened there, and a
// sender on the ChannelFilter deny list never reaches this point.
void MyMesh::botOnChannelText(mesh::Packet* packet, const char* sender, const char* msg) {
// Bail out if the sender is us: our own reply comes back through the mesh and
// would otherwise ping-pong forever. The cooldown alone would not stop that,
// it would only slow it down.
if (sender[0] != 0) {
if (strcmp(sender, _prefs.node_name) == 0) return;
// Peer bots: skip before any trigger or command matching. Measured need --
// tracker puts "Ping" on this channel by itself, and answering those ate the
// cooldown, so a human question landed in a closed window.
if (BOT_IGNORE_SENDERS[0] != 0 && bot_list_has(BOT_IGNORE_SENDERS, text)) {
if (BOT_IGNORE_SENDERS[0] != 0 && chan_list_has(BOT_IGNORE_SENDERS, sender)) {
bot_ignored++;
MESH_DEBUG_PRINTLN("bot: ignoruji odesilatele z BOT_IGNORE_SENDERS");
return;
}
msg = sep + 2;
}
char reply[BOT_REPLY_LEN];
@@ -402,7 +330,7 @@ void MyMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Gro
}
// Then this sender's own window. Name-based, so spoofable -- fine, this is a
// politeness throttle and channel messages carry no identity anyway.
if (!botPeerAllowed(sep ? text : "")) {
if (!botPeerAllowed(sender)) {
MESH_DEBUG_PRINTLN("bot: reply suppressed, sender cooldown");
bot_throttled++;
return;
@@ -419,12 +347,12 @@ void MyMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::Gro
bool MyMesh::botHandleCommand(const char* command, char* reply) {
if (memcmp(command, "bot", 3) != 0 || (command[3] != 0 && command[3] != ' ')) return false;
if (!bot_channel_valid) {
if (bot_channel_idx < 0) {
strcpy(reply, "bot: DISABLED (bad BOT_CHANNEL_PSK)");
return true;
}
sprintf(reply, "bot: chan %02X, trigger '%s', cmds '%s', ignore '%s', cooldown %d ms/odesilatel + %d ms floor, replies %u, throttled %u, ignored %u, last %u",
(uint32_t)bot_channel.hash[0], BOT_TRIGGER,
(uint32_t)known_channels[bot_channel_idx].hash[0], BOT_TRIGGER,
BOT_COMMANDS[0] ? BOT_COMMANDS : "(vse)",
BOT_IGNORE_SENDERS[0] ? BOT_IGNORE_SENDERS : "(nikdo)",
(int)BOT_REPLY_COOLDOWN_MS, (int)BOT_MIN_GAP_MS,
+168
View File
@@ -0,0 +1,168 @@
#pragma once
// CUSTOM (TeTeHacko): shared channel plumbing for ChannelBot.h and
// ChannelFilter.h -- not part of upstream simple_repeater. Included at the
// bottom of MyMesh.cpp (before the other two), so these are plain MyMesh
// methods with full access to state.
//
// A repeater is normally deaf to channel traffic only because the two virtuals
// below are no-ops in mesh::Mesh (Mesh.h:160, Mesh.cpp:37). Overriding them
// decrypts matching GRP_TXT packets on the side; forwarding is untouched --
// Mesh::onRecvPacket() calls routeRecvPacket() either way (Mesh.cpp:237-259).
// The ONE deliberate exception is the ChannelFilter veto in onChannelText(),
// which uses packet->markDoNotRetransmit() -- the exact mechanism the ANON
// branch uses at Mesh.cpp:229 -- to stop THIS node re-airing a matched packet.
//
// Registry slots are MAX_KNOWN_CHANNELS(4) because searchChannelsByHash()
// callers cap matches at 4 (Mesh.cpp:247). A channel named by both the bot and
// the filter shares one slot (flags are OR-ed).
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
#include "ChanListUtil.h"
// Inbound text, after decrypt: 4 B timestamp + 1 B type + "sender: msg".
#define CHAN_TEXT_LEN 160
// The PSK is given as HEX, which is exactly the form `meshcore-cli get_channel
// <n>` prints -- no base64 round trip by hand, and no base64.hpp dependency in
// this build (only companion_radio pulls that in). 32 hex chars = 128-bit key
// (what the phone app generates), 64 = 256-bit. Shorter keys are zero-padded in
// the 32-byte secret, same as BaseChatMesh::addChannel().
// Returns the registry index, or -1 (bad hex/length, or registry full).
int MyMesh::channelAddFromPsk(const char* psk_hex, int psk_len, uint8_t flag) {
if (psk_len != 32 && psk_len != 64) {
MESH_DEBUG_PRINTLN("channelAddFromPsk: PSK must be 32 or 64 hex chars, got %d", psk_len);
return -1;
}
int key_len = psk_len / 2;
uint8_t secret[PUB_KEY_SIZE];
memset(secret, 0, sizeof(secret));
for (int i = 0; i < key_len; i++) {
int hi = chan_hex_nibble(psk_hex[i * 2]);
int lo = chan_hex_nibble(psk_hex[i * 2 + 1]);
if (hi < 0 || lo < 0) {
MESH_DEBUG_PRINTLN("channelAddFromPsk: PSK is not hex");
return -1;
}
secret[i] = (uint8_t)((hi << 4) | lo);
}
// one slot per channel: a PSK named twice (bot + filter) just ORs its flags
for (int i = 0; i < num_known_channels; i++) {
if (memcmp(known_channels[i].secret, secret, sizeof(secret)) == 0) {
known_channel_flags[i] |= flag;
return i;
}
}
if (num_known_channels >= MAX_KNOWN_CHANNELS) {
MESH_DEBUG_PRINTLN("channelAddFromPsk: registry full (%d)", MAX_KNOWN_CHANNELS);
return -1;
}
int idx = num_known_channels++;
memcpy(known_channels[idx].secret, secret, sizeof(secret));
// Same derivation as BaseChatMesh::addChannel() (hash over the REAL key
// length, not the padded 32), so the hash matches what every other node
// computes. Cross-checked live: the 128-bit #tth-test key hashes to 0x75.
mesh::Utils::sha256(known_channels[idx].hash, sizeof(known_channels[idx].hash),
known_channels[idx].secret, key_len);
known_channel_flags[idx] = flag;
return idx;
}
void MyMesh::channelsInit() {
num_known_channels = 0;
memset(known_channels, 0, sizeof(known_channels));
memset(known_channel_flags, 0, sizeof(known_channel_flags));
#ifdef FILTER_CHANNEL_PSKS
filter_dropped = 0;
{
// comma-separated hex PSKs
const char* seg = FILTER_CHANNEL_PSKS;
while (*seg) {
const char* comma = strchr(seg, ',');
int len = comma ? (int)(comma - seg) : (int)strlen(seg);
channelAddFromPsk(seg, len, CHAN_FLAG_FILTER);
if (!comma) break;
seg = comma + 1;
}
}
#endif
#ifdef BOT_CHANNEL_PSK
botInit();
#endif
}
// Mirrors BaseChatMesh::searchChannelsByHash() over the registry. Matching on
// hash[0] alone is upstream's design: PATH_HASH_SIZE is 1, so collisions are
// expected and resolved by MACThenDecrypt() failing in the caller.
int MyMesh::searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel channels[], int max_matches) {
int n = 0;
for (int i = 0; i < num_known_channels && n < max_matches; i++) {
if (known_channels[i].hash[0] == hash[0]) {
channels[n++] = known_channels[i];
}
}
return n;
}
void MyMesh::onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel,
uint8_t* data, size_t len) {
if (type != PAYLOAD_TYPE_GRP_TXT) return; // GRP_DATA (telemetry etc.) is not ours
if (len < 5) return;
if ((data[4] >> 2) != 0) return; // only plain text, per BaseChatMesh.cpp:374
// which registry entry decrypted this? (the caller passes a COPY, not our slot)
int chan_idx = -1;
for (int i = 0; i < num_known_channels; i++) {
if (memcmp(known_channels[i].secret, channel.secret, sizeof(channel.secret)) == 0) {
chan_idx = i;
break;
}
}
if (chan_idx < 0) return;
// Work on a bounded copy. Upstream NUL-terminates the caller's buffer in place
// (data[len] = 0), which is fine there but relies on headroom this function
// cannot verify -- and every other parse in this fork is bounds-checked.
char text[CHAN_TEXT_LEN];
size_t body = len - 5;
if (body >= sizeof(text)) body = sizeof(text) - 1;
memcpy(text, &data[5], body);
text[body] = 0;
// "<sender>: <msg>". A channel packet carries no identity; this prefix is the
// only sender there is (and therefore spoofable -- see ChannelFilter.h).
const char* sender = "";
const char* msg = text;
char* sep = strstr(text, ": ");
if (sep) {
*sep = 0;
sender = text;
msg = sep + 2;
}
onChannelText(packet, chan_idx, sender, msg);
}
void MyMesh::onChannelText(mesh::Packet* packet, int chan_idx, const char* sender, const char* msg) {
#ifdef FILTER_CHANNEL_PSKS
if ((known_channel_flags[chan_idx] & CHAN_FLAG_FILTER)
&& sender[0] != 0 && filterDenied(sender)) {
// Veto the forward of THIS packet -- routeRecvPacket() checks the mark
// (Mesh.cpp:357). Local processing already happened (rxlog/pktfeed capture
// on receive), so the observer evidence trail is intact; the node just
// refuses to re-air it. And the bot must not answer a denied sender either.
packet->markDoNotRetransmit();
filter_dropped++;
MESH_DEBUG_PRINTLN("filter: drop fwd, sender na deny listu");
return;
}
#endif
#ifdef BOT_CHANNEL_PSK
if (chan_idx == bot_channel_idx) {
botOnChannelText(packet, sender, msg);
}
#endif
}
#endif // BOT_CHANNEL_PSK || FILTER_CHANNEL_PSKS
+89
View File
@@ -0,0 +1,89 @@
#pragma once
// CUSTOM (TeTeHacko): channel-message deny list -- not part of upstream
// simple_repeater. Included at the bottom of MyMesh.cpp, after ChannelCommon.h.
//
// WHAT THIS IS (and is not)
//
// A repeater that knows a channel's PSK (FILTER_CHANNEL_PSKS, see
// ChannelCommon.h) decrypts each GRP_TXT on it and refuses to FORWARD messages
// whose "<sender>: " prefix is on a runtime deny list. Born 5. 9. 2026, when a
// runaway AI bot looped an 11-part Gemini quota dump onto #meshcore for hours
// and every repeater dutifully re-aired it.
//
// * The sender name is just text inside the encrypted payload -- GRP_TXT
// carries NO identity (only adverts do). Anyone can rename around this.
// It is containment of a runaway/rude node, not security. (For the
// content-neutral automatic layer, see FairnessLimiter.h.)
// * Only forwarding by THIS node is affected. Reception, rxlog/pktfeed
// capture (CoreScope feed) and the rest of the mesh are untouched.
// * DIRECT-routed packets are not seen here (their forward is decided before
// any decrypt, Mesh.cpp:94) -- channel messages flood, so in practice this
// covers them.
// * Upstream would not take this (privacy/no-censorship principles, see
// issue #169 discussion) -- fork-only, do not upstream.
//
// The deny list lives in _prefs.filter_deny (comma-separated exact names,
// case-insensitive) so the stock savePrefs()/loadPrefs() machinery persists
// it, and it is editable at runtime over RF admin: an incident response is
// `filter add <name>`, not a mast reflash.
#ifdef FILTER_CHANNEL_PSKS
bool MyMesh::filterDenied(const char* sender) const {
if (_prefs.filter_deny[0] == 0) return false;
return chan_list_has(_prefs.filter_deny, sender);
}
// `filter` / `filter list` -- show state; `filter add|del <name>` -- edit;
// `filter clear` -- empty the list. Names may contain spaces (everything after
// the subcommand is the name); commas are the storage separator so they are
// rejected. Matching is exact and case-insensitive (chan_list_has).
bool MyMesh::filterHandleCommand(const char* command, char* reply, int reply_max) {
if (memcmp(command, "filter", 6) != 0 || (command[6] != 0 && command[6] != ' ')) return false;
if (memcmp(&command[6], " add ", 5) == 0) {
const char* name = &command[11];
int rc = chan_list_add(_prefs.filter_deny, sizeof(_prefs.filter_deny), name, strlen(name));
if (rc == CHAN_LIST_OK) {
savePrefs();
sprintf(reply, "OK - deny: %s", _prefs.filter_deny);
} else if (rc == CHAN_LIST_DUP) {
strcpy(reply, "Err - already listed");
} else if (rc == CHAN_LIST_FULL) {
strcpy(reply, "Err - list full");
} else {
strcpy(reply, "Err - bad name (empty, too long, or contains ',')");
}
return true;
}
if (memcmp(&command[6], " del ", 5) == 0) {
if (chan_list_del(_prefs.filter_deny, &command[11])) {
savePrefs();
strcpy(reply, "OK");
} else {
strcpy(reply, "Err - not listed");
}
return true;
}
if (strcmp(&command[6], " clear") == 0) {
_prefs.filter_deny[0] = 0;
savePrefs();
strcpy(reply, "OK - deny list cleared");
return true;
}
if (command[6] == 0 || strcmp(&command[6], " list") == 0) {
snprintf(reply, reply_max, "filter: %d chan, dropped %u, deny: %s",
(int)num_known_channels, filter_dropped,
_prefs.filter_deny[0] ? _prefs.filter_deny : "(nikdo)");
return true;
}
strcpy(reply, "Err - filter [add|del <name>|list|clear]");
return true;
}
#endif // FILTER_CHANNEL_PSKS
+66 -4
View File
@@ -724,6 +724,29 @@ bool MyMesh::allowPacketForward(const mesh::Packet *packet) {
return true;
}
// CUSTOM (TeTeHacko): `fairness` -- denied-forward stats; `fairness on|off` --
// runtime kill switch (persisted, so a mast reboot keeps the chosen state).
bool MyMesh::fairnessHandleCommand(const char *command, char *reply) {
if (memcmp(command, "fairness", 8) != 0 || (command[8] != 0 && command[8] != ' ')) return false;
if (command[8] == ' ') {
const char *arg = &command[9];
if (strcmp(arg, "on") == 0 || strcmp(arg, "off") == 0) {
_prefs.fairness_enabled = (arg[1] == 'n') ? 1 : 0;
savePrefs();
sprintf(reply, "OK - fairness %s", _prefs.fairness_enabled ? "on" : "off");
} else {
strcpy(reply, "Err - fairness [on|off]");
}
return true;
}
sprintf(reply, "fairness: %s, denied group %u, sender %u, advert %u",
_prefs.fairness_enabled ? "on" : "OFF",
fairness_limiter.deniedGroup(), fairness_limiter.deniedSenderNormal(),
fairness_limiter.deniedSenderLow());
return true;
}
const char *MyMesh::getLogDateTime() {
static char tmp[32];
uint32_t now = getRTCClock()->getCurrentTime();
@@ -1175,6 +1198,7 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
last_millis = 0;
uptime_millis = 0;
next_local_advert = next_flood_advert = 0;
next_fair_sender_normal_refill = next_fair_sender_low_refill = next_fair_group_refill = 0;
dirty_contacts_expiry = 0;
set_radio_at = revert_radio_at = 0;
_logging = false;
@@ -1198,8 +1222,8 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
pktfeed_next_seq = 1; // seq 0 is reserved for "empty slot" / initial cursor
pktfeed_stage_len = 0;
#endif
#ifdef BOT_CHANNEL_PSK
botInit();
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
channelsInit(); // registers the bot channel and/or the filter channels
#endif
// defaults
@@ -1255,6 +1279,12 @@ MyMesh::MyMesh(mesh::MainBoard &board, mesh::Radio &radio, mesh::MillisecondCloc
_prefs.flood_max = 64;
_prefs.flood_max_unscoped = 64;
_prefs.flood_max_advert = 8;
// CUSTOM (TeTeHacko): FairnessLimiter on by default; `fairness off` is the
// runtime kill switch (persisted, so it survives a reboot on the mast).
#ifndef FAIRNESS_ENABLED_DEFAULT
#define FAIRNESS_ENABLED_DEFAULT 1
#endif
_prefs.fairness_enabled = FAIRNESS_ENABLED_DEFAULT;
_prefs.interference_threshold = 0; // disabled
_prefs.cad_enabled = 0; // hardware CAD before TX (off by default; 'set cad on')
_prefs.loop_detect = LOOP_DETECT_MINIMAL;
@@ -1297,6 +1327,15 @@ void MyMesh::begin(FILESYSTEM *fs) {
// load persisted prefs
_cli.loadPrefs(_fs);
acl.load(_fs, self_id);
// Fairness buckets start with just ONE token (not the full cap): a repeater
// stuck in a crash loop must not hand out a fresh burst on every boot.
fairness_limiter.refillSenderNormal();
fairness_limiter.refillSenderLow();
fairness_limiter.refillGroup();
next_fair_sender_normal_refill = futureMillis(FAIRNESS_SENDER_NORMAL_REFILL_MS);
next_fair_sender_low_refill = futureMillis(FAIRNESS_SENDER_LOW_REFILL_MS);
next_fair_group_refill = futureMillis(FAIRNESS_GROUP_REFILL_MS);
// TODO: key_store.begin();
region_map.load(_fs);
@@ -1656,6 +1695,13 @@ void MyMesh::handleCommand(uint32_t sender_timestamp, char *command, char *reply
// CUSTOM (TeTeHacko): `bot` — read-only channel bot diagnostics. See ChannelBot.h.
if (botHandleCommand(command, reply)) return;
#endif
#ifdef FILTER_CHANNEL_PSKS
// CUSTOM (TeTeHacko): `filter add|del|list|clear` — runtime deny list for
// channel messages this repeater refuses to forward. See ChannelFilter.h.
if (filterHandleCommand(command, reply, reply_max)) return;
#endif
// CUSTOM (TeTeHacko): `fairness [on|off]` — forwarding rate limiter stats + kill switch.
if (fairnessHandleCommand(command, reply)) return;
// CUSTOM (TeTeHacko): `blink [n]` — flash the LED to identify this board.
// Outside the BLE guard on purpose: a USB-only build needs it just as much,
// since a board with no data cable and no BLE cannot be identified at all.
@@ -1692,6 +1738,19 @@ void MyMesh::loop() {
mesh::Mesh::loop();
// Fairness limiter refilling. The `else if` chain keeps the three timers from
// aligning on one loop pass; each adds ONE token per bucket per interval.
if (next_fair_sender_normal_refill && millisHasNowPassed(next_fair_sender_normal_refill)) {
fairness_limiter.refillSenderNormal();
next_fair_sender_normal_refill = futureMillis(FAIRNESS_SENDER_NORMAL_REFILL_MS);
} else if (next_fair_sender_low_refill && millisHasNowPassed(next_fair_sender_low_refill)) {
fairness_limiter.refillSenderLow();
next_fair_sender_low_refill = futureMillis(FAIRNESS_SENDER_LOW_REFILL_MS);
} else if (next_fair_group_refill && millisHasNowPassed(next_fair_group_refill)) {
fairness_limiter.refillGroup();
next_fair_group_refill = futureMillis(FAIRNESS_GROUP_REFILL_MS);
}
if (next_flood_advert && millisHasNowPassed(next_flood_advert)) {
mesh::Packet *pkt = createSelfAdvert();
uint32_t delay_millis = 0;
@@ -1733,9 +1792,12 @@ void MyMesh::loop() {
last_millis = now;
}
// CUSTOM (TeTeHacko): channel bot method bodies. Included here, at the very
// CUSTOM (TeTeHacko): channel module method bodies. Included here, at the very
// bottom, so they see the complete MyMesh definition (same convention the Solo
// firmware uses for its own bot).
// firmware uses for its own bot). Order matters: ChannelCommon.h defines the
// helpers (chan_list_has, channelAddFromPsk) the other two use.
#include "ChannelCommon.h"
#include "ChannelFilter.h"
#include "ChannelBot.h"
// To check if there is pending work
+46 -5
View File
@@ -33,6 +33,7 @@
#include <helpers/StaticPoolPacketManager.h>
#include <helpers/StatsFormatHelper.h>
#include <helpers/TxtDataHelpers.h>
#include <helpers/FairnessLimiter.h>
#include <helpers/RegionMap.h>
#include <helpers/RoutingPolicy.h>
#include "RateLimiter.h"
@@ -205,6 +206,10 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
RegionEntry* recv_pkt_region;
TransportKey default_scope;
RateLimiter discover_limiter, anon_limiter;
// CUSTOM (TeTeHacko): token-bucket limiter over FORWARDED traffic (port of
// upstream proposal #1502). Kill switch: _prefs.fairness_enabled.
FairnessLimiter fairness_limiter;
unsigned long next_fair_sender_normal_refill, next_fair_sender_low_refill, next_fair_group_refill;
uint32_t pending_discover_tag;
unsigned long pending_discover_until;
bool region_load_active;
@@ -230,14 +235,27 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
uint8_t pktfeed_stage[MAX_TRANS_UNIT];
uint8_t pktfeed_stage_len; // 0 = nothing staged
#endif
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
// CUSTOM (TeTeHacko): registry of channels this node can DECRYPT (the bot
// channel and/or the filter channels). Shared by ChannelBot.h and
// ChannelFilter.h; fed to searchChannelsByHash(), whose API caps matches at 4.
#define MAX_KNOWN_CHANNELS 4
#define CHAN_FLAG_BOT 0x01 // ChannelBot answers on this channel
#define CHAN_FLAG_FILTER 0x02 // deny list applies to this channel
mesh::GroupChannel known_channels[MAX_KNOWN_CHANNELS];
uint8_t known_channel_flags[MAX_KNOWN_CHANNELS];
uint8_t num_known_channels;
#endif
#ifdef FILTER_CHANNEL_PSKS
uint32_t filter_dropped; // forwards vetoed by the deny list
#endif
#ifdef BOT_CHANNEL_PSK
// Default zde, ne az v ChannelBot.h -- ten se includuje na konci MyMesh.cpp,
// tedy dlouho po teto deklaraci pole.
#ifndef BOT_PEER_SLOTS
#define BOT_PEER_SLOTS 8
#endif
mesh::GroupChannel bot_channel; // 1 B hash + 32 B secret, derived from BOT_CHANNEL_PSK
bool bot_channel_valid; // false = PSK malformed, bot silently off
int8_t bot_channel_idx; // index into known_channels, -1 = PSK malformed, bot silently off
unsigned long bot_next_reply_at; // cooldown gate, 0 = not armed
uint32_t bot_replies_sent;
uint32_t bot_ignored; // zprav zahozenych podle BOT_IGNORE_SENDERS
@@ -275,11 +293,24 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
void commitPktFeed(const mesh::Packet* pkt);
void formatPktFeedReply(char* reply, int max_len, uint32_t cursor);
#endif
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
// CUSTOM (TeTeHacko): shared channel plumbing. Definitions in ChannelCommon.h,
// included at the bottom of MyMesh.cpp.
void channelsInit();
int channelAddFromPsk(const char* psk_hex, int psk_len, uint8_t flag);
void onChannelText(mesh::Packet* packet, int chan_idx, const char* sender, const char* msg);
#endif
#ifdef FILTER_CHANNEL_PSKS
// CUSTOM (TeTeHacko): deny-list forwarding filter. Definitions in ChannelFilter.h.
bool filterDenied(const char* sender) const;
bool filterHandleCommand(const char* command, char* reply, int reply_max);
#endif
#ifdef BOT_CHANNEL_PSK
// CUSTOM (TeTeHacko): channel bot. Definitions in ChannelBot.h, included at
// the bottom of MyMesh.cpp. See that file for why this lives in the analyzer
// build rather than in companion_radio.
void botInit();
void botOnChannelText(mesh::Packet* packet, const char* sender, const char* msg);
bool botTriggerMatches(const char* text) const;
void botFormatPath(char* out, const mesh::Packet* pkt) const;
int botCommandReply(char* out, int max_len, const char* cmd, const mesh::Packet* pkt);
@@ -288,6 +319,8 @@ class MyMesh : public mesh::Mesh, public CommonCLICallbacks {
bool botPeerAllowed(const char* name);
bool botHandleCommand(const char* command, char* reply);
#endif
// CUSTOM (TeTeHacko): `fairness [on|off]` CLI. Defined in MyMesh.cpp.
bool fairnessHandleCommand(const char* command, char* reply);
uint8_t handleLoginReq(const mesh::Identity& sender, const uint8_t* secret, uint32_t sender_timestamp, const uint8_t* data, bool is_flood);
uint8_t handleAnonRegionsReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data);
uint8_t handleAnonOwnerReq(const mesh::Identity& sender, uint32_t sender_timestamp, const uint8_t* data);
@@ -309,15 +342,23 @@ protected:
// Díky tomuhle overridu ji dostanou i volání send*(), která ji nepředávají
// explicitně (ACKy, PATH-return, zerohop odpovědi sousedovi).
uint8_t getSelfPathHashSize() const override { return _prefs.path_hash_mode + 1; }
#ifdef BOT_CHANNEL_PSK
#if defined(BOT_CHANNEL_PSK) || defined(FILTER_CHANNEL_PSKS)
// CUSTOM (TeTeHacko): both are no-op virtuals in mesh::Mesh, which is the only
// reason a repeater is normally deaf to channel traffic. Overriding them does
// NOT affect forwarding -- Mesh::onRecvPacket() calls routeRecvPacket() either
// way (Mesh.cpp:236-249).
// NOT affect forwarding by itself -- Mesh::onRecvPacket() calls routeRecvPacket()
// either way (Mesh.cpp:237-259). The ChannelFilter DOES veto forwarding of
// matched packets, via packet->markDoNotRetransmit() (same mechanism the ANON
// branch uses at Mesh.cpp:229).
int searchChannelsByHash(const uint8_t* hash, mesh::GroupChannel channels[], int max_matches) override;
void onGroupDataRecv(mesh::Packet* packet, uint8_t type, const mesh::GroupChannel& channel,
uint8_t* data, size_t len) override;
#endif
// CUSTOM (TeTeHacko): FairnessLimiter veto. mesh::Mesh consults this as the
// LAST condition of every forward decision, so a token is only taken for a
// packet that would otherwise transmit. Runtime kill switch in prefs.
bool takeForwardingRateLimit(const mesh::Packet* packet) override {
return !_prefs.fairness_enabled || fairness_limiter.allowPacket(packet);
}
const char* getLogDateTime() override;
void logRxRaw(float snr, float rssi, const uint8_t raw[], int len) override;
+13
View File
@@ -19,6 +19,17 @@ extra_configs =
[secrets]
ble_pin = 123456
; CUSTOM (TeTeHacko): channels the ChannelFilter deny list applies to
; (examples/simple_repeater/ChannelFilter.h). These keys are PUBLIC by
; construction, not secrets: hashtag channels derive key = SHA256(name)[:16]
; (anyone joins #meshcore by typing the name), and the Public channel key is
; the globally published izOH6cXN6mrJ5e26oRXNcg==. Derivation verified live
; 5. 9. 2026: SHA256("#meshcore")[:16] hashes to channel byte 0xEF, matching
; the on-air packets. Order: #meshcore, Public, #test.
[channel_filter]
build_flags =
-D FILTER_CHANNEL_PSKS='"2fa78a5aef618e7c2a78f0ab5c8869b3,8b3387e9c5cdea6ac9e5edbaa115cd72,9cd8fcf22a47333b591d96a2b848b73f"'
[arduino_base]
framework = arduino
monitor_speed = 115200
@@ -185,6 +196,7 @@ build_src_filter =
+<../src/Packet.cpp>
+<../src/helpers/ConfigSerializer.cpp>
+<../src/helpers/DynamicConfigSerializer.cpp>
+<../src/helpers/FairnessLimiter.cpp>
lib_deps =
google/googletest @ 1.17.0
@@ -223,6 +235,7 @@ build_src_filter =
+<../src/Packet.cpp>
+<../src/helpers/ConfigSerializer.cpp>
+<../src/helpers/DynamicConfigSerializer.cpp>
+<../src/helpers/FairnessLimiter.cpp>
lib_deps =
google/googletest @ 1.17.0
+11 -6
View File
@@ -11,9 +11,12 @@ void Mesh::loop() {
Dispatcher::loop();
}
bool Mesh::allowPacketForward(const mesh::Packet* packet) {
bool Mesh::allowPacketForward(const mesh::Packet* packet) {
return false; // by default, Transport NOT enabled
}
bool Mesh::takeForwardingRateLimit(const mesh::Packet* packet) {
return true; // by default, rate limiting is not implemented
}
uint32_t Mesh::getRetransmitDelay(const mesh::Packet* packet) {
uint32_t t = (_radio->getEstAirtimeFor(packet->getRawLength()) * 52 / 50) / 2;
@@ -60,7 +63,8 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
if (offset >= len) { // TRACE has reached end of given path
onTraceRecv(pkt, trace_tag, auth_code, flags, pkt->path, &pkt->payload[i], len);
} else if ((size_t)i + offset + (1u << path_sz) <= pkt->payload_len
&& self_id.isHashMatch(&pkt->payload[i + offset], 1 << path_sz) && allowPacketForward(pkt) && !_tables->wasSeen(pkt)) {
&& self_id.isHashMatch(&pkt->payload[i + offset], 1 << path_sz) && allowPacketForward(pkt) && !_tables->wasSeen(pkt)
&& takeForwardingRateLimit(pkt)) {
_tables->markSeen(pkt);
// append SNR (Not hash!)
pkt->path[pkt->path_len++] = (int8_t) (pkt->getSNR()*4);
@@ -103,12 +107,12 @@ DispatcherAction Mesh::onRecvPacket(Packet* pkt) {
return ACTION_RELEASE;
}
if (!_tables->wasSeen(pkt)) {
if (!_tables->wasSeen(pkt) && takeForwardingRateLimit(pkt)) {
_tables->markSeen(pkt);
removeSelfFromPath(pkt);
uint32_t d = getDirectRetransmitDelay(pkt);
return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority
return ACTION_RETRANSMIT_DELAYED(0, d); // Routed traffic is HIGHEST priority
}
}
return ACTION_RELEASE; // this node is NOT the next hop (OR this packet has already been forwarded), so discard.
@@ -355,7 +359,8 @@ void Mesh::removeSelfFromPath(Packet* pkt) {
DispatcherAction Mesh::routeRecvPacket(Packet* packet) {
uint8_t n = packet->getPathHashCount();
if (packet->isRouteFlood() && !packet->isMarkedDoNotRetransmit()
&& (n + 1)*packet->getPathHashSize() <= MAX_PATH_SIZE && allowPacketForward(packet)) {
&& (n + 1)*packet->getPathHashSize() <= MAX_PATH_SIZE && allowPacketForward(packet)
&& takeForwardingRateLimit(packet)) {
// append this node's hash to 'path'
self_id.copyHashTo(&packet->path[n * packet->getPathHashSize()], packet->getPathHashSize());
packet->setPathHashCount(n + 1);
@@ -388,7 +393,7 @@ DispatcherAction Mesh::forwardMultipartDirect(Packet* pkt) {
}
void Mesh::routeDirectRecvAcks(Packet* packet, uint32_t delay_millis) {
if (!packet->isMarkedDoNotRetransmit()) {
if (!packet->isMarkedDoNotRetransmit() && takeForwardingRateLimit(packet)) {
uint8_t extra = getExtraAckTransmitCount();
while (extra > 0) {
delay_millis += getDirectRetransmitDelay(packet) + 300;
+8
View File
@@ -56,6 +56,14 @@ protected:
*/
virtual bool allowPacketForward(const Packet* packet);
/**
* \brief Takes a token from the rate-limiter, deciding whether this packet should be forwarded.
* May CONSUME limiter state, so callers keep it as the LAST condition of a forward decision
* and call it at most once per packet. (CUSTOM TeTeHacko: port of upstream proposal #1502.)
* \returns true, if the packet should be forwarded
*/
virtual bool takeForwardingRateLimit(const Packet* packet);
/**
* \returns number of milliseconds delay to apply to retransmitting the given packet.
*/
+8
View File
@@ -72,6 +72,11 @@ public:
uint8_t loop_detect = 0;
uint8_t cad_enabled = 0; // hardware Channel Activity Detection before TX (boolean)
uint8_t extra_sf[4];
// CUSTOM (TeTeHacko): antispam knobs of simple_repeater. Live here so that the
// existing savePrefs()/loadPrefs() machinery persists them; other examples
// just leave them at defaults.
uint8_t fairness_enabled = 0; // FairnessLimiter runtime kill switch
char filter_deny[128]; // channel-filter deny list, comma-separated node names
private:
class RadioPrefs : public CommonRadioPrefs {
@@ -186,6 +191,8 @@ private:
def("f_max_uns", _parent->flood_max_unscoped);
def("f_max_adv", _parent->flood_max_advert);
def("loop", _parent->loop_detect);
def("fair_en", _parent->fairness_enabled);
def("f_deny", _parent->filter_deny, sizeof(_parent->filter_deny));
}
public:
RepeatPrefs(NodePrefs* parent) : _parent(parent) { }
@@ -231,6 +238,7 @@ public:
guest_password[0] = 0;
bridge_secret[0] = 0;
owner_info[0] = 0;
filter_deny[0] = 0;
}
CommonRadioPrefs* getRadioPrefs() { return &radio; }
+154
View File
@@ -0,0 +1,154 @@
#include "FairnessLimiter.h"
#include <MeshCore.h>
uint8_t FairnessLimiter::peekGroup(const uint8_t* hash) {
auto i = group_idx(hash);
if (i >= GROUP_MAP_SIZE) {
return 0;
}
return group_map[i];
}
bool FairnessLimiter::takeGroup(const uint8_t* hash) {
auto i = group_idx(hash);
bool allow = false;
if (i < GROUP_MAP_SIZE && group_map[i] > 0) {
group_map[i]--;
allow = true;
} else {
denied_group++;
}
MESH_DEBUG_PRINTLN("FAIR, group=%02X allow=%u", (uint32_t)hash[0], (uint32_t)allow);
return allow;
}
void FairnessLimiter::refillGroup() {
for (int i = 0; i < GROUP_MAP_SIZE; i++) {
if (group_map[i] < group_cap) {
group_map[i]++;
}
}
}
uint8_t FairnessLimiter::peekSenderNormal(const uint8_t* hash) {
// Always zero as 0x00 and 0xFF are reserved
if (hash[0] == 0x00 || hash[0] == 0xFF) {
return 0;
}
auto i = sender_normal_idx(hash);
if (i >= SENDER_NORMAL_MAP_SIZE) {
return 0;
}
return sender_normal_map[i];
}
bool FairnessLimiter::takeSenderNormal(const uint8_t* hash) {
// Always false as 0x00 and 0xFF are reserved
if (hash[0] == 0x00 || hash[0] == 0xFF) {
return false;
}
auto i = sender_normal_idx(hash);
bool allow = false;
if (i < SENDER_NORMAL_MAP_SIZE && sender_normal_map[i] > 0) {
sender_normal_map[i]--;
allow = true;
} else {
denied_sender_normal++;
}
MESH_DEBUG_PRINTLN("FAIR, sender=%02X prio=normal allow=%u", (uint32_t)hash[0], (uint32_t)allow);
return allow;
}
void FairnessLimiter::refillSenderNormal() {
for (int i = 0; i < SENDER_NORMAL_MAP_SIZE; i++) {
if (sender_normal_map[i] < sender_normal_cap) {
sender_normal_map[i]++;
}
}
}
uint8_t FairnessLimiter::peekSenderLow(const uint8_t* hash) {
// Always zero as 0x00 and 0xFF are reserved
if (hash[0] == 0x00 || hash[0] == 0xFF) {
return 0;
}
auto i = sender_low_idx(hash);
if (i >= SENDER_LOW_MAP_SIZE) {
return 0;
}
return sender_low_map[i];
}
bool FairnessLimiter::takeSenderLow(const uint8_t* hash) {
// Always false as 0x00 and 0xFF are reserved
if (hash[0] == 0x00 || hash[0] == 0xFF) {
return false;
}
auto i = sender_low_idx(hash);
bool allow = false;
if (i < SENDER_LOW_MAP_SIZE && sender_low_map[i] > 0) {
sender_low_map[i]--;
allow = true;
} else {
denied_sender_low++;
}
MESH_DEBUG_PRINTLN("FAIR, sender=%02X prio=low allow=%u", (uint32_t)hash[0], (uint32_t)allow);
return allow;
}
void FairnessLimiter::refillSenderLow() {
for (int i = 0; i < SENDER_LOW_MAP_SIZE; i++) {
if (sender_low_map[i] < sender_low_cap) {
sender_low_map[i]++;
}
}
}
bool FairnessLimiter::allowPacket(const mesh::Packet* pkt) {
// Don't limit versions we don't understand.
if (pkt->getPayloadVer() != PAYLOAD_VER_1) {
return true;
}
#if FAIRNESS_ALLOW_DIRECT
// Don't limit direct
if (!pkt->isRouteFlood()) {
return true;
}
#endif
uint8_t hash[1] = { 0x00 };
auto type = pkt->getPayloadType();
// Packets by group channel hash
if (type == PAYLOAD_TYPE_GRP_TXT || type == PAYLOAD_TYPE_GRP_DATA) {
if (pkt->payload_len < 1) return true; // malformed, not ours to judge
hash[0] = pkt->payload[0];
return takeGroup(hash);
}
// Packets with a plaintext 1-byte src hash at payload[1] (see Mesh.cpp,
// PAYLOAD_TYPE_PATH/REQ/RESPONSE/TXT_MSG parse: dest_hash, then src_hash)
if (type == PAYLOAD_TYPE_PATH || type == PAYLOAD_TYPE_REQ || type == PAYLOAD_TYPE_RESPONSE ||
type == PAYLOAD_TYPE_TXT_MSG || type == PAYLOAD_TYPE_ANON_REQ) {
if (pkt->payload_len < 2) return true; // malformed, not ours to judge
hash[0] = pkt->payload[1];
return takeSenderNormal(hash);
}
if (type == PAYLOAD_TYPE_ADVERT) {
if (pkt->payload_len < 1) return true; // malformed, not ours to judge
hash[0] = pkt->payload[0]; // first byte of sender pub key
return takeSenderLow(hash);
}
// Not classified (allowed through):
// PAYLOAD_TYPE_ACK, PAYLOAD_TYPE_TRACE, PAYLOAD_TYPE_MULTIPART,
// PAYLOAD_TYPE_CONTROL, PAYLOAD_TYPE_RAW_CUSTOM
return true;
}
+115
View File
@@ -0,0 +1,115 @@
#pragma once
// CUSTOM (TeTeHacko): port of Beanow's "fairness limiter" (upstream proposal
// meshcore-dev/MeshCore#1502, branch beanow/wp-repeat). Token-bucket rate
// limiting of FORWARDED packets, bucketed by the 1-byte identifiers that are
// already in the clear on the air -- so it needs no protocol change and no
// decryption. It is an approximation by design: buckets collide (masks below)
// and every key is sender-controlled, so this is containment of accidental or
// lazy floods, not security. DIRECT (routed) traffic is never limited.
//
// Deviations from Beanow's branch, on purpose:
// * no RTCClock dependency -- it was only feeding log timestamps; logging
// goes through MESH_DEBUG_PRINTLN like the rest of this tree, which also
// lets the class run in native unit tests without a clock mock.
// * allowPacket() bounds-checks payload_len before reading payload bytes.
// The whole CI suite runs under ASAN because of earlier OOB parses; a
// limiter keyed on payload[1] must not be the next one.
#include <Packet.h>
#include <stdint.h>
// For senders 0x00 and 0xFF are reserved (Identity.cpp rejects them as path
// hash prefixes). Group channel hashes are pure sha256, so no reserved values.
// Note: mask, cap and refill interval are highly connected parameters.
#define GROUP_MASK 0b00011111 // 5-bit address
#define SENDER_NORMAL_MASK 0b00111111 // 6-bit address
#define SENDER_LOW_MASK 0b01111111 // 7-bit address
// Refill intervals: ONE token per bucket per interval. Steady-state rate is
// 1/interval, cap bounds the burst. Overridable per env from platformio ini.
#ifndef FAIRNESS_GROUP_REFILL_MS
#define FAIRNESS_GROUP_REFILL_MS (3 * 60 * 1000)
#endif
#ifndef FAIRNESS_SENDER_NORMAL_REFILL_MS
#define FAIRNESS_SENDER_NORMAL_REFILL_MS (4 * 60 * 1000)
#endif
#ifndef FAIRNESS_SENDER_LOW_REFILL_MS
#define FAIRNESS_SENDER_LOW_REFILL_MS (120 * 60 * 1000)
#endif
// Capacity (max burst) per bucket.
#ifndef FAIRNESS_GROUP_CAP
#define FAIRNESS_GROUP_CAP 20
#endif
#ifndef FAIRNESS_SENDER_NORMAL_CAP
#define FAIRNESS_SENDER_NORMAL_CAP 30
#endif
#ifndef FAIRNESS_SENDER_LOW_CAP
#define FAIRNESS_SENDER_LOW_CAP 4
#endif
// Simply allow all direct messages?
#ifndef FAIRNESS_ALLOW_DIRECT
#define FAIRNESS_ALLOW_DIRECT 1
#endif
// Derived from the masks, WONT fit in uint8 when full 0xFF mask.
#define GROUP_MAP_SIZE (GROUP_MASK + 1)
#define SENDER_NORMAL_MAP_SIZE (SENDER_NORMAL_MASK + 1)
#define SENDER_LOW_MAP_SIZE (SENDER_LOW_MASK + 1)
/**
* A token bucket rate limiter, which attempts to limit by sender or group channel.
*
* It provides some mitigation against accidental spam, as well as DoS attacks.
* However it's merely an approximation, as there will be ID collisions and easy
* ways to game it.
*
* Until a V2 protocol provides new means of limiting, the goal is a "better than
* nothing" reduction in wasteful repeats, freeing airtime for useful repeats.
*/
class FairnessLimiter {
// Capacity of when a bucket is full.
uint8_t group_cap = FAIRNESS_GROUP_CAP, sender_normal_cap = FAIRNESS_SENDER_NORMAL_CAP,
sender_low_cap = FAIRNESS_SENDER_LOW_CAP;
// Deny stats
uint32_t denied_group = 0, denied_sender_normal = 0, denied_sender_low = 0;
// Token buckets
uint8_t sender_normal_map[SENDER_NORMAL_MAP_SIZE] = {};
uint8_t sender_low_map[SENDER_LOW_MAP_SIZE] = {};
uint8_t group_map[GROUP_MAP_SIZE] = {};
public:
FairnessLimiter() {}
uint8_t peekGroup(const uint8_t* hash);
void refillGroup();
uint8_t peekSenderNormal(const uint8_t* hash);
void refillSenderNormal();
uint8_t peekSenderLow(const uint8_t* hash);
void refillSenderLow();
/**
* \brief Classify the packet and take a token from the matching bucket.
* CONSUMES a token when one is available -- call it only for a packet that
* would otherwise be forwarded, and only once per packet.
* \returns true if the packet should be forwarded
*/
bool allowPacket(const mesh::Packet* pkt);
// Inspect stats
uint32_t deniedSenderNormal() const { return denied_sender_normal; }
uint32_t deniedSenderLow() const { return denied_sender_low; }
uint32_t deniedGroup() const { return denied_group; }
static int sender_normal_idx(const uint8_t* hash) { return hash[0] & SENDER_NORMAL_MASK; }
static int sender_low_idx(const uint8_t* hash) { return hash[0] & SENDER_LOW_MASK; }
static int group_idx(const uint8_t* hash) { return hash[0] & GROUP_MASK; }
protected:
bool takeSenderNormal(const uint8_t* hash);
bool takeSenderLow(const uint8_t* hash);
bool takeGroup(const uint8_t* hash);
};
+136
View File
@@ -0,0 +1,136 @@
#include <gtest/gtest.h>
// Pure helpers shared by the repeater channel modules (deny list, bot ignore
// list). The header is self-contained on purpose so it compiles natively.
#include "../../examples/simple_repeater/ChanListUtil.h"
// ── chan_list_has: exact, case-insensitive, never substring ──────────────────
TEST(ChanListHas, ExactMatch) {
EXPECT_TRUE(chan_list_has("DandyPDA", "DandyPDA"));
EXPECT_TRUE(chan_list_has("a,DandyPDA,b", "DandyPDA"));
EXPECT_FALSE(chan_list_has("", "DandyPDA"));
EXPECT_FALSE(chan_list_has("DandyPDA", ""));
}
TEST(ChanListHas, CaseInsensitive) {
EXPECT_TRUE(chan_list_has("dandypda", "DandyPDA"));
EXPECT_TRUE(chan_list_has("DANDYPDA", "dandypda"));
}
// "TTH" in the list must not silence "tracker" -- the trap that made the bot's
// ignore list exact-match in the first place.
TEST(ChanListHas, NeverSubstring) {
EXPECT_FALSE(chan_list_has("TTH", "tracker"));
EXPECT_FALSE(chan_list_has("tracker", "TTH"));
}
TEST(ChanListHas, EntriesAreTrimmed) {
EXPECT_TRUE(chan_list_has("a, DandyPDA ,b", "DandyPDA"));
}
TEST(ChanListHas, Utf8NamesMatchByteExact) {
EXPECT_TRUE(chan_list_has("BUBEN \xF0\x9F\xA5\x81", "BUBEN \xF0\x9F\xA5\x81"));
EXPECT_FALSE(chan_list_has("BUBEN \xF0\x9F\xA5\x81", "BUBEN"));
}
// ── chan_list_add ─────────────────────────────────────────────────────────────
TEST(ChanListAdd, AppendsWithComma) {
char list[128] = "";
EXPECT_EQ(chan_list_add(list, sizeof(list), "DandyPDA", 8), CHAN_LIST_OK);
EXPECT_STREQ(list, "DandyPDA");
EXPECT_EQ(chan_list_add(list, sizeof(list), "Foo", 3), CHAN_LIST_OK);
EXPECT_STREQ(list, "DandyPDA,Foo");
}
TEST(ChanListAdd, TrimsSpaces) {
char list[128] = "";
EXPECT_EQ(chan_list_add(list, sizeof(list), " DandyPDA ", 12), CHAN_LIST_OK);
EXPECT_STREQ(list, "DandyPDA");
}
TEST(ChanListAdd, NamesMayContainSpaces) {
char list[128] = "";
EXPECT_EQ(chan_list_add(list, sizeof(list), "Dejv Bobry mobile", 17), CHAN_LIST_OK);
EXPECT_TRUE(chan_list_has(list, "Dejv Bobry mobile"));
}
TEST(ChanListAdd, RejectsBadNames) {
char list[16] = "";
EXPECT_EQ(chan_list_add(list, sizeof(list), "", 0), CHAN_LIST_BAD_NAME);
EXPECT_EQ(chan_list_add(list, sizeof(list), " ", 3), CHAN_LIST_BAD_NAME);
EXPECT_EQ(chan_list_add(list, sizeof(list), "a,b", 3), CHAN_LIST_BAD_NAME);
char longname[CHAN_NAME_MAX + 8];
memset(longname, 'x', sizeof(longname));
EXPECT_EQ(chan_list_add(list, sizeof(list), longname, CHAN_NAME_MAX), CHAN_LIST_BAD_NAME);
EXPECT_STREQ(list, ""); // nothing leaked in
}
TEST(ChanListAdd, RejectsDuplicatesCaseInsensitively) {
char list[128] = "DandyPDA";
EXPECT_EQ(chan_list_add(list, sizeof(list), "dandypda", 8), CHAN_LIST_DUP);
EXPECT_STREQ(list, "DandyPDA");
}
TEST(ChanListAdd, RefusesWhenFull) {
char list[12] = "0123456789"; // 10 chars used, cap 12
EXPECT_EQ(chan_list_add(list, sizeof(list), "ab", 2), CHAN_LIST_FULL);
EXPECT_STREQ(list, "0123456789");
// exactly fitting entry is fine: 10 + comma + 0 chars is the edge below
char list2[13] = "0123456789";
EXPECT_EQ(chan_list_add(list2, sizeof(list2), "a", 1), CHAN_LIST_OK);
EXPECT_STREQ(list2, "0123456789,a");
}
// ── chan_list_del ─────────────────────────────────────────────────────────────
TEST(ChanListDel, RemovesMiddleEntry) {
char list[128] = "a,DandyPDA,b";
EXPECT_TRUE(chan_list_del(list, "DandyPDA"));
EXPECT_STREQ(list, "a,b");
}
TEST(ChanListDel, RemovesOnlyEntry) {
char list[128] = "DandyPDA";
EXPECT_TRUE(chan_list_del(list, "DandyPDA"));
EXPECT_STREQ(list, "");
}
TEST(ChanListDel, RemovesFirstAndLast) {
char list[128] = "a,b,c";
EXPECT_TRUE(chan_list_del(list, "a"));
EXPECT_STREQ(list, "b,c");
EXPECT_TRUE(chan_list_del(list, "c"));
EXPECT_STREQ(list, "b");
}
TEST(ChanListDel, CaseInsensitive) {
char list[128] = "DandyPDA";
EXPECT_TRUE(chan_list_del(list, "DANDYPDA"));
EXPECT_STREQ(list, "");
}
TEST(ChanListDel, AbsentEntryLeavesListAlone) {
char list[128] = "a,b";
EXPECT_FALSE(chan_list_del(list, "c"));
EXPECT_STREQ(list, "a,b");
}
// ── round trip: what add put in, has finds and del removes ───────────────────
TEST(ChanList, RoundTrip) {
char list[128] = "";
ASSERT_EQ(chan_list_add(list, sizeof(list), "DandyPDA", 8), CHAN_LIST_OK);
ASSERT_EQ(chan_list_add(list, sizeof(list), "honzaa\xF0\x9F\x98\x9B", 10), CHAN_LIST_OK);
EXPECT_TRUE(chan_list_has(list, "DandyPDA"));
EXPECT_TRUE(chan_list_has(list, "honzaa\xF0\x9F\x98\x9B"));
EXPECT_TRUE(chan_list_del(list, "DandyPDA"));
EXPECT_FALSE(chan_list_has(list, "DandyPDA"));
EXPECT_TRUE(chan_list_has(list, "honzaa\xF0\x9F\x98\x9B"));
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
@@ -0,0 +1,147 @@
#include <gtest/gtest.h>
#include "helpers/FairnessLimiter.h"
using namespace mesh;
// PAYLOAD_VER_1 = 0, so a plain route|type header is already version 1.
static Packet makePacket(uint8_t route, uint8_t type, std::initializer_list<uint8_t> payload) {
Packet p;
p.header = route | (type << PH_TYPE_SHIFT);
p.payload_len = 0;
for (uint8_t b : payload) p.payload[p.payload_len++] = b;
p.path_len = 0;
return p;
}
// ── classification ───────────────────────────────────────────────────────────
TEST(FairnessLimiter, DirectIsNeverLimited) {
FairnessLimiter fl; // zero tokens everywhere (no refill yet)
Packet p = makePacket(ROUTE_TYPE_DIRECT, PAYLOAD_TYPE_TXT_MSG, {0x10, 0x22});
for (int i = 0; i < 100; i++) EXPECT_TRUE(fl.allowPacket(&p));
EXPECT_EQ(fl.deniedSenderNormal(), 0u);
}
TEST(FairnessLimiter, UnclassifiedTypesAllowedThrough) {
FairnessLimiter fl; // zero tokens: if these were classified, they'd deny
Packet ack = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_ACK, {1, 2, 3, 4});
EXPECT_TRUE(fl.allowPacket(&ack));
EXPECT_EQ(fl.deniedGroup() + fl.deniedSenderNormal() + fl.deniedSenderLow(), 0u);
}
TEST(FairnessLimiter, MalformedShortPayloadAllowedThrough) {
FairnessLimiter fl;
Packet grp = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, {});
EXPECT_TRUE(fl.allowPacket(&grp)); // no payload[0] to read
Packet txt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_TXT_MSG, {0x10});
EXPECT_TRUE(fl.allowPacket(&txt)); // no payload[1] to read
EXPECT_EQ(fl.deniedGroup() + fl.deniedSenderNormal(), 0u);
}
// ── group bucket (GRP_TXT keyed by payload[0] = channel hash) ────────────────
TEST(FairnessLimiter, GroupBucketDrainsThenDenies) {
FairnessLimiter fl;
fl.refillGroup(); // 1 token per bucket
Packet p = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, {0xEF, 0, 0});
EXPECT_TRUE(fl.allowPacket(&p)); // consumes the single token
EXPECT_FALSE(fl.allowPacket(&p)); // bucket empty
EXPECT_EQ(fl.deniedGroup(), 1u);
}
TEST(FairnessLimiter, GroupRefillRestoresOneToken) {
FairnessLimiter fl;
fl.refillGroup();
Packet p = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, {0xEF, 0, 0});
EXPECT_TRUE(fl.allowPacket(&p));
EXPECT_FALSE(fl.allowPacket(&p));
fl.refillGroup();
EXPECT_TRUE(fl.allowPacket(&p));
EXPECT_FALSE(fl.allowPacket(&p));
}
TEST(FairnessLimiter, GroupCapBoundsTheBurst) {
FairnessLimiter fl;
for (int i = 0; i < 10 * FAIRNESS_GROUP_CAP; i++) fl.refillGroup();
Packet p = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, {0xEF, 0, 0});
int allowed = 0;
for (int i = 0; i < 10 * FAIRNESS_GROUP_CAP; i++) {
if (fl.allowPacket(&p)) allowed++;
}
EXPECT_EQ(allowed, FAIRNESS_GROUP_CAP);
}
// The masks make collisions expected: 0xEF and 0xEF^0x20 share a 5-bit bucket,
// while 0xEE does not. This documents the approximation, it is not a bug.
TEST(FairnessLimiter, GroupBucketsCollideOnMask) {
FairnessLimiter fl;
fl.refillGroup();
Packet a = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, {0xEF, 0, 0});
Packet b = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, {(uint8_t)(0xEF ^ 0x20), 0, 0});
Packet c = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, {0xEE, 0, 0});
EXPECT_TRUE(fl.allowPacket(&a));
EXPECT_FALSE(fl.allowPacket(&b)); // same bucket as a
EXPECT_TRUE(fl.allowPacket(&c)); // its own bucket
}
// ── sender-normal bucket (TXT_MSG etc. keyed by payload[1] = 1 B src hash) ───
TEST(FairnessLimiter, SenderBucketKeysOnSrcHash) {
FairnessLimiter fl;
fl.refillSenderNormal();
// dest 0x10 src 0x22 vs dest 0x99 src 0x22: SAME sender, same bucket
Packet a = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_TXT_MSG, {0x10, 0x22, 0, 0});
Packet b = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_TXT_MSG, {0x99, 0x22, 0, 0});
EXPECT_TRUE(fl.allowPacket(&a));
EXPECT_FALSE(fl.allowPacket(&b));
EXPECT_EQ(fl.deniedSenderNormal(), 1u);
}
TEST(FairnessLimiter, ReservedSenderHashesAlwaysDeny) {
FairnessLimiter fl;
for (int i = 0; i < 5; i++) fl.refillSenderNormal();
Packet z = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_TXT_MSG, {0x10, 0x00, 0, 0});
Packet f = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_TXT_MSG, {0x10, 0xFF, 0, 0});
EXPECT_FALSE(fl.allowPacket(&z)); // 0x00 reserved (Identity.cpp:56)
EXPECT_FALSE(fl.allowPacket(&f)); // 0xFF reserved
}
// ── advert bucket (keyed by payload[0] = pubkey first byte) ──────────────────
TEST(FairnessLimiter, AdvertBucketIsSeparateFromGroupBucket) {
FairnessLimiter fl;
fl.refillSenderLow();
// no group refill: a GRP_TXT with the same first byte must NOT be allowed
// via the advert bucket, and the advert must not touch the group counter.
Packet adv = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_ADVERT, {0x42, 0, 0});
Packet grp = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, {0x42, 0, 0});
EXPECT_TRUE(fl.allowPacket(&adv));
EXPECT_FALSE(fl.allowPacket(&grp));
EXPECT_EQ(fl.deniedSenderLow(), 0u);
EXPECT_EQ(fl.deniedGroup(), 1u);
}
TEST(FairnessLimiter, AdvertCapIsLow) {
FairnessLimiter fl;
for (int i = 0; i < 100; i++) fl.refillSenderLow();
Packet adv = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_ADVERT, {0x42, 0, 0});
int allowed = 0;
for (int i = 0; i < 100; i++) {
if (fl.allowPacket(&adv)) allowed++;
}
EXPECT_EQ(allowed, FAIRNESS_SENDER_LOW_CAP);
}
// ── transport-flood route is a flood too ─────────────────────────────────────
TEST(FairnessLimiter, TransportFloodIsLimitedLikeFlood) {
FairnessLimiter fl; // zero tokens
Packet p = makePacket(ROUTE_TYPE_TRANSPORT_FLOOD, PAYLOAD_TYPE_GRP_TXT, {0xEF, 0, 0});
EXPECT_FALSE(fl.allowPacket(&p));
EXPECT_EQ(fl.deniedGroup(), 1u);
}
int main(int argc, char** argv) {
::testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}
+3
View File
@@ -98,6 +98,9 @@ build_flags =
; are ~3-4 min apart: 64 records ≈ 10+ min of typical traffic buys margin for
; busy evenings; drop detection via the E-trailer catches any overflow.
-D PKTFEED_SIZE=64
; Antispam deny list on the community channels (ChannelFilter.h); the keys in
; [channel_filter] are public by construction. Runtime: `filter add <name>`.
${channel_filter.build_flags}
; -D MESH_PACKET_LOGGING=1
build_src_filter = ${SenseCap_Solar.build_src_filter}
+<../examples/simple_repeater/*.cpp>