mirror of
https://github.com/jhuebert/MeshCore.git
synced 2026-12-04 11:24:33 +00:00
feat: alternation in filter sender/text patterns (unescaped | now means OR)
Stage 1 of plans/2026-10-01-filter-regex-alternation.md: a new fork-owned
wrapper, PatternMatch.h/.cpp, owns the user-facing pattern language and adds
top-level '|' alternation to sender=/text=:
filter add sender=^Alice$|^Bob$
The vendored TinyRegex engine is untouched — it keeps its three documented
modifications, and syntax is added one layer up, in the wrapper. The pattern
is stored as text exactly as before, so there is no persistence change, no
FILTER_CFG_VERSION bump and no static_assert change.
Wrapper behaviour:
- top-level '|' splits the pattern; each alternative is compiled and matched
in order, first match wins, so anchors bind per alternative (^Alice|Bob$
is "(^Alice)|(Bob$)"). '\|' and '[|]' stay literal pipes;
- empty alternatives ("A|", "|A", "A||B") are rejected — an empty branch
matches everything;
- at most FILTER_PATTERN_MAX_ALTS (8, new build-flag-overridable tunable in
PacketFilterConfig.h) alternatives per pattern;
- evaluation stops at the first alternative that exhausts the engine step
budget, fail-open, counted once in budget_aborts as before.
Groups stay unsupported and parentheses keep today's literal behavior, so
"^(Alice|Bob)$" is accepted and matches a sender literally named "(Alice|Bob)"
— documented as the trap it is, in FILTER.md.
Compatibility: one intentional reinterpretation. A stored pattern containing
an unescaped '|' previously matched a literal pipe and now means OR; write
'\|' for a literal pipe. Noted in FILTER.md and in this subject line, which
is what the release body's filter-changes section lists.
Reply strings: existing ones stay byte-identical ("Err - bad/long sender
regex" / "Err - bad/long text regex" remain the fallback for engine-level
rejections); only newly rejected patterns gain strings — "Err - empty
alternative in regex" and "Err - too many alternatives (max 8)".
Verified: pio test -e native_packet_filter 213 cases pass (196 pre-existing,
unchanged, plus 17 new covering alternation, per-branch anchors, escapes,
structural rejections, budget interaction, CLI round-trip and checkContent
rules); pio test -e native_battery_gate 29 pass. Firmware compile check
pio run -e Xiao_S3_WIO_repeater: +712 B flash, +8 B RAM, no new static RAM
in the filter itself (48 B of stack during evaluation).
FILTER.md documents the syntax, the per-branch anchor footgun, the cap, the
pattern-length pressure and the compat break; AGENTS.md gains the amendments
approved in the plan (fork-owned file set, code map, hard invariant #5,
backwards-compat rule, test counts).
Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
This commit is contained in:
1 parent
86f1eefafa
commit
69b8b15b91
10 files changed
+472
-45
No files matched your search
@@ -44,6 +44,9 @@ commit** — the guides are user-facing API documentation, not optional docs.
|
||||
override via build flags; persistence-layout caveats noted inline.
|
||||
- `TinyRegex.h/.cpp` — vendored kokke/tiny-regex-c + step budget (see Hard
|
||||
invariants; treat as upstream).
|
||||
- `PatternMatch.h/.cpp` — the user-facing pattern language: top-level `|`
|
||||
alternation, structural validation, `FILTER_PATTERN_MAX_ALTS`; thin wrapper
|
||||
over the vendored engine.
|
||||
- `CliUtil.h` — shared CLI helpers (`nextToken`, `radd`, `CLI_REPLY_MAX`)
|
||||
used by filter and battery CLIs alike.
|
||||
- `BatteryGate.h/.cpp` — low-battery forward suspension, `battery` CLI.
|
||||
@@ -52,9 +55,9 @@ commit** — the guides are user-facing API documentation, not optional docs.
|
||||
dispatch, lazy-save loop).
|
||||
- `main.cpp` — serial CLI entry (upstream + fork's buffer-hardening lines).
|
||||
|
||||
**Tests:** `test/test_packet_filter/` (191 behavior-level cases: matching,
|
||||
content rules, limiter, persistence upgrades, CLI surface, TinyRegex) and
|
||||
`test/test_battery_gate/`. Test-only shims: `NativeShim.h`,
|
||||
**Tests:** `test/test_packet_filter/` (213 behavior-level cases: matching,
|
||||
content rules, limiter, persistence upgrades, CLI surface, TinyRegex,
|
||||
PatternMatch) and `test/test_battery_gate/`. Test-only shims: `NativeShim.h`,
|
||||
`NativeTestStubs.cpp`, `RegionMapStub.cpp`, `FilterTestHelpers.h`.
|
||||
|
||||
**Build & CI:** `pio test -e native_packet_filter` / `-e
|
||||
@@ -81,6 +84,7 @@ release channels (dev → `repeater-filter`, stable → `repeater-filter-stable`
|
||||
Fork-owned file set (free to edit):
|
||||
- `examples/simple_repeater/PacketFilter.h/.cpp`, `PacketFilterConfig.h`
|
||||
- `examples/simple_repeater/TinyRegex.h/.cpp`, `CliUtil.h`, `BatteryGate.h/.cpp`
|
||||
- `examples/simple_repeater/PatternMatch.h/.cpp`
|
||||
- `test/test_packet_filter/`, `test/test_battery_gate/`
|
||||
- `FILTER.md`, `.github/workflows/filter-build.yml`, `sync-upstream.yml`
|
||||
|
||||
@@ -142,6 +146,11 @@ FILTER.md:
|
||||
prob-before-throttle, stats semantics (hits travel with the rule on
|
||||
move/del; a stats reset never grants a throttle free pass) are observable
|
||||
behavior. Changing them is a breaking decision, not a refactor side effect.
|
||||
- **New pattern syntax must not silently change the meaning of an
|
||||
already-storable pattern.** If it would, either ship an escape (`\|`) or
|
||||
reject the ambiguous form with an error. Deliberate exception: `|` became OR
|
||||
in 2026-10 (alternation) — a stored pattern containing an unescaped `|`
|
||||
previously matched a literal pipe.
|
||||
|
||||
## Hard invariants (do not break)
|
||||
|
||||
@@ -157,6 +166,12 @@ FILTER.md:
|
||||
4. **First match wins.** Rule evaluation order (listed order, packet-level in
|
||||
`checkPacket()`, whole-list single pass in `checkContent()`, stash
|
||||
consumption) is load-bearing; the prob roll runs before the throttle gate.
|
||||
5. **Pattern syntax lives in the wrapper, not in the vendored engine.**
|
||||
`examples/simple_repeater/PatternMatch.*` owns every user-visible syntax
|
||||
decision (alternation splitting, structural validation, the alternative
|
||||
cap). `TinyRegex.cpp` keeps only the three documented modifications and
|
||||
`TinyRegex.h`'s only role is the engine API. A change that adds syntax by
|
||||
editing the engine violates this.
|
||||
|
||||
## Tests & verification — all code paths covered
|
||||
|
||||
@@ -164,12 +179,12 @@ FILTER.md:
|
||||
paths, added in the same commit. The suites are behavior-level (native
|
||||
googletest); reach them via the same CLI/`checkPacket`/`checkContent`
|
||||
entry points a user or the firmware would.
|
||||
- Pure refactors keep both suites green **unchanged** — the suite (191 filter
|
||||
- Pure refactors keep both suites green **unchanged** — the suite (213 filter
|
||||
cases) is the safety net that proves no behavior slipped.
|
||||
- Run both suites, then re-read the diff:
|
||||
|
||||
```
|
||||
pio test -e native_packet_filter # filter + TinyRegex + CLI + persistence
|
||||
pio test -e native_packet_filter # filter + PatternMatch + TinyRegex + CLI + persistence
|
||||
pio test -e native_battery_gate # battery gate
|
||||
```
|
||||
|
||||
|
||||
@@ -79,6 +79,9 @@ filter add chan=#test sender=^SpamBot$
|
||||
filter add chan=#test text=^BEACON
|
||||
```
|
||||
|
||||
Inside a single `sender=`/`text=` pattern, `|` is the OR — see
|
||||
[Writing sender/text patterns](#writing-sender-text-patterns).
|
||||
|
||||
### Good to know
|
||||
|
||||
- Some values accept comma-separated alternatives, which acts as an OR inside
|
||||
@@ -697,17 +700,24 @@ is only needed for initial flashing and emergencies.
|
||||
| Channels in the store | 16 (names up to 15 characters) |
|
||||
| Sender pattern length | 23 characters |
|
||||
| Text pattern length | 47 characters |
|
||||
| Alternatives per pattern | 8 (`\|`-separated) |
|
||||
| Advert rate-limit window | 0–720 hours (0 = off) |
|
||||
| CLI reply length | short (~160 bytes) — use `filter get <idx>` for detail |
|
||||
|
||||
- Overly long or complex patterns are **rejected with an error**, not silently
|
||||
shortened. Keep patterns short and specific.
|
||||
- Pattern lengths count the **whole** pattern, every `|` and anchor included:
|
||||
`sender=` fits about three short exact names (`^Alice$|^Bob$|^Carol$` is 21 of
|
||||
23 characters) and `text=` about six. Need more? Add a second rule, or use
|
||||
one broader alternative such as `^Bot`.
|
||||
- Rules, channels, and settings survive reboots. Counters and the advert cache
|
||||
do not — they start fresh after every reboot.
|
||||
- Very complicated patterns can be slow to match. Prefer short, distinctive
|
||||
patterns like `^BEACON` over long wildcard chains. The `aborted` counter in
|
||||
`filter stats` grows if a pattern gives up mid-match; simplify it if you see
|
||||
that.
|
||||
that. Alternatives are tried in turn, and an anchored alternative is far
|
||||
cheaper than an unanchored one — `^PING$|^PONG$` costs much less than
|
||||
`PING|PONG`.
|
||||
- Rules are evaluated **top to bottom, first match wins** over the whole list —
|
||||
packet-level and content conditions live in the same ordered list. Older
|
||||
fork firmware ran content rules in a separate second pass; with interleaved
|
||||
@@ -722,6 +732,9 @@ is only needed for initial flashing and emergencies.
|
||||
change with the `logonly` → `forward` rename, so firmware that still says
|
||||
`logonly` reads `forward` rules and behaves identically (count, then
|
||||
forward).
|
||||
- One intentional reinterpretation: in a stored pattern an unescaped `|` used
|
||||
to mean a literal pipe and now means OR. Firmware from 2026-10 onwards reads
|
||||
such a rule differently — write `\|` if you want a literal pipe.
|
||||
- **Never lock out your own admin.** Rules are first-match-wins, so a broad
|
||||
early drop rule can silence remote admin login from your app (login replies
|
||||
ride the flood path). Before enabling any catch-all drop rule, add a
|
||||
@@ -743,7 +756,10 @@ complete reference.
|
||||
2. Matching is **case-sensitive** and searches anywhere unless anchored.
|
||||
3. `^` at the start and `$` at the end make the match exact.
|
||||
4. Use `.*` for "anything", not a shell-style `*`.
|
||||
5. There are **no groups, OR operators, counted repeats, or flags**.
|
||||
5. There are **no groups, counted repeats, or flags**.
|
||||
6. `|` separates alternatives: `sender=^Alice$|^Bob$`. Anchors belong to
|
||||
their own alternative, so `^Alice|Bob$` means *starts with Alice* **or**
|
||||
*ends with Bob* — put the `$` on both sides for an exact match of either.
|
||||
|
||||
### Supported syntax
|
||||
|
||||
@@ -764,6 +780,7 @@ complete reference.
|
||||
| `\w` | Letter, digit, or underscore | `^\w+$` | Matches `Bot_42`; not `Bot-42` |
|
||||
| `\s` | Any whitespace (space, tab, …) | `^RX\s+OK$` | Matches `RX OK` and `RX OK` |
|
||||
| `\.` (escaped punctuation) | The literal character | `^v1\.2$` | Matches `v1.2`; not `v1x2` |
|
||||
| `A\|B` | Either alternative (up to 8) | `^Alice$\|^Bob$` | Matches `Alice` or `Bob`; not `Alice2` |
|
||||
|
||||
Tips:
|
||||
|
||||
@@ -781,8 +798,7 @@ as ordinary text rather than rejected:
|
||||
|
||||
| You might try | What actually happens | Do this instead |
|
||||
|---|---|---|
|
||||
| OR: `Alice\|Bob` | Matches the literal name `Alice\|Bob` | Two rules, one per name |
|
||||
| Groups: `(ab)+` | Matches the literal text `(ab)+` | Write the sequence out, or separate rules |
|
||||
| Groups: `sender=^(Alice\|Bob)$` | Matches a sender literally named `(Alice\|Bob)` — **not** Alice or Bob. Parentheses are ordinary characters here | `sender=^Alice$\|^Bob$` |
|
||||
| Counted repeat: `\d{3}` | Matches literal `{3}` | `\d\d\d` |
|
||||
| Case-insensitive: `/i`, `(?i)` | Not supported; always case-sensitive | `^[Bb][Oo][Tt]$` |
|
||||
| Word boundary: `\b` | Matches the literal letter `b` | See the word-boundary recipe below |
|
||||
@@ -790,10 +806,12 @@ as ordinary text rather than rejected:
|
||||
| `\n`, `\t` escapes | Match the letters `n`, `t` | `\s` for whitespace |
|
||||
| Newlines / multiline mode | No per-line matching | Patterns apply to the whole field |
|
||||
|
||||
The command `filter add sender=^Alice|Bob$` therefore matches the literal
|
||||
sender name `Alice|Bob`, **not** either name — and it's accepted without an
|
||||
error. After copying a pattern from another tool, verify with
|
||||
`filter get <idx>` and a test message.
|
||||
`filter add sender=^Alice|Bob$` is accepted, but it means *starts with
|
||||
Alice* **or** *ends with Bob* — `Alice2`, `xxBob`, and `AliceBob` all match it.
|
||||
For an exact match of either name, write `filter add sender=^Alice$|^Bob$`.
|
||||
|
||||
After copying a pattern from another tool, verify with `filter get <idx>` and a
|
||||
test message.
|
||||
|
||||
### Recipe table
|
||||
|
||||
@@ -814,11 +832,20 @@ Patterns are values for `sender` or `text`, exactly as typed at the CLI.
|
||||
| `RX` followed later by `OK` | `RX.*OK` | Not `OK then RX` |
|
||||
| Inside brackets | `\[[^\]]*\]` | Matches `[...]` content |
|
||||
|
||||
**OR between names:** use separate rules (repeat the channel too):
|
||||
**OR between names:** one rule, alternatives separated by `|`:
|
||||
|
||||
```text
|
||||
filter add chan=#test sender=^BotA$
|
||||
filter add chan=#test sender=^WeatherBot$
|
||||
filter add chan=#test sender=^BotA$|^WeatherBot$
|
||||
```
|
||||
|
||||
At most 8 alternatives per pattern, and the whole pattern — every `|` and
|
||||
anchor included — must fit the pattern-length limit. When you outgrow that,
|
||||
either add a second rule (repeat the shared conditions) or use one broader
|
||||
alternative:
|
||||
|
||||
```text
|
||||
filter add chan=#test sender=^BotA$|^BotB$|^BotC$
|
||||
filter add chan=#test sender=^Bot # covers the whole family
|
||||
```
|
||||
|
||||
**Word boundaries:** there is no `\b`. To drop `BOT` as a standalone word
|
||||
@@ -893,7 +920,10 @@ filter stats
|
||||
| Sender/text never matches | Can the repeater decrypt the channel? Is it group text? Are you matching the right field (sender without colon, text without name)? |
|
||||
| Matches too broadly | Add `^`/`$` anchors; escape literal dots; remember `sender=Bot` matches `MyBot2` |
|
||||
| Combined rule matches nothing | Every condition must be true — test each one alone; check `route=`/case |
|
||||
| Pattern from an online tester misbehaves | Remove `/slashes/`, flags, groups, OR, `{counts}`, `\b` — see the table above |
|
||||
| Pattern from an online tester misbehaves | Remove `/slashes/`, flags, groups, `{counts}`, `\b` — see the table above |
|
||||
| `Err - empty alternative in regex` | A `|` with nothing on one side — write `^A$\|^B$`, never `A\|` |
|
||||
| `Err - too many alternatives (max 8)` | Fewer alternatives per pattern, a broader one (e.g. `^Bot`), or a second rule |
|
||||
| Wrote `^(A\|B)$` and nothing matches | There are no groups: parentheses are ordinary characters. Write `^A$\|^B$` |
|
||||
| "Bad/long regex" error | Pattern too long (see [Limits](#limits-and-good-to-knows)) or broken syntax; shorten or simplify |
|
||||
| `aborted` counter grows | Pattern too complex — simplify it |
|
||||
| Drop rule never fires | An earlier overlapping rule (often a `forward` probe) is matching first |
|
||||
@@ -517,13 +517,9 @@ bool FilterRules::channelMatchesStore(const FilterRule* r, const mesh::GroupChan
|
||||
}
|
||||
|
||||
bool FilterRules::regexMatches(const char* pattern, const char* subject) {
|
||||
int matchlength;
|
||||
int idx = re_match(pattern, subject, &matchlength);
|
||||
if (re_budget_exhausted()) {
|
||||
budget_aborts++; // fail-open: worst case is a spam message repeated
|
||||
return false;
|
||||
}
|
||||
return idx >= 0; // re_matchp() sets matchlength=0 even on no-match; use idx
|
||||
if (patternMatches(pattern, subject)) return true;
|
||||
if (patternAborted()) budget_aborts++; // fail-open: worst case is a spam message repeated
|
||||
return false;
|
||||
}
|
||||
|
||||
uint8_t FilterRules::checkContent(mesh::Packet* pkt, uint8_t type, const mesh::GroupChannel& channel,
|
||||
@@ -782,10 +778,23 @@ static bool parsePath(const char* tok, FilterRule* r) {
|
||||
|
||||
// ---------------------------------------------------------------- filter add
|
||||
|
||||
static bool setPattern(char* dest, size_t dest_sz, const char* pattern) {
|
||||
if (strlen(pattern) >= dest_sz) return false; // reject too-long, never truncate a regex
|
||||
// Store a sender=/text= pattern: reject a value too long for this rule's
|
||||
// storage (never truncate a regex) or one the pattern wrapper refuses, then
|
||||
// copy it verbatim. `field` names the pattern in the reply.
|
||||
static bool setPattern(char* dest, size_t dest_sz, const char* pattern, const char* field,
|
||||
char* reply) {
|
||||
if (strlen(pattern) >= dest_sz) { // reject too-long, never truncate a regex
|
||||
snprintf(reply, CLI_REPLY_MAX, "Err - bad/long %s regex", field);
|
||||
return false;
|
||||
}
|
||||
char why[48]; // wrapper reasons, e.g. alternation
|
||||
if (!patternValid(pattern, why, sizeof(why))) {
|
||||
if (why[0]) snprintf(reply, CLI_REPLY_MAX, "Err - %s", why);
|
||||
else snprintf(reply, CLI_REPLY_MAX, "Err - bad/long %s regex", field);
|
||||
return false;
|
||||
}
|
||||
strcpy(dest, pattern);
|
||||
return re_compile(pattern) != 0; // validate syntax at add time
|
||||
return true;
|
||||
}
|
||||
|
||||
static bool addRuleParam(FilterRules& filter, FilterRule* r, RegionMap* regions,
|
||||
@@ -906,19 +915,11 @@ static bool addRuleParam(FilterRules& filter, FilterRule* r, RegionMap* regions,
|
||||
}
|
||||
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;
|
||||
}
|
||||
return true;
|
||||
return setPattern(r->sender, FILTER_SENDER_PATTERN_LEN, val, "sender", reply);
|
||||
}
|
||||
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;
|
||||
}
|
||||
return true;
|
||||
return setPattern(r->text, FILTER_TEXT_PATTERN_LEN, val, "text", reply);
|
||||
}
|
||||
if (strcmp(key, "action") == 0) {
|
||||
if (strcmp(val, "drop") == 0) r->action = FILTER_ACT_DROP;
|
||||
|
||||
@@ -30,7 +30,7 @@
|
||||
#include <helpers/IdentityStore.h> // FILESYSTEM typedef
|
||||
#include <helpers/RegionMap.h> // RegionEntry (region= predicate)
|
||||
#include "PacketFilterConfig.h"
|
||||
#include "TinyRegex.h"
|
||||
#include "PatternMatch.h"
|
||||
|
||||
// actions
|
||||
#define FILTER_ACT_ALLOW 0
|
||||
|
||||
@@ -35,6 +35,12 @@
|
||||
#define FILTER_TEXT_PATTERN_LEN 48 // text regex storage length (NUL incl.)
|
||||
#endif
|
||||
|
||||
#ifndef FILTER_PATTERN_MAX_ALTS
|
||||
// Alternatives ('|'-separated) allowed per sender=/text= pattern. A parse
|
||||
// limit, not a stored field: it does not affect the persisted record layout.
|
||||
#define FILTER_PATTERN_MAX_ALTS 8
|
||||
#endif
|
||||
|
||||
#ifndef FILTER_REGION_LIST_LEN
|
||||
#define FILTER_REGION_LIST_LEN 32 // region= comma list storage length (NUL incl.)
|
||||
#endif
|
||||
|
||||
@@ -0,0 +1,102 @@
|
||||
// PatternMatch.cpp — top-level '|' alternation and structural validation over
|
||||
// the vendored regex engine. See PatternMatch.h for the dialect.
|
||||
|
||||
#include "PatternMatch.h"
|
||||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
#include "PacketFilterConfig.h"
|
||||
#include "TinyRegex.h"
|
||||
|
||||
// The split buffer must hold the longest storable pattern; text patterns are
|
||||
// the wider of the two rule storages, so one buffer sized by it covers both.
|
||||
#define PATTERN_SPLIT_MAX FILTER_TEXT_PATTERN_LEN
|
||||
|
||||
// budget abort flag of the last patternMatches() call
|
||||
static bool g_aborted = false;
|
||||
|
||||
enum SplitResult {
|
||||
SPLIT_OK = 0,
|
||||
SPLIT_EMPTY_ALT, // "A|", "|A", "A||B": an empty branch would match everything
|
||||
SPLIT_TOO_MANY, // more alternatives than FILTER_PATTERN_MAX_ALTS
|
||||
SPLIT_UNUSABLE, // does not fit buf (callers reject over-long patterns first)
|
||||
};
|
||||
|
||||
// Copy `pattern` into `buf` and terminate every top-level alternative in place,
|
||||
// so the alternatives can be walked as consecutive NUL-terminated strings.
|
||||
// Returns the alternative count, or 0 with *result set on rejection. A '\'
|
||||
// escape and a [...] class both hold literal bytes: '\|' and '[|]' are pipes,
|
||||
// '[\]|]' is a class holding ']'.
|
||||
static int splitAlternatives(const char* pattern, char* buf, size_t buf_sz,
|
||||
SplitResult* result) {
|
||||
size_t len = strlen(pattern);
|
||||
if (len + 1 > buf_sz) { *result = SPLIT_UNUSABLE; return 0; }
|
||||
memcpy(buf, pattern, len + 1);
|
||||
|
||||
int alts = 1;
|
||||
size_t start = 0; // offset where the alternative being scanned begins
|
||||
bool in_class = false; // inside [...] — '|' there is a class member
|
||||
for (size_t i = 0; i < len; i++) {
|
||||
char c = buf[i];
|
||||
if (c == '\\') { i++; continue; } // escaped byte
|
||||
if (in_class) {
|
||||
if (c == ']') in_class = false;
|
||||
continue;
|
||||
}
|
||||
if (c == '[') { in_class = true; continue; }
|
||||
if (c != '|') continue;
|
||||
|
||||
if (i == start) { *result = SPLIT_EMPTY_ALT; return 0; }
|
||||
if (alts >= FILTER_PATTERN_MAX_ALTS) { *result = SPLIT_TOO_MANY; return 0; }
|
||||
buf[i] = 0; // terminate this alternative in place
|
||||
start = i + 1;
|
||||
alts++;
|
||||
}
|
||||
if (start == len) { *result = SPLIT_EMPTY_ALT; return 0; } // trailing '|'
|
||||
|
||||
*result = SPLIT_OK;
|
||||
return alts;
|
||||
}
|
||||
|
||||
bool patternValid(const char* pattern, char* err, size_t err_sz) {
|
||||
err[0] = 0;
|
||||
char buf[PATTERN_SPLIT_MAX];
|
||||
SplitResult result;
|
||||
int alts = splitAlternatives(pattern, buf, sizeof(buf), &result);
|
||||
if (alts == 0) {
|
||||
if (result == SPLIT_EMPTY_ALT) snprintf(err, err_sz, "empty alternative in regex");
|
||||
else if (result == SPLIT_TOO_MANY) {
|
||||
snprintf(err, err_sz, "too many alternatives (max %d)", FILTER_PATTERN_MAX_ALTS);
|
||||
}
|
||||
return false;
|
||||
}
|
||||
const char* alt = buf;
|
||||
for (int i = 0; i < alts; i++) {
|
||||
if (re_compile(alt) == NULL) return false; // engine rejects it: no reason given
|
||||
alt += strlen(alt) + 1;
|
||||
}
|
||||
return true;
|
||||
}
|
||||
|
||||
bool patternMatches(const char* pattern, const char* subject) {
|
||||
g_aborted = false;
|
||||
char buf[PATTERN_SPLIT_MAX];
|
||||
SplitResult result;
|
||||
int alts = splitAlternatives(pattern, buf, sizeof(buf), &result);
|
||||
if (alts == 0) return false; // stored pattern cannot split: never matches
|
||||
const char* alt = buf;
|
||||
for (int i = 0; i < alts; i++) {
|
||||
re_t compiled = re_compile(alt);
|
||||
if (compiled == NULL) return false; // stored pattern the engine rejects
|
||||
int matchlength;
|
||||
int idx = re_matchp(compiled, subject, &matchlength);
|
||||
if (re_budget_exhausted()) { g_aborted = true; return false; } // fail-open
|
||||
if (idx >= 0) return true;
|
||||
alt += strlen(alt) + 1;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
|
||||
bool patternAborted(void) {
|
||||
return g_aborted;
|
||||
}
|
||||
@@ -0,0 +1,47 @@
|
||||
// PatternMatch.h — the user-facing sender=/text= pattern language: the vendored
|
||||
// regex engine plus top-level '|' alternation and structural validation.
|
||||
// Personal fork feature; this file pair is fork-owned like the rest of the
|
||||
// packet filter's code set, and the vendored engine (TinyRegex.h/.cpp) stays
|
||||
// untouched — everything a user can type is decided here.
|
||||
//
|
||||
// Dialect (see FILTER.md for the user-facing reference):
|
||||
// - '|' at the top level splits the pattern into alternatives, which are
|
||||
// matched in order, first match wins: "Alice|Bob" matches either name.
|
||||
// '\|' is a literal pipe and '|' inside a [...] class is a class member.
|
||||
// - Anchors bind to their own alternative, standard regex style:
|
||||
// "^Alice|Bob$" is "(^Alice)|(Bob$)". For an exact match of either, write
|
||||
// "^Alice$|^Bob$".
|
||||
// - There are no groups: '(' and ')' stay ordinary characters, as they were
|
||||
// before alternation existed, so "^(Alice|Bob)$" matches a sender literally
|
||||
// named "(Alice|Bob)" — parentheses are documented as not supported.
|
||||
// - At most FILTER_PATTERN_MAX_ALTS alternatives; an empty alternative
|
||||
// ("A|", "|A", "A||B") is rejected, because an empty branch matches
|
||||
// everything.
|
||||
// A pattern is stored as text and re-split on every evaluation, so the
|
||||
// compiled engine state never outlives one evaluation. Cost is bounded by
|
||||
// FILTER_PATTERN_MAX_ALTS x the engine's per-call step budget, and evaluation
|
||||
// stops at the first alternative that exhausts that budget (fail-open).
|
||||
|
||||
#ifndef _PATTERN_MATCH_H
|
||||
#define _PATTERN_MATCH_H
|
||||
|
||||
#include <stddef.h>
|
||||
|
||||
// Syntax-check a pattern at add time. Returns false if it is rejected.
|
||||
// `err` must be a buffer of at least `err_sz` bytes (err_sz >= 1); it is always
|
||||
// written and holds a short reason only for rejections made here (empty
|
||||
// alternative, too many alternatives) — an empty `err` means the vendored
|
||||
// engine rejected the pattern itself, so the caller should use its own
|
||||
// "bad/long ... regex" fallback wording.
|
||||
bool patternValid(const char* pattern, char* err, size_t err_sz);
|
||||
|
||||
// True if the pattern matches anywhere in `subject`. On step-budget exhaustion
|
||||
// the whole evaluation gives up: no match, patternAborted() true, fail-open
|
||||
// (the engine has always failed open).
|
||||
bool patternMatches(const char* pattern, const char* subject);
|
||||
|
||||
// Non-zero if the last patternMatches() gave up on the step budget. Cleared by
|
||||
// the next patternMatches() call; the caller counts these as budget aborts.
|
||||
bool patternAborted(void);
|
||||
|
||||
#endif // _PATTERN_MATCH_H
|
||||
@@ -34,6 +34,10 @@
|
||||
*
|
||||
* NOTE: no groups '(...)' and no alternation '|'. NOTE: '\n' and '\t' are NOT
|
||||
* C-style escapes ('\n' matches a literal 'n'); use '\s' for whitespace.
|
||||
*
|
||||
* The user-facing sender=/text= dialect lives one layer up, in
|
||||
* PatternMatch.h/.cpp: alternation ('|'), the alternative cap and structural
|
||||
* validation. Syntax is added there, not here.
|
||||
*/
|
||||
|
||||
#ifndef _TINY_REGEX_C
|
||||
|
||||
+7
-5
@@ -193,11 +193,12 @@ lib_deps =
|
||||
google/googletest @ 1.17.0
|
||||
|
||||
; Native tests for the simple_repeater packet filter (fork-owned
|
||||
; examples/simple_repeater/PacketFilter* + TinyRegex). NativeShim.h is force-
|
||||
; included first: it provides the Arduino FILESYSTEM/File stand-ins and ltoa()
|
||||
; declaration the filter code needs on the host. src/helpers/RegionMap.cpp is
|
||||
; not linked (needs Stream::printf); test/test_packet_filter/RegionMapStub.cpp
|
||||
; resolves findByNamePrefix() from a fixed table instead.
|
||||
; examples/simple_repeater/PacketFilter* + PatternMatch* + TinyRegex).
|
||||
; NativeShim.h is force-included first: it provides the Arduino FILESYSTEM/File
|
||||
; stand-ins and ltoa() declaration the filter code needs on the host.
|
||||
; src/helpers/RegionMap.cpp is not linked (needs Stream::printf);
|
||||
; test/test_packet_filter/RegionMapStub.cpp resolves findByNamePrefix() from a
|
||||
; fixed table instead.
|
||||
[env:native_packet_filter]
|
||||
platform = native
|
||||
test_framework = googletest
|
||||
@@ -217,6 +218,7 @@ build_src_filter =
|
||||
+<../src/Packet.cpp>
|
||||
+<../src/helpers/TxtDataHelpers.cpp>
|
||||
+<../examples/simple_repeater/PacketFilter.cpp>
|
||||
+<../examples/simple_repeater/PatternMatch.cpp>
|
||||
+<../examples/simple_repeater/TinyRegex.cpp>
|
||||
lib_deps =
|
||||
google/googletest @ 1.17.0
|
||||
|
||||
@@ -3,8 +3,8 @@
|
||||
// [env:native_packet_filter] in platformio.ini; see that env for the shim and
|
||||
// stub notes.
|
||||
//
|
||||
// Sections: TinyRegex, packet-level matching, content rules, advert rate
|
||||
// limiter, management/persistence, and the filter CLI.
|
||||
// Sections: TinyRegex, PatternMatch, packet-level matching, content rules,
|
||||
// advert rate limiter, management/persistence, and the filter CLI.
|
||||
//
|
||||
// Coverage map (2026-09-13 host-native gap analysis; on-air semantics mirrored
|
||||
// from the Phase-4 raw-packet suites):
|
||||
@@ -21,6 +21,7 @@
|
||||
// gate) section; throttle= parse/echo/capacity -> filter CLI surface;
|
||||
// throttle persistence + v6 record growth -> management/persistence
|
||||
// regex budget/anchors/classes -> TinyRegex* tests
|
||||
// pattern alternation (split/reject/budget) -> PatternMatch* tests
|
||||
// hook order (battery gate -> checkPacket -> disable_fwd, MyMesh.cpp
|
||||
// allowPacketForward; checkContent in onGroupDataRecv) is a MyMesh
|
||||
// wiring property, asserted by code review of the hook lines, not here
|
||||
@@ -196,6 +197,141 @@ TEST(TinyRegexClasses, EdgeClasses) {
|
||||
EXPECT_EQ(match("[a-]+", "a-a"), 0); // trailing '-' is a literal
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// UNIT TESTS: PatternMatch (top-level '|' alternation + validation)
|
||||
// ============================================================
|
||||
|
||||
// Native tests for PatternMatch — the user-facing pattern language layered on
|
||||
// the vendored engine: '|' alternation, anchors per branch, structural
|
||||
// rejections, and the step-budget interaction.
|
||||
|
||||
#include <gtest/gtest.h>
|
||||
|
||||
#include "PatternMatch.h"
|
||||
|
||||
namespace {
|
||||
|
||||
// reason patternValid() reports for a rejected pattern; "" when the wrapper
|
||||
// defers to the engine (caller's own "bad/long ... regex" fallback)
|
||||
std::string why(const char* pattern) {
|
||||
char err[48];
|
||||
bool ok = patternValid(pattern, err, sizeof(err));
|
||||
EXPECT_FALSE(ok) << pattern; // the reason only exists for rejected patterns
|
||||
return std::string(err);
|
||||
}
|
||||
|
||||
// true if the pattern is accepted (its wrapper reason is printed if it is not)
|
||||
bool accepted(const char* pattern) {
|
||||
char err[48];
|
||||
bool ok = patternValid(pattern, err, sizeof(err));
|
||||
EXPECT_TRUE(ok) << pattern << ": " << err;
|
||||
return ok;
|
||||
}
|
||||
|
||||
} // namespace
|
||||
|
||||
TEST(PatternMatchAlternation, MatchesEitherAlternative) {
|
||||
EXPECT_TRUE(patternMatches("Alice|Bob", "Alice"));
|
||||
EXPECT_TRUE(patternMatches("Alice|Bob", "Bob"));
|
||||
EXPECT_FALSE(patternMatches("Alice|Bob", "Carol"));
|
||||
}
|
||||
|
||||
TEST(PatternMatchAlternation, UnanchoredAlternativesMatchAnywhere) {
|
||||
// same dialect as before: unanchored means search-anywhere
|
||||
EXPECT_TRUE(patternMatches("Alice|Bob", "not-Alice"));
|
||||
EXPECT_TRUE(patternMatches("Alice|Bob", "xxBobxx"));
|
||||
EXPECT_TRUE(patternMatches("Bot|PING", "xxPINGxx"));
|
||||
}
|
||||
|
||||
TEST(PatternMatchAlternation, AnchorsBindToTheirOwnBranch) {
|
||||
EXPECT_TRUE(patternMatches("^A$|^B$", "A"));
|
||||
EXPECT_TRUE(patternMatches("^A$|^B$", "B"));
|
||||
EXPECT_FALSE(patternMatches("^A$|^B$", "AB"));
|
||||
// POSIX semantics: "^Alice|Bob$" is "(^Alice)|(Bob$)" — not an exact match of
|
||||
// either: "AliceX" matches the first branch, "xxBob" the second
|
||||
EXPECT_TRUE(patternMatches("^Alice|Bob$", "AliceX"));
|
||||
EXPECT_TRUE(patternMatches("^Alice|Bob$", "xxBob"));
|
||||
EXPECT_FALSE(patternMatches("^Alice|Bob$", "xAlicex xxBobx"));
|
||||
}
|
||||
|
||||
TEST(PatternMatchEscapes, EscapedPipeAndClassPipeAreLiteral) {
|
||||
EXPECT_TRUE(patternMatches("a\\|b", "a|b"));
|
||||
EXPECT_FALSE(patternMatches("a\\|b", "aXXb"));
|
||||
EXPECT_TRUE(patternMatches("[|]", "x|y")); // pipe inside a class
|
||||
EXPECT_TRUE(patternMatches("[|]", "|"));
|
||||
EXPECT_TRUE(patternMatches("x[ab|]z", "xbz")); // class member, not a split
|
||||
EXPECT_TRUE(patternMatches("x[ab|]z", "x|z"));
|
||||
EXPECT_FALSE(patternMatches("x[ab|]z", "xz"));
|
||||
// escaped class terminator keeps the class open, so the '|' after it is still
|
||||
// top level: "A" matching proves the split happened
|
||||
EXPECT_TRUE(patternMatches("[\\]]|A", "A"));
|
||||
EXPECT_TRUE(patternMatches("[\\]]|A", "x]")); // first branch is the class {]}
|
||||
}
|
||||
|
||||
TEST(PatternMatchValidation, EmptyAlternativesRejected) {
|
||||
EXPECT_EQ(why("A|"), "empty alternative in regex");
|
||||
EXPECT_EQ(why("|A"), "empty alternative in regex");
|
||||
EXPECT_EQ(why("A||B"), "empty alternative in regex");
|
||||
EXPECT_EQ(why("|"), "empty alternative in regex");
|
||||
}
|
||||
|
||||
TEST(PatternMatchValidation, AlternativeCapEnforced) {
|
||||
EXPECT_TRUE(accepted("a|b|c|d|e|f|g|h")); // exactly the cap
|
||||
EXPECT_EQ(why("a|b|c|d|e|f|g|h|i"), "too many alternatives (max 8)");
|
||||
}
|
||||
|
||||
TEST(PatternMatchValidation, EngineErrorsCarryNoReason) {
|
||||
// the wrapper defers broken branch syntax to the engine; the caller's own
|
||||
// "bad/long ... regex" wording stays authoritative
|
||||
EXPECT_EQ(why("A|[a"), "");
|
||||
EXPECT_EQ(why("A|BC\\"), "");
|
||||
// branch past the engine's symbol capacity (29 max)
|
||||
std::string deep_branch(30, 'a');
|
||||
EXPECT_EQ(why(deep_branch.c_str()), "");
|
||||
}
|
||||
|
||||
TEST(PatternMatchValidation, ParenthesesStayLiteral) {
|
||||
// no groups: '(' and ')' are ordinary characters, exactly as before
|
||||
// alternation existed — so the grouped spelling never matches a name
|
||||
EXPECT_TRUE(patternMatches("^(A|B)$", "(A|B)"));
|
||||
EXPECT_FALSE(patternMatches("^(A|B)$", "Alice"));
|
||||
EXPECT_FALSE(patternMatches("^(A|B)$", "A"));
|
||||
EXPECT_TRUE(patternMatches("\\(x\\)", "(x)"));
|
||||
EXPECT_TRUE(accepted("^(A|B)$")); // accepted, as it always was
|
||||
}
|
||||
|
||||
TEST(PatternMatchNoAlternation, UnchangedDialectWithoutPipe) {
|
||||
EXPECT_TRUE(patternMatches("^hello world$", "hello world"));
|
||||
EXPECT_FALSE(patternMatches("^hello world$", "hello world!"));
|
||||
EXPECT_TRUE(patternMatches("Bot[0-9]+$", "Bot42"));
|
||||
EXPECT_FALSE(patternMatches("Bot[0-9]+$", "Bot"));
|
||||
EXPECT_TRUE(patternMatches("\\d+", "ab-1234"));
|
||||
EXPECT_TRUE(patternMatches("v1\\.2", "v1.2"));
|
||||
EXPECT_FALSE(patternMatches("v1\\.2", "v1x2"));
|
||||
EXPECT_TRUE(patternMatches("RX.*OK", "RX then OK"));
|
||||
EXPECT_FALSE(patternMatches("RX.*OK", "OK then RX"));
|
||||
}
|
||||
|
||||
TEST(PatternMatchBudget, AbortStopsEvaluationAndIsReported) {
|
||||
re_set_step_budget(10);
|
||||
EXPECT_FALSE(patternMatches("a*a*a*a*a*b|a*a*a*a*a*c", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa"));
|
||||
EXPECT_TRUE(patternAborted());
|
||||
|
||||
// a cheap pattern afterwards clears the flag (as the engine does per call)
|
||||
EXPECT_TRUE(patternMatches("abc|cde", "xxabcxx"));
|
||||
EXPECT_FALSE(patternAborted());
|
||||
re_set_step_budget(5000); // restore the compiled-in default
|
||||
}
|
||||
|
||||
TEST(PatternMatchBudget, BudgetIsPerAlternative) {
|
||||
// each alternative gets the full budget, so a later branch can still match
|
||||
// after an expensive earlier one that ran out of patience
|
||||
re_set_step_budget(20);
|
||||
EXPECT_TRUE(patternMatches("a*a*a*a*a*b|abc", "abc"));
|
||||
EXPECT_FALSE(patternAborted());
|
||||
re_set_step_budget(5000);
|
||||
}
|
||||
|
||||
// ============================================================
|
||||
// UNIT TESTS: packet-level rule matching (checkPacket)
|
||||
// ============================================================
|
||||
@@ -785,6 +921,53 @@ TEST_F(FilterTest, RegexBudgetAbortFailsOpenAndCounts) {
|
||||
re_set_step_budget(5000); // restore the compiled-in default
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, AlternationSenderAndText) {
|
||||
expectOk(filter, "add sender=^Alice$|^Bob$ text=^PING$|^PONG$ action=drop");
|
||||
auto chan = channelFromStore(filter, 0);
|
||||
|
||||
struct { const char* sender; const char* text; uint8_t want; } cases[] = {
|
||||
{ "Alice", "PING", FILTER_ACT_DROP },
|
||||
{ "Bob", "PONG", FILTER_ACT_DROP },
|
||||
{ "Carol", "PING", FILTER_ACT_ALLOW }, // no sender alternative matches
|
||||
{ "Alice", "HELLO", FILTER_ACT_ALLOW }, // no text alternative matches
|
||||
};
|
||||
for (auto& c : cases) {
|
||||
auto payload = makeGroupText(c.sender, c.text);
|
||||
auto pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, payload.len);
|
||||
EXPECT_EQ(filter.checkContent(&pkt, PAYLOAD_TYPE_GRP_TXT, chan, payload.data,
|
||||
payload.len, nullptr),
|
||||
c.want)
|
||||
<< c.sender << ": " << c.text;
|
||||
}
|
||||
EXPECT_EQ(filter.getRule(0)->hits, 2u); // only the two matching pairs
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, AlternationFirstMatchWinsAgainstOverlappingRule) {
|
||||
expectOk(filter, "add text=^PING$|^PONG$");
|
||||
expectOk(filter, "add text=PING");
|
||||
auto chan = channelFromStore(filter, 0);
|
||||
auto payload = makeGroupText("S", "PING");
|
||||
auto pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, payload.len);
|
||||
EXPECT_EQ(filter.checkContent(&pkt, PAYLOAD_TYPE_GRP_TXT, chan, payload.data,
|
||||
payload.len, nullptr),
|
||||
FILTER_ACT_DROP);
|
||||
EXPECT_EQ(filter.getRule(0)->hits, 1u);
|
||||
EXPECT_EQ(filter.getRule(1)->hits, 0u);
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, AlternationBudgetAbortFailsOpenAndCountsOnce) {
|
||||
expectOk(filter, "add text=a*a*a*a*a*b|^PING$"); // first branch burns the budget
|
||||
re_set_step_budget(10);
|
||||
auto payload = makeGroupText("S", "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaa");
|
||||
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_ALLOW); // fail-open: forwarded, not dropped
|
||||
EXPECT_EQ(filter.getBudgetAborts(), 1u); // one abort, not one per alternative
|
||||
re_set_step_budget(5000); // restore the compiled-in default
|
||||
}
|
||||
|
||||
// ---------------------------------------------------------------- searchChannelsByHash
|
||||
|
||||
TEST_F(FilterTest, SearchChannelsByHash) {
|
||||
@@ -2147,6 +2330,43 @@ TEST_F(FilterTest, AddRejectsOverlongRegexWithoutTruncating) {
|
||||
EXPECT_EQ(filter.getNumRules(), 0);
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, AddAcceptsAlternationAndGetRoundTrips) {
|
||||
ASSERT_EQ(cli(filter, "add sender=^Alice$|^Bob$ text=^PING$|^PONG$"),
|
||||
"OK - rule 0 added");
|
||||
// get output must stay valid add input: the pattern round-trips verbatim
|
||||
std::string got = cli(filter, "get 0");
|
||||
EXPECT_NE(got.find("sender=^Alice$|^Bob$"), std::string::npos);
|
||||
EXPECT_NE(got.find("text=^PING$|^PONG$"), std::string::npos);
|
||||
EXPECT_EQ(strcmp(filter.getRule(0)->sender, "^Alice$|^Bob$"), 0);
|
||||
EXPECT_EQ(strcmp(filter.getRule(0)->text, "^PING$|^PONG$"), 0);
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, AddAcceptsGroupedSpellingButItNeverMatches) {
|
||||
// no groups: parentheses stay ordinary characters, so this rule matches a
|
||||
// sender literally named "(Alice|Bob)" and nothing else
|
||||
ASSERT_EQ(cli(filter, "add sender=^(Alice|Bob)$"), "OK - rule 0 added");
|
||||
auto chan = channelFromStore(filter, 0);
|
||||
auto from_alice = makeGroupText("Alice", "hi");
|
||||
auto pkt = makePacket(ROUTE_TYPE_FLOOD, PAYLOAD_TYPE_GRP_TXT, from_alice.len);
|
||||
EXPECT_EQ(filter.checkContent(&pkt, PAYLOAD_TYPE_GRP_TXT, chan, from_alice.data,
|
||||
from_alice.len, nullptr),
|
||||
FILTER_ACT_ALLOW);
|
||||
EXPECT_EQ(filter.getRule(0)->hits, 0u);
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, AddRejectsAlternationStructure) {
|
||||
EXPECT_EQ(cli(filter, "add sender=A|"), "Err - empty alternative in regex");
|
||||
EXPECT_EQ(cli(filter, "add text=|A"), "Err - empty alternative in regex");
|
||||
EXPECT_EQ(cli(filter, "add sender=A||B"), "Err - empty alternative in regex");
|
||||
EXPECT_EQ(cli(filter, "add text=a|b|c|d|e|f|g|h|i"),
|
||||
"Err - too many alternatives (max 8)");
|
||||
EXPECT_EQ(filter.getNumRules(), 0); // every reject rolls the half-added rule back
|
||||
// a broken branch keeps the pre-existing engine wording
|
||||
EXPECT_EQ(cli(filter, "add sender=A|[a"), "Err - bad/long sender regex");
|
||||
EXPECT_EQ(cli(filter, "add sender=Alice\\|Bob"), "OK - rule 0 added"); // escaped pipe
|
||||
EXPECT_NE(cli(filter, "get 0").find("sender=Alice\\|Bob"), std::string::npos);
|
||||
}
|
||||
|
||||
TEST_F(FilterTest, AddPathRejectsEmptySegments) {
|
||||
// parseHexHash needs >= 2 hex chars, so empty chain segments must fail
|
||||
EXPECT_EQ(cli(filter, "add path=10>"), "Err - bad path spec");
|
||||
|
||||
Reference in new issue
Block a user