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;