diff --git a/FILTER.md b/FILTER.md index 54ee60ad..6a717808 100644 --- a/FILTER.md +++ b/FILTER.md @@ -128,6 +128,16 @@ Content rules match against a store of named channels and their keys: - Deleting a channel keeps existing rules working (their references are updated; the deleted channel simply no longer matches). +**The store is not the rule list.** Rules reference store entries by index and +never own them: deleting a rule (or `filter clear`) leaves auto-added channels +in place, so a `#name` channel created by the shorthand can outlive the rule +that created it. That is usually harmless — a stored channel is also offered +for decryption while the filter is on — but the store holds a hard maximum of +16 entries no matter how few rules use them. When it is full, new `chan=#...` +references are rejected with `Err - chan store full` until you free a slot with +`filter chan del `; candidates can be found by comparing `filter chan +list` against the `chan=` lines of `filter get `. + While the filter is enabled, group payloads on any stored channel are offered for decryption — so a keyed channel rule doubles as an implicit "decrypt this channel" registration, letting content rules fire on channels the repeater @@ -202,7 +212,11 @@ All commands begin with `filter`. Replies are short (the remote CLI reply buffer ### `filter add` predicate keys Space-separated `key=value` tokens. Multiple values inside one key use commas -(`type=advert,txt`, `chan=#a,#b`, `hsize=1,2`). +(`type=advert,txt`, `chan=#a,#b`, `hsize=1,2`). Values containing spaces must be +wrapped in double quotes: `text="^RX in place"` (alternatively, `\s` matches a +literal space: `text="^RX\sin\splace"`). Quote characters are stripped by the +CLI tokenizer, so a pattern cannot contain a literal `"` (an odd number of +quotes is rejected) — work around one with `.` if a message text ever includes it. | Key | Values | Matches | |---|---|---| @@ -243,6 +257,9 @@ filter add type=advert path=^A1B2C3 action=drop # Drop group text on Public whose text looks like a flood of test beacons filter add chan=Public text=^BEACON action=drop +# Drop an auto-reply bot's beacon: sender AND text must both match +filter add chan=#test sender=^SpamBot text="^RX in place" action=drop + # Damp Direct-of-motion chatter: only very long payloads on flood routes filter add route=flood len=[180,*] action=drop @@ -294,6 +311,9 @@ filter add chan=#local,#weather sender=^BotName$ action=drop # substring match instead of exact: filter add chan=#local,#weather sender=BotName action=drop + +# predicates combine (AND): match the sender AND the message text +filter add chan=#local sender=^BotName$ text="^RX in place" action=drop ``` ### 8.4 Shadow mode before enforcement diff --git a/examples/simple_repeater/BatteryGate.cpp b/examples/simple_repeater/BatteryGate.cpp index 527088c6..8787185b 100644 --- a/examples/simple_repeater/BatteryGate.cpp +++ b/examples/simple_repeater/BatteryGate.cpp @@ -1,6 +1,7 @@ // BatteryGate.cpp — see BatteryGate.h for the design overview. #include "BatteryGate.h" +#include "CliUtil.h" #define BATT_CFG_FILE "/batt_cfg" #define BATT_CFG_VERSION 1 @@ -141,30 +142,6 @@ void BatteryGate::save(FILESYSTEM* fs) { // ---------------------------------------------------------------- CLI -static char* nextToken(char** p) { - char* s = *p; - while (*s == ' ') s++; - if (*s == 0) { *p = s; return NULL; } - char* t = s; - while (*s && *s != ' ') s++; - if (*s) { *s = 0; s++; } - *p = s; - return t; -} - -// bounded reply append (CLI reply buffer is 160 bytes) -static void radd(char** out, int* remain, const char* fmt, ...) { - if (*remain <= 0) return; - va_list ap; - va_start(ap, fmt); - int n = vsnprintf(*out, *remain, fmt, ap); - va_end(ap); - if (n < 0) { *remain = 0; return; } - if (n >= *remain) { *out += *remain - 1; *remain = 0; return; } - *out += n; - *remain -= n; -} - static bool parseMilliVolts(const char* tok, bool* numeric, uint16_t* out) { *numeric = false; if (tok == NULL || tok[0] == 0) return false; diff --git a/examples/simple_repeater/CliUtil.h b/examples/simple_repeater/CliUtil.h new file mode 100644 index 00000000..769794f3 --- /dev/null +++ b/examples/simple_repeater/CliUtil.h @@ -0,0 +1,51 @@ +// CliUtil.h — small helpers shared by the simple_repeater fork's CLI command +// handlers (filter, battery, and future ones). Fork-owned code; keeping the +// tokenizer and the reply writer in one place guarantees every CLI parses +// input and builds replies identically. +// +// nextToken() and radd() were previously duplicated (and had diverged) in +// PacketFilter.cpp and BatteryGate.cpp — new CLI helpers belong here instead. + +#ifndef _CLI_UTIL_H +#define _CLI_UTIL_H + +#include +#include + +// split the next space-separated token off in place; spaces inside double +// quotes stay part of the token and the quote characters themselves are +// stripped (callers taking regex values reject an odd quote count for a +// clean error instead of silently swallowing the tokens that follow) +inline char* nextToken(char** p) { + char* s = *p; + while (*s == ' ') s++; + if (*s == 0) { *p = s; return NULL; } + char* t = s; + bool inQ = false; + char* w = s; + while (*s) { + if (*s == '"') { inQ = !inQ; s++; continue; } + if (*s == ' ' && !inQ) break; + *w++ = *s++; + } + // skip the delimiter before terminating, so *s still holds the original byte + if (*s) s++; + *w = 0; + *p = s; + return t; +} + +// bounded reply append (CLI reply buffer is 160 bytes) +inline void radd(char** out, int* remain, const char* fmt, ...) { + if (*remain <= 0) return; + va_list ap; + va_start(ap, fmt); + int n = vsnprintf(*out, *remain, fmt, ap); + va_end(ap); + if (n < 0) { *remain = 0; return; } + if (n >= *remain) { *out += *remain - 1; *remain = 0; return; } + *out += n; + *remain -= n; +} + +#endif diff --git a/examples/simple_repeater/PacketFilter.cpp b/examples/simple_repeater/PacketFilter.cpp index f7271844..0ed7114b 100644 --- a/examples/simple_repeater/PacketFilter.cpp +++ b/examples/simple_repeater/PacketFilter.cpp @@ -2,6 +2,7 @@ // See PacketFilter.h for the rule model. #include "PacketFilter.h" +#include "CliUtil.h" #include static int hexVal(char c) { @@ -531,30 +532,6 @@ void FilterRules::save(FILESYSTEM* fs) { // ---------------------------------------------------------------- CLI -static char* nextToken(char** p) { - char* s = *p; - while (*s == ' ') s++; - if (*s == 0) { *p = s; return NULL; } - char* t = s; - while (*s && *s != ' ') s++; - if (*s) { *s = 0; s++; } - *p = s; - return t; -} - -// bounded reply append (CLI reply buffer is 160 bytes) -static void radd(char** out, int* remain, const char* fmt, ...) { - if (*remain <= 0) return; - va_list ap; - va_start(ap, fmt); - int n = vsnprintf(*out, *remain, fmt, ap); - va_end(ap); - if (n < 0) { *remain = 0; return; } - if (n >= *remain) { *out += *remain - 1; *remain = 0; return; } - *out += n; - *remain -= n; -} - // interval value: hops/len = unsigned decimal; snr = signed dB (snapped to the // quarter-dB grid, stored as quarter-dB int) static bool parseIvNum(const char* s, bool snr_mode, uint16_t* out) { @@ -704,12 +681,19 @@ static bool addRuleParam(FilterRules& filter, FilterRule* r, RegionMap* regions, char* np = names; char* nm; while ((nm = strsep(&np, ",")) != NULL) { - if (nm[0] == 0) { strcpy(reply, "Err - empty chan name"); return false; } + if (nm[0] == 0 || (nm[0] == '#' && nm[1] == 0)) { strcpy(reply, "Err - empty chan name"); return false; } FilterChannel* ch = filter.findChannel(nm); if (ch == NULL && nm[0] == '#') { ch = filter.addChannel(nm, NULL); // auto-provision '#' names with derived PSK } - if (ch == NULL) { sprintf(reply, "Err - unknown chan '%s'", nm); return false; } + if (ch == NULL) { + if (nm[0] == '#' && filter.getNumChannels() >= FILTER_MAX_CHANNELS) { + strcpy(reply, "Err - chan store full"); + } else { + sprintf(reply, "Err - unknown chan '%s'", nm); + } + return false; + } int idx = ch - filter.getChannel(0); r->chan_mask |= (1 << idx); r->chan_flags |= FILTER_CHANFLG_MASK_SET; @@ -805,6 +789,7 @@ static bool addRuleParam(FilterRules& filter, FilterRule* r, RegionMap* regions, return true; } if (strcmp(key, "sender") == 0) { + if (val[0] == 0) { strcpy(reply, "Err - empty regex"); return false; } // matches everything if (!setPattern(r->sender, FILTER_SENDER_PATTERN_LEN, val)) { strcpy(reply, "Err - bad/long sender regex"); return false; @@ -812,6 +797,7 @@ static bool addRuleParam(FilterRules& filter, FilterRule* r, RegionMap* regions, return true; } if (strcmp(key, "text") == 0) { + if (val[0] == 0) { strcpy(reply, "Err - empty regex"); return false; } // matches everything if (!setPattern(r->text, FILTER_TEXT_PATTERN_LEN, val)) { strcpy(reply, "Err - bad/long text regex"); return false; @@ -865,6 +851,7 @@ static void cliChanAdd(FilterRules& filter, char* params, char* reply) { char* psk = nextToken(&p); if (name == NULL) { strcpy(reply, "Err - usage: filter chan add []"); return; } if (strlen(name) >= FILTER_CHAN_NAME_LEN) { strcpy(reply, "Err - name too long"); return; } + if (name[0] == '#' && name[1] == 0) { strcpy(reply, "Err - empty chan name"); return; } if (filter.findChannel(name) != NULL) { strcpy(reply, "Err - channel exists"); return; } if ((psk == NULL || psk[0] == 0) && name[0] != '#') { strcpy(reply, "Err - psk required for non-# names"); @@ -887,6 +874,11 @@ static void cliChanDel(FilterRules& filter, char* params, char* reply) { } static void cliAdd(FilterRules& filter, RegionMap* regions, char* params, char* reply) { + // an odd quote count would silently swallow the tokens that follow + int quotes = 0; + for (const char* s = params; *s; s++) if (*s == '"') quotes++; + if (quotes & 1) { strcpy(reply, "Err - unbalanced quotes"); return; } + FilterRule* r = filter.addRule(); if (r == NULL) { strcpy(reply, "Err - rule list full"); return; } int idx = filter.getNumRules() - 1; @@ -966,8 +958,14 @@ static void cliGet(FilterRules& filter, int idx, char* reply) { } if (r->chan_flags & FILTER_CHANFLG_HASH_SET) radd(&out, &remain, " chanhash=%02X", r->chan_hash); if (r->regions[0]) radd(&out, &remain, " region=%s", r->regions); - if (r->sender[0]) radd(&out, &remain, " sender=%s", r->sender); - if (r->text[0]) radd(&out, &remain, " text=%s", r->text); + if (r->sender[0]) { + if (strchr(r->sender, ' ')) radd(&out, &remain, " sender=\"%s\"", r->sender); + else radd(&out, &remain, " sender=%s", r->sender); + } + if (r->text[0]) { + if (strchr(r->text, ' ')) radd(&out, &remain, " text=\"%s\"", r->text); + else radd(&out, &remain, " text=%s", r->text); + } radd(&out, &remain, " hits=%lu", (unsigned long)r->hits); } @@ -983,7 +981,7 @@ static void cliStats(FilterRules& filter, char* reply) { } static bool cliRuleIdx(FilterRules& filter, char* arg, int& idx, char* reply) { - if (arg == NULL || arg[0] == 0) { strcpy(reply, "Err - rule index required"); return false; } + if (arg == NULL || arg[0] < '0' || arg[0] > '9') { strcpy(reply, "Err - rule index required"); return false; } idx = atoi(arg); if (idx < 0 || idx >= filter.getNumRules()) { strcpy(reply, "Err - no such rule"); return false; } return true; @@ -1043,7 +1041,7 @@ void filterCLI(FilterRules& filter, const char* command, char* reply, RegionMap* } } else if (strcmp(cmd, "clear") == 0) { filter.clearRules(); - strcpy(reply, "OK - rules cleared"); + strcpy(reply, "OK - rules cleared (chans kept)"); } else if (strcmp(cmd, "ratelimit") == 0) { char* sub = nextToken(&p); if (sub == NULL) { diff --git a/test/test_packet_filter/test_packet_filter.cpp b/test/test_packet_filter/test_packet_filter.cpp index 0231eff6..41e17d1a 100644 --- a/test/test_packet_filter/test_packet_filter.cpp +++ b/test/test_packet_filter/test_packet_filter.cpp @@ -1151,6 +1151,37 @@ TEST_F(FilterTest, AddSenderAndTextPatterns) { EXPECT_STREQ(filter.getRule(0)->text, "^BEACON"); } +TEST_F(FilterTest, AddQuotedTextWithSpaces) { + expectOk(filter, "add text=\"^RX in place\""); + EXPECT_STREQ(filter.getRule(0)->text, "^RX in place"); + auto payload = makeGroupText("Alice", "RX in place now"); + auto pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, payload.len); + auto chan = channelFromStore(filter, 0); + EXPECT_EQ(filter.checkContent(&pkt, PAYLOAD_TYPE_GRP_TXT, chan, payload.data, + payload.len, nullptr), + FILTER_ACT_DROP); +} + +TEST_F(FilterTest, SenderAndTextPredicatesCombine) { + expectOk(filter, "add sender=^SpamBot text=\"^RX in place\""); + auto chan = channelFromStore(filter, 0); + auto pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, 20); + auto hit = makeGroupText("SpamBot", "RX in place"); + EXPECT_EQ(filter.checkContent(&pkt, PAYLOAD_TYPE_GRP_TXT, chan, hit.data, + hit.len, nullptr), + FILTER_ACT_DROP); + auto wrongSender = makeGroupText("OtherGuy", "RX in place"); + EXPECT_EQ(filter.checkContent(&pkt, PAYLOAD_TYPE_GRP_TXT, chan, wrongSender.data, + wrongSender.len, nullptr), + FILTER_ACT_ALLOW); +} + +TEST_F(FilterTest, GetQuotesValuesContainingSpaces) { + expectOk(filter, "add sender=^SpamBot text=\"^RX in place\""); + EXPECT_NE(cli(filter, "get 0").find("sender=^SpamBot text=\"^RX in place\""), + std::string::npos); +} + TEST_F(FilterTest, AddLogOnlyAction) { expectOk(filter, "add sender=x action=logonly"); EXPECT_EQ(filter.getRule(0)->action, FILTER_ACT_LOG_ONLY); @@ -1177,6 +1208,11 @@ TEST_F(FilterTest, AddRejectsBadValues) { { "add region=Nowhere", "Err - unknown region" }, { "add action=ban", "Err - action must be drop|logonly" }, { "add sender=[a", "Err - bad/long sender regex" }, // compile check rejects + { "add text=[a", "Err - bad/long text regex" }, // compile check rejects + { "add text=", "Err - empty regex" }, // empty regex matches everything + { "add sender=", "Err - empty regex" }, + { "add chan=#", "Err - empty chan name" }, // bare '#' = empty hashtag + { "add text=\"unterminated", "Err - unbalanced quotes" }, }; for (auto& c : cases) { EXPECT_EQ(cli(filter, c.cmd).find(c.err_fragment), 0) << c.cmd; @@ -1196,6 +1232,19 @@ TEST_F(FilterTest, AddRejectsWhenFull) { EXPECT_EQ(cli(filter, "add type=advert"), "Err - rule list full"); } +TEST_F(FilterTest, RuleIdxRejectsNonNumeric) { + expectOk(filter, "add type=advert"); + EXPECT_EQ(cli(filter, "get abc").substr(0, 5), "Err -"); // atoi() would silently pick rule 0 + EXPECT_EQ(cli(filter, "disable abc").substr(0, 5), "Err -"); + EXPECT_EQ(cli(filter, "enable 1x").substr(0, 5), "Err -"); + EXPECT_EQ(filter.getRule(0)->enabled, true); // untouched by the rejects +} + +TEST_F(FilterTest, ChanAddRejectsBareHash) { + EXPECT_EQ(cli(filter, "chan add #"), "Err - empty chan name"); + EXPECT_EQ(cli(filter, "chan add"), "Err - usage: filter chan add []"); +} + // ---------------------------------------------------------------- rule bookkeeping TEST_F(FilterTest, GetEnableDisableDelClear) { @@ -1215,7 +1264,7 @@ TEST_F(FilterTest, GetEnableDisableDelClear) { EXPECT_EQ(cli(filter, "del 0"), "OK - rule 0 deleted"); EXPECT_EQ(filter.getNumRules(), 1); - EXPECT_EQ(cli(filter, "clear"), "OK - rules cleared"); + EXPECT_EQ(cli(filter, "clear"), "OK - rules cleared (chans kept)"); EXPECT_EQ(filter.getNumRules(), 0); } @@ -1266,6 +1315,15 @@ TEST_F(FilterTest, ChanStoreFull) { EXPECT_EQ(cli(filter, "chan add #onemore"), "Err - bad psk or store full"); } +TEST_F(FilterTest, AddChanAutoProvisionStoreFull) { + // Public + 15 more fills the 16-slot store; auto-provision must report the + // real reason, not "unknown chan" + for (int i = 0; i < FILTER_MAX_CHANNELS - 1; i++) { + ASSERT_EQ(cli(filter, ("chan add #full" + std::to_string(i)).c_str()).substr(0, 3), "OK "); + } + EXPECT_EQ(cli(filter, "add chan=#overflow"), "Err - chan store full"); +} + TEST_F(FilterTest, ChanDelRemapsRuleMasks) { expectOk(filter, "chan add #a"); expectOk(filter, "chan add #b");