config.py 17 KB

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