config.py 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. ("rights", OrderedDict([
  158. ("type", {
  159. "value": "owner_only",
  160. "help": "rights backend",
  161. "type": str_or_callable,
  162. "internal": rights.INTERNAL_TYPES}),
  163. ("file", {
  164. "value": "/etc/radicale/rights",
  165. "help": "file for rights management from_file",
  166. "type": filepath})])),
  167. ("storage", OrderedDict([
  168. ("type", {
  169. "value": "multifilesystem",
  170. "help": "storage backend",
  171. "type": str_or_callable,
  172. "internal": storage.INTERNAL_TYPES}),
  173. ("filesystem_folder", {
  174. "value": "/var/lib/radicale/collections",
  175. "help": "path where collections are stored",
  176. "type": filepath}),
  177. ("max_sync_token_age", {
  178. "value": "2592000", # 30 days
  179. "help": "delete sync token that are older",
  180. "type": positive_int}),
  181. ("hook", {
  182. "value": "",
  183. "help": "command that is run after changes to storage",
  184. "type": str}),
  185. ("_filesystem_fsync", {
  186. "value": "True",
  187. "help": "sync all changes to filesystem during requests",
  188. "type": bool})])),
  189. ("web", OrderedDict([
  190. ("type", {
  191. "value": "internal",
  192. "help": "web interface backend",
  193. "type": str_or_callable,
  194. "internal": web.INTERNAL_TYPES})])),
  195. ("logging", OrderedDict([
  196. ("level", {
  197. "value": "warning",
  198. "help": "threshold for the logger",
  199. "type": logging_level}),
  200. ("mask_passwords", {
  201. "value": "True",
  202. "help": "mask passwords in logs",
  203. "type": bool})])),
  204. ("headers", OrderedDict([
  205. ("_allow_extra", str)]))])
  206. def parse_compound_paths(*compound_paths: Optional[str]
  207. ) -> List[Tuple[str, bool]]:
  208. """Parse a compound path and return the individual paths.
  209. Paths in a compound path are joined by ``os.pathsep``. If a path starts
  210. with ``?`` the return value ``IGNORE_IF_MISSING`` is set.
  211. When multiple ``compound_paths`` are passed, the last argument that is
  212. not ``None`` is used.
  213. Returns a dict of the format ``[(PATH, IGNORE_IF_MISSING), ...]``
  214. """
  215. compound_path = ""
  216. for p in compound_paths:
  217. if p is not None:
  218. compound_path = p
  219. paths = []
  220. for path in compound_path.split(os.pathsep):
  221. ignore_if_missing = path.startswith("?")
  222. if ignore_if_missing:
  223. path = path[1:]
  224. path = filepath(path)
  225. if path:
  226. paths.append((path, ignore_if_missing))
  227. return paths
  228. def load(paths: Optional[Iterable[Tuple[str, bool]]] = None
  229. ) -> "Configuration":
  230. """
  231. Create instance of ``Configuration`` for use with
  232. ``radicale.app.Application``.
  233. ``paths`` a list of configuration files with the format
  234. ``[(PATH, IGNORE_IF_MISSING), ...]``.
  235. If a configuration file is missing and IGNORE_IF_MISSING is set, the
  236. config is set to ``Configuration.SOURCE_MISSING``.
  237. The configuration can later be changed with ``Configuration.update()``.
  238. """
  239. if paths is None:
  240. paths = []
  241. configuration = Configuration(DEFAULT_CONFIG_SCHEMA)
  242. for path, ignore_if_missing in paths:
  243. parser = RawConfigParser()
  244. config_source = "config file %r" % path
  245. config: types.CONFIG
  246. try:
  247. with open(path, "r") as f:
  248. parser.read_file(f)
  249. config = {s: {o: parser[s][o] for o in parser.options(s)}
  250. for s in parser.sections()}
  251. except Exception as e:
  252. if not (ignore_if_missing and isinstance(e, (
  253. FileNotFoundError, NotADirectoryError, PermissionError))):
  254. raise RuntimeError("Failed to load %s: %s" % (config_source, e)
  255. ) from e
  256. config = Configuration.SOURCE_MISSING
  257. configuration.update(config, config_source)
  258. return configuration
  259. _Self = TypeVar("_Self", bound="Configuration")
  260. class Configuration:
  261. SOURCE_MISSING: ClassVar[types.CONFIG] = {}
  262. _schema: types.CONFIG_SCHEMA
  263. _values: types.MUTABLE_CONFIG
  264. _configs: List[Tuple[types.CONFIG, str, bool]]
  265. def __init__(self, schema: types.CONFIG_SCHEMA) -> None:
  266. """Initialize configuration.
  267. ``schema`` a dict that describes the configuration format.
  268. See ``DEFAULT_CONFIG_SCHEMA``.
  269. The content of ``schema`` must not change afterwards, it is kept
  270. as an internal reference.
  271. Use ``load()`` to create an instance for use with
  272. ``radicale.app.Application``.
  273. """
  274. self._schema = schema
  275. self._values = {}
  276. self._configs = []
  277. default = {section: {option: self._schema[section][option]["value"]
  278. for option in self._schema[section]
  279. if option not in INTERNAL_OPTIONS}
  280. for section in self._schema}
  281. self.update(default, "default config", privileged=True)
  282. def update(self, config: types.CONFIG, source: Optional[str] = None,
  283. privileged: bool = False) -> None:
  284. """Update the configuration.
  285. ``config`` a dict of the format {SECTION: {OPTION: VALUE, ...}, ...}.
  286. The configuration is checked for errors according to the config schema.
  287. The content of ``config`` must not change afterwards, it is kept
  288. as an internal reference.
  289. ``source`` a description of the configuration source (used in error
  290. messages).
  291. ``privileged`` allows updating sections and options starting with "_".
  292. """
  293. if source is None:
  294. source = "unspecified config"
  295. new_values: types.MUTABLE_CONFIG = {}
  296. for section in config:
  297. if (section not in self._schema or
  298. section.startswith("_") and not privileged):
  299. raise ValueError(
  300. "Invalid section %r in %s" % (section, source))
  301. new_values[section] = {}
  302. extra_type = None
  303. extra_type = self._schema[section].get("_allow_extra")
  304. if "type" in self._schema[section]:
  305. if "type" in config[section]:
  306. plugin = config[section]["type"]
  307. else:
  308. plugin = self.get(section, "type")
  309. if plugin not in self._schema[section]["type"]["internal"]:
  310. extra_type = unspecified_type
  311. for option in config[section]:
  312. type_ = extra_type
  313. if option in self._schema[section]:
  314. type_ = self._schema[section][option]["type"]
  315. if (not type_ or option in INTERNAL_OPTIONS or
  316. option.startswith("_") and not privileged):
  317. raise RuntimeError("Invalid option %r in section %r in "
  318. "%s" % (option, section, source))
  319. raw_value = config[section][option]
  320. try:
  321. if type_ == bool and not isinstance(raw_value, bool):
  322. raw_value = _convert_to_bool(raw_value)
  323. new_values[section][option] = type_(raw_value)
  324. except Exception as e:
  325. raise RuntimeError(
  326. "Invalid %s value for option %r in section %r in %s: "
  327. "%r" % (type_.__name__, option, section, source,
  328. raw_value)) from e
  329. self._configs.append((config, source, bool(privileged)))
  330. for section in new_values:
  331. self._values[section] = self._values.get(section, {})
  332. self._values[section].update(new_values[section])
  333. def get(self, section: str, option: str) -> Any:
  334. """Get the value of ``option`` in ``section``."""
  335. with contextlib.suppress(KeyError):
  336. return self._values[section][option]
  337. raise KeyError(section, option)
  338. def get_raw(self, section: str, option: str) -> Any:
  339. """Get the raw value of ``option`` in ``section``."""
  340. for config, _, _ in reversed(self._configs):
  341. if option in config.get(section, {}):
  342. return config[section][option]
  343. raise KeyError(section, option)
  344. def get_source(self, section: str, option: str) -> str:
  345. """Get the source that provides ``option`` in ``section``."""
  346. for config, source, _ in reversed(self._configs):
  347. if option in config.get(section, {}):
  348. return source
  349. raise KeyError(section, option)
  350. def sections(self) -> List[str]:
  351. """List all sections."""
  352. return list(self._values.keys())
  353. def options(self, section: str) -> List[str]:
  354. """List all options in ``section``"""
  355. return list(self._values[section].keys())
  356. def sources(self) -> List[Tuple[str, bool]]:
  357. """List all config sources."""
  358. return [(source, config is self.SOURCE_MISSING) for
  359. config, source, _ in self._configs]
  360. def copy(self: _Self, plugin_schema: Optional[types.CONFIG_SCHEMA] = None
  361. ) -> _Self:
  362. """Create a copy of the configuration
  363. ``plugin_schema`` is a optional dict that contains additional options
  364. for usage with a plugin. See ``DEFAULT_CONFIG_SCHEMA``.
  365. """
  366. if plugin_schema is None:
  367. schema = self._schema
  368. else:
  369. new_schema = dict(self._schema)
  370. for section, options in plugin_schema.items():
  371. if (section not in new_schema or
  372. "type" not in new_schema[section] or
  373. "internal" not in new_schema[section]["type"]):
  374. raise ValueError("not a plugin section: %r" % section)
  375. new_section = dict(new_schema[section])
  376. new_type = dict(new_section["type"])
  377. new_type["internal"] = (self.get(section, "type"),)
  378. new_section["type"] = new_type
  379. for option, value in options.items():
  380. if option in new_section:
  381. raise ValueError("option already exists in %r: %r" %
  382. (section, option))
  383. new_section[option] = value
  384. new_schema[section] = new_section
  385. schema = new_schema
  386. copy = type(self)(schema)
  387. for config, source, privileged in self._configs:
  388. copy.update(config, source, privileged)
  389. return copy