config.py 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008-2017 Guillaume Ayoub
  3. # Copyright © 2008 Nicolas Kandel
  4. # Copyright © 2008 Pascal Halter
  5. # Copyright © 2017-2020 Unrud <unrud@outlook.com>
  6. # Copyright © 2024-2024 Peter Bieringer <pb@bieringer.de>
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Configuration module
  22. Use ``load()`` to obtain an instance of ``Configuration`` for use with
  23. ``radicale.app.Application``.
  24. """
  25. import contextlib
  26. import json
  27. import math
  28. import os
  29. import string
  30. import sys
  31. from collections import OrderedDict
  32. from configparser import RawConfigParser
  33. from typing import (Any, Callable, ClassVar, Iterable, List, Optional,
  34. Sequence, Tuple, TypeVar, Union)
  35. from radicale import auth, hook, rights, storage, types, web
  36. from radicale.item import check_and_sanitize_props
  37. DEFAULT_CONFIG_PATH: str = os.pathsep.join([
  38. "?/etc/radicale/config",
  39. "?~/.config/radicale/config"])
  40. def positive_int(value: Any) -> int:
  41. value = int(value)
  42. if value < 0:
  43. raise ValueError("value is negative: %d" % value)
  44. return value
  45. def positive_float(value: Any) -> float:
  46. value = float(value)
  47. if not math.isfinite(value):
  48. raise ValueError("value is infinite")
  49. if math.isnan(value):
  50. raise ValueError("value is not a number")
  51. if value < 0:
  52. raise ValueError("value is negative: %f" % value)
  53. return value
  54. def logging_level(value: Any) -> str:
  55. if value not in ("debug", "info", "warning", "error", "critical"):
  56. raise ValueError("unsupported level: %r" % value)
  57. return value
  58. def filepath(value: Any) -> str:
  59. if not value:
  60. return ""
  61. value = os.path.expanduser(value)
  62. if sys.platform == "win32":
  63. value = os.path.expandvars(value)
  64. return os.path.abspath(value)
  65. def list_of_ip_address(value: Any) -> List[Tuple[str, int]]:
  66. def ip_address(value):
  67. try:
  68. address, port = value.rsplit(":", 1)
  69. return address.strip(string.whitespace + "[]"), int(port)
  70. except ValueError:
  71. raise ValueError("malformed IP address: %r" % value)
  72. return [ip_address(s) for s in value.split(",")]
  73. def str_or_callable(value: Any) -> Union[str, Callable]:
  74. if callable(value):
  75. return value
  76. return str(value)
  77. def unspecified_type(value: Any) -> Any:
  78. return value
  79. def _convert_to_bool(value: Any) -> bool:
  80. if value.lower() not in RawConfigParser.BOOLEAN_STATES:
  81. raise ValueError("not a boolean: %r" % value)
  82. return RawConfigParser.BOOLEAN_STATES[value.lower()]
  83. def json_str(value: Any) -> dict:
  84. if not value:
  85. return {}
  86. ret = json.loads(value)
  87. for (name_coll, props) in ret.items():
  88. checked_props = check_and_sanitize_props(props)
  89. ret[name_coll] = checked_props
  90. return ret
  91. INTERNAL_OPTIONS: Sequence[str] = ("_allow_extra",)
  92. # Default configuration
  93. DEFAULT_CONFIG_SCHEMA: types.CONFIG_SCHEMA = OrderedDict([
  94. ("server", OrderedDict([
  95. ("hosts", {
  96. "value": "localhost:5232",
  97. "help": "set server hostnames including ports",
  98. "aliases": ("-H", "--hosts",),
  99. "type": list_of_ip_address}),
  100. ("max_connections", {
  101. "value": "8",
  102. "help": "maximum number of parallel connections",
  103. "type": positive_int}),
  104. ("max_content_length", {
  105. "value": "100000000",
  106. "help": "maximum size of request body in bytes",
  107. "type": positive_int}),
  108. ("timeout", {
  109. "value": "30",
  110. "help": "socket timeout",
  111. "type": positive_float}),
  112. ("ssl", {
  113. "value": "False",
  114. "help": "use SSL connection",
  115. "aliases": ("-s", "--ssl",),
  116. "opposite_aliases": ("-S", "--no-ssl",),
  117. "type": bool}),
  118. ("certificate", {
  119. "value": "/etc/ssl/radicale.cert.pem",
  120. "help": "set certificate file",
  121. "aliases": ("-c", "--certificate",),
  122. "type": filepath}),
  123. ("key", {
  124. "value": "/etc/ssl/radicale.key.pem",
  125. "help": "set private key file",
  126. "aliases": ("-k", "--key",),
  127. "type": filepath}),
  128. ("certificate_authority", {
  129. "value": "",
  130. "help": "set CA certificate for validating clients",
  131. "aliases": ("--certificate-authority",),
  132. "type": filepath}),
  133. ("_internal_server", {
  134. "value": "False",
  135. "help": "the internal server is used",
  136. "type": bool})])),
  137. ("encoding", OrderedDict([
  138. ("request", {
  139. "value": "utf-8",
  140. "help": "encoding for responding requests",
  141. "type": str}),
  142. ("stock", {
  143. "value": "utf-8",
  144. "help": "encoding for storing local collections",
  145. "type": str})])),
  146. ("auth", OrderedDict([
  147. ("type", {
  148. "value": "none",
  149. "help": "authentication method",
  150. "type": str_or_callable,
  151. "internal": auth.INTERNAL_TYPES}),
  152. ("htpasswd_filename", {
  153. "value": "/etc/radicale/users",
  154. "help": "htpasswd filename",
  155. "type": filepath}),
  156. ("htpasswd_encryption", {
  157. "value": "autodetect",
  158. "help": "htpasswd encryption method",
  159. "type": str}),
  160. ("realm", {
  161. "value": "Radicale - Password Required",
  162. "help": "message displayed when a password is needed",
  163. "type": str}),
  164. ("delay", {
  165. "value": "1",
  166. "help": "incorrect authentication delay",
  167. "type": positive_float}),
  168. ("strip_domain", {
  169. "value": "False",
  170. "help": "strip domain from username",
  171. "type": bool}),
  172. ("lc_username", {
  173. "value": "False",
  174. "help": "convert username to lowercase, must be true for case-insensitive auth providers",
  175. "type": bool})])),
  176. ("rights", OrderedDict([
  177. ("type", {
  178. "value": "owner_only",
  179. "help": "rights backend",
  180. "type": str_or_callable,
  181. "internal": rights.INTERNAL_TYPES}),
  182. ("permit_delete_collection", {
  183. "value": "True",
  184. "help": "permit delete of a collection",
  185. "type": bool}),
  186. ("file", {
  187. "value": "/etc/radicale/rights",
  188. "help": "file for rights management from_file",
  189. "type": filepath})])),
  190. ("storage", OrderedDict([
  191. ("type", {
  192. "value": "multifilesystem",
  193. "help": "storage backend",
  194. "type": str_or_callable,
  195. "internal": storage.INTERNAL_TYPES}),
  196. ("filesystem_folder", {
  197. "value": "/var/lib/radicale/collections",
  198. "help": "path where collections are stored",
  199. "type": filepath}),
  200. ("max_sync_token_age", {
  201. "value": "2592000", # 30 days
  202. "help": "delete sync token that are older",
  203. "type": positive_int}),
  204. ("skip_broken_item", {
  205. "value": "True",
  206. "help": "skip broken item instead of triggering exception",
  207. "type": bool}),
  208. ("hook", {
  209. "value": "",
  210. "help": "command that is run after changes to storage",
  211. "type": str}),
  212. ("_filesystem_fsync", {
  213. "value": "True",
  214. "help": "sync all changes to filesystem during requests",
  215. "type": bool}),
  216. ("predefined_collections", {
  217. "value": "",
  218. "help": "predefined user collections",
  219. "type": json_str})])),
  220. ("hook", OrderedDict([
  221. ("type", {
  222. "value": "none",
  223. "help": "hook backend",
  224. "type": str,
  225. "internal": hook.INTERNAL_TYPES}),
  226. ("rabbitmq_endpoint", {
  227. "value": "",
  228. "help": "endpoint where rabbitmq server is running",
  229. "type": str}),
  230. ("rabbitmq_topic", {
  231. "value": "",
  232. "help": "topic to declare queue",
  233. "type": str}),
  234. ("rabbitmq_queue_type", {
  235. "value": "",
  236. "help": "queue type for topic declaration",
  237. "type": str})])),
  238. ("web", OrderedDict([
  239. ("type", {
  240. "value": "internal",
  241. "help": "web interface backend",
  242. "type": str_or_callable,
  243. "internal": web.INTERNAL_TYPES})])),
  244. ("logging", OrderedDict([
  245. ("level", {
  246. "value": "info",
  247. "help": "threshold for the logger",
  248. "type": logging_level}),
  249. ("bad_put_request_content", {
  250. "value": "False",
  251. "help": "log bad PUT request content",
  252. "type": bool}),
  253. ("backtrace_on_debug", {
  254. "value": "False",
  255. "help": "log backtrace on level=debug",
  256. "type": bool}),
  257. ("request_header_on_debug", {
  258. "value": "False",
  259. "help": "log request header on level=debug",
  260. "type": bool}),
  261. ("request_content_on_debug", {
  262. "value": "False",
  263. "help": "log request content on level=debug",
  264. "type": bool}),
  265. ("response_content_on_debug", {
  266. "value": "False",
  267. "help": "log response content on level=debug",
  268. "type": bool}),
  269. ("rights_rule_doesnt_match_on_debug", {
  270. "value": "False",
  271. "help": "log rights rules which doesn't match on level=debug",
  272. "type": bool}),
  273. ("mask_passwords", {
  274. "value": "True",
  275. "help": "mask passwords in logs",
  276. "type": bool})])),
  277. ("headers", OrderedDict([
  278. ("_allow_extra", str)])),
  279. ("reporting", OrderedDict([
  280. ("max_freebusy_occurrence", {
  281. "value": "10000",
  282. "help": "number of occurrences per event when reporting",
  283. "type": positive_int})]))
  284. ])
  285. def parse_compound_paths(*compound_paths: Optional[str]
  286. ) -> List[Tuple[str, bool]]:
  287. """Parse a compound path and return the individual paths.
  288. Paths in a compound path are joined by ``os.pathsep``. If a path starts
  289. with ``?`` the return value ``IGNORE_IF_MISSING`` is set.
  290. When multiple ``compound_paths`` are passed, the last argument that is
  291. not ``None`` is used.
  292. Returns a dict of the format ``[(PATH, IGNORE_IF_MISSING), ...]``
  293. """
  294. compound_path = ""
  295. for p in compound_paths:
  296. if p is not None:
  297. compound_path = p
  298. paths = []
  299. for path in compound_path.split(os.pathsep):
  300. ignore_if_missing = path.startswith("?")
  301. if ignore_if_missing:
  302. path = path[1:]
  303. path = filepath(path)
  304. if path:
  305. paths.append((path, ignore_if_missing))
  306. return paths
  307. def load(paths: Optional[Iterable[Tuple[str, bool]]] = None
  308. ) -> "Configuration":
  309. """
  310. Create instance of ``Configuration`` for use with
  311. ``radicale.app.Application``.
  312. ``paths`` a list of configuration files with the format
  313. ``[(PATH, IGNORE_IF_MISSING), ...]``.
  314. If a configuration file is missing and IGNORE_IF_MISSING is set, the
  315. config is set to ``Configuration.SOURCE_MISSING``.
  316. The configuration can later be changed with ``Configuration.update()``.
  317. """
  318. if paths is None:
  319. paths = []
  320. configuration = Configuration(DEFAULT_CONFIG_SCHEMA)
  321. for path, ignore_if_missing in paths:
  322. parser = RawConfigParser()
  323. config_source = "config file %r" % path
  324. config: types.CONFIG
  325. try:
  326. with open(path, "r") as f:
  327. parser.read_file(f)
  328. config = {s: {o: parser[s][o] for o in parser.options(s)}
  329. for s in parser.sections()}
  330. except Exception as e:
  331. if not (ignore_if_missing and isinstance(e, (
  332. FileNotFoundError, NotADirectoryError, PermissionError))):
  333. raise RuntimeError("Failed to load %s: %s" % (config_source, e)
  334. ) from e
  335. config = Configuration.SOURCE_MISSING
  336. configuration.update(config, config_source)
  337. return configuration
  338. _Self = TypeVar("_Self", bound="Configuration")
  339. class Configuration:
  340. SOURCE_MISSING: ClassVar[types.CONFIG] = {}
  341. _schema: types.CONFIG_SCHEMA
  342. _values: types.MUTABLE_CONFIG
  343. _configs: List[Tuple[types.CONFIG, str, bool]]
  344. def __init__(self, schema: types.CONFIG_SCHEMA) -> None:
  345. """Initialize configuration.
  346. ``schema`` a dict that describes the configuration format.
  347. See ``DEFAULT_CONFIG_SCHEMA``.
  348. The content of ``schema`` must not change afterwards, it is kept
  349. as an internal reference.
  350. Use ``load()`` to create an instance for use with
  351. ``radicale.app.Application``.
  352. """
  353. self._schema = schema
  354. self._values = {}
  355. self._configs = []
  356. default = {section: {option: self._schema[section][option]["value"]
  357. for option in self._schema[section]
  358. if option not in INTERNAL_OPTIONS}
  359. for section in self._schema}
  360. self.update(default, "default config", privileged=True)
  361. def update(self, config: types.CONFIG, source: Optional[str] = None,
  362. privileged: bool = False) -> None:
  363. """Update the configuration.
  364. ``config`` a dict of the format {SECTION: {OPTION: VALUE, ...}, ...}.
  365. The configuration is checked for errors according to the config schema.
  366. The content of ``config`` must not change afterwards, it is kept
  367. as an internal reference.
  368. ``source`` a description of the configuration source (used in error
  369. messages).
  370. ``privileged`` allows updating sections and options starting with "_".
  371. """
  372. if source is None:
  373. source = "unspecified config"
  374. new_values: types.MUTABLE_CONFIG = {}
  375. for section in config:
  376. if (section not in self._schema or
  377. section.startswith("_") and not privileged):
  378. raise ValueError(
  379. "Invalid section %r in %s" % (section, source))
  380. new_values[section] = {}
  381. extra_type = None
  382. extra_type = self._schema[section].get("_allow_extra")
  383. if "type" in self._schema[section]:
  384. if "type" in config[section]:
  385. plugin = config[section]["type"]
  386. else:
  387. plugin = self.get(section, "type")
  388. if plugin not in self._schema[section]["type"]["internal"]:
  389. extra_type = unspecified_type
  390. for option in config[section]:
  391. type_ = extra_type
  392. if option in self._schema[section]:
  393. type_ = self._schema[section][option]["type"]
  394. if (not type_ or option in INTERNAL_OPTIONS or
  395. option.startswith("_") and not privileged):
  396. raise RuntimeError("Invalid option %r in section %r in "
  397. "%s" % (option, section, source))
  398. raw_value = config[section][option]
  399. try:
  400. if type_ == bool and not isinstance(raw_value, bool):
  401. raw_value = _convert_to_bool(raw_value)
  402. new_values[section][option] = type_(raw_value)
  403. except Exception as e:
  404. raise RuntimeError(
  405. "Invalid %s value for option %r in section %r in %s: "
  406. "%r" % (type_.__name__, option, section, source,
  407. raw_value)) from e
  408. self._configs.append((config, source, bool(privileged)))
  409. for section in new_values:
  410. self._values[section] = self._values.get(section, {})
  411. self._values[section].update(new_values[section])
  412. def get(self, section: str, option: str) -> Any:
  413. """Get the value of ``option`` in ``section``."""
  414. with contextlib.suppress(KeyError):
  415. return self._values[section][option]
  416. raise KeyError(section, option)
  417. def get_raw(self, section: str, option: str) -> Any:
  418. """Get the raw value of ``option`` in ``section``."""
  419. for config, _, _ in reversed(self._configs):
  420. if option in config.get(section, {}):
  421. return config[section][option]
  422. raise KeyError(section, option)
  423. def get_source(self, section: str, option: str) -> str:
  424. """Get the source that provides ``option`` in ``section``."""
  425. for config, source, _ in reversed(self._configs):
  426. if option in config.get(section, {}):
  427. return source
  428. raise KeyError(section, option)
  429. def sections(self) -> List[str]:
  430. """List all sections."""
  431. return list(self._values.keys())
  432. def options(self, section: str) -> List[str]:
  433. """List all options in ``section``"""
  434. return list(self._values[section].keys())
  435. def sources(self) -> List[Tuple[str, bool]]:
  436. """List all config sources."""
  437. return [(source, config is self.SOURCE_MISSING) for
  438. config, source, _ in self._configs]
  439. def copy(self: _Self, plugin_schema: Optional[types.CONFIG_SCHEMA] = None
  440. ) -> _Self:
  441. """Create a copy of the configuration
  442. ``plugin_schema`` is a optional dict that contains additional options
  443. for usage with a plugin. See ``DEFAULT_CONFIG_SCHEMA``.
  444. """
  445. if plugin_schema is None:
  446. schema = self._schema
  447. else:
  448. new_schema = dict(self._schema)
  449. for section, options in plugin_schema.items():
  450. if (section not in new_schema or
  451. "type" not in new_schema[section] or
  452. "internal" not in new_schema[section]["type"]):
  453. raise ValueError("not a plugin section: %r" % section)
  454. new_section = dict(new_schema[section])
  455. new_type = dict(new_section["type"])
  456. new_type["internal"] = (self.get(section, "type"),)
  457. new_section["type"] = new_type
  458. for option, value in options.items():
  459. if option in new_section:
  460. raise ValueError("option already exists in %r: %r" %
  461. (section, option))
  462. new_section[option] = value
  463. new_schema[section] = new_section
  464. schema = new_schema
  465. copy = type(self)(schema)
  466. for config, source, privileged in self._configs:
  467. copy.update(config, source, privileged)
  468. return copy