config.py 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568
  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. ("ldap_uri", {
  169. "value": "ldap://localhost",
  170. "help": "URI to the ldap server",
  171. "type": str}),
  172. ("ldap_base", {
  173. "value": "none",
  174. "help": "LDAP base DN of the ldap server",
  175. "type": str}),
  176. ("ldap_reader_dn", {
  177. "value": "none",
  178. "help": "the DN of a ldap user with read access to get the user accounts",
  179. "type": str}),
  180. ("ldap_secret", {
  181. "value": "none",
  182. "help": "the password of the ldap_reader_dn",
  183. "type": str}),
  184. ("ldap_filter", {
  185. "value": "(cn={0})",
  186. "help": "the search filter to find the user DN to authenticate by the username",
  187. "type": str}),
  188. ("ldap_load_groups", {
  189. "value": "False",
  190. "help": "load the ldap groups of the authenticated user",
  191. "type": bool}),
  192. ("ldap_use_ssl", {
  193. "value": "False",
  194. "help": "Use ssl on the ldap connection",
  195. "type": bool}),
  196. ("ldap_ssl_verify_mode", {
  197. "value": "REQUIRED",
  198. "help": "The certifikat verification mode. NONE, OPTIONAL, default is REQUIRED",
  199. "type": str}),
  200. ("ldap_ssl_ca_file", {
  201. "value": "",
  202. "help": "The path to the CA file in pem format which is used to certificate the server certificate",
  203. "type": str}),
  204. ("strip_domain", {
  205. "value": "False",
  206. "help": "strip domain from username",
  207. "type": bool}),
  208. ("lc_username", {
  209. "value": "False",
  210. "help": "convert username to lowercase, must be true for case-insensitive auth providers",
  211. "type": bool})])),
  212. ("rights", OrderedDict([
  213. ("type", {
  214. "value": "owner_only",
  215. "help": "rights backend",
  216. "type": str_or_callable,
  217. "internal": rights.INTERNAL_TYPES}),
  218. ("permit_delete_collection", {
  219. "value": "True",
  220. "help": "permit delete of a collection",
  221. "type": bool}),
  222. ("permit_overwrite_collection", {
  223. "value": "True",
  224. "help": "permit overwrite of a collection",
  225. "type": bool}),
  226. ("file", {
  227. "value": "/etc/radicale/rights",
  228. "help": "file for rights management from_file",
  229. "type": filepath})])),
  230. ("storage", OrderedDict([
  231. ("type", {
  232. "value": "multifilesystem",
  233. "help": "storage backend",
  234. "type": str_or_callable,
  235. "internal": storage.INTERNAL_TYPES}),
  236. ("filesystem_folder", {
  237. "value": "/var/lib/radicale/collections",
  238. "help": "path where collections are stored",
  239. "type": filepath}),
  240. ("max_sync_token_age", {
  241. "value": "2592000", # 30 days
  242. "help": "delete sync token that are older",
  243. "type": positive_int}),
  244. ("skip_broken_item", {
  245. "value": "True",
  246. "help": "skip broken item instead of triggering exception",
  247. "type": bool}),
  248. ("hook", {
  249. "value": "",
  250. "help": "command that is run after changes to storage",
  251. "type": str}),
  252. ("_filesystem_fsync", {
  253. "value": "True",
  254. "help": "sync all changes to filesystem during requests",
  255. "type": bool}),
  256. ("predefined_collections", {
  257. "value": "",
  258. "help": "predefined user collections",
  259. "type": json_str})])),
  260. ("hook", OrderedDict([
  261. ("type", {
  262. "value": "none",
  263. "help": "hook backend",
  264. "type": str,
  265. "internal": hook.INTERNAL_TYPES}),
  266. ("rabbitmq_endpoint", {
  267. "value": "",
  268. "help": "endpoint where rabbitmq server is running",
  269. "type": str}),
  270. ("rabbitmq_topic", {
  271. "value": "",
  272. "help": "topic to declare queue",
  273. "type": str}),
  274. ("rabbitmq_queue_type", {
  275. "value": "",
  276. "help": "queue type for topic declaration",
  277. "type": str})])),
  278. ("web", OrderedDict([
  279. ("type", {
  280. "value": "internal",
  281. "help": "web interface backend",
  282. "type": str_or_callable,
  283. "internal": web.INTERNAL_TYPES})])),
  284. ("logging", OrderedDict([
  285. ("level", {
  286. "value": "info",
  287. "help": "threshold for the logger",
  288. "type": logging_level}),
  289. ("bad_put_request_content", {
  290. "value": "False",
  291. "help": "log bad PUT request content",
  292. "type": bool}),
  293. ("backtrace_on_debug", {
  294. "value": "False",
  295. "help": "log backtrace on level=debug",
  296. "type": bool}),
  297. ("request_header_on_debug", {
  298. "value": "False",
  299. "help": "log request header on level=debug",
  300. "type": bool}),
  301. ("request_content_on_debug", {
  302. "value": "False",
  303. "help": "log request content on level=debug",
  304. "type": bool}),
  305. ("response_content_on_debug", {
  306. "value": "False",
  307. "help": "log response content on level=debug",
  308. "type": bool}),
  309. ("rights_rule_doesnt_match_on_debug", {
  310. "value": "False",
  311. "help": "log rights rules which doesn't match on level=debug",
  312. "type": bool}),
  313. ("mask_passwords", {
  314. "value": "True",
  315. "help": "mask passwords in logs",
  316. "type": bool})])),
  317. ("headers", OrderedDict([
  318. ("_allow_extra", str)])),
  319. ("reporting", OrderedDict([
  320. ("max_freebusy_occurrence", {
  321. "value": "10000",
  322. "help": "number of occurrences per event when reporting",
  323. "type": positive_int})]))
  324. ])
  325. def parse_compound_paths(*compound_paths: Optional[str]
  326. ) -> List[Tuple[str, bool]]:
  327. """Parse a compound path and return the individual paths.
  328. Paths in a compound path are joined by ``os.pathsep``. If a path starts
  329. with ``?`` the return value ``IGNORE_IF_MISSING`` is set.
  330. When multiple ``compound_paths`` are passed, the last argument that is
  331. not ``None`` is used.
  332. Returns a dict of the format ``[(PATH, IGNORE_IF_MISSING), ...]``
  333. """
  334. compound_path = ""
  335. for p in compound_paths:
  336. if p is not None:
  337. compound_path = p
  338. paths = []
  339. for path in compound_path.split(os.pathsep):
  340. ignore_if_missing = path.startswith("?")
  341. if ignore_if_missing:
  342. path = path[1:]
  343. path = filepath(path)
  344. if path:
  345. paths.append((path, ignore_if_missing))
  346. return paths
  347. def load(paths: Optional[Iterable[Tuple[str, bool]]] = None
  348. ) -> "Configuration":
  349. """
  350. Create instance of ``Configuration`` for use with
  351. ``radicale.app.Application``.
  352. ``paths`` a list of configuration files with the format
  353. ``[(PATH, IGNORE_IF_MISSING), ...]``.
  354. If a configuration file is missing and IGNORE_IF_MISSING is set, the
  355. config is set to ``Configuration.SOURCE_MISSING``.
  356. The configuration can later be changed with ``Configuration.update()``.
  357. """
  358. if paths is None:
  359. paths = []
  360. configuration = Configuration(DEFAULT_CONFIG_SCHEMA)
  361. for path, ignore_if_missing in paths:
  362. parser = RawConfigParser()
  363. config_source = "config file %r" % path
  364. config: types.CONFIG
  365. try:
  366. with open(path) as f:
  367. parser.read_file(f)
  368. config = {s: {o: parser[s][o] for o in parser.options(s)}
  369. for s in parser.sections()}
  370. except Exception as e:
  371. if not (ignore_if_missing and isinstance(e, (
  372. FileNotFoundError, NotADirectoryError, PermissionError))):
  373. raise RuntimeError("Failed to load %s: %s" % (config_source, e)
  374. ) from e
  375. config = Configuration.SOURCE_MISSING
  376. configuration.update(config, config_source)
  377. return configuration
  378. _Self = TypeVar("_Self", bound="Configuration")
  379. class Configuration:
  380. SOURCE_MISSING: ClassVar[types.CONFIG] = {}
  381. _schema: types.CONFIG_SCHEMA
  382. _values: types.MUTABLE_CONFIG
  383. _configs: List[Tuple[types.CONFIG, str, bool]]
  384. def __init__(self, schema: types.CONFIG_SCHEMA) -> None:
  385. """Initialize configuration.
  386. ``schema`` a dict that describes the configuration format.
  387. See ``DEFAULT_CONFIG_SCHEMA``.
  388. The content of ``schema`` must not change afterwards, it is kept
  389. as an internal reference.
  390. Use ``load()`` to create an instance for use with
  391. ``radicale.app.Application``.
  392. """
  393. self._schema = schema
  394. self._values = {}
  395. self._configs = []
  396. default = {section: {option: self._schema[section][option]["value"]
  397. for option in self._schema[section]
  398. if option not in INTERNAL_OPTIONS}
  399. for section in self._schema}
  400. self.update(default, "default config", privileged=True)
  401. def update(self, config: types.CONFIG, source: Optional[str] = None,
  402. privileged: bool = False) -> None:
  403. """Update the configuration.
  404. ``config`` a dict of the format {SECTION: {OPTION: VALUE, ...}, ...}.
  405. The configuration is checked for errors according to the config schema.
  406. The content of ``config`` must not change afterwards, it is kept
  407. as an internal reference.
  408. ``source`` a description of the configuration source (used in error
  409. messages).
  410. ``privileged`` allows updating sections and options starting with "_".
  411. """
  412. if source is None:
  413. source = "unspecified config"
  414. new_values: types.MUTABLE_CONFIG = {}
  415. for section in config:
  416. if (section not in self._schema or
  417. section.startswith("_") and not privileged):
  418. raise ValueError(
  419. "Invalid section %r in %s" % (section, source))
  420. new_values[section] = {}
  421. extra_type = None
  422. extra_type = self._schema[section].get("_allow_extra")
  423. if "type" in self._schema[section]:
  424. if "type" in config[section]:
  425. plugin = config[section]["type"]
  426. else:
  427. plugin = self.get(section, "type")
  428. if plugin not in self._schema[section]["type"]["internal"]:
  429. extra_type = unspecified_type
  430. for option in config[section]:
  431. type_ = extra_type
  432. if option in self._schema[section]:
  433. type_ = self._schema[section][option]["type"]
  434. if (not type_ or option in INTERNAL_OPTIONS or
  435. option.startswith("_") and not privileged):
  436. raise RuntimeError("Invalid option %r in section %r in "
  437. "%s" % (option, section, source))
  438. raw_value = config[section][option]
  439. try:
  440. if type_ == bool and not isinstance(raw_value, bool):
  441. raw_value = _convert_to_bool(raw_value)
  442. new_values[section][option] = type_(raw_value)
  443. except Exception as e:
  444. raise RuntimeError(
  445. "Invalid %s value for option %r in section %r in %s: "
  446. "%r" % (type_.__name__, option, section, source,
  447. raw_value)) from e
  448. self._configs.append((config, source, bool(privileged)))
  449. for section in new_values:
  450. self._values[section] = self._values.get(section, {})
  451. self._values[section].update(new_values[section])
  452. def get(self, section: str, option: str) -> Any:
  453. """Get the value of ``option`` in ``section``."""
  454. with contextlib.suppress(KeyError):
  455. return self._values[section][option]
  456. raise KeyError(section, option)
  457. def get_raw(self, section: str, option: str) -> Any:
  458. """Get the raw value of ``option`` in ``section``."""
  459. for config, _, _ in reversed(self._configs):
  460. if option in config.get(section, {}):
  461. return config[section][option]
  462. raise KeyError(section, option)
  463. def get_source(self, section: str, option: str) -> str:
  464. """Get the source that provides ``option`` in ``section``."""
  465. for config, source, _ in reversed(self._configs):
  466. if option in config.get(section, {}):
  467. return source
  468. raise KeyError(section, option)
  469. def sections(self) -> List[str]:
  470. """List all sections."""
  471. return list(self._values.keys())
  472. def options(self, section: str) -> List[str]:
  473. """List all options in ``section``"""
  474. return list(self._values[section].keys())
  475. def sources(self) -> List[Tuple[str, bool]]:
  476. """List all config sources."""
  477. return [(source, config is self.SOURCE_MISSING) for
  478. config, source, _ in self._configs]
  479. def copy(self: _Self, plugin_schema: Optional[types.CONFIG_SCHEMA] = None
  480. ) -> _Self:
  481. """Create a copy of the configuration
  482. ``plugin_schema`` is a optional dict that contains additional options
  483. for usage with a plugin. See ``DEFAULT_CONFIG_SCHEMA``.
  484. """
  485. if plugin_schema is None:
  486. schema = self._schema
  487. else:
  488. new_schema = dict(self._schema)
  489. for section, options in plugin_schema.items():
  490. if (section not in new_schema or
  491. "type" not in new_schema[section] or
  492. "internal" not in new_schema[section]["type"]):
  493. raise ValueError("not a plugin section: %r" % section)
  494. new_section = dict(new_schema[section])
  495. new_type = dict(new_section["type"])
  496. new_type["internal"] = (self.get(section, "type"),)
  497. new_section["type"] = new_type
  498. for option, value in options.items():
  499. if option in new_section:
  500. raise ValueError("option already exists in %r: %r" %
  501. (section, option))
  502. new_section[option] = value
  503. new_schema[section] = new_section
  504. schema = new_schema
  505. copy = type(self)(schema)
  506. for config, source, privileged in self._configs:
  507. copy.update(config, source, privileged)
  508. return copy