| 1 |
--[[ |
| 2 |
Copyright (c) 2025, Vsevolod Stakhov <[email protected]> |
| 3 |
|
| 4 |
Licensed under the Apache License, Version 2.0 (the "License"); |
| 5 |
you may not use this file except in compliance with the License. |
| 6 |
You may obtain a copy of the License at |
| 7 |
|
| 8 |
http://www.apache.org/licenses/LICENSE-2.0 |
| 9 |
|
| 10 |
Unless required by applicable law or agreed to in writing, software |
| 11 |
distributed under the License is distributed on an "AS IS" BASIS, |
| 12 |
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 13 |
See the License for the specific language governing permissions and |
| 14 |
limitations under the License. |
| 15 |
]] -- |
| 16 |
|
| 17 |
--[[[ |
| 18 |
-- @module lua_aliases |
| 19 |
-- Email aliases resolution and local domains management |
| 20 |
-- |
| 21 |
-- This module provides functionality for: |
| 22 |
-- - Parsing Unix-style aliases (/etc/aliases format) |
| 23 |
-- - Parsing virtual aliases (Postfix virtual format) |
| 24 |
-- - Resolving email addresses through alias chains |
| 25 |
-- - Detecting local vs external domains |
| 26 |
-- - Classifying message direction (inbound/outbound/internal) |
| 27 |
--]] |
| 28 |
|
| 29 |
local rspamd_logger = require "rspamd_logger" |
| 30 |
local lua_util = require "lua_util" |
| 31 |
local lua_maps = require "lua_maps" |
| 32 |
|
| 33 |
local N = "lua_aliases" |
| 34 |
|
| 35 |
local exports = {} |
| 36 |
|
| 37 |
--- Count elements in a table (including hash tables) |
| 38 |
-- @param tbl table to count |
| 39 |
-- @return number of elements |
| 40 |
local function table_length(tbl) |
| 41 |
if not tbl then return 0 end |
| 42 |
local count = 0 |
| 43 |
for _ in pairs(tbl) do |
| 44 |
count = count + 1 |
| 45 |
end |
| 46 |
return count |
| 47 |
end |
| 48 |
|
| 49 |
-- Module state |
| 50 |
local module_state = { |
| 51 |
initialized = false, |
| 52 |
config = nil, |
| 53 |
local_domains = {}, -- Set of local domains or backend |
| 54 |
unix_aliases = {}, -- Unix aliases map or backend |
| 55 |
virtual_aliases = {}, -- Virtual aliases map or backend |
| 56 |
rspamd_aliases = {}, -- Rspamd-specific aliases |
| 57 |
cache = {}, -- Resolution cache |
| 58 |
backends = {}, -- Storage backends instances |
| 59 |
} |
| 60 |
|
| 61 |
--[[ Backend abstraction ]] -- |
| 62 |
|
| 63 |
--- Backend interface: |
| 64 |
-- backend:get(key) -> value or nil |
| 65 |
-- backend:type() -> string |
| 66 |
|
| 67 |
-- File backend (already implemented via parse_* functions) |
| 68 |
local FileBackend = {} |
| 69 |
FileBackend.__index = FileBackend |
| 70 |
|
| 71 |
function FileBackend.new(file_path, parser_func) |
| 72 |
local self = setmetatable({}, FileBackend) |
| 73 |
self.file_path = file_path |
| 74 |
self.parser_func = parser_func |
| 75 |
self.data = nil |
| 76 |
self.loaded = false |
| 77 |
return self |
| 78 |
end |
| 79 |
|
| 80 |
function FileBackend:load() |
| 81 |
if not self.loaded then |
| 82 |
self.data = self.parser_func(self.file_path) |
| 83 |
self.loaded = true |
| 84 |
end |
| 85 |
return self.data ~= nil |
| 86 |
end |
| 87 |
|
| 88 |
function FileBackend:get(key) |
| 89 |
if not self.loaded then |
| 90 |
self:load() |
| 91 |
end |
| 92 |
return self.data and self.data[key:lower()] |
| 93 |
end |
| 94 |
|
| 95 |
function FileBackend:type() |
| 96 |
return "file" |
| 97 |
end |
| 98 |
|
| 99 |
-- Map backend (using lua_maps) |
| 100 |
local MapBackend = {} |
| 101 |
MapBackend.__index = MapBackend |
| 102 |
|
| 103 |
function MapBackend.new(rspamd_config, map_config, map_type) |
| 104 |
local self = setmetatable({}, MapBackend) |
| 105 |
self.map_type = map_type or 'hash' |
| 106 |
|
| 107 |
-- Create map using lua_maps |
| 108 |
self.map = lua_maps.map_add_from_ucl(map_config, self.map_type, |
| 109 |
'aliases map (' .. self.map_type .. ')') |
| 110 |
|
| 111 |
if not self.map then |
| 112 |
rspamd_logger.errx(rspamd_config, 'cannot create map from config: %s', |
| 113 |
map_config) |
| 114 |
return nil |
| 115 |
end |
| 116 |
|
| 117 |
return self |
| 118 |
end |
| 119 |
|
| 120 |
function MapBackend:get(key) |
| 121 |
if not self.map then |
| 122 |
return nil |
| 123 |
end |
| 124 |
|
| 125 |
local result = self.map:get_key(key:lower()) |
| 126 |
return result |
| 127 |
end |
| 128 |
|
| 129 |
function MapBackend:type() |
| 130 |
return "map:" .. self.map_type |
| 131 |
end |
| 132 |
|
| 133 |
-- CDB backend (using existing CDB support) |
| 134 |
local CDBBackend = {} |
| 135 |
CDBBackend.__index = CDBBackend |
| 136 |
|
| 137 |
function CDBBackend.new(rspamd_config, cdb_path) |
| 138 |
local self = setmetatable({}, CDBBackend) |
| 139 |
|
| 140 |
-- Use lua_maps CDB support |
| 141 |
local map_config = { |
| 142 |
cdb = cdb_path, |
| 143 |
external = true, |
| 144 |
} |
| 145 |
|
| 146 |
self.map = lua_maps.map_add_from_ucl(map_config, 'cdb', 'aliases cdb') |
| 147 |
if not self.map then |
| 148 |
rspamd_logger.errx(rspamd_config, 'cannot load CDB from %s', cdb_path) |
| 149 |
return nil |
| 150 |
end |
| 151 |
|
| 152 |
return self |
| 153 |
end |
| 154 |
|
| 155 |
function CDBBackend:get(key) |
| 156 |
if not self.map then |
| 157 |
return nil |
| 158 |
end |
| 159 |
|
| 160 |
return self.map:get_key(key:lower()) |
| 161 |
end |
| 162 |
|
| 163 |
function CDBBackend:type() |
| 164 |
return "cdb" |
| 165 |
end |
| 166 |
|
| 167 |
-- Forward declarations for parser functions |
| 168 |
local parse_unix_aliases |
| 169 |
local parse_virtual_aliases |
| 170 |
local parse_local_domains |
| 171 |
|
| 172 |
--- Create backend from configuration |
| 173 |
-- @param rspamd_config rspamd config object |
| 174 |
-- @param config backend configuration (table or string) |
| 175 |
-- @param default_parser default parser for file backend |
| 176 |
-- @return backend instance or nil |
| 177 |
local function create_backend(rspamd_config, config, default_parser) |
| 178 |
-- String path -> file backend |
| 179 |
if type(config) == 'string' then |
| 180 |
return FileBackend.new(config, default_parser) |
| 181 |
end |
| 182 |
|
| 183 |
-- Table configuration |
| 184 |
if type(config) ~= 'table' then |
| 185 |
return nil |
| 186 |
end |
| 187 |
|
| 188 |
local backend_type = config.type or 'file' |
| 189 |
|
| 190 |
if backend_type == 'file' then |
| 191 |
if config.path then |
| 192 |
return FileBackend.new(config.path, default_parser) |
| 193 |
end |
| 194 |
elseif backend_type == 'map' then |
| 195 |
if config.url or config.urls then |
| 196 |
return MapBackend.new(rspamd_config, config, config.map_type or 'hash') |
| 197 |
end |
| 198 |
elseif backend_type == 'redis' then |
| 199 |
rspamd_logger.errx(rspamd_config, |
| 200 |
'Redis backend is not supported for aliases (requires async with task context). Use CDB or Map instead.') |
| 201 |
return nil |
| 202 |
elseif backend_type == 'cdb' then |
| 203 |
if config.path then |
| 204 |
return CDBBackend.new(rspamd_config, config.path) |
| 205 |
end |
| 206 |
end |
| 207 |
|
| 208 |
rspamd_logger.errx(rspamd_config, 'unknown backend type or invalid config: %s', backend_type) |
| 209 |
return nil |
| 210 |
end |
| 211 |
|
| 212 |
--- Initialize the module with configuration |
| 213 |
-- @param rspamd_config rspamd config object |
| 214 |
-- @param opts configuration options |
| 215 |
-- @return true on success |
| 216 |
local function init(rspamd_config, opts) |
| 217 |
if module_state.initialized then |
| 218 |
rspamd_logger.warnx(rspamd_config, 'lua_aliases already initialized') |
| 219 |
return true |
| 220 |
end |
| 221 |
|
| 222 |
module_state.config = rspamd_config |
| 223 |
opts = opts or {} |
| 224 |
|
| 225 |
-- Load local domains |
| 226 |
if opts.local_domains then |
| 227 |
if type(opts.local_domains) == 'table' and not opts.local_domains.type then |
| 228 |
-- Inline array of domains |
| 229 |
for _, domain in ipairs(opts.local_domains) do |
| 230 |
module_state.local_domains[domain:lower()] = true |
| 231 |
end |
| 232 |
rspamd_logger.infox(rspamd_config, 'loaded %s local domains from inline config', |
| 233 |
#opts.local_domains) |
| 234 |
else |
| 235 |
-- Backend configuration |
| 236 |
local backend = create_backend(rspamd_config, opts.local_domains, parse_local_domains) |
| 237 |
if backend then |
| 238 |
module_state.backends.local_domains = backend |
| 239 |
rspamd_logger.infox(rspamd_config, 'initialized local domains backend: %s', |
| 240 |
backend:type()) |
| 241 |
|
| 242 |
-- For file backend, load immediately |
| 243 |
if backend.type and backend:type() == 'file' then |
| 244 |
if backend:load() then |
| 245 |
module_state.local_domains = backend.data |
| 246 |
rspamd_logger.infox(rspamd_config, 'loaded %s local domains', |
| 247 |
table_length(module_state.local_domains)) |
| 248 |
end |
| 249 |
end |
| 250 |
end |
| 251 |
end |
| 252 |
end |
| 253 |
|
| 254 |
-- Load system aliases |
| 255 |
if opts.system_aliases then |
| 256 |
local backend = create_backend(rspamd_config, opts.system_aliases, parse_unix_aliases) |
| 257 |
if backend then |
| 258 |
module_state.backends.system_aliases = backend |
| 259 |
rspamd_logger.infox(rspamd_config, 'initialized system aliases backend: %s', |
| 260 |
backend:type()) |
| 261 |
|
| 262 |
-- For file backend, load immediately |
| 263 |
if backend.type and backend:type() == 'file' then |
| 264 |
if backend:load() then |
| 265 |
module_state.unix_aliases = backend.data |
| 266 |
rspamd_logger.infox(rspamd_config, 'loaded %s system aliases', |
| 267 |
table_length(module_state.unix_aliases)) |
| 268 |
end |
| 269 |
else |
| 270 |
-- For other backends, keep reference |
| 271 |
module_state.unix_aliases = backend |
| 272 |
end |
| 273 |
end |
| 274 |
end |
| 275 |
|
| 276 |
-- Load virtual aliases |
| 277 |
if opts.virtual_aliases then |
| 278 |
local backend = create_backend(rspamd_config, opts.virtual_aliases, parse_virtual_aliases) |
| 279 |
if backend then |
| 280 |
module_state.backends.virtual_aliases = backend |
| 281 |
rspamd_logger.infox(rspamd_config, 'initialized virtual aliases backend: %s', |
| 282 |
backend:type()) |
| 283 |
|
| 284 |
-- For file backend, load immediately |
| 285 |
if backend.type and backend:type() == 'file' then |
| 286 |
if backend:load() then |
| 287 |
module_state.virtual_aliases = backend.data |
| 288 |
rspamd_logger.infox(rspamd_config, 'loaded %s virtual aliases', |
| 289 |
table_length(module_state.virtual_aliases)) |
| 290 |
end |
| 291 |
else |
| 292 |
-- For other backends, keep reference |
| 293 |
module_state.virtual_aliases = backend |
| 294 |
end |
| 295 |
end |
| 296 |
end |
| 297 |
|
| 298 |
-- Load rspamd-specific aliases (always inline) |
| 299 |
if opts.rspamd_aliases then |
| 300 |
if type(opts.rspamd_aliases) == 'table' then |
| 301 |
module_state.rspamd_aliases = opts.rspamd_aliases |
| 302 |
rspamd_logger.infox(rspamd_config, 'loaded %s rspamd aliases from inline config', |
| 303 |
table_length(opts.rspamd_aliases)) |
| 304 |
end |
| 305 |
end |
| 306 |
|
| 307 |
module_state.initialized = true |
| 308 |
return true |
| 309 |
end |
| 310 |
exports.init = init |
| 311 |
|
| 312 |
--- Parse Unix-style aliases file (/etc/aliases format) |
| 313 |
-- Format: |
| 314 |
-- alias: target1, target2, ... |
| 315 |
-- # Comments |
| 316 |
-- continuation lines with backslash \ |
| 317 |
-- |
| 318 |
-- @param file_path path to aliases file |
| 319 |
-- @return table of aliases {alias -> {targets...}} or nil on error |
| 320 |
function parse_unix_aliases(file_path) |
| 321 |
local aliases = {} |
| 322 |
|
| 323 |
local f, err = io.open(file_path, 'r') |
| 324 |
if not f then |
| 325 |
if module_state.config then |
| 326 |
rspamd_logger.warnx(module_state.config, |
| 327 |
'cannot open aliases file %s: %s', file_path, err) |
| 328 |
end |
| 329 |
return nil |
| 330 |
end |
| 331 |
|
| 332 |
local current_line = "" |
| 333 |
local line_num = 0 |
| 334 |
|
| 335 |
for line in f:lines() do |
| 336 |
line_num = line_num + 1 |
| 337 |
|
| 338 |
-- Strip trailing whitespace |
| 339 |
line = line:gsub('%s+$', '') |
| 340 |
|
| 341 |
-- Handle line continuation |
| 342 |
if line:match('\\$') then |
| 343 |
current_line = current_line .. line:gsub('\\$', '') |
| 344 |
goto continue |
| 345 |
else |
| 346 |
current_line = current_line .. line |
| 347 |
end |
| 348 |
|
| 349 |
-- Skip empty lines and comments |
| 350 |
if current_line:match('^%s*$') or current_line:match('^%s*#') then |
| 351 |
current_line = "" |
| 352 |
goto continue |
| 353 |
end |
| 354 |
|
| 355 |
-- Parse alias line: "alias: target1, target2, ..." |
| 356 |
local alias, targets = current_line:match('^%s*([^:]+):%s*(.*)$') |
| 357 |
|
| 358 |
if alias and targets then |
| 359 |
alias = alias:gsub('%s+$', ''):lower() -- Normalize alias |
| 360 |
|
| 361 |
-- Split targets by comma |
| 362 |
local target_list = {} |
| 363 |
for target in targets:gmatch('[^,]+') do |
| 364 |
target = target:gsub('^%s+', ''):gsub('%s+$', '') -- Trim |
| 365 |
|
| 366 |
-- Skip special targets for now (:include:, |program, /file) |
| 367 |
if not target:match('^:include:') and |
| 368 |
not target:match('^|') and |
| 369 |
not target:match('^/') then |
| 370 |
-- Normalize target |
| 371 |
target = target:lower() |
| 372 |
-- Add domain if missing and it's not email format |
| 373 |
if not target:match('@') then |
| 374 |
-- It's a local user, we'll handle it later |
| 375 |
table.insert(target_list, target) |
| 376 |
else |
| 377 |
table.insert(target_list, target) |
| 378 |
end |
| 379 |
else |
| 380 |
if module_state.config then |
| 381 |
rspamd_logger.debugm(N, module_state.config, |
| 382 |
'skipping special target in %s:%d: %s', file_path, line_num, target) |
| 383 |
end |
| 384 |
end |
| 385 |
end |
| 386 |
|
| 387 |
if #target_list > 0 then |
| 388 |
aliases[alias] = target_list |
| 389 |
end |
| 390 |
else |
| 391 |
if module_state.config then |
| 392 |
rspamd_logger.debugm(N, module_state.config, |
| 393 |
'cannot parse line %d in %s: %s', line_num, file_path, current_line) |
| 394 |
end |
| 395 |
end |
| 396 |
|
| 397 |
current_line = "" |
| 398 |
:: continue :: |
| 399 |
end |
| 400 |
|
| 401 |
f:close() |
| 402 |
return aliases |
| 403 |
end |
| 404 |
|
| 405 |
exports.parse_unix_aliases = parse_unix_aliases |
| 406 |
|
| 407 |
--- Parse virtual aliases file (Postfix virtual format) |
| 408 |
-- Format: |
| 409 |
-- [email protected] [email protected] |
| 410 |
-- @catchall.com [email protected] |
| 411 |
-- |
| 412 |
-- @param file_path path to virtual aliases file |
| 413 |
-- @return table of aliases {source -> target} or nil on error |
| 414 |
function parse_virtual_aliases(file_path) |
| 415 |
local aliases = {} |
| 416 |
|
| 417 |
local f, err = io.open(file_path, 'r') |
| 418 |
if not f then |
| 419 |
if module_state.config then |
| 420 |
rspamd_logger.warnx(module_state.config, |
| 421 |
'cannot open virtual aliases file %s: %s', file_path, err) |
| 422 |
end |
| 423 |
return nil |
| 424 |
end |
| 425 |
|
| 426 |
local line_num = 0 |
| 427 |
for line in f:lines() do |
| 428 |
line_num = line_num + 1 |
| 429 |
|
| 430 |
-- Skip empty lines and comments |
| 431 |
if line:match('^%s*$') or line:match('^%s*#') then |
| 432 |
goto continue |
| 433 |
end |
| 434 |
|
| 435 |
-- Parse: source target |
| 436 |
local source, target = line:match('^%s*(%S+)%s+(%S+)') |
| 437 |
|
| 438 |
if source and target then |
| 439 |
source = source:lower() |
| 440 |
target = target:lower() |
| 441 |
aliases[source] = target |
| 442 |
else |
| 443 |
if module_state.config then |
| 444 |
rspamd_logger.debugm(N, module_state.config, |
| 445 |
'cannot parse line %d in %s: %s', line_num, file_path, line) |
| 446 |
end |
| 447 |
end |
| 448 |
|
| 449 |
:: continue :: |
| 450 |
end |
| 451 |
|
| 452 |
f:close() |
| 453 |
return aliases |
| 454 |
end |
| 455 |
|
| 456 |
exports.parse_virtual_aliases = parse_virtual_aliases |
| 457 |
|
| 458 |
--- Parse local domains file (one domain per line) |
| 459 |
-- Format: |
| 460 |
-- example.com |
| 461 |
-- mail.example.com |
| 462 |
-- # comments |
| 463 |
-- |
| 464 |
-- @param file_path path to local domains file |
| 465 |
-- @return set of domains {domain -> true} or nil on error |
| 466 |
function parse_local_domains(file_path) |
| 467 |
local domains = {} |
| 468 |
|
| 469 |
local f, err = io.open(file_path, 'r') |
| 470 |
if not f then |
| 471 |
if module_state.config then |
| 472 |
rspamd_logger.warnx(module_state.config, |
| 473 |
'cannot open local domains file %s: %s', file_path, err) |
| 474 |
end |
| 475 |
return nil |
| 476 |
end |
| 477 |
|
| 478 |
for line in f:lines() do |
| 479 |
-- Skip empty lines and comments |
| 480 |
if not line:match('^%s*$') and not line:match('^%s*#') then |
| 481 |
local domain = line:match('^%s*(%S+)') |
| 482 |
if domain then |
| 483 |
domains[domain:lower()] = true |
| 484 |
end |
| 485 |
end |
| 486 |
end |
| 487 |
|
| 488 |
f:close() |
| 489 |
return domains |
| 490 |
end |
| 491 |
|
| 492 |
exports.parse_local_domains = parse_local_domains |
| 493 |
|
| 494 |
--- Get value from backend or table |
| 495 |
-- @param source backend object or table |
| 496 |
-- @param key lookup key |
| 497 |
-- @return value or nil |
| 498 |
local function get_from_source(source, key) |
| 499 |
if not source then |
| 500 |
return nil |
| 501 |
end |
| 502 |
|
| 503 |
-- If it's a backend object with :get() method |
| 504 |
if type(source) == 'table' and source.get then |
| 505 |
return source:get(key) |
| 506 |
end |
| 507 |
|
| 508 |
-- Otherwise treat as plain table |
| 509 |
return source[key] |
| 510 |
end |
| 511 |
|
| 512 |
--- Check if a domain is local |
| 513 |
-- @param domain domain name to check |
| 514 |
-- @return true if domain is local, false otherwise |
| 515 |
local function is_local_domain(domain) |
| 516 |
if not domain then |
| 517 |
return false |
| 518 |
end |
| 519 |
|
| 520 |
domain = domain:lower() |
| 521 |
local result = get_from_source(module_state.local_domains, domain) |
| 522 |
|
| 523 |
lua_util.debugm(N, module_state.config, |
| 524 |
'is_local_domain: domain=%s result=%s', |
| 525 |
domain, result) |
| 526 |
|
| 527 |
return result ~= nil and result ~= false |
| 528 |
end |
| 529 |
exports.is_local_domain = is_local_domain |
| 530 |
|
| 531 |
--- Check if an email address is local |
| 532 |
-- @param addr email address (string or table with 'domain' field) |
| 533 |
-- @return true if address is in local domain, false otherwise |
| 534 |
local function is_local_address(addr) |
| 535 |
local domain |
| 536 |
|
| 537 |
if type(addr) == 'string' then |
| 538 |
domain = addr:match('@([^@]+)$') |
| 539 |
elseif type(addr) == 'table' and addr.domain then |
| 540 |
domain = addr.domain |
| 541 |
end |
| 542 |
|
| 543 |
return is_local_domain(domain) |
| 544 |
end |
| 545 |
exports.is_local_address = is_local_address |
| 546 |
|
| 547 |
--- Apply service-specific alias rules (Gmail, plus-aliases) |
| 548 |
-- This replaces the old lua_util.remove_email_aliases() function |
| 549 |
-- @param email_addr email address table with user, domain, addr fields |
| 550 |
-- @return new_user, tags, new_domain or nil |
| 551 |
local function apply_service_rules(email_addr) |
| 552 |
local function check_gmail_user(addr) |
| 553 |
-- Remove all points |
| 554 |
local no_dots_user = string.gsub(addr.user, '%.', '') |
| 555 |
local cap, pluses = string.match(no_dots_user, '^([^%+][^%+]*)(%+.*)$') |
| 556 |
if cap then |
| 557 |
return cap, lua_util.str_split(pluses, '+'), nil |
| 558 |
elseif no_dots_user ~= addr.user then |
| 559 |
return no_dots_user, {}, nil |
| 560 |
end |
| 561 |
|
| 562 |
return nil |
| 563 |
end |
| 564 |
|
| 565 |
local function check_address(addr) |
| 566 |
if addr.user then |
| 567 |
local cap, pluses = string.match(addr.user, '^([^%+][^%+]*)(%+.*)$') |
| 568 |
if cap then |
| 569 |
return cap, lua_util.str_split(pluses, '+'), nil |
| 570 |
end |
| 571 |
end |
| 572 |
|
| 573 |
return nil |
| 574 |
end |
| 575 |
|
| 576 |
local function check_gmail(addr) |
| 577 |
local nu, tags, nd = check_gmail_user(addr) |
| 578 |
if nu then |
| 579 |
return nu, tags, nd |
| 580 |
end |
| 581 |
return nil |
| 582 |
end |
| 583 |
|
| 584 |
local function check_googlemail(addr) |
| 585 |
local nd = 'gmail.com' |
| 586 |
local nu, tags = check_gmail_user(addr) |
| 587 |
if nu then |
| 588 |
return nu, tags, nd |
| 589 |
end |
| 590 |
return nil, nil, nd |
| 591 |
end |
| 592 |
|
| 593 |
local specific_domains = { |
| 594 |
['gmail.com'] = check_gmail, |
| 595 |
['googlemail.com'] = check_googlemail, |
| 596 |
} |
| 597 |
|
| 598 |
if email_addr then |
| 599 |
if email_addr.domain and specific_domains[email_addr.domain] then |
| 600 |
local nu, tags, nd = specific_domains[email_addr.domain](email_addr) |
| 601 |
if nu or nd then |
| 602 |
return nu, tags, nd |
| 603 |
end |
| 604 |
else |
| 605 |
local nu, tags, nd = check_address(email_addr) |
| 606 |
if nu or nd then |
| 607 |
return nu, tags, nd |
| 608 |
end |
| 609 |
end |
| 610 |
|
| 611 |
return nil |
| 612 |
end |
| 613 |
end |
| 614 |
exports.apply_service_rules = apply_service_rules |
| 615 |
|
| 616 |
--- Resolve one step of aliasing |
| 617 |
-- @param email_str normalized email string |
| 618 |
-- @return result (string, array of strings, or nil), rule_type |
| 619 |
local function resolve_one_step(email_str) |
| 620 |
-- Check virtual aliases first |
| 621 |
local virtual_result = get_from_source(module_state.virtual_aliases, email_str) |
| 622 |
if virtual_result then |
| 623 |
return virtual_result, 'virtual' |
| 624 |
end |
| 625 |
|
| 626 |
-- Check rspamd aliases |
| 627 |
if module_state.rspamd_aliases[email_str] then |
| 628 |
return module_state.rspamd_aliases[email_str], 'rspamd' |
| 629 |
end |
| 630 |
|
| 631 |
-- Check unix aliases (user part only) |
| 632 |
local user = email_str:match('^([^@]+)@') |
| 633 |
if user then |
| 634 |
local unix_result = get_from_source(module_state.unix_aliases, user) |
| 635 |
if unix_result then |
| 636 |
-- Normalize result to always be array |
| 637 |
if type(unix_result) == 'string' then |
| 638 |
unix_result = { unix_result } |
| 639 |
end |
| 640 |
|
| 641 |
if type(unix_result) == 'table' and #unix_result > 0 then |
| 642 |
-- Add domain to targets that don't have one |
| 643 |
local domain = email_str:match('@([^@]+)$') |
| 644 |
if domain then |
| 645 |
local normalized = {} |
| 646 |
for _, target in ipairs(unix_result) do |
| 647 |
if not target:match('@') then |
| 648 |
table.insert(normalized, target .. '@' .. domain) |
| 649 |
else |
| 650 |
table.insert(normalized, target) |
| 651 |
end |
| 652 |
end |
| 653 |
return normalized, 'unix' |
| 654 |
else |
| 655 |
return unix_result, 'unix' |
| 656 |
end |
| 657 |
end |
| 658 |
end |
| 659 |
end |
| 660 |
|
| 661 |
-- No alias found |
| 662 |
return nil, nil |
| 663 |
end |
| 664 |
|
| 665 |
--- Resolve email address recursively with loop detection |
| 666 |
-- @param addr email address (string or table) |
| 667 |
-- @param opts options: max_depth, track_chain, expand_multiple |
| 668 |
-- @return canonical (string or array), chain, metadata |
| 669 |
local function resolve_address_recursive(addr, opts) |
| 670 |
opts = opts or {} |
| 671 |
local max_depth = opts.max_depth or 10 |
| 672 |
local track_chain = opts.track_chain |
| 673 |
local expand_multiple = opts.expand_multiple |
| 674 |
|
| 675 |
-- Convert to normalized form |
| 676 |
local email_str |
| 677 |
local original_str |
| 678 |
if type(addr) == 'string' then |
| 679 |
original_str = addr |
| 680 |
email_str = addr:lower() |
| 681 |
elseif type(addr) == 'table' and addr.addr then |
| 682 |
original_str = addr.addr |
| 683 |
email_str = addr.addr:lower() |
| 684 |
else |
| 685 |
return addr, nil, { error = 'invalid address format' } |
| 686 |
end |
| 687 |
|
| 688 |
-- Track visited addresses for loop detection |
| 689 |
local visited = {} |
| 690 |
local chain = track_chain and { email_str } or nil |
| 691 |
local rules_applied = {} |
| 692 |
|
| 693 |
--- Recursive resolve helper |
| 694 |
-- @param current_addr current address to resolve |
| 695 |
-- @param depth current recursion depth |
| 696 |
-- @param path current resolution path (for loop detection) |
| 697 |
-- @return array of canonical addresses |
| 698 |
local function resolve_recursive(current_addr, depth, path, orig) |
| 699 |
path = path or {} |
| 700 |
-- Check depth limit |
| 701 |
if depth > max_depth then |
| 702 |
lua_util.debugm(N, module_state.config, |
| 703 |
'max recursion depth %s reached for %s', max_depth, email_str) |
| 704 |
return { current_addr } |
| 705 |
end |
| 706 |
|
| 707 |
-- Check for loops (only in current path, not all visited) |
| 708 |
if path[current_addr] then |
| 709 |
lua_util.debugm(N, module_state.config, |
| 710 |
'alias loop detected for %s at %s', email_str, current_addr) |
| 711 |
return { current_addr } |
| 712 |
end |
| 713 |
|
| 714 |
-- Track in visited for metadata |
| 715 |
visited[current_addr] = true |
| 716 |
-- Create new path with current address |
| 717 |
local new_path = {} |
| 718 |
for k, v in pairs(path) do |
| 719 |
new_path[k] = v |
| 720 |
end |
| 721 |
new_path[current_addr] = true |
| 722 |
|
| 723 |
-- Try to resolve one step |
| 724 |
local result, rule_type = resolve_one_step(current_addr) |
| 725 |
|
| 726 |
if not result then |
| 727 |
-- No more aliases, this is canonical |
| 728 |
return { orig or current_addr } |
| 729 |
end |
| 730 |
|
| 731 |
-- Track rule application |
| 732 |
if rule_type and not rules_applied[rule_type] then |
| 733 |
rules_applied[rule_type] = 0 |
| 734 |
end |
| 735 |
if rule_type then |
| 736 |
rules_applied[rule_type] = rules_applied[rule_type] + 1 |
| 737 |
end |
| 738 |
|
| 739 |
-- Normalize result to array |
| 740 |
local targets |
| 741 |
if type(result) == 'string' then |
| 742 |
targets = { result } |
| 743 |
elseif type(result) == 'table' then |
| 744 |
targets = result |
| 745 |
else |
| 746 |
return { current_addr } |
| 747 |
end |
| 748 |
|
| 749 |
-- If we have multiple targets and expand_multiple is false, take first |
| 750 |
if #targets > 1 and not expand_multiple then |
| 751 |
if track_chain and chain then |
| 752 |
table.insert(chain, targets[1]) |
| 753 |
end |
| 754 |
return resolve_recursive(targets[1], depth + 1, new_path) |
| 755 |
end |
| 756 |
|
| 757 |
-- Expand multiple targets |
| 758 |
local canonical_addrs = {} |
| 759 |
for _, target in ipairs(targets) do |
| 760 |
if track_chain and chain then |
| 761 |
table.insert(chain, target) |
| 762 |
end |
| 763 |
|
| 764 |
-- Recursively resolve each target with current path |
| 765 |
-- Each branch gets the same path, allowing convergence while detecting loops |
| 766 |
local resolved = resolve_recursive(target, depth + 1, new_path) |
| 767 |
for _, resolved_addr in ipairs(resolved) do |
| 768 |
table.insert(canonical_addrs, resolved_addr) |
| 769 |
end |
| 770 |
end |
| 771 |
|
| 772 |
return canonical_addrs |
| 773 |
end |
| 774 |
|
| 775 |
-- Start resolution |
| 776 |
local canonical_addrs = resolve_recursive(email_str, 1, nil, original_str) |
| 777 |
|
| 778 |
-- Build metadata |
| 779 |
local metadata = { |
| 780 |
depth = table_length(visited), |
| 781 |
rules_applied = rules_applied, |
| 782 |
expanded = #canonical_addrs > 1, |
| 783 |
} |
| 784 |
|
| 785 |
-- Return result |
| 786 |
if #canonical_addrs == 1 then |
| 787 |
return canonical_addrs[1], chain, metadata |
| 788 |
else |
| 789 |
return canonical_addrs, chain, metadata |
| 790 |
end |
| 791 |
end |
| 792 |
|
| 793 |
--- Resolve a single email address (backward compatible, non-recursive) |
| 794 |
-- @param addr email address (string or table) |
| 795 |
-- @param opts options table (can specify max_depth) |
| 796 |
-- @return canonical address or original address if no alias found |
| 797 |
local function resolve_address(addr, opts) |
| 798 |
opts = opts or {} |
| 799 |
|
| 800 |
-- Use recursive resolver with specified depth (default 10 for compatibility) |
| 801 |
local simple_opts = { |
| 802 |
max_depth = opts.max_depth or 10, |
| 803 |
track_chain = opts.track_chain or false, |
| 804 |
expand_multiple = opts.expand_multiple or false, |
| 805 |
} |
| 806 |
|
| 807 |
local canonical = resolve_address_recursive(addr, simple_opts) |
| 808 |
return canonical |
| 809 |
end |
| 810 |
exports.resolve_address = resolve_address |
| 811 |
exports.resolve_address_recursive = resolve_address_recursive |
| 812 |
|
| 813 |
--- Classify message direction (inbound/outbound/internal/forwarded) |
| 814 |
-- @param task rspamd task |
| 815 |
-- @param opts classification options |
| 816 |
-- @return classification table with direction, from_local, to_local, canonical addresses, etc. |
| 817 |
local function classify_message(task, opts) |
| 818 |
opts = opts or {} |
| 819 |
local resolve_opts = { |
| 820 |
max_depth = opts.max_depth or 10, |
| 821 |
track_chain = opts.track_chain or false, |
| 822 |
expand_multiple = opts.expand_multiple or true, |
| 823 |
} |
| 824 |
|
| 825 |
local classification = { |
| 826 |
direction = nil, |
| 827 |
from_local = false, |
| 828 |
to_local = false, |
| 829 |
canonical_from = nil, |
| 830 |
canonical_recipients = {}, |
| 831 |
forwarding_detected = nil, |
| 832 |
aliases_resolved = { |
| 833 |
from = nil, |
| 834 |
recipients = {}, |
| 835 |
} |
| 836 |
} |
| 837 |
|
| 838 |
-- Get authenticated user and IP |
| 839 |
local user = task:get_user() |
| 840 |
local ip = task:get_ip() |
| 841 |
local is_authenticated = user ~= nil |
| 842 |
local is_local_ip = ip and ip:is_local() |
| 843 |
|
| 844 |
-- Resolve From address |
| 845 |
local from_smtp = task:get_from('smtp') |
| 846 |
if from_smtp and from_smtp[1] then |
| 847 |
local from_addr = from_smtp[1] |
| 848 |
|
| 849 |
-- Check if from is local domain |
| 850 |
classification.from_local = is_local_address(from_addr) |
| 851 |
|
| 852 |
-- Apply service rules to extract tags (but don't modify addr in task) |
| 853 |
local from_copy = { |
| 854 |
addr = from_addr.addr, |
| 855 |
user = from_addr.user, |
| 856 |
domain = from_addr.domain, |
| 857 |
name = from_addr.name, |
| 858 |
} |
| 859 |
local _, tags = apply_service_rules(from_copy) |
| 860 |
if tags and #tags > 0 then |
| 861 |
classification.from_tagged = tags |
| 862 |
end |
| 863 |
|
| 864 |
-- Resolve from address |
| 865 |
local canonical_from, from_chain, from_meta = resolve_address_recursive( |
| 866 |
from_addr, resolve_opts) |
| 867 |
|
| 868 |
classification.canonical_from = canonical_from |
| 869 |
classification.aliases_resolved.from = { |
| 870 |
chain = from_chain, |
| 871 |
metadata = from_meta, |
| 872 |
} |
| 873 |
end |
| 874 |
|
| 875 |
-- Resolve recipients |
| 876 |
local rcpts_smtp = task:get_recipients('smtp') |
| 877 |
if rcpts_smtp then |
| 878 |
local any_local = false |
| 879 |
local rcpt_count = 0 |
| 880 |
|
| 881 |
for _, rcpt in ipairs(rcpts_smtp) do |
| 882 |
rcpt_count = rcpt_count + 1 |
| 883 |
-- Check if recipient is local |
| 884 |
local rcpt_is_local = is_local_address(rcpt) |
| 885 |
if rcpt_is_local then |
| 886 |
any_local = true |
| 887 |
end |
| 888 |
|
| 889 |
-- Resolve recipient |
| 890 |
local canonical_rcpt, rcpt_chain, rcpt_meta = resolve_address_recursive( |
| 891 |
rcpt, resolve_opts) |
| 892 |
|
| 893 |
-- Handle multiple expansions |
| 894 |
if type(canonical_rcpt) == 'table' then |
| 895 |
for _, addr in ipairs(canonical_rcpt) do |
| 896 |
table.insert(classification.canonical_recipients, addr) |
| 897 |
end |
| 898 |
else |
| 899 |
table.insert(classification.canonical_recipients, canonical_rcpt) |
| 900 |
end |
| 901 |
|
| 902 |
table.insert(classification.aliases_resolved.recipients, { |
| 903 |
original = rcpt.addr, |
| 904 |
canonical = canonical_rcpt, |
| 905 |
chain = rcpt_chain, |
| 906 |
metadata = rcpt_meta, |
| 907 |
is_local = rcpt_is_local, |
| 908 |
}) |
| 909 |
end |
| 910 |
|
| 911 |
classification.to_local = (rcpt_count > 0) and any_local |
| 912 |
end |
| 913 |
|
| 914 |
-- Determine direction |
| 915 |
if classification.from_local and classification.to_local then |
| 916 |
classification.direction = 'internal' |
| 917 |
elseif classification.from_local and not classification.to_local then |
| 918 |
classification.direction = 'outbound' |
| 919 |
elseif not classification.from_local and classification.to_local then |
| 920 |
classification.direction = 'inbound' |
| 921 |
else |
| 922 |
-- Neither from nor to is local - might be forwarded or external |
| 923 |
classification.direction = 'external' |
| 924 |
end |
| 925 |
|
| 926 |
-- Check for forwarding (from opts if provided by plugin) |
| 927 |
if opts.forwarding_detected then |
| 928 |
classification.forwarding_detected = { |
| 929 |
type = opts.forwarding_type, |
| 930 |
info = opts.forwarding_info, |
| 931 |
} |
| 932 |
classification.direction = 'forwarded' |
| 933 |
end |
| 934 |
|
| 935 |
-- Override with authenticated/local IP logic |
| 936 |
if is_authenticated or is_local_ip then |
| 937 |
-- Authenticated users or local IPs sending mail = outbound |
| 938 |
if not classification.to_local then |
| 939 |
classification.direction = 'outbound' |
| 940 |
elseif classification.to_local and classification.from_local then |
| 941 |
classification.direction = 'internal' |
| 942 |
end |
| 943 |
end |
| 944 |
|
| 945 |
return classification |
| 946 |
end |
| 947 |
exports.classify_message = classify_message |
| 948 |
|
| 949 |
--- Get module state (for debugging) |
| 950 |
-- @return module state table |
| 951 |
local function get_state() |
| 952 |
return module_state |
| 953 |
end |
| 954 |
exports.get_state = get_state |
| 955 |
|
| 956 |
--- Reset module state (for testing) |
| 957 |
local function reset() |
| 958 |
module_state = { |
| 959 |
initialized = false, |
| 960 |
config = nil, |
| 961 |
local_domains = {}, |
| 962 |
unix_aliases = {}, |
| 963 |
virtual_aliases = {}, |
| 964 |
rspamd_aliases = {}, |
| 965 |
cache = {}, |
| 966 |
backends = {}, |
| 967 |
} |
| 968 |
end |
| 969 |
exports.reset = reset |
| 970 |
|
| 971 |
return exports |