refactor config structure
This commit is contained in:
@@ -79,17 +79,17 @@ class ModifyMilterConfig(BaseConfig):
|
|||||||
pretend = cfg["global"]["pretend"]
|
pretend = cfg["global"]["pretend"]
|
||||||
assert isinstance(pretend, bool), \
|
assert isinstance(pretend, bool), \
|
||||||
"global: pretend: invalid value, should be bool"
|
"global: pretend: invalid value, should be bool"
|
||||||
self["pretend"] = pretend
|
self.pretend = pretend
|
||||||
else:
|
else:
|
||||||
self["pretend"] = False
|
self.pretend = False
|
||||||
|
|
||||||
if "socket" in cfg["global"]:
|
if "socket" in cfg["global"]:
|
||||||
socket = cfg["global"]["socket"]
|
socket = cfg["global"]["socket"]
|
||||||
assert isinstance(socket, str), \
|
assert isinstance(socket, str), \
|
||||||
"global: socket: invalid value, should be string"
|
"global: socket: invalid value, should be string"
|
||||||
self["socket"] = socket
|
self.socket = socket
|
||||||
else:
|
else:
|
||||||
self["socket"] = None
|
self.socket = None
|
||||||
|
|
||||||
if "local_addrs" in cfg["global"]:
|
if "local_addrs" in cfg["global"]:
|
||||||
local_addrs = cfg["global"]["local_addrs"]
|
local_addrs = cfg["global"]["local_addrs"]
|
||||||
@@ -106,17 +106,17 @@ class ModifyMilterConfig(BaseConfig):
|
|||||||
"172.16.0.0/12",
|
"172.16.0.0/12",
|
||||||
"192.168.0.0/16"]
|
"192.168.0.0/16"]
|
||||||
|
|
||||||
self["local_addrs"] = []
|
self.local_addrs = []
|
||||||
try:
|
try:
|
||||||
for addr in local_addrs:
|
for addr in local_addrs:
|
||||||
self["local_addrs"].append(IPNetwork(addr))
|
self.local_addrs.append(IPNetwork(addr))
|
||||||
except AddrFormatError as e:
|
except AddrFormatError as e:
|
||||||
raise ValueError(f"{self['name']}: local_addrs: {e}")
|
raise ValueError(f"{self.name}: local_addrs: {e}")
|
||||||
|
|
||||||
self.logger.debug(f"socket={self['socket']}, "
|
self.logger.debug(f"socket={self.socket}, "
|
||||||
f"local_addrs={self['local_addrs']}, "
|
f"local_addrs={self.local_addrs}, "
|
||||||
f"pretend={self['pretend']}, "
|
f"pretend={self.pretend}, "
|
||||||
f"loglevel={self['loglevel']}")
|
f"loglevel={self.loglevel}")
|
||||||
|
|
||||||
assert "rules" in cfg, \
|
assert "rules" in cfg, \
|
||||||
"mandatory parameter 'rules' not found"
|
"mandatory parameter 'rules' not found"
|
||||||
@@ -124,10 +124,15 @@ class ModifyMilterConfig(BaseConfig):
|
|||||||
"rules: invalid value, should be list"
|
"rules: invalid value, should be list"
|
||||||
|
|
||||||
self.logger.debug("initialize rules config")
|
self.logger.debug("initialize rules config")
|
||||||
self["rules"] = []
|
self.rules = []
|
||||||
for idx, rule_cfg in enumerate(cfg["rules"]):
|
for idx, rule_cfg in enumerate(cfg["rules"]):
|
||||||
self["rules"].append(
|
if "name" not in rule_cfg:
|
||||||
RuleConfig(idx, self, rule_cfg, debug))
|
rule_cfg["name"] = "Rule #{idx}"
|
||||||
|
if "loglevel" not in rule_cfg:
|
||||||
|
rule_cfg["loglevel"] = self.loglevel
|
||||||
|
if "pretend" not in rule_cfg:
|
||||||
|
rule_cfg["pretend"] = self.pretend
|
||||||
|
self.rules.append(RuleConfig(rule_cfg, debug))
|
||||||
|
|
||||||
|
|
||||||
class ModifyMilter(Milter.Base):
|
class ModifyMilter(Milter.Base):
|
||||||
@@ -140,10 +145,10 @@ class ModifyMilter(Milter.Base):
|
|||||||
|
|
||||||
@staticmethod
|
@staticmethod
|
||||||
def set_config(cfg):
|
def set_config(cfg):
|
||||||
ModifyMilter._loglevel = cfg["loglevel"]
|
ModifyMilter._loglevel = cfg.loglevel
|
||||||
for rule_cfg in cfg["rules"]:
|
for rule_cfg in cfg.rules:
|
||||||
ModifyMilter._rules.append(
|
ModifyMilter._rules.append(
|
||||||
Rule(cfg, rule_cfg))
|
Rule(rule_cfg, cfg.local_addrs))
|
||||||
|
|
||||||
def __init__(self):
|
def __init__(self):
|
||||||
self.logger = logging.getLogger(__name__)
|
self.logger = logging.getLogger(__name__)
|
||||||
|
|||||||
@@ -16,8 +16,6 @@ __all__ = [
|
|||||||
"ActionConfig",
|
"ActionConfig",
|
||||||
"Action"]
|
"Action"]
|
||||||
|
|
||||||
import os
|
|
||||||
|
|
||||||
from pymodmilter import BaseConfig
|
from pymodmilter import BaseConfig
|
||||||
from pymodmilter import modify, notify, storage
|
from pymodmilter import modify, notify, storage
|
||||||
from pymodmilter.base import CustomLogger
|
from pymodmilter.base import CustomLogger
|
||||||
@@ -25,100 +23,108 @@ from pymodmilter.conditions import ConditionsConfig, Conditions
|
|||||||
|
|
||||||
|
|
||||||
class ActionConfig(BaseConfig):
|
class ActionConfig(BaseConfig):
|
||||||
def __init__(self, idx, rule_cfg, cfg, debug):
|
TYPES = {"add_header": "_add_header",
|
||||||
if "name" in cfg:
|
"mod_header": "_mod_header",
|
||||||
assert isinstance(cfg["name"], str), \
|
"del_header": "_del_header",
|
||||||
f"{rule_cfg['name']}: Action #{idx}: name: invalid value, " \
|
"add_disclaimer": "_add_disclaimer",
|
||||||
f"should be string"
|
"rewrite_links": "_rewrite_links",
|
||||||
cfg["name"] = f"{rule_cfg['name']}: {cfg['name']}"
|
"store": "_store",
|
||||||
else:
|
"notify": "_notify"}
|
||||||
cfg["name"] = f"{rule_cfg['name']}: Action #{idx}"
|
|
||||||
|
|
||||||
if "loglevel" not in cfg:
|
|
||||||
cfg["loglevel"] = rule_cfg["loglevel"]
|
|
||||||
|
|
||||||
|
def __init__(self, cfg, debug):
|
||||||
super().__init__(cfg, debug)
|
super().__init__(cfg, debug)
|
||||||
|
|
||||||
self["pretend"] = rule_cfg["pretend"]
|
self.pretend = False
|
||||||
self["conditions"] = None
|
|
||||||
|
|
||||||
if "pretend" in cfg:
|
if "pretend" in cfg:
|
||||||
pretend = cfg["pretend"]
|
assert isinstance(cfg["pretend"], bool), \
|
||||||
assert isinstance(pretend, bool), \
|
f"{self.name}: pretend: invalid value, should be bool"
|
||||||
f"{self['name']}: pretend: invalid value, should be bool"
|
self.pretend = cfg["pretend"]
|
||||||
self["pretend"] = pretend
|
|
||||||
|
|
||||||
assert "type" in cfg, \
|
assert "type" in cfg, \
|
||||||
f"{self['name']}: mandatory parameter 'type' not found"
|
f"{self.name}: mandatory parameter 'type' not found"
|
||||||
assert isinstance(cfg["type"], str), \
|
assert isinstance(cfg["type"], str), \
|
||||||
f"{self['name']}: type: invalid value, should be string"
|
f"{self.name}: type: invalid value, should be string"
|
||||||
|
assert cfg["type"] in ActionConfig.TYPES, \
|
||||||
|
f"{self.name}: type: invalid action type"
|
||||||
|
|
||||||
if cfg["type"] == "add_header":
|
getattr(self, cfg["type"])(cfg)
|
||||||
self["class"] = modify.AddHeader
|
|
||||||
self["headersonly"] = True
|
if "conditions" in cfg:
|
||||||
|
assert isinstance(cfg["conditions"], dict), \
|
||||||
|
f"{self.name}: conditions: invalid value, should be dict"
|
||||||
|
cfg["conditions"]["name"] = f"{self.name}: condition"
|
||||||
|
if "loglevel" not in cfg["conditions"]:
|
||||||
|
cfg["conditions"]["loglevel"] = self.loglevel
|
||||||
|
self.conditions = ConditionsConfig(cfg["conditions"], debug)
|
||||||
|
else:
|
||||||
|
self.conditions = None
|
||||||
|
|
||||||
|
self.logger.debug(f"{self.name}: pretend={self.pretend}, "
|
||||||
|
f"loglevel={self.loglevel}, "
|
||||||
|
f"type={cfg['type']}, "
|
||||||
|
f"args={self.args}")
|
||||||
|
|
||||||
|
def add_header(self, cfg):
|
||||||
|
self.action = modify.AddHeader
|
||||||
|
self.headersonly = True
|
||||||
self.add_string_arg(cfg, ["field", "value"])
|
self.add_string_arg(cfg, ["field", "value"])
|
||||||
elif cfg["type"] == "mod_header":
|
|
||||||
self["class"] = modify.ModHeader
|
def mod_header(self, cfg):
|
||||||
self["headersonly"] = True
|
self.action = modify.ModHeader
|
||||||
|
self.headersonly = True
|
||||||
args = ["field", "value"]
|
args = ["field", "value"]
|
||||||
if "search" in cfg:
|
if "search" in cfg:
|
||||||
args.append("search")
|
args.append("search")
|
||||||
|
|
||||||
self.add_string_arg(cfg, args)
|
self.add_string_arg(cfg, args)
|
||||||
elif cfg["type"] == "del_header":
|
|
||||||
self["class"] = modify.DelHeader
|
def del_header(self, cfg):
|
||||||
self["headersonly"] = True
|
self.action = modify.DelHeader
|
||||||
|
self.headersonly = True
|
||||||
args = ["field"]
|
args = ["field"]
|
||||||
if "value" in cfg:
|
if "value" in cfg:
|
||||||
args.append("value")
|
args.append("value")
|
||||||
|
|
||||||
self.add_string_arg(cfg, args)
|
self.add_string_arg(cfg, args)
|
||||||
elif cfg["type"] == "add_disclaimer":
|
|
||||||
self["class"] = modify.AddDisclaimer
|
def add_disclaimer(self, cfg):
|
||||||
self["headersonly"] = False
|
self.action = modify.AddDisclaimer
|
||||||
|
self.headersonly = False
|
||||||
if "error_policy" not in cfg:
|
if "error_policy" not in cfg:
|
||||||
cfg["error_policy"] = "wrap"
|
cfg["error_policy"] = "wrap"
|
||||||
|
|
||||||
self.add_string_arg(
|
self.add_string_arg(
|
||||||
cfg, ["action", "html_template", "text_template",
|
cfg, ["action", "html_template", "text_template",
|
||||||
"error_policy"])
|
"error_policy"])
|
||||||
assert self["args"]["action"] in ["append", "prepend"], \
|
assert self.args["action"] in ["append", "prepend"], \
|
||||||
f"{self['name']}: action: invalid value, " \
|
f"{self.name}: action: invalid value, " \
|
||||||
f"should be 'append' or 'prepend'"
|
f"should be 'append' or 'prepend'"
|
||||||
assert self["args"]["error_policy"] in ("wrap",
|
assert self.args["error_policy"] in ("wrap",
|
||||||
"ignore",
|
"ignore",
|
||||||
"reject"), \
|
"reject"), \
|
||||||
f"{self['name']}: error_policy: invalid value, " \
|
f"{self.name}: error_policy: invalid value, " \
|
||||||
f"should be 'wrap', 'ignore' or 'reject'"
|
f"should be 'wrap', 'ignore' or 'reject'"
|
||||||
|
|
||||||
elif cfg["type"] == "rewrite_links":
|
def rewrite_links(self, cfg):
|
||||||
self["class"] = modify.RewriteLinks
|
self.action = modify.RewriteLinks
|
||||||
self["headersonly"] = False
|
self.headersonly = False
|
||||||
self.add_string_arg(cfg, "repl")
|
self.add_string_arg(cfg, "repl")
|
||||||
|
|
||||||
elif cfg["type"] == "store":
|
def store(self, cfg):
|
||||||
self["headersonly"] = False
|
self.headersonly = False
|
||||||
|
|
||||||
assert "storage_type" in cfg, \
|
assert "storage_type" in cfg, \
|
||||||
f"{self['name']}: mandatory parameter 'storage_type' not found"
|
f"{self.name}: mandatory parameter 'storage_type' not found"
|
||||||
assert isinstance(cfg["storage_type"], str), \
|
assert isinstance(cfg["storage_type"], str), \
|
||||||
f"{self['name']}: storage_type: invalid value, " \
|
f"{self.name}: storage_type: invalid value, " \
|
||||||
f"should be string"
|
f"should be string"
|
||||||
self["storage_type"] = cfg["storage_type"]
|
|
||||||
|
|
||||||
if "original" in cfg:
|
if "original" in cfg:
|
||||||
self.add_bool_arg(cfg, "original")
|
self.add_bool_arg(cfg, "original")
|
||||||
|
|
||||||
if self["storage_type"] == "file":
|
if cfg["storage_type"] == "file":
|
||||||
self["class"] = storage.FileMailStorage
|
self.action = storage.FileMailStorage
|
||||||
self.add_string_arg(cfg, "directory")
|
self.add_string_arg(cfg, "directory")
|
||||||
# check if directory exists and is writable
|
|
||||||
if not os.path.isdir(self["args"]["directory"]) or \
|
|
||||||
not os.access(self["args"]["directory"], os.W_OK):
|
|
||||||
raise RuntimeError(
|
|
||||||
f"{self['name']}: file quarantine directory "
|
|
||||||
f"'{self['directory']}' does not exist or is "
|
|
||||||
f"not writable")
|
|
||||||
|
|
||||||
if "skip_metadata" in cfg:
|
if "skip_metadata" in cfg:
|
||||||
self.add_bool_arg(cfg, "skip_metadata")
|
self.add_bool_arg(cfg, "skip_metadata")
|
||||||
@@ -128,11 +134,11 @@ class ActionConfig(BaseConfig):
|
|||||||
|
|
||||||
else:
|
else:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f"{self['name']}: storage_type: invalid storage type")
|
f"{self.name}: storage_type: invalid storage type")
|
||||||
|
|
||||||
elif cfg["type"] == "notify":
|
def notify(self, cfg):
|
||||||
self["headersonly"] = False
|
self.headersonly = False
|
||||||
self["class"] = notify.EMailNotification
|
self.action = notify.EMailNotification
|
||||||
|
|
||||||
args = ["smtp_host", "envelope_from", "from_header", "subject",
|
args = ["smtp_host", "envelope_from", "from_header", "subject",
|
||||||
"template"]
|
"template"]
|
||||||
@@ -143,45 +149,27 @@ class ActionConfig(BaseConfig):
|
|||||||
self.add_int_arg(cfg, "smtp_port")
|
self.add_int_arg(cfg, "smtp_port")
|
||||||
|
|
||||||
if "embed_imgs" in cfg:
|
if "embed_imgs" in cfg:
|
||||||
assert isinstance(cfg["embed_imgs"], list), \
|
assert isinstance(cfg["embed_imgs"], list) and all(
|
||||||
f"{self['name']}: embed_imgs: invalid value, " \
|
[isinstance(img, str) for img in cfg["embed_imgs"]]), \
|
||||||
f"should be list"
|
f"{self.name}: embed_imgs: invalid value, " \
|
||||||
for img in cfg["embed_imgs"]:
|
f"should be list of strings"
|
||||||
assert isinstance(img, str), \
|
self.args["embed_imgs"] = cfg["embed_imgs"]
|
||||||
f"{self['name']}: embed_imgs: invalid entry, " \
|
|
||||||
f"should be string"
|
|
||||||
|
|
||||||
self["args"]["embed_imgs"] = cfg["embed_imgs"]
|
|
||||||
|
|
||||||
else:
|
|
||||||
raise RuntimeError(f"{self['name']}: type: invalid action type")
|
|
||||||
|
|
||||||
if "conditions" in cfg:
|
|
||||||
conditions = cfg["conditions"]
|
|
||||||
assert isinstance(conditions, dict), \
|
|
||||||
f"{self['name']}: conditions: invalid value, should be dict"
|
|
||||||
self["conditions"] = ConditionsConfig(self, conditions, debug)
|
|
||||||
|
|
||||||
self.logger.debug(f"{self['name']}: pretend={self['pretend']}, "
|
|
||||||
f"loglevel={self['loglevel']}, "
|
|
||||||
f"type={cfg['type']}, "
|
|
||||||
f"args={self['args']}")
|
|
||||||
|
|
||||||
|
|
||||||
class Action:
|
class Action:
|
||||||
"""Action to implement a pre-configured action to perform on e-mails."""
|
"""Action to implement a pre-configured action to perform on e-mails."""
|
||||||
|
|
||||||
def __init__(self, milter_cfg, cfg):
|
def __init__(self, cfg, local_addrs):
|
||||||
if cfg["conditions"] is None:
|
self.logger = cfg.logger
|
||||||
|
if cfg.conditions is None:
|
||||||
self.conditions = None
|
self.conditions = None
|
||||||
else:
|
else:
|
||||||
self.conditions = Conditions(milter_cfg, cfg["conditions"])
|
self.conditions = Conditions(cfg.conditions, local_addrs)
|
||||||
|
|
||||||
self.pretend = cfg["pretend"]
|
self.pretend = cfg.pretend
|
||||||
self._name = cfg["name"]
|
self.name = cfg.name
|
||||||
self._class = cfg["class"](**cfg["args"])
|
self.action = cfg.action(**cfg.args)
|
||||||
self._headersonly = cfg["headersonly"]
|
self._headersonly = cfg.headersonly
|
||||||
self.logger = cfg.logger
|
|
||||||
|
|
||||||
def headersonly(self):
|
def headersonly(self):
|
||||||
"""Return the needs of this action."""
|
"""Return the needs of this action."""
|
||||||
@@ -190,8 +178,8 @@ class Action:
|
|||||||
def execute(self, milter):
|
def execute(self, milter):
|
||||||
"""Execute configured action."""
|
"""Execute configured action."""
|
||||||
logger = CustomLogger(
|
logger = CustomLogger(
|
||||||
self.logger, {"qid": milter.qid, "name": self._name})
|
self.logger, {"qid": milter.qid, "name": self.name})
|
||||||
if self.conditions is None or \
|
if self.conditions is None or \
|
||||||
self.conditions.match(milter):
|
self.conditions.match(milter):
|
||||||
return self._class.execute(
|
return self.action.execute(
|
||||||
milter=milter, pretend=self.pretend, logger=logger)
|
milter=milter, pretend=self.pretend, logger=logger)
|
||||||
|
|||||||
@@ -38,49 +38,33 @@ class CustomLogger(logging.LoggerAdapter):
|
|||||||
|
|
||||||
|
|
||||||
class BaseConfig:
|
class BaseConfig:
|
||||||
def __init__(self, cfg={}, debug=False, logger=None):
|
def __init__(self, cfg={}, debug=False):
|
||||||
self._cfg = {}
|
|
||||||
if "name" in cfg:
|
if "name" in cfg:
|
||||||
assert isinstance(cfg["name"], str), \
|
assert isinstance(cfg["name"], str), \
|
||||||
"rule: name: invalid value, should be string"
|
"name: invalid value, should be string"
|
||||||
self["name"] = cfg["name"]
|
self.name = cfg["name"]
|
||||||
else:
|
else:
|
||||||
self["name"] = __name__
|
self.name = __name__
|
||||||
|
|
||||||
|
self.logger = logging.getLogger(self.name)
|
||||||
if debug:
|
if debug:
|
||||||
self["loglevel"] = logging.DEBUG
|
self.loglevel = logging.DEBUG
|
||||||
elif "loglevel" in cfg:
|
elif "loglevel" in cfg:
|
||||||
if isinstance(cfg["loglevel"], int):
|
if isinstance(cfg["loglevel"], int):
|
||||||
self["loglevel"] = cfg["loglevel"]
|
self.loglevel = cfg["loglevel"]
|
||||||
else:
|
else:
|
||||||
level = getattr(logging, cfg["loglevel"].upper(), None)
|
level = getattr(logging, cfg["loglevel"].upper(), None)
|
||||||
assert isinstance(level, int), \
|
assert isinstance(level, int), \
|
||||||
f"{self['name']}: loglevel: invalid value"
|
f"{self.name}: loglevel: invalid value"
|
||||||
self["loglevel"] = level
|
self.loglevel = level
|
||||||
else:
|
else:
|
||||||
self["loglevel"] = logging.INFO
|
self.loglevel = logging.INFO
|
||||||
|
|
||||||
if logger is None:
|
self.logger.setLevel(self.loglevel)
|
||||||
logger = logging.getLogger(self["name"])
|
|
||||||
logger.setLevel(self["loglevel"])
|
|
||||||
|
|
||||||
self.logger = logger
|
# the keys/values in args are used as parameters
|
||||||
|
# to initialize action classes
|
||||||
# the keys/values of args are used as parameters
|
self.args = {}
|
||||||
# to functions
|
|
||||||
self["args"] = {}
|
|
||||||
|
|
||||||
def __setitem__(self, key, value):
|
|
||||||
self._cfg[key] = value
|
|
||||||
|
|
||||||
def __getitem__(self, key):
|
|
||||||
return self._cfg[key]
|
|
||||||
|
|
||||||
def __delitem__(self, key):
|
|
||||||
del self._cfg[key]
|
|
||||||
|
|
||||||
def __contains__(self, key):
|
|
||||||
return key in self._cfg
|
|
||||||
|
|
||||||
def add_string_arg(self, cfg, args):
|
def add_string_arg(self, cfg, args):
|
||||||
if isinstance(args, str):
|
if isinstance(args, str):
|
||||||
@@ -88,10 +72,10 @@ class BaseConfig:
|
|||||||
|
|
||||||
for arg in args:
|
for arg in args:
|
||||||
assert arg in cfg, \
|
assert arg in cfg, \
|
||||||
f"{self['name']}: mandatory parameter '{arg}' not found"
|
f"{self.name}: mandatory parameter '{arg}' not found"
|
||||||
assert isinstance(cfg[arg], str), \
|
assert isinstance(cfg[arg], str), \
|
||||||
f"{self['name']}: {arg}: invalid value, should be string"
|
f"{self.name}: {arg}: invalid value, should be string"
|
||||||
self["args"][arg] = cfg[arg]
|
self.args[arg] = cfg[arg]
|
||||||
|
|
||||||
def add_bool_arg(self, cfg, args):
|
def add_bool_arg(self, cfg, args):
|
||||||
if isinstance(args, str):
|
if isinstance(args, str):
|
||||||
@@ -99,10 +83,10 @@ class BaseConfig:
|
|||||||
|
|
||||||
for arg in args:
|
for arg in args:
|
||||||
assert arg in cfg, \
|
assert arg in cfg, \
|
||||||
f"{self['name']}: mandatory parameter '{arg}' not found"
|
f"{self.name}: mandatory parameter '{arg}' not found"
|
||||||
assert isinstance(cfg[arg], bool), \
|
assert isinstance(cfg[arg], bool), \
|
||||||
f"{self['name']}: {arg}: invalid value, should be bool"
|
f"{self.name}: {arg}: invalid value, should be bool"
|
||||||
self["args"][arg] = cfg[arg]
|
self.args[arg] = cfg[arg]
|
||||||
|
|
||||||
def add_int_arg(self, cfg, args):
|
def add_int_arg(self, cfg, args):
|
||||||
if isinstance(args, str):
|
if isinstance(args, str):
|
||||||
@@ -110,10 +94,10 @@ class BaseConfig:
|
|||||||
|
|
||||||
for arg in args:
|
for arg in args:
|
||||||
assert arg in cfg, \
|
assert arg in cfg, \
|
||||||
f"{self['name']}: mandatory parameter '{arg}' not found"
|
f"{self.name}: mandatory parameter '{arg}' not found"
|
||||||
assert isinstance(cfg[arg], int), \
|
assert isinstance(cfg[arg], int), \
|
||||||
f"{self['name']}: {arg}: invalid value, should be integer"
|
f"{self.name}: {arg}: invalid value, should be integer"
|
||||||
self["args"][arg] = cfg[arg]
|
self.args[arg] = cfg[arg]
|
||||||
|
|
||||||
|
|
||||||
class MilterMessage(MIMEPart):
|
class MilterMessage(MIMEPart):
|
||||||
|
|||||||
@@ -23,12 +23,7 @@ from pymodmilter import BaseConfig, CustomLogger
|
|||||||
|
|
||||||
|
|
||||||
class ConditionsConfig(BaseConfig):
|
class ConditionsConfig(BaseConfig):
|
||||||
def __init__(self, parent_cfg, cfg, debug):
|
def __init__(self, cfg, debug):
|
||||||
if "loglevel" not in cfg:
|
|
||||||
cfg["loglevel"] = parent_cfg["loglevel"]
|
|
||||||
|
|
||||||
cfg["name"] = f"{parent_cfg['name']}: condition"
|
|
||||||
|
|
||||||
super().__init__(cfg, debug)
|
super().__init__(cfg, debug)
|
||||||
|
|
||||||
if "local" in cfg:
|
if "local" in cfg:
|
||||||
@@ -37,10 +32,10 @@ class ConditionsConfig(BaseConfig):
|
|||||||
if "hosts" in cfg:
|
if "hosts" in cfg:
|
||||||
assert isinstance(cfg["hosts"], list) and all(
|
assert isinstance(cfg["hosts"], list) and all(
|
||||||
[isinstance(host, str) for host in cfg["hosts"]]), \
|
[isinstance(host, str) for host in cfg["hosts"]]), \
|
||||||
f"{self['name']}: hosts: invalid value, " \
|
f"{self.name}: hosts: invalid value, " \
|
||||||
f"should be list of strings"
|
f"should be list of strings"
|
||||||
|
|
||||||
self["args"]["hosts"] = cfg["hosts"]
|
self.args["hosts"] = cfg["hosts"]
|
||||||
|
|
||||||
for arg in ("envfrom", "envto"):
|
for arg in ("envfrom", "envto"):
|
||||||
if arg in cfg:
|
if arg in cfg:
|
||||||
@@ -55,21 +50,22 @@ class ConditionsConfig(BaseConfig):
|
|||||||
if "metavar" in cfg:
|
if "metavar" in cfg:
|
||||||
self.add_string_arg(cfg, "metavar")
|
self.add_string_arg(cfg, "metavar")
|
||||||
|
|
||||||
self.logger.debug(f"{self['name']}: "
|
self.logger.debug(f"{self.name}: "
|
||||||
f"loglevel={self['loglevel']}, "
|
f"loglevel={self.loglevel}, "
|
||||||
f"args={self['args']}")
|
f"args={self.args}")
|
||||||
|
|
||||||
|
|
||||||
class Conditions:
|
class Conditions:
|
||||||
"""Conditions to implement conditions for rules and actions."""
|
"""Conditions to implement conditions for rules and actions."""
|
||||||
|
|
||||||
def __init__(self, milter_cfg, cfg):
|
def __init__(self, cfg, local_addrs):
|
||||||
self._local_addrs = milter_cfg["local_addrs"]
|
self.logger = cfg.logger
|
||||||
self._name = cfg["name"]
|
self.name = cfg.name
|
||||||
|
self.local_addrs = local_addrs
|
||||||
|
|
||||||
for arg in ("local", "hosts", "envfrom", "envto", "header", "metavar",
|
for arg in ("local", "hosts", "envfrom", "envto", "header", "metavar",
|
||||||
"var"):
|
"var"):
|
||||||
value = cfg["args"][arg] if arg in cfg["args"] else None
|
value = cfg.args[arg] if arg in cfg.args else None
|
||||||
setattr(self, arg, value)
|
setattr(self, arg, value)
|
||||||
if value is None:
|
if value is None:
|
||||||
continue
|
continue
|
||||||
@@ -96,17 +92,15 @@ class Conditions:
|
|||||||
except re.error as e:
|
except re.error as e:
|
||||||
raise RuntimeError(e)
|
raise RuntimeError(e)
|
||||||
|
|
||||||
self.logger = cfg.logger
|
|
||||||
|
|
||||||
def match_host(self, host):
|
def match_host(self, host):
|
||||||
logger = CustomLogger(
|
logger = CustomLogger(
|
||||||
self.logger, {"name": self._name})
|
self.logger, {"name": self.name})
|
||||||
|
|
||||||
ip = IPAddress(host)
|
ip = IPAddress(host)
|
||||||
|
|
||||||
if self.local is not None:
|
if self.local is not None:
|
||||||
is_local = False
|
is_local = False
|
||||||
for addr in self._local_addrs:
|
for addr in self.local_addrs:
|
||||||
if ip in addr:
|
if ip in addr:
|
||||||
is_local = True
|
is_local = True
|
||||||
break
|
break
|
||||||
@@ -140,7 +134,7 @@ class Conditions:
|
|||||||
|
|
||||||
def match(self, milter):
|
def match(self, milter):
|
||||||
logger = CustomLogger(
|
logger = CustomLogger(
|
||||||
self.logger, {"qid": milter.qid, "name": self._name})
|
self.logger, {"qid": milter.qid, "name": self.name})
|
||||||
|
|
||||||
if self.envfrom is not None:
|
if self.envfrom is not None:
|
||||||
envfrom = milter.msginfo["mailfrom"]
|
envfrom = milter.msginfo["mailfrom"]
|
||||||
|
|||||||
@@ -22,46 +22,52 @@ from pymodmilter.conditions import ConditionsConfig, Conditions
|
|||||||
|
|
||||||
|
|
||||||
class RuleConfig(BaseConfig):
|
class RuleConfig(BaseConfig):
|
||||||
def __init__(self, idx, milter_cfg, cfg, debug=False):
|
def __init__(self, cfg, debug=False):
|
||||||
if "name" in cfg:
|
|
||||||
assert isinstance(cfg["name"], str), \
|
|
||||||
f"Rule #{idx}: name: invalid value, should be string"
|
|
||||||
else:
|
|
||||||
cfg["name"] = f"Rule #{idx}"
|
|
||||||
|
|
||||||
if "loglevel" not in cfg:
|
|
||||||
cfg["loglevel"] = milter_cfg["loglevel"]
|
|
||||||
|
|
||||||
super().__init__(cfg, debug)
|
super().__init__(cfg, debug)
|
||||||
|
|
||||||
self["pretend"] = milter_cfg["pretend"]
|
self.conditions = None
|
||||||
self["conditions"] = None
|
self.actions = []
|
||||||
self["actions"] = []
|
|
||||||
|
|
||||||
|
self.pretend = False
|
||||||
if "pretend" in cfg:
|
if "pretend" in cfg:
|
||||||
pretend = cfg["pretend"]
|
assert isinstance(cfg["pretend"], bool), \
|
||||||
assert isinstance(pretend, bool), \
|
f"{self.name}: pretend: invalid value, should be bool"
|
||||||
f"{self['name']}: pretend: invalid value, should be bool"
|
self.pretend = cfg["pretend"]
|
||||||
self["pretend"] = pretend
|
|
||||||
|
|
||||||
assert "actions" in cfg, \
|
assert "actions" in cfg, \
|
||||||
f"{self['name']}: mandatory parameter 'actions' not found"
|
f"{self.name}: mandatory parameter 'actions' not found"
|
||||||
actions = cfg["actions"]
|
actions = cfg["actions"]
|
||||||
assert isinstance(actions, list), \
|
assert isinstance(actions, list), \
|
||||||
f"{self['name']}: actions: invalid value, should be list"
|
f"{self.name}: actions: invalid value, should be list"
|
||||||
|
|
||||||
self.logger.debug(f"{self['name']}: pretend={self['pretend']}, "
|
self.logger.debug(f"{self.name}: pretend={self.pretend}, "
|
||||||
f"loglevel={self['loglevel']}")
|
f"loglevel={self.loglevel}")
|
||||||
|
|
||||||
if "conditions" in cfg:
|
if "conditions" in cfg:
|
||||||
conditions = cfg["conditions"]
|
assert isinstance(cfg["conditions"], dict), \
|
||||||
assert isinstance(conditions, dict), \
|
f"{self.name}: conditions: invalid value, should be dict"
|
||||||
f"{self['name']}: conditions: invalid value, should be dict"
|
cfg["conditions"]["name"] = f"{self.name}: condition"
|
||||||
self["conditions"] = ConditionsConfig(self, conditions, debug)
|
if "loglevel" not in cfg["conditions"]:
|
||||||
|
cfg["conditions"]["loglevel"] = self.loglevel
|
||||||
|
self.conditions = ConditionsConfig(cfg["conditions"], debug)
|
||||||
|
else:
|
||||||
|
self.conditions = None
|
||||||
|
|
||||||
for idx, action_cfg in enumerate(cfg["actions"]):
|
for idx, action_cfg in enumerate(cfg["actions"]):
|
||||||
self["actions"].append(
|
if "name" in action_cfg:
|
||||||
ActionConfig(idx, self, action_cfg, debug))
|
assert isinstance(action_cfg["name"], str), \
|
||||||
|
f"{self.name}: Action #{idx}: name: invalid value, " \
|
||||||
|
f"should be string"
|
||||||
|
action_cfg["name"] = f"{self.name}: {action_cfg['name']}"
|
||||||
|
else:
|
||||||
|
action_cfg["name"] = f"{self.name}: Action #{idx}"
|
||||||
|
|
||||||
|
if "loglevel" not in action_cfg:
|
||||||
|
action_cfg["loglevel"] = self.loglevel
|
||||||
|
if "pretend" not in action_cfg:
|
||||||
|
action_cfg["pretend"] = self.pretend
|
||||||
|
self.actions.append(
|
||||||
|
ActionConfig(action_cfg, debug))
|
||||||
|
|
||||||
|
|
||||||
class Rule:
|
class Rule:
|
||||||
@@ -69,19 +75,19 @@ class Rule:
|
|||||||
Rule to implement multiple actions on emails.
|
Rule to implement multiple actions on emails.
|
||||||
"""
|
"""
|
||||||
|
|
||||||
def __init__(self, milter_cfg, cfg):
|
def __init__(self, cfg, local_addrs):
|
||||||
self.logger = cfg.logger
|
self.logger = cfg.logger
|
||||||
|
|
||||||
if cfg["conditions"] is None:
|
if cfg.conditions is None:
|
||||||
self.conditions = None
|
self.conditions = None
|
||||||
else:
|
else:
|
||||||
self.conditions = Conditions(milter_cfg, cfg["conditions"])
|
self.conditions = Conditions(cfg.conditions, local_addrs)
|
||||||
|
|
||||||
self.actions = []
|
self.actions = []
|
||||||
for action_cfg in cfg["actions"]:
|
for action_cfg in cfg.actions:
|
||||||
self.actions.append(Action(milter_cfg, action_cfg))
|
self.actions.append(Action(action_cfg, local_addrs))
|
||||||
|
|
||||||
self.pretend = cfg["pretend"]
|
self.pretend = cfg.pretend
|
||||||
|
|
||||||
def execute(self, milter):
|
def execute(self, milter):
|
||||||
"""Execute all actions of this rule."""
|
"""Execute all actions of this rule."""
|
||||||
|
|||||||
@@ -84,24 +84,24 @@ def main():
|
|||||||
cfg = ModifyMilterConfig(args.config, args.debug)
|
cfg = ModifyMilterConfig(args.config, args.debug)
|
||||||
|
|
||||||
if not args.debug:
|
if not args.debug:
|
||||||
logger.setLevel(cfg["loglevel"])
|
logger.setLevel(cfg.loglevel)
|
||||||
|
|
||||||
if args.socket:
|
if args.socket:
|
||||||
socket = args.socket
|
socket = args.socket
|
||||||
elif "socket" in cfg:
|
elif cfg.socket:
|
||||||
socket = cfg["socket"]
|
socket = cfg.socket
|
||||||
else:
|
else:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
"listening socket is neither specified on the command line "
|
"listening socket is neither specified on the command line "
|
||||||
"nor in the configuration file")
|
"nor in the configuration file")
|
||||||
|
|
||||||
if not cfg["rules"]:
|
if not cfg.rules:
|
||||||
raise RuntimeError("no rules configured")
|
raise RuntimeError("no rules configured")
|
||||||
|
|
||||||
for rule_cfg in cfg["rules"]:
|
for rule_cfg in cfg.rules:
|
||||||
if not rule_cfg["actions"]:
|
if not rule_cfg.actions:
|
||||||
raise RuntimeError(
|
raise RuntimeError(
|
||||||
f"{rule_cfg['name']}: no actions configured")
|
f"{rule_cfg.name}: no actions configured")
|
||||||
|
|
||||||
except (RuntimeError, AssertionError) as e:
|
except (RuntimeError, AssertionError) as e:
|
||||||
logger.error(e)
|
logger.error(e)
|
||||||
|
|||||||
@@ -57,6 +57,12 @@ class FileMailStorage(BaseMailStorage):
|
|||||||
def __init__(self, directory, original=False, skip_metadata=False,
|
def __init__(self, directory, original=False, skip_metadata=False,
|
||||||
metavar=None):
|
metavar=None):
|
||||||
super().__init__()
|
super().__init__()
|
||||||
|
# check if directory exists and is writable
|
||||||
|
if not os.path.isdir(directory) or \
|
||||||
|
not os.access(directory, os.W_OK):
|
||||||
|
raise RuntimeError(
|
||||||
|
f"directory '{directory}' does not exist or is "
|
||||||
|
f"not writable")
|
||||||
self.directory = directory
|
self.directory = directory
|
||||||
self.original = original
|
self.original = original
|
||||||
self.skip_metadata = skip_metadata
|
self.skip_metadata = skip_metadata
|
||||||
|
|||||||
Reference in New Issue
Block a user