mirror of
https://github.com/jhuebert/MeshCore.git
synced 2026-12-03 10:54:13 +00:00
fix(filter,battery): refuse malformed commands instead of half-applying them
A typo'd tail was silently ignored while the command still replied OK: `filter off junk`, `del 0 junk`, `move 0 1 junk`, `ratelimit advert 48 junk` and `battery off junk` all reported success. That is the worst failure mode a management command has — the operator cannot tell whether the command did what they meant, or something else, or nothing. Every command form now refuses a trailing token with its own usage line, checked BEFORE any side effect, via one shared cliNoExtra() helper rather than a copy per command. An unbalanced quote is an error on every form, not just `filter add`, because the tokenizer would otherwise swallow the rest of the line into one value. An over-long command is refused whole: truncating it and acting on the prefix is safe memory but not safe policy — a cut `chan add` would store a mangled name. parseIntRange() now also checks ERANGE and leaves its output untouched on failure, so a rejected number cannot leave a stale one behind. `filter chan list <start-idx>` lets a full 16-channel store be walked: the reply cannot fit them all, and `chan del` takes a NAME, so a channel cut off by the reply buffer could neither be seen nor reliably removed. A truncated listing now ends with `next=N`; entries are only ever appended whole, and the bare listing keeps its old format whenever everything fits. `filter stats reset` exposes the resetStats() that already existed and had no CLI route. Counters go: per-rule hits, airtime, limiter drops, regex aborts. Rate state does NOT: throttle_seen/throttle_last_ms survive, so a stats reset cannot hand a throttled rule a free pass. Advert history is history, not a counter, and is kept. 375 cases green across all four native envs, 321 clean under sanitizers, firmware compiles.
This commit is contained in:
1 parent
2ee4d29fce
commit
8d37899cae
5 files changed
+310
-37
No files matched your search
@@ -234,12 +234,14 @@ admin (see [Managing the repeater remotely](#managing-the-repeater-remotely)).
|
||||
| `filter on` / `filter off` | Enable/disable the whole filter (rules are kept) |
|
||||
| `filter add <cond>=<val> ...` | Add a rule (space-separated conditions, see [What you can match on](#what-you-can-match-on)) |
|
||||
| `filter list` | One line per rule, e.g. `on 1/16: 0eDBE9` — see below for how to read it |
|
||||
| `filter stats` | Totals: limiter drops, regex aborts, airtime saved, and a per-rule hit count |
|
||||
| `filter stats reset` | Zero the counters above (per-rule hits, airtime saved, limiter drops, regex aborts). Rate state is **not** reset: a throttled rule gets no free pass, and advert history is kept |
|
||||
| `filter get <idx>` | Full detail of one rule, including its `throttle=`/`pass=` rate gate, hit count and saved-airtime stat |
|
||||
| `filter enable <idx>` / `filter disable <idx>` | Toggle a single rule |
|
||||
| `filter move <from> <to>` | Move a rule so it ends up **at** index `<to>` (the rules in between shift; hit counters travel with the rule) |
|
||||
| `filter del <idx>` | Delete a rule (later rules shift down one index) |
|
||||
| `filter clear` | Delete all rules (channels and ratelimit are kept) |
|
||||
| `filter chan` / `filter chan list` | List the stored channels |
|
||||
| `filter chan` / `filter chan list [<start-idx>]` | List the stored channels. A full store does not fit one reply, so a cut-off listing ends with `next=N`; repeat the command with that index to see the rest |
|
||||
| `filter chan add <name> [<psk-hex>]` | Add a channel; key optional for `#` names, 32 or 64 hex digits |
|
||||
| `filter chan del <name>` | Remove a channel (existing rules are updated) |
|
||||
| `filter ratelimit` | Show the advert ratelimit window and cache usage |
|
||||
@@ -1001,6 +1003,8 @@ filter get 0
|
||||
filter stats
|
||||
```
|
||||
|
||||
| Typo in a command did nothing | Nothing is ignored any more: a command with an unexpected extra word, unbalanced quotes, or an over-long line is refused with a usage line and changes nothing |
|
||||
| A channel is missing from `filter chan list` | The store holds more than fits one reply — the listing ends with `next=N`; run `filter chan list N` for the rest |
|
||||
| Symptom | Check |
|
||||
|---|---|
|
||||
| Rule gets no hits | Is the filter on (`filter on`)? Is the rule enabled? Did an earlier rule match first? |
|
||||
|
||||
@@ -206,14 +206,19 @@ static void cliStatus(BatteryGate& gate, mesh::MainBoard& board, char* reply) {
|
||||
}
|
||||
|
||||
void batteryCLI(BatteryGate& gate, mesh::MainBoard& board, const char* command, char* reply) {
|
||||
// Refused whole rather than acted on as a prefix, and unbalanced quotes are an
|
||||
// error rather than a silent misparse — both checked before anything changes.
|
||||
char buf[MAX_PACKET_PAYLOAD + 1];
|
||||
cliCopyCommand(buf, sizeof(buf), command);
|
||||
if (!cliQuotesBalanced(command)) { strcpy(reply, "Err - unbalanced quotes"); return; }
|
||||
if (!cliCopyCommand(buf, sizeof(buf), command)) { strcpy(reply, "Err - command too long"); return; }
|
||||
char* p = buf;
|
||||
char* cmd = nextToken(&p);
|
||||
|
||||
if (cmd == NULL) {
|
||||
if (!cliNoExtra(p, reply, BATT_USAGE)) return;
|
||||
cliStatus(gate, board, reply);
|
||||
} else if (strcmp(cmd, "off") == 0) {
|
||||
if (!cliNoExtra(p, reply, BATT_USAGE)) return;
|
||||
gate.setEnabled(false);
|
||||
snprintf(reply, CLI_REPLY_MAX, "OK - battery gate off");
|
||||
} else {
|
||||
|
||||
@@ -10,6 +10,7 @@
|
||||
#ifndef _CLI_UTIL_H
|
||||
#define _CLI_UTIL_H
|
||||
|
||||
#include <errno.h>
|
||||
#include <stdarg.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
@@ -39,15 +40,20 @@ inline char* nextToken(char** p) {
|
||||
}
|
||||
|
||||
// Copy a command tail (everything after the verb) into a scratch buffer for
|
||||
// nextToken() to consume in place, truncating safely at the buffer size.
|
||||
// nextToken() to consume in place. Returns false if the command does not fit.
|
||||
//
|
||||
// Reporting the overflow matters: truncating a command and then acting on the
|
||||
// prefix is safe memory, but not safe policy — `filter chan add name <psk>...`
|
||||
// cut short would store a mangled name. A command that does not fit is refused
|
||||
// whole.
|
||||
// Deliberately dependency-free: both CLI handlers use it, and the battery
|
||||
// gate's host test build links neither StrHelper nor ltoa().
|
||||
inline void cliCopyCommand(char* buf, size_t sz, const char* command) {
|
||||
if (sz == 0) return;
|
||||
inline bool cliCopyCommand(char* buf, size_t sz, const char* command) {
|
||||
if (sz == 0) return false;
|
||||
size_t n = strlen(command);
|
||||
if (n >= sz) n = sz - 1;
|
||||
memcpy(buf, command, n);
|
||||
buf[n] = 0;
|
||||
if (n >= sz) return false;
|
||||
memcpy(buf, command, n + 1);
|
||||
return true;
|
||||
}
|
||||
|
||||
// all CLI reply buffers are 160 B: main.cpp uses char reply[160] (serial and
|
||||
@@ -55,6 +61,28 @@ inline void cliCopyCommand(char* buf, size_t sz, const char* command) {
|
||||
// Reply writers must bound to this, never MAX_PACKET_PAYLOAD.
|
||||
#define CLI_REPLY_MAX 160
|
||||
|
||||
// An odd number of double quotes means the tokenizer would swallow the rest of
|
||||
// the line into one value. Cheap to check up front, and it turns a silent
|
||||
// misparse into an error the user can see.
|
||||
inline bool cliQuotesBalanced(const char* command) {
|
||||
int n = 0;
|
||||
for (const char* s = command; *s; s++) if (*s == '"') n++;
|
||||
return (n % 2) == 0;
|
||||
}
|
||||
|
||||
// Refuse a trailing token the command form does not take, using that form's
|
||||
// usage line. Silently ignoring the tail turns a typo into a no-op that still
|
||||
// replies OK, which is the worst failure mode a management command can have:
|
||||
// `filter off junk` would report success while doing something the user did not
|
||||
// ask for, or the opposite. Call this BEFORE any side effect.
|
||||
inline bool cliNoExtra(char* p, char* reply, const char* usage) {
|
||||
if (nextToken(&p) != NULL) {
|
||||
snprintf(reply, CLI_REPLY_MAX, "%s", usage);
|
||||
return false;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
// bounded reply append (CLI reply buffer is 160 bytes)
|
||||
inline void radd(char** out, int* remain, const char* fmt, ...) {
|
||||
if (*remain <= 0) return;
|
||||
@@ -71,12 +99,14 @@ inline void radd(char** out, int* remain, const char* fmt, ...) {
|
||||
// Parse a decimal token that must be entirely a number in [lo, hi]: a trailing
|
||||
// byte ("12x", "0x10"), an empty token and an out-of-range value are all
|
||||
// refused. Callers keep their own error wording, which is why this only
|
||||
// answers yes/no.
|
||||
// answers yes/no. `out` is left untouched unless the whole token parses, so a
|
||||
// rejected value can never leave a stale one behind.
|
||||
inline bool parseIntRange(const char* tok, long lo, long hi, long* out) {
|
||||
if (tok == NULL || tok[0] == 0) return false;
|
||||
errno = 0;
|
||||
char* end;
|
||||
long v = strtol(tok, &end, 10);
|
||||
if (end == tok || *end != 0 || v < lo || v > hi) return false;
|
||||
if (end == tok || *end != 0 || errno == ERANGE || v < lo || v > hi) return false;
|
||||
*out = v;
|
||||
return true;
|
||||
}
|
||||
|
||||
@@ -1210,17 +1210,48 @@ static void cliStatus(FilterRules& filter, char* reply) {
|
||||
(unsigned long)filter.getBudgetAborts());
|
||||
}
|
||||
|
||||
static void cliChanList(FilterRules& filter, char* reply) {
|
||||
char* out = reply;
|
||||
int remain = CLI_REPLY_MAX;
|
||||
if (filter.getNumChannels() == 0) {
|
||||
// List channels from `start`. A full store does not fit the 160-byte reply, and
|
||||
// `chan del` takes a NAME — so a channel that was cut off could neither be seen
|
||||
// nor reliably removed. `filter chan list <start-idx>` walks the rest, and a
|
||||
// truncated listing ends with `next=N` naming the first index not shown. Entries
|
||||
// are only ever appended whole; the bare form keeps its old format whenever
|
||||
// everything fits.
|
||||
static void cliChanList(FilterRules& filter, int start, char* reply) {
|
||||
const int n = filter.getNumChannels();
|
||||
if (n == 0) {
|
||||
strcpy(reply, "no channels");
|
||||
return;
|
||||
}
|
||||
for (int i = 0; i < filter.getNumChannels(); i++) {
|
||||
auto ch = filter.getChannel(i);
|
||||
radd(&out, &remain, "%s%d:%s:%02X", i ? " " : "", i, ch->name, ch->hash);
|
||||
if (start >= n) {
|
||||
snprintf(reply, CLI_REPLY_MAX, "Err - start index %d is past the last channel (%d)", start, n - 1);
|
||||
return;
|
||||
}
|
||||
|
||||
char entry[FILTER_CHAN_NAME_LEN + 16]; // "<idx>:<name>:<2 hex>", plus a leading space
|
||||
// pass 1: exactly the old listing, so a store that fits is unchanged
|
||||
char* out = reply;
|
||||
int remain = CLI_REPLY_MAX;
|
||||
int i = start;
|
||||
bool complete = true;
|
||||
for (; i < n; i++) {
|
||||
auto ch = filter.getChannel(i);
|
||||
snprintf(entry, sizeof(entry), "%s%d:%s:%02X", (i > start) ? " " : "", i, ch->name, ch->hash);
|
||||
if ((int)strlen(entry) >= remain) { complete = false; break; }
|
||||
radd(&out, &remain, "%s", entry);
|
||||
}
|
||||
if (complete) return;
|
||||
|
||||
// pass 2: re-list with room held back for the continuation marker
|
||||
out = reply;
|
||||
remain = CLI_REPLY_MAX - 14; // "; next=NNN" and the NUL
|
||||
i = start;
|
||||
for (; i < n; i++) {
|
||||
auto ch = filter.getChannel(i);
|
||||
snprintf(entry, sizeof(entry), "%s%d:%s:%02X", (i > start) ? " " : "", i, ch->name, ch->hash);
|
||||
if ((int)strlen(entry) >= remain) break;
|
||||
radd(&out, &remain, "%s", entry);
|
||||
}
|
||||
radd(&out, &remain, "; next=%d", i); // resume here
|
||||
}
|
||||
|
||||
static void cliChanAdd(FilterRules& filter, char* params, char* reply) {
|
||||
@@ -1405,42 +1436,66 @@ static bool cliRuleIdx(FilterRules& filter, char* arg, int& idx, char* reply) {
|
||||
return true;
|
||||
}
|
||||
|
||||
#define FILTER_USAGE "Err - usage: on|off|add|list|get|enable|disable|move|del|clear|chan|ratelimit|stats"
|
||||
|
||||
void filterCLI(FilterRules& filter, const char* command, char* reply, RegionMap* regions) {
|
||||
// An oversized command is refused whole rather than acted on as a prefix, and
|
||||
// unbalanced quotes are an error rather than a silent misparse. Both are
|
||||
// checked before anything is touched.
|
||||
char buf[MAX_PACKET_PAYLOAD + 1];
|
||||
cliCopyCommand(buf, sizeof(buf), command);
|
||||
if (!cliQuotesBalanced(command)) { strcpy(reply, "Err - unbalanced quotes"); return; }
|
||||
if (!cliCopyCommand(buf, sizeof(buf), command)) { strcpy(reply, "Err - command too long"); return; }
|
||||
char* p = buf;
|
||||
char* cmd = nextToken(&p);
|
||||
|
||||
if (cmd == NULL) {
|
||||
cliStatus(filter, reply);
|
||||
} else if (strcmp(cmd, "on") == 0) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: on")) return;
|
||||
filter.setEnabled(true);
|
||||
strcpy(reply, "OK - filter on");
|
||||
} else if (strcmp(cmd, "off") == 0) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: off")) return;
|
||||
filter.setEnabled(false);
|
||||
strcpy(reply, "OK - filter off");
|
||||
} else if (strcmp(cmd, "chan") == 0) {
|
||||
char* sub = nextToken(&p);
|
||||
if (sub == NULL || strcmp(sub, "list") == 0) {
|
||||
cliChanList(filter, reply);
|
||||
char* tok = nextToken(&p);
|
||||
int start = 0;
|
||||
if (tok != NULL) {
|
||||
long v;
|
||||
if (!parseIntRange(tok, 0, FILTER_MAX_CHANNELS - 1, &v)) {
|
||||
strcpy(reply, "Err - chan list start index must be 0..15");
|
||||
return;
|
||||
}
|
||||
start = (int)v;
|
||||
}
|
||||
if (!cliNoExtra(p, reply, "Err - usage: chan list [<start-idx>]")) return;
|
||||
cliChanList(filter, start, reply);
|
||||
} else if (strcmp(sub, "add") == 0) {
|
||||
cliChanAdd(filter, p, reply);
|
||||
} else if (strcmp(sub, "del") == 0) {
|
||||
cliChanDel(filter, p, reply);
|
||||
} else {
|
||||
strcpy(reply, "Err - usage: chan list|add <name> [<psk>]|del <name>");
|
||||
strcpy(reply, "Err - usage: chan list [<start-idx>]|add <name> [<psk-hex>]|del <name>");
|
||||
}
|
||||
} else if (strcmp(cmd, "add") == 0) {
|
||||
cliAdd(filter, regions, p, reply);
|
||||
} else if (strcmp(cmd, "list") == 0) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: list")) return;
|
||||
cliList(filter, reply);
|
||||
} else if (strcmp(cmd, "get") == 0) {
|
||||
int idx;
|
||||
if (cliRuleIdx(filter, nextToken(&p), idx, reply)) cliGet(filter, idx, reply);
|
||||
if (cliRuleIdx(filter, nextToken(&p), idx, reply)) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: get <idx>")) return;
|
||||
cliGet(filter, idx, reply);
|
||||
}
|
||||
} else if (strcmp(cmd, "enable") == 0 || strcmp(cmd, "disable") == 0) {
|
||||
bool on = (strcmp(cmd, "enable") == 0);
|
||||
int idx;
|
||||
if (cliRuleIdx(filter, nextToken(&p), idx, reply)) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: enable|disable <idx>")) return;
|
||||
filter.getRule(idx)->enabled = on;
|
||||
filter.markDirty();
|
||||
snprintf(reply, CLI_REPLY_MAX, "OK - rule %d %s", idx, on ? "enabled" : "disabled");
|
||||
@@ -1449,6 +1504,7 @@ void filterCLI(FilterRules& filter, const char* command, char* reply, RegionMap*
|
||||
int from, to;
|
||||
if (cliRuleIdx(filter, nextToken(&p), from, reply) &&
|
||||
cliRuleIdx(filter, nextToken(&p), to, reply)) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: move <from> <to>")) return;
|
||||
if (from == to) {
|
||||
strcpy(reply, "Err - move: source and target are the same rule"); // no-op move is rejected
|
||||
} else {
|
||||
@@ -1459,10 +1515,12 @@ void filterCLI(FilterRules& filter, const char* command, char* reply, RegionMap*
|
||||
} else if (strcmp(cmd, "del") == 0) {
|
||||
int idx;
|
||||
if (cliRuleIdx(filter, nextToken(&p), idx, reply)) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: del <idx>")) return;
|
||||
filter.delRule(idx);
|
||||
snprintf(reply, CLI_REPLY_MAX, "OK - rule %d deleted", idx);
|
||||
}
|
||||
} else if (strcmp(cmd, "clear") == 0) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: clear")) return;
|
||||
filter.clearRules();
|
||||
strcpy(reply, "OK - rules cleared (chans kept)");
|
||||
} else if (strcmp(cmd, "ratelimit") == 0) {
|
||||
@@ -1474,19 +1532,33 @@ void filterCLI(FilterRules& filter, const char* command, char* reply, RegionMap*
|
||||
long v;
|
||||
if (!parseIntRange(nextToken(&p), 0, FILTER_ADVERT_HOURS_MAX, &v)) {
|
||||
snprintf(reply, CLI_REPLY_MAX, "Err - hours must be 0..%d (0=off)", FILTER_ADVERT_HOURS_MAX);
|
||||
} else if (!cliNoExtra(p, reply, "Err - usage: ratelimit advert <hours>")) {
|
||||
return;
|
||||
} else {
|
||||
filter.setAdvertRatelimit((uint16_t)v);
|
||||
snprintf(reply, CLI_REPLY_MAX, "OK - advert ratelimit %ldh", v);
|
||||
}
|
||||
} else if (strcmp(sub, "clear") == 0) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: ratelimit clear")) return;
|
||||
filter.clearAdvertCache();
|
||||
strcpy(reply, "OK - advert cache cleared");
|
||||
} else {
|
||||
strcpy(reply, "Err - usage: ratelimit advert <hours>|clear");
|
||||
strcpy(reply, "Err - usage: ratelimit [advert <hours>|clear]");
|
||||
}
|
||||
} else if (strcmp(cmd, "stats") == 0) {
|
||||
cliStats(filter, reply);
|
||||
char* sub = nextToken(&p);
|
||||
if (sub == NULL) {
|
||||
cliStats(filter, reply);
|
||||
} else if (strcmp(sub, "reset") == 0) {
|
||||
if (!cliNoExtra(p, reply, "Err - usage: stats [reset]")) return;
|
||||
// counters only: the advert history and every rule's rate budget survive,
|
||||
// so a stats reset can never hand a throttled rule a free pass
|
||||
filter.resetStats();
|
||||
strcpy(reply, "OK - filter stats reset");
|
||||
} else {
|
||||
strcpy(reply, "Err - usage: stats [reset]");
|
||||
}
|
||||
} else {
|
||||
strcpy(reply, "Err - usage: on|off|add|list|get|enable|disable|move|del|clear|chan|ratelimit|stats");
|
||||
strcpy(reply, FILTER_USAGE);
|
||||
}
|
||||
}
|
||||
@@ -28,7 +28,9 @@
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include <algorithm>
|
||||
#include <string>
|
||||
#include <vector>
|
||||
|
||||
#include "FilterTestHelpers.h"
|
||||
|
||||
@@ -37,6 +39,18 @@ static constexpr uint8_t CFG_VERSION = 6;
|
||||
static constexpr unsigned long CFG_SAVE_DELAY_MS = 3000;
|
||||
static const char* CFG_FILE = "/filter_cfg";
|
||||
|
||||
static std::vector<std::string> splitOnSpace(const std::string& s) {
|
||||
std::vector<std::string> out;
|
||||
std::string cur;
|
||||
for (char c : s) {
|
||||
if (c == ' ') { out.push_back(cur); cur.clear(); }
|
||||
else cur += c;
|
||||
}
|
||||
out.push_back(cur);
|
||||
return out;
|
||||
}
|
||||
|
||||
|
||||
|
||||
// ============================================================
|
||||
// UNIT TESTS: TinyRegex (vendored tiny-regex-c + step budget)
|
||||
@@ -1463,6 +1477,166 @@ TEST_F(FilterTest, CheckAloneRepeatedlyNeverSpendsTheBudget) {
|
||||
EXPECT_EQ(filter.getAdvertCacheCount(), 0);
|
||||
}
|
||||
|
||||
// A command the CLI does not understand, or a typo'd tail, must never look like
|
||||
// it worked. Silently ignoring the tail turns a mistake into a success reply.
|
||||
TEST_F(FilterTest, ExtraTokensAreRejectedBeforeAnythingChanges) {
|
||||
ASSERT_EQ(cli(filter, "add type=advert"), "OK - rule 0 added"); // so index checks pass
|
||||
ASSERT_EQ(cli(filter, "add type=txt"), "OK - rule 1 added");
|
||||
struct Case { const char* cmd; const char* usage; };
|
||||
const Case cases[] = {
|
||||
{ "on junk", "Err - usage: on" },
|
||||
{ "off junk", "Err - usage: off" },
|
||||
{ "list junk", "Err - usage: list" },
|
||||
{ "clear junk", "Err - usage: clear" },
|
||||
{ "get 0 junk", "Err - usage: get <idx>" },
|
||||
{ "enable 0 junk", "Err - usage: enable|disable <idx>" },
|
||||
{ "del 0 junk", "Err - usage: del <idx>" },
|
||||
{ "move 0 1 junk", "Err - usage: move <from> <to>" },
|
||||
{ "ratelimit advert 48 junk", "Err - usage: ratelimit advert <hours>" },
|
||||
{ "ratelimit clear junk", "Err - usage: ratelimit clear" },
|
||||
{ "stats junk", "Err - usage: stats [reset]" },
|
||||
{ "chan list 0 junk", "Err - usage: chan list [<start-idx>]" },
|
||||
};
|
||||
for (const auto& c : cases) {
|
||||
EXPECT_EQ(cli(filter, c.cmd), c.usage) << c.cmd;
|
||||
}
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, RejectedTailsLeaveTheConfigUntouched) {
|
||||
ASSERT_EQ(cli(filter, "add type=advert"), "OK - rule 0 added");
|
||||
filter.setEnabled(true);
|
||||
filter.setAdvertRatelimit(48);
|
||||
filter.clearAdvertCache();
|
||||
|
||||
// every one of these would have mutated something if the tail were ignored
|
||||
EXPECT_EQ(cli(filter, "off junk").substr(0, 5), "Err -");
|
||||
EXPECT_TRUE(filter.isEnabled());
|
||||
EXPECT_EQ(cli(filter, "clear junk").substr(0, 5), "Err -");
|
||||
EXPECT_EQ(filter.getNumRules(), 1);
|
||||
EXPECT_EQ(cli(filter, "del 0 junk").substr(0, 5), "Err -");
|
||||
EXPECT_EQ(filter.getNumRules(), 1);
|
||||
EXPECT_EQ(cli(filter, "move 0 0 junk").substr(0, 5), "Err -");
|
||||
EXPECT_EQ(cli(filter, "ratelimit advert 0 junk").substr(0, 5), "Err -");
|
||||
EXPECT_EQ(filter.getAdvertRatelimit(), 48);
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, OversizedAndUnbalancedCommandsAreRefusedWhole) {
|
||||
// a valid prefix plus an invalid tail must not be applied as the prefix
|
||||
std::string long_cmd = "add sender=";
|
||||
long_cmd += std::string(300, 'a');
|
||||
EXPECT_EQ(cli(filter, long_cmd.c_str()), "Err - command too long");
|
||||
EXPECT_EQ(filter.getNumRules(), 0);
|
||||
|
||||
EXPECT_EQ(cli(filter, "off \"unterminated"), "Err - unbalanced quotes");
|
||||
EXPECT_TRUE(filter.isEnabled()); // nothing was applied
|
||||
|
||||
EXPECT_EQ(cli(filter, "chan add \"a b 00112233445566778899aabbccddeeff"),
|
||||
"Err - unbalanced quotes");
|
||||
EXPECT_EQ(filter.findChannel("a b 00112233445566778899aabbccddeeff"), nullptr);
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, StatsResetClearsCountersButKeepsRateState) {
|
||||
filter.setAdvertRatelimit(48);
|
||||
// bank an advert window first, with no rule in the way
|
||||
uint8_t key[4] = { 0x11, 0x22, 0x33, 0x44 };
|
||||
auto relayed = makeAdvert(key);
|
||||
EXPECT_EQ(forwardPacket(filter, relayed, 1000), FILTER_ACT_ALLOW);
|
||||
ASSERT_EQ(filter.getAdvertCacheCount(), 1);
|
||||
|
||||
// then bank a rule hit and some throttle state
|
||||
ASSERT_EQ(cli(filter, "add type=advert throttle=60"), "OK - rule 0 added");
|
||||
filter.getRule(0)->throttle_seen = true; // spend the free pass
|
||||
uint8_t other_key[4] = { 0x55, 0x66, 0x77, 0x88 };
|
||||
auto dropped = makeAdvert(other_key);
|
||||
EXPECT_EQ(forwardPacket(filter, dropped, 1000), FILTER_ACT_DROP);
|
||||
filter.getRule(0)->throttle_pass = 5; // a counter
|
||||
ASSERT_GT(filter.getRule(0)->hits, 0u);
|
||||
|
||||
EXPECT_EQ(cli(filter, "stats reset"), "OK - filter stats reset");
|
||||
EXPECT_EQ(filter.getRule(0)->hits, 0u);
|
||||
EXPECT_EQ(filter.getRule(0)->air_ms, 0u);
|
||||
EXPECT_EQ(filter.getLimiterDrops(), 0u);
|
||||
// throttle_pass is a counter, so it goes with the rest...
|
||||
EXPECT_EQ(filter.getRule(0)->throttle_pass, 0u);
|
||||
// ... but the RATE state is not: a stats reset must never hand a throttled
|
||||
// rule a free pass, which is what throttle_seen/throttle_last_ms carry
|
||||
EXPECT_EQ(filter.getAdvertCacheCount(), 1); // advert history is not a counter
|
||||
EXPECT_EQ(filter.getAdvertRatelimit(), 48);
|
||||
EXPECT_EQ(cli(filter, "stats").substr(0, 4), "lim:");
|
||||
EXPECT_TRUE(filter.getRule(0)->throttle_seen);
|
||||
// The invariant, stated behaviourally: throttle=N lets one match per N
|
||||
// seconds slip PAST the rule; the rest are decided by it. Right after a reset
|
||||
// the window is still open, so this match must be decided — a stats reset buys
|
||||
// no extra slips.
|
||||
auto within = makeAdvert(other_key);
|
||||
EXPECT_EQ(forwardPacket(filter, within, 2000), FILTER_ACT_DROP);
|
||||
EXPECT_EQ(filter.getRule(0)->hits, 1u);
|
||||
|
||||
// once the window has genuinely passed, the next match is the one that slips
|
||||
auto after = makeAdvert(other_key);
|
||||
EXPECT_EQ(forwardPacket(filter, after, 62000), FILTER_ACT_ALLOW);
|
||||
EXPECT_EQ(filter.getRule(0)->hits, 1u);
|
||||
EXPECT_EQ(filter.getRule(0)->throttle_pass, 1u);
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, ChanListContinuesWhereItWasCut) {
|
||||
// fill the store with long names so the listing cannot fit in one reply
|
||||
for (int i = 0; i < FILTER_MAX_CHANNELS - 1; i++) {
|
||||
std::string name = "longchannel" + std::to_string(i); // distinct, and long enough to overflow
|
||||
std::string add = cli(filter, ("chan add " + name + " 00112233445566778899aabbccddeeff").c_str());
|
||||
ASSERT_EQ(add.substr(0, 3), "OK ") << name << " -> " << add;
|
||||
}
|
||||
ASSERT_EQ(filter.getNumChannels(), FILTER_MAX_CHANNELS);
|
||||
|
||||
std::string head = cli(filter, "chan list");
|
||||
EXPECT_GT(head.size(), 0u);
|
||||
size_t next_at = head.find("; next=");
|
||||
ASSERT_NE(next_at, std::string::npos) << "a full store must say where to resume";
|
||||
|
||||
int start = atoi(head.substr(next_at + 7).c_str());
|
||||
EXPECT_GT(start, 0);
|
||||
EXPECT_LT(start, filter.getNumChannels());
|
||||
// every visible entry is whole: the marker follows a complete "idx:name:hash"
|
||||
EXPECT_EQ(head.find(":") != std::string::npos, true);
|
||||
|
||||
// the resumed listing starts at the index the marker named
|
||||
std::string tail = cli(filter, ("chan list " + std::to_string(start)).c_str());
|
||||
size_t p0 = tail.find(":");
|
||||
ASSERT_NE(p0, std::string::npos);
|
||||
EXPECT_EQ(atoi(tail.substr(0, p0).c_str()), start);
|
||||
|
||||
// together the two pages name every channel exactly once, in order, and never
|
||||
// split an entry: each token is a whole "idx:name:hash"
|
||||
std::vector<int> seen;
|
||||
for (const std::string* page : { &head, &tail }) {
|
||||
for (const std::string& tok : splitOnSpace(*page)) {
|
||||
if (tok.empty() || !isdigit((unsigned char)tok[0])) continue; // skip the "next=N" marker
|
||||
// a whole entry is exactly "idx:name:hash": two colons, and no cut name
|
||||
EXPECT_EQ(std::count(tok.begin(), tok.end(), ':'), 2) << "partial entry: " << tok;
|
||||
int idx = atoi(tok.substr(0, tok.find(':')).c_str());
|
||||
EXPECT_EQ(std::find(seen.begin(), seen.end(), idx), seen.end()) << "repeated index " << idx;
|
||||
seen.push_back(idx);
|
||||
}
|
||||
}
|
||||
ASSERT_EQ(seen.size(), (size_t)filter.getNumChannels());
|
||||
for (int i = 0; i < filter.getNumChannels(); i++) EXPECT_EQ(seen[i], i) << "coverage gap at " << i;
|
||||
|
||||
// walking to the end eventually stops offering a continuation
|
||||
std::string last = cli(filter, ("chan list " + std::to_string(filter.getNumChannels() - 1)).c_str());
|
||||
EXPECT_EQ(last.find("; next="), std::string::npos);
|
||||
// ... and past the end is an error, not an empty success
|
||||
EXPECT_EQ(cli(filter, ("chan list " + std::to_string(filter.getNumChannels())).c_str()).substr(0, 5), "Err -");
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, ShortStoreListsWithoutAContinuation) {
|
||||
// the bare listing keeps its old shape when everything fits
|
||||
ASSERT_EQ(cli(filter, "chan add #one 00112233445566778899aabbccddeeff").substr(0, 3), "OK ");
|
||||
std::string all = cli(filter, "chan list");
|
||||
EXPECT_EQ(all.find("; next="), std::string::npos);
|
||||
EXPECT_NE(all.find("0:Public"), std::string::npos);
|
||||
EXPECT_NE(all.find("1:#one"), std::string::npos);
|
||||
}
|
||||
|
||||
// ===================================================================
|
||||
// CONTENT VERDICT STASH LIFETIME
|
||||
// ===================================================================
|
||||
@@ -2470,18 +2644,6 @@ TEST_F(FilterTest, LoopSavesOnceWhenClean) {
|
||||
|
||||
static const uint8_t PROB_KEY[4] = { 0x11, 0x22, 0x33, 0x44 };
|
||||
|
||||
// Split a reply on spaces (test-only helper for parsing `filter list`).
|
||||
static std::vector<std::string> splitOnSpace(const std::string& s) {
|
||||
std::vector<std::string> out;
|
||||
std::string cur;
|
||||
for (char c : s) {
|
||||
if (c == ' ') { out.push_back(cur); cur.clear(); }
|
||||
else cur += c;
|
||||
}
|
||||
out.push_back(cur);
|
||||
return out;
|
||||
}
|
||||
|
||||
// distinct packets: same shape, varying first payload byte (the packet hash
|
||||
// covers the payload, so each i rolls independently)
|
||||
static mesh::Packet probAdvert(int i) {
|
||||
@@ -3799,7 +3961,7 @@ TEST_F(FilterTest, RatelimitCommands) {
|
||||
EXPECT_EQ(cli(filter, "ratelimit advert -1"), "Err - hours must be 0..720 (0=off)");
|
||||
EXPECT_EQ(cli(filter, "ratelimit advert 0"), "OK - advert ratelimit 0h");
|
||||
EXPECT_EQ(filter.getAdvertRatelimit(), 0);
|
||||
EXPECT_EQ(cli(filter, "ratelimit bogus"), "Err - usage: ratelimit advert <hours>|clear");
|
||||
EXPECT_EQ(cli(filter, "ratelimit bogus"), "Err - usage: ratelimit [advert <hours>|clear]");
|
||||
// a non-number must not be read as 0, which would silently turn the limiter off
|
||||
EXPECT_EQ(cli(filter, "ratelimit advert abc"), "Err - hours must be 0..720 (0=off)");
|
||||
EXPECT_EQ(cli(filter, "ratelimit advert 12x"), "Err - hours must be 0..720 (0=off)");
|
||||
|
||||
Reference in new issue
Block a user