[Feature] Add follow_master option for proxy mirror connections
When a mirror has a short timeout to avoid delays from misconfigured
mirrors, the mirror connection gets prematurely terminated if the
upstream takes longer than the mirror timeout. The new follow_master
option ties the mirror's lifetime to the master upstream: the mirror
stays alive while the upstream is processing and is terminated once the
upstream completes or permanently errors out.
Vsevolod Stakhov [Fri, 27 Feb 2026 11:15:36 +0000 (11:15 +0000)]
[Fix] Force recompilation of stale hyperscan classes instead of skipping
When a cached hyperscan blob fails validation during load (stale IDs
pointing to wrong re_class), mark the class with needs_recompile flag.
On subsequent exists_async check in hs_helper, ignore the "exists"
result and proceed with recompilation instead of skipping.
Vsevolod Stakhov [Fri, 27 Feb 2026 11:01:13 +0000 (11:01 +0000)]
[Fix] Do not enable HS cleanup when disable_hyperscan is set
When disable_hyperscan is true, workers skip loading hyperscan databases
and never notify main about known cache files. This caused main to delete
all cached .hs.zst files on exit since none were marked as "known".
Also promote worker hyperscan notification to info log level.
Vsevolod Stakhov [Fri, 27 Feb 2026 10:22:18 +0000 (10:22 +0000)]
[Feature] Per-class deterministic regexp IDs in re_cache
Group regexp IDs by class instead of assigning them globally.
Each class gets a deterministic base_offset in the global array,
and hyperscan stores intra-class IDs (0..M-1). This prevents
adding/removing a regexp in one class from shifting IDs in all
other classes, eliminating stale hyperscan databases and
unnecessary recompilations.
Key changes:
- Sort classes by class_id, regexps within each class by content hash
- Assign contiguous global IDs per class (base_offset + local_index)
- Use class-local regexp count in per-class hash (not global count)
- Hyperscan compile stores intra-class IDs, callback translates back
- Bump blob magic version to reject old format databases
Vsevolod Stakhov [Thu, 26 Feb 2026 12:54:05 +0000 (12:54 +0000)]
[Feature] Wire Lua rspamd_fasttext through maps infrastructure
Add load_map(cfg, path) to rspamd_fasttext module that loads FastText
models via the maps infrastructure (HTTP URLs + file with shared mmap).
The fasttext_embed neural provider now registers models as maps at
config time via a new init callback, enabling shared memory across
workers and automatic reload on map updates.
Vsevolod Stakhov [Wed, 25 Feb 2026 15:26:58 +0000 (15:26 +0000)]
[Fix] Fix SIGSEGV on termination in fasttext map dtor callback
Two bugs in the map callback lifecycle caused a crash during
rspamd_map_remove_all at shutdown:
1. Type mismatch: fin_callback published *target = model pointer
(fasttext_model*), but the dtor cast it to fasttext_map_data* -
the standard map pattern requires *target = data->cur_data.
2. Use-after-free: map->user_data pointed into the fasttext_langdet
object which was destroyed before rspamd_map_remove_all ran.
Fix by allocating the user_data target on cfg->cfg_pool (outlives
the lang detector), following the standard map consumer pattern,
and accessing the model through a get_model() indirection.
Vsevolod Stakhov [Wed, 25 Feb 2026 14:59:53 +0000 (14:59 +0000)]
[Fix] Use 16K map cache header for mmap alignment on ARM64
Apple Silicon requires mmap offsets to be 16K-aligned (page size is
16384, not 4096). Bump RSPAMD_MAP_CACHE_HEADER_SIZE to 16384 to work
on all common architectures.
Vsevolod Stakhov [Wed, 25 Feb 2026 14:51:07 +0000 (14:51 +0000)]
[Feature] Wire fasttext lang detector through maps infrastructure
The fasttext language detector now supports HTTP/HTTPS URLs for model
loading via the maps system, enabling automatic download, disk caching,
periodic reload, and cross-worker mmap sharing.
Changes:
- fasttext_model::load() accepts an offset parameter for mmap at a
non-zero position (used with page-aligned map cache files)
- fasttext_langdet uses rspamd_map_is_map() to detect URLs vs local
paths; URLs go through rspamd_map_add() with RSPAMD_MAP_FILE_NO_READ
- Map callbacks (read/fin/dtor) handle atomic model swap on reload
- Local file paths continue to work as before with direct loading
Vsevolod Stakhov [Wed, 25 Feb 2026 12:57:35 +0000 (12:57 +0000)]
[Feature] Page-aligned map cache header for no_file_read mmap support
Upgrade HTTP map cache file format to use a page-aligned (4096 byte)
header so that no_file_read consumers (CDB, fasttext models) can mmap
the cached file directly at a fixed offset without needing a separate
sidecar file.
Changes:
- Bump cache magic to rmcd2001; old rmcd2000 files are read gracefully
and rewritten on next update
- Header page (4096 bytes) contains struct + etag + zero padding; data
payload always starts at RSPAMD_MAP_CACHE_HEADER_SIZE offset
- For no_file_read maps with HTTP backends, pass the cache file path
to read_callback (instead of payload bytes) with no_file_read_offset
set to 4096; for file backends offset remains 0
- Add rspamd_map_get_no_file_read_offset() public API for consumers
- Refactor cache path computation into rspamd_map_cache_file_path()
helper, removing 4 duplicate hash+snprintf blocks
- Handle all 3 HTTP data delivery paths: live GET (controller),
SHM cache read (scanner workers), disk cache preload (startup)
Vsevolod Stakhov [Tue, 24 Feb 2026 21:42:03 +0000 (21:42 +0000)]
[Fix] Propagate source/classification URL flags to query-extracted URLs
When a URL is found inside the query string of another URL (e.g.
http://redir.com/?q=http://target.com), the inner URL now inherits
source/classification flags (FROM_TEXT, CONTENT, SUBJECT, INVISIBLE)
from the outer URL via RSPAMD_URL_FLAG_PROPAGATE_MASK.
Previously, inner URLs only received the QUERY flag, losing all context
about where the parent URL was found. This caused inconsistencies in
plugins that filter URLs by source flags (e.g. RBL content URL filtering).
Also fixes two bugs in the subject path (rspamd_url_task_subject_callback):
- hostlen check used outer URL instead of inner query URL
- QUERY flag was not set on URLs extracted from subject URL queries
Dmitriy Alekseev [Tue, 24 Feb 2026 17:19:40 +0000 (18:19 +0100)]
fix: properly set bayes class labels to S and H for class spam and ham class names, adjust bayes expiry to write occurrences as spam and ham instead of S and H
[Conf] Disable Validity SenderScore RBLs by default
Both bl.score.senderscore.com and score.senderscore.com require
a registered MyValidity account to function. Unregistered IPs
receive 127.255.255.255 (blocked) for all queries, making the
RBLs non-functional without prior account setup regardless of
query volume.
Disable senderscore_reputation (score.senderscore.com) by default
and update the senderscore (bl.score.senderscore.com) comment to
reflect the actual registration requirement. Users must register
their querying IPs at https://my.validity.com before enabling
either RBL.
Vsevolod Stakhov [Tue, 24 Feb 2026 13:38:31 +0000 (13:38 +0000)]
[Fix] Move binary msgpack data from KEYS to ARGV in Bayes Redis scripts
When expand_keys is enabled, lutil.template() is applied to all KEYS
arguments of EVALSHA commands. This corrupts binary msgpack blobs by
stripping 0x24 ('$') bytes, breaking str8 headers where the length
byte equals 36. Move non-key arguments (msgpack tokens, config, labels)
to ARGV which is not subject to key expansion.
Also fix msgpack_str_len off-by-one for str32 (4+len -> 5+len).
Vsevolod Stakhov [Tue, 24 Feb 2026 11:37:27 +0000 (11:37 +0000)]
[Fix] Fix subprocess cleanup race in spawn_process SIGCHLD handler
When the I/O handler finishes reading the subprocess reply before
SIGCHLD arrives, neither handler would call rspamd_lua_cbdata_free:
the I/O handler skips cleanup because dead=FALSE, and the SIGCHLD
handler skips cleanup because replied=TRUE. This leaves the subprocess
in the main process workers table, causing shutdown to wait for a
child that has already exited.
Fix by always calling rspamd_lua_cbdata_free in the SIGCHLD handler
when replied=TRUE, since the I/O handler has already finished and
deferred cleanup to us.
Vsevolod Stakhov [Tue, 24 Feb 2026 11:29:54 +0000 (11:29 +0000)]
[Fix] Use main Lua state in config object destructors
The periodic, cached config, and symbol callback destructors stored a
raw lua_State pointer captured at registration time. If this was a
thread/coroutine state from the thread pool, it could be garbage
collected before the destructor runs during config cleanup, causing a
use-after-free crash in luaL_unref.
Use RSPAMD_LUA_CFG_STATE(cfg) instead, which is the main Lua state
that remains valid throughout config_free until rspamd_lua_close.
Vsevolod Stakhov [Tue, 24 Feb 2026 11:07:50 +0000 (11:07 +0000)]
[Fix] Prevent LuaJIT GC stalls after neural training
The LuaJIT GC atomic phase is non-incremental and processes the entire
gray/grayagain object graph in one uninterruptible pass. After neural
training completes, the controller's Lua heap is bloated with training
temporaries, causing the next GC cycle's atomic phase to stall the
event loop at 100% CPU for an extended period.
Two fixes:
- Force collectgarbage('collect') in ann_trained callback to clean up
training temporaries before they accumulate
- Stop/restart GC around fork() in spawn_process to prevent the child
from inheriting a mid-cycle GC state that triggers thrashing
Vsevolod Stakhov [Mon, 23 Feb 2026 09:14:35 +0000 (09:14 +0000)]
[Feature] Fasttext embed: multi-scale conv1d pooling for text features
Add conv1d output mode to the fasttext_embed provider that applies
multi-scale max-over-time pooling over sliding word windows in Lua,
producing compact feature vectors for the neural plugin's dense ANN.
For each kernel size (default {1, 3, 5}), word vectors are averaged
within sliding windows, then max-pooled across positions per channel.
Each scale's features are L2-normalized independently for balanced
contribution. This replaces the previous approach of feeding raw NCW
matrices into KANN conv1d layers.
Also adds max1d and input3d layer bindings to the KANN Lua API, and
includes conv1d settings (kernel_sizes, conv_pooling, max_words) in
the providers_config_digest for automatic retraining on config change.
Vsevolod Stakhov [Sun, 22 Feb 2026 18:11:44 +0000 (18:11 +0000)]
[Feature] Fasttext embed: SIF word weighting for sentence vectors
Add Smooth Inverse Frequency (SIF) weighting to the fasttext embedding
provider. Common words (the, is, a) get near-zero weight while
distinctive words (viagra, invoice) get high weight, significantly
improving embedding quality without changing dimensionality.
Expose get_word_frequency() from the fasttext shim C++ API and Lua
bindings, returning p(word) = count/ntokens from the model vocabulary.
SIF is enabled by default (sif_weight=true, sif_a=1e-3). Combined with
multi-model mean+max pooling, improves F1 from 0.87 to 0.90 in testing.
[Minor] Replace hash table with linear search for class deduplication
Number of classes per classifier is always small (N < 10 in practice),
so hash table overhead outweighs its O(1) lookup benefit. Linear search
over the already-built UCL array is simpler and faster here.
Vsevolod Stakhov [Sun, 22 Feb 2026 11:07:49 +0000 (11:07 +0000)]
[Feature] Fasttext embed: multi-model and mean+max pooling
Use all configured language_models for every message by default
(multi_model=true), concatenating vectors from each model for
richer cross-lingual representations.
Add mean+max pooling (pooling="mean_max" default) which concatenates
the average word vector with element-wise max pooling, capturing both
typical and prominent semantic features.
With 2 quantized 50-dim models this produces 200-dim vectors instead
of 50, significantly improving classification (F1 0.51 -> 0.87 in
testing).
Vsevolod Stakhov [Sat, 21 Feb 2026 17:27:42 +0000 (17:27 +0000)]
[Fix] Fasttext shim: fix binary format parsing and harden against corrupt models
- Fix QMatrix load order: read codesize+codes before PQ (not after)
- Fix PQ centroid count: use dim*ksub (not nsubq*ksub*dsub)
- Fix PQ centroid addressing: match FastText's get_centroids() for last sub-quantizer
- Fix dictionary load: read size_ field before nwords/nlabels
- Fix output matrix: always read qout bool between input and output matrices
- Fix subword n-gram skip: only skip single-char BOW/EOW, not full wrapped word
Add comprehensive sanity checks for all untrusted values from model files:
- Validate dimensions, entry counts, matrix sizes against sane upper bounds
- Overflow-safe multiplication for matrix element counts
- Bounds checks on centroid, codes, and dense matrix data access
- Null pointer guards on all matrix operations
- Replace throwing .at() with bounds-checked pointer return
- Limit string reads to 1024 bytes to prevent runaway allocation
- Return nullptr/false from loaders on validation failure
- Guard Lua bindings against empty/short vectors from get_word_vector
[Feature] WebUI: Add multi-class classifier support to learning UI
- Support /learnclass endpoint with Classifier and Class headers
for multi-class learning.
- Handle both old (array) and new (metadata object) /bayes/classifiers
response formats for backward compatibility.
- Add dynamic UI switching based on classifier type:
* Binary classifiers: show HAM/SPAM upload buttons
* Multi-class classifiers: show class dropdown + Learn button
- Display classifier metadata as text badges in dropdown:
[multi-class] [per-user]
- Hide "All classifiers" option when multi-class classifiers present
(different classifiers may have different class sets).
Vsevolod Stakhov [Sat, 21 Feb 2026 16:46:19 +0000 (16:46 +0000)]
[Minor] Fasttext shim: addressing review comments
- Use ICU U8_NEXT for UTF-8 iteration instead of handcrafted code
- Replace exception-based error handling with fail-bit pattern in
binary_reader, propagating errors via tl::expected
- Replace std::sort with std::reverse after min-heap extraction
Vsevolod Stakhov [Fri, 20 Feb 2026 11:21:38 +0000 (11:21 +0000)]
[Feature] Replace libfasttext with mmap-based built-in shim
Replace the external libfasttext shared library dependency with a
zero-dependency C++20 shim that reads .bin/.ftz models directly.
The large input matrix is mmap'd with MAP_SHARED/PROT_READ so all
worker processes share the same physical pages after fork.
This eliminates:
- C++ exception ABI issues across shared library boundaries
(no more fork-probe hack in lua_fasttext)
- The ENABLE_FASTTEXT cmake option (always compiled in now)
- Per-worker heap copies of the model (~500MB-7GB savings)
[Minor] Use explicit class for colorizing ham/spam in Bayesian statistics table
Use statfile.class field from /stat response to determine CSS class
for table cells instead of guessing from symbol name. Falls back to
symbol name matching for backward compatibility with older Rspamd.
Dmitriy Alekseev [Fri, 20 Feb 2026 16:31:33 +0000 (17:31 +0100)]
[Fix] Fix multiclass Bayes learn cache and classifier isolation
Propagate task->classifier from the HTTP header so class-targeted
learning skips unrelated classifiers early. Validate the requested
class exists in a statfile before tokenisation to fail fast with a
clear 404 error on misconfigured setups.
Replace numeric class_id hash cache keys in learned_ids with direct class
name strings throughout the Redis cache layer (C, Lua, Redis scripts) to
fix uint64_t precision loss through Lua's 53-bit doubles, which caused
equality checks to always fail for arbitrary multiclass class names.
Add RSPAMD_FLAG_CLASSIFIER_MULTICLASS at config load time
to route probability lookups to the correct result type per classifier.
Store multiclass and binary Bayes results under per-classifier mempool
keys (multiclass_result:<name>, bayes_prob:<name>) and update the
set/get API to take a classifier_name parameter, preventing
cross-contamination when multiple classifiers are configured.
Switch multiclass result allocation from heap (g_new0/g_new) to task
memory pool, eliminating the need for rspamd_multiclass_result_free.
Inject can_learn_prob and can_learn_class into the mempool before
invoking Lua learn conditions, replacing the legacy asymmetric
spam_min/ham_max pair with a unified min_prob threshold.
Remove the cl_skipped gate in rspamd_stat_cache_check so the Redis
learned_ids cache is always consulted before learn conditions run for
proper logging and response handling on relearning same emails.
Vsevolod Stakhov [Thu, 19 Feb 2026 17:32:10 +0000 (17:32 +0000)]
[Fix] Backward-compatible version negotiation for multi-flag fuzzy
Use an unused bit (bit 4) in the version byte as a v2 capability flag.
New clients send version 4|0x10 initially; old servers mask to 4 and
work normally, new servers see the cap bit and send v2 replies. Once
a v2 reply is received, subsequent requests use native version 5.
Vsevolod Stakhov [Thu, 19 Feb 2026 16:16:18 +0000 (16:16 +0000)]
[Fix] Store small PDF objects without counting toward limit
Small objects are now stored but don't count toward max_pdf_objects,
so padding evasion objects can't exhaust the budget while legitimate
small references (like JavaScript dictionaries) are preserved.
Vsevolod Stakhov [Thu, 19 Feb 2026 14:59:58 +0000 (14:59 +0000)]
[Fix] Defeat PDF object padding evasion in extract_outer_objects
Decouple iteration limit from storage limit so that thousands of tiny
dummy obj/endobj pairs no longer consume all max_pdf_objects slots.
- Add min_obj_content_size (default 32) config: objects smaller than
this are skipped during extraction (they carry no useful content)
- extract_outer_objects now iterates ALL start/end positions but only
stores objects that pass the size filter, up to max_pdf_objects
- attach_pdf_streams similarly iterates all stream positions
- Add timeout checks in both loops to stay within pdf_process_timeout
Vsevolod Stakhov [Thu, 19 Feb 2026 10:58:41 +0000 (10:58 +0000)]
[Fix] Refine structural alternative check to leaf text/* parts
The previous check counted any sibling in multipart/alternative,
but multipart/related with only images or malformed empty related
parts are not real alternatives. Now only leaf text/* non-html
siblings count (e.g. text/calendar, text/enriched).
Vsevolod Stakhov [Thu, 19 Feb 2026 10:31:07 +0000 (10:31 +0000)]
[Fix] Check MIME structure for alternatives in has_only_html_part
has_only_html_part() relied solely on alt_text_part to find alternatives,
but parts like text/calendar (detected as ics with no_text=true) are not
in text_parts and thus invisible to the search. Now we also walk the MIME
tree: if the HTML part sits inside a multipart/alternative with other
siblings, it has a structural alternative and MIME_HTML_ONLY should not
fire.
Vsevolod Stakhov [Wed, 18 Feb 2026 19:01:23 +0000 (19:01 +0000)]
[Fix] Fix XML detection overriding HTML in content type detection
HTML parts containing an embedded <?xml?> prolog (e.g. inside the body)
were misdetected as application/xml. Since xml type has no_text=true,
this excluded the HTML part from text_parts entirely, causing
has_only_html_part() to return false and MIME_HTML_ONLY to not fire.
- Remove xml binary pattern from patterns.lua (it preempted the text
heuristic which correctly prioritises HTML)
- Guard xml text pattern so it cannot override HTML when HTML markers
are also present
- Raise xml text pattern weight to 40 to preserve pure XML detection
Vsevolod Stakhov [Wed, 18 Feb 2026 15:33:02 +0000 (15:33 +0000)]
[Fix] Filter forbidden_ids from multi-flag extra flags in v2 reply
Extract forbidden flag checks into rspamd_fuzzy_filter_forbidden_v2()
which filters both primary and extra flags. If primary is forbidden
but valid extras remain, promotes first valid extra to primary.
Vsevolod Stakhov [Wed, 18 Feb 2026 11:23:31 +0000 (11:23 +0000)]
[Feature] Add multi-flag fuzzy hash support with Lua-based Redis update path
Support up to 8 flag slots per fuzzy hash (primary + 7 extra), enabling
multiple rules to match against the same digest with independent flag/value
pairs. The highest-value flag is always promoted to the primary slot for
backward compatibility.
The Redis update path (ADD/DEL/REFRESH) is moved from a C MULTI/EXEC
pipeline with an embedded EVAL string to a proper Lua architecture
following the Bayes pattern: a Redis script in lualib/redis_scripts/
loaded via lua_redis.load_redis_script_from_file(), with a Lua module
(lua_fuzzy_redis.lua) providing an async update functor called from C
via lua_pcall. This gives automatic EVALSHA + NOSCRIPT recovery and
keeps the multi-flag merge logic in a maintainable .lua file.
Wire protocol extended with epoch 12 (RSPAMD_FUZZY_EPOCH12) carrying
rspamd_fuzzy_reply_v2 with n_extra_flags and up to 7 extra flag entries.
[Fix] Distinguish explicit multi-class from legacy binary configs
Check is_spam_converted flag to differentiate between:
- Explicit class declaration (new format) -> multi-class
- Converted is_spam=true/false (legacy) -> binary
This fixes incorrect "binary" detection for explicit multi-class
configurations using class="spam" and class="ham".
Vsevolod Stakhov [Mon, 16 Feb 2026 19:08:55 +0000 (19:08 +0000)]
[Fix] Fix JSON emission for implicit arrays in libucl
When emitting UCL objects with implicit arrays (multiple values for the
same key) as JSON, the emitter was producing invalid output by:
- Not printing the key before the array for non-first elements
- Missing comma separators between elements
This caused rspamadm configdump -j to output malformed JSON like:
"actions": {...}[
instead of:
"actions": {...},
"group": [
[Feature] WebUI: Add classifier metadata to Bayes statistics table
- Display `classifier name` with type badges (`multi-class`, `per-user`)
and `class` field for each statfile with fallback for old server responses
- Group statfiles by classifier name with rowspan (similar to server grouping)
- Update hover handler to support nested rowspan cells
- Highlight all parent rowspan cells when hovering classifier or statfile
Vsevolod Stakhov [Mon, 16 Feb 2026 16:00:52 +0000 (16:00 +0000)]
[Minor] Fix compile warnings
- Fix hexdigests array size (use empty brackets for compiler to determine)
- Fix char8_t to char32_t implicit conversion in replxx terminal
- Fix hex format specifier in hyperscan debug logging (%xd not %x)
- Add forward declaration for struct rspamd_external_libs_ctx
- Remove unused is_msgpack variable in protocol.c
- Fix logic bug: c >= 'a' || c <= 'f' should be && in hex parsing
Vsevolod Stakhov [Mon, 16 Feb 2026 15:36:19 +0000 (15:36 +0000)]
[Fix] Catch all exceptions when loading fasttext model to avoid crash
When the fasttext language detection model file doesn't exist or is
corrupted, fasttext library throws an exception. Add a catch-all handler
to prevent crashes when the model path is invalid or the file is missing.
Also improved error messages to include the model path for debugging.
Vsevolod Stakhov [Mon, 16 Feb 2026 15:36:16 +0000 (15:36 +0000)]
[Minor] Backport ucl_object_iterate_end() from libucl to fix iterator leak
Add ucl_object_iterate_end() function to free resources associated with
an inline iterator when iteration is abandoned before completion. This
fixes a potential memory leak when iterating over UCL_OBJECT types where
internal heap state is allocated.
Changes backported from libucl 0.9.3:
- Add ucl_hash_iterate_free() to ucl_hash.c/h
- Add ucl_object_iterate_end() to ucl_util.c and ucl.h
- Add ucl_iterate_object_end macro alias
Note: Rspamd already had the security fixes for:
- heap-buffer-overflow in ucl_maybe_parse_number
- heap-buffer-overflow in ucl_parse_multiline_string
- Use-After-Free in ucl_hash_insert
- Invalid JSON emission when merging objects
Vsevolod Stakhov [Mon, 16 Feb 2026 15:00:03 +0000 (15:00 +0000)]
[Feature] Add rspamd_text:normalize_newlines() for CRLF/LF conversion
Add fast C API and Lua binding to normalize line endings in rspamd_text:
- Two-pass algorithm using rspamd_memcspn for efficient scanning
- LF to CRLF conversion (for SMTP compliance, fixes issue #5888)
- CRLF to LF conversion (for Unix compatibility)
- Supports mempool for memory allocation
- Proper ownership handling: frees old memory if owned, sets OWN flag if using g_malloc
Update lua_smtp.lua to normalize messages to CRLF before SMTP DATA,
ensuring compatibility with strict servers like Exchange.
Includes comprehensive unit tests covering:
- No-op cases (already normalized, no newlines)
- Basic conversions in both directions
- Mixed/inconsistent line endings
- Weird line endings (lone CR, multiple CR)
- Edge cases (empty, single char, large text, null bytes)
- Mode parameter variations (crlf/windows/lf/unix, case insensitive)
Vsevolod Stakhov [Sat, 14 Feb 2026 19:17:22 +0000 (19:17 +0000)]
[Feature] Sync UUID v7 random portion with Log-Tag header
When an MTA provides a Log-Tag header that overrides the pool UID,
patch the task UUID's random portion (bytes 8-15) to stay in sync.
Uses a fast hash of the tag to derive the bytes while preserving
the UUID v7 variant bits.
Vsevolod Stakhov [Sat, 14 Feb 2026 15:35:59 +0000 (15:35 +0000)]
[Feature] Add structured formatter to metadata_exporter
Add a 'structured' output format that emits rich msgpack metadata
including UUID correlation, extracted text, base64-encoded attachment
and image content, URLs, and reply detection. Uses task:get_uuid()
for cross-system correlation instead of generating UUIDs in Lua.
Vsevolod Stakhov [Sat, 14 Feb 2026 15:35:51 +0000 (15:35 +0000)]
[Feature] Add native UUID v7 per task with Lua binding
Generate a UUID v7 (time-ordered, RFC 9562) natively in C at task
creation time. The task's log UID is derived from the UUID's random
portion so that UID and UUID are always correlated.
- rspamd_uuid_v7() in util.c: 48-bit ms timestamp + crypto-random bits
- task_uuid[37] field in rspamd_task, populated in rspamd_task_new()
- task:get_uuid() Lua method for plugin access
Vsevolod Stakhov [Fri, 13 Feb 2026 17:18:39 +0000 (17:18 +0000)]
[Fix] Preserve UNSCORED flag when config defines symbol without score
When rspamd_config_add_symbol was called for an existing symbol without
a score (NAN), line 1811 unconditionally replaced all flags, clearing
RSPAMD_SYMBOL_FLAG_UNSCORED. This caused Lua-registered scores to be
ignored: if a symbol appeared in config (e.g. groups.conf) without a
score, the UNSCORED flag was lost, and the Lua score-setting block in
lua_config_register_symbol_from_table was skipped, leaving score at 0.
Now flags are updated correctly in both cases:
- Real score provided: flags fully replaced with UNSCORED cleared
- NAN score: flags updated but UNSCORED preserved from existing symbol
Also initialize score to NAN in lua_config_set_metric_symbol to avoid
passing uninitialized stack garbage to rspamd_config_add_symbol.
Vsevolod Stakhov [Fri, 13 Feb 2026 16:47:13 +0000 (16:47 +0000)]
[Feature] Add dual-mode HTML fuzzy: template matching + phishing detection
When html_ignore_domains is enabled, generate two HTML fuzzy commands per
part: a template command (domains ignored) and a domain-sensitive command
(domains included). If the template matches but domains don't, the new
FUZZY_HTML_PHISHING symbol fires, detecting reused HTML templates with
swapped phishing links.
Vsevolod Stakhov [Fri, 13 Feb 2026 14:09:59 +0000 (14:09 +0000)]
[Fix] Fix custom tokenizer UAF and improve CJK fuzzy detection
Fix use-after-free in custom tokenizer integration: when tokens were
shallow-copied from a custom tokenizer result, cleanup_result would free
per-token normalized/stemmed/unicode strings while the copies still
referenced them. Now copy these strings into the mempool before cleanup.
Improve fuzzy hash generation for CJK (Japanese/Chinese/Korean) text:
- Lower shingle word count threshold by 3x for CJK languages (64→21,
floor 32→12) since CJK morphemes carry higher semantic density
- Boost text_multiplier by 3x for CJK to compensate for 3-byte UTF-8
characters, allowing short CJK emails to pass the min_bytes gate
Previously, short Japanese phishing emails (~50 chars, ~20 words) would
generate zero fuzzy hashes — failing both the word count gate for shingles
and the byte length gate for direct hash.
Vsevolod Stakhov [Fri, 13 Feb 2026 10:58:25 +0000 (10:58 +0000)]
[Fix] Use class_name as Redis label for multiclass Bayes without class_labels config
get_class_label() fell through to the legacy "S"/"H" fallback when
class_labels hash table was NULL, even when an explicit class_name
(e.g. "cold_marketing") was set on the statfile. Since all non-binary
classes have is_spam=FALSE, every class mapped to "H", causing:
- All tokens stored under the same Redis hash field "H"
- All learn counters going to learns_ham
- Classification returning identical data for all classes
- Mempool runtime caching collisions (all saved under key _H)
Fix: check class_name with !is_spam_converted before the S/H fallback
so explicit multiclass configs use their actual class name as the Redis
label, while legacy binary configs (auto-converted from spam=true/false)
still use "S"/"H".
Also fix controller learn log to show actual class name instead of
always "spam"/"ham".
Vsevolod Stakhov [Fri, 13 Feb 2026 10:11:25 +0000 (10:11 +0000)]
[Rework] Rewrite fuzzy_html_phishing rule with proper config awareness
Rewrite fuzzy HTML phishing mismatch detection to read fuzzy_check
config at load time and only check symbols from rules that have
html_shingles enabled. Fix broken virtual symbol registration by
registering callback first and linking virtuals via parent id.
Skip registration entirely when no rules have html_shingles.
Vsevolod Stakhov [Fri, 13 Feb 2026 07:37:27 +0000 (07:37 +0000)]
[Fix] Resolve composite references in inverted index for fast path
When the inverted index fast path collects potentially active composites,
it scans symbols already in the scan result. Composite symbols are not
yet in the scan result at that point, so composites referencing other
composites as atoms were never activated and silently failed to fire.
Fix by resolving composite references at index build time: recursively
collect leaf (non-composite) atoms and propagate dependent composites
to those atoms' index entries. Also refactor atom name parsing into a
shared helper to reduce duplication.
Vsevolod Stakhov [Fri, 13 Feb 2026 07:24:50 +0000 (07:24 +0000)]
[Fix] Remove check for non-existent fuzzy_result mempool variable
The fuzzy_result mempool variable is never set by fuzzy_check, so the
early return was always triggered, making the phishing mismatch check
a no-op. The actual logic uses get_symbols_all() which works correctly.
Vsevolod Stakhov [Fri, 13 Feb 2026 07:23:20 +0000 (07:23 +0000)]
[Feature] Add ignore_link_domains option for HTML fuzzy rules
Allow HTML fuzzy shingles to match purely on structure (tag skeleton +
classes) by stripping link domains from structural tokens. Domain hashes
are still computed separately for the metadata fields. A separate cache
key suffix (_nd) prevents cross-contamination with normal hashes.
Vsevolod Stakhov [Thu, 12 Feb 2026 17:35:32 +0000 (17:35 +0000)]
[Fix] Handle native boolean values in lua_util.toboolean()
toboolean() only handled string and number inputs, falling through to
the error branch for native Lua booleans and always returning false.
This broke the fuzzy_check "checks" configuration block since UCL
converts boolean values to native Lua booleans, and apply_checks_overrides
in lua_fuzzy.lua passes them through toboolean() via bool_opt().