config.py 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424
  1. # This file is part of Radicale Server - Calendar 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. from collections import OrderedDict
  28. from configparser import RawConfigParser
  29. from radicale import auth, rights, storage, web
  30. DEFAULT_CONFIG_PATH = os.pathsep.join([
  31. "?/etc/radicale/config",
  32. "?~/.config/radicale/config"])
  33. def positive_int(value):
  34. value = int(value)
  35. if value < 0:
  36. raise ValueError("value is negative: %d" % value)
  37. return value
  38. def positive_float(value):
  39. value = float(value)
  40. if not math.isfinite(value):
  41. raise ValueError("value is infinite")
  42. if math.isnan(value):
  43. raise ValueError("value is not a number")
  44. if value < 0:
  45. raise ValueError("value is negative: %f" % value)
  46. return value
  47. def logging_level(value):
  48. if value not in ("debug", "info", "warning", "error", "critical"):
  49. raise ValueError("unsupported level: %r" % value)
  50. return value
  51. def filepath(value):
  52. if not value:
  53. return ""
  54. value = os.path.expanduser(value)
  55. if os.name == "nt":
  56. value = os.path.expandvars(value)
  57. return os.path.abspath(value)
  58. def list_of_ip_address(value):
  59. def ip_address(value):
  60. try:
  61. address, port = value.strip().rsplit(":", 1)
  62. return address.strip("[] "), int(port)
  63. except ValueError:
  64. raise ValueError("malformed IP address: %r" % value)
  65. return [ip_address(s.strip()) for s in value.split(",")]
  66. def str_or_callable(value):
  67. if callable(value):
  68. return value
  69. return str(value)
  70. def unspecified_type(value):
  71. return value
  72. def _convert_to_bool(value):
  73. if value.lower() not in RawConfigParser.BOOLEAN_STATES:
  74. raise ValueError("Not a boolean: %r" % value)
  75. return RawConfigParser.BOOLEAN_STATES[value.lower()]
  76. INTERNAL_OPTIONS = ("_allow_extra",)
  77. # Default configuration
  78. DEFAULT_CONFIG_SCHEMA = OrderedDict([
  79. ("server", OrderedDict([
  80. ("hosts", {
  81. "value": "localhost:5232",
  82. "help": "set server hostnames including ports",
  83. "aliases": ["-H", "--hosts"],
  84. "type": list_of_ip_address}),
  85. ("max_connections", {
  86. "value": "8",
  87. "help": "maximum number of parallel connections",
  88. "type": positive_int}),
  89. ("max_content_length", {
  90. "value": "100000000",
  91. "help": "maximum size of request body in bytes",
  92. "type": positive_int}),
  93. ("timeout", {
  94. "value": "30",
  95. "help": "socket timeout",
  96. "type": positive_int}),
  97. ("ssl", {
  98. "value": "False",
  99. "help": "use SSL connection",
  100. "aliases": ["-s", "--ssl"],
  101. "opposite": ["-S", "--no-ssl"],
  102. "type": bool}),
  103. ("certificate", {
  104. "value": "/etc/ssl/radicale.cert.pem",
  105. "help": "set certificate file",
  106. "aliases": ["-c", "--certificate"],
  107. "type": filepath}),
  108. ("key", {
  109. "value": "/etc/ssl/radicale.key.pem",
  110. "help": "set private key file",
  111. "aliases": ["-k", "--key"],
  112. "type": filepath}),
  113. ("certificate_authority", {
  114. "value": "",
  115. "help": "set CA certificate for validating clients",
  116. "aliases": ["--certificate-authority"],
  117. "type": filepath}),
  118. ("_internal_server", {
  119. "value": "False",
  120. "help": "the internal server is used",
  121. "type": bool})])),
  122. ("encoding", OrderedDict([
  123. ("request", {
  124. "value": "utf-8",
  125. "help": "encoding for responding requests",
  126. "type": str}),
  127. ("stock", {
  128. "value": "utf-8",
  129. "help": "encoding for storing local collections",
  130. "type": str})])),
  131. ("auth", OrderedDict([
  132. ("type", {
  133. "value": "none",
  134. "help": "authentication method",
  135. "type": str_or_callable,
  136. "internal": auth.INTERNAL_TYPES}),
  137. ("htpasswd_filename", {
  138. "value": "/etc/radicale/users",
  139. "help": "htpasswd filename",
  140. "type": filepath}),
  141. ("htpasswd_encryption", {
  142. "value": "md5",
  143. "help": "htpasswd encryption method",
  144. "type": str}),
  145. ("realm", {
  146. "value": "Radicale - Password Required",
  147. "help": "message displayed when a password is needed",
  148. "type": str}),
  149. ("delay", {
  150. "value": "1",
  151. "help": "incorrect authentication delay",
  152. "type": positive_float})])),
  153. ("rights", OrderedDict([
  154. ("type", {
  155. "value": "owner_only",
  156. "help": "rights backend",
  157. "type": str_or_callable,
  158. "internal": rights.INTERNAL_TYPES}),
  159. ("file", {
  160. "value": "/etc/radicale/rights",
  161. "help": "file for rights management from_file",
  162. "type": filepath})])),
  163. ("storage", OrderedDict([
  164. ("type", {
  165. "value": "multifilesystem",
  166. "help": "storage backend",
  167. "type": str_or_callable,
  168. "internal": storage.INTERNAL_TYPES}),
  169. ("filesystem_folder", {
  170. "value": "/var/lib/radicale/collections",
  171. "help": "path where collections are stored",
  172. "type": filepath}),
  173. ("max_sync_token_age", {
  174. "value": "2592000", # 30 days
  175. "help": "delete sync token that are older",
  176. "type": positive_int}),
  177. ("hook", {
  178. "value": "",
  179. "help": "command that is run after changes to storage",
  180. "type": str}),
  181. ("_filesystem_fsync", {
  182. "value": "True",
  183. "help": "sync all changes to filesystem during requests",
  184. "type": bool})])),
  185. ("web", OrderedDict([
  186. ("type", {
  187. "value": "internal",
  188. "help": "web interface backend",
  189. "type": str_or_callable,
  190. "internal": web.INTERNAL_TYPES})])),
  191. ("logging", OrderedDict([
  192. ("level", {
  193. "value": "warning",
  194. "help": "threshold for the logger",
  195. "type": logging_level}),
  196. ("mask_passwords", {
  197. "value": "True",
  198. "help": "mask passwords in logs",
  199. "type": bool})])),
  200. ("headers", OrderedDict([
  201. ("_allow_extra", str)]))])
  202. def parse_compound_paths(*compound_paths):
  203. """Parse a compound path and return the individual paths.
  204. Paths in a compound path are joined by ``os.pathsep``. If a path starts
  205. with ``?`` the return value ``IGNORE_IF_MISSING`` is set.
  206. When multiple ``compound_paths`` are passed, the last argument that is
  207. not ``None`` is used.
  208. Returns a dict of the format ``[(PATH, IGNORE_IF_MISSING), ...]``
  209. """
  210. compound_path = ""
  211. for p in compound_paths:
  212. if p is not None:
  213. compound_path = p
  214. paths = []
  215. for path in compound_path.split(os.pathsep):
  216. ignore_if_missing = path.startswith("?")
  217. if ignore_if_missing:
  218. path = path[1:]
  219. path = filepath(path)
  220. if path:
  221. paths.append((path, ignore_if_missing))
  222. return paths
  223. def load(paths=()):
  224. """
  225. Create instance of ``Configuration`` for use with
  226. ``radicale.app.Application``.
  227. ``paths`` a list of configuration files with the format
  228. ``[(PATH, IGNORE_IF_MISSING), ...]``.
  229. If a configuration file is missing and IGNORE_IF_MISSING is set, the
  230. config is set to ``Configuration.SOURCE_MISSING``.
  231. The configuration can later be changed with ``Configuration.update()``.
  232. """
  233. configuration = Configuration(DEFAULT_CONFIG_SCHEMA)
  234. for path, ignore_if_missing in paths:
  235. parser = RawConfigParser()
  236. config_source = "config file %r" % path
  237. try:
  238. if not parser.read(path):
  239. config = Configuration.SOURCE_MISSING
  240. if not ignore_if_missing:
  241. raise RuntimeError("No such file: %r" % path)
  242. else:
  243. config = {s: {o: parser[s][o] for o in parser.options(s)}
  244. for s in parser.sections()}
  245. except Exception as e:
  246. raise RuntimeError(
  247. "Failed to load %s: %s" % (config_source, e)) from e
  248. configuration.update(config, config_source)
  249. return configuration
  250. class Configuration:
  251. SOURCE_MISSING = {}
  252. def __init__(self, schema):
  253. """Initialize configuration.
  254. ``schema`` a dict that describes the configuration format.
  255. See ``DEFAULT_CONFIG_SCHEMA``.
  256. The content of ``schema`` must not change afterwards, it is kept
  257. as an internal reference.
  258. Use ``load()`` to create an instance for use with
  259. ``radicale.app.Application``.
  260. """
  261. self._schema = schema
  262. self._values = {}
  263. self._configs = []
  264. default = {section: {option: self._schema[section][option]["value"]
  265. for option in self._schema[section]
  266. if option not in INTERNAL_OPTIONS}
  267. for section in self._schema}
  268. self.update(default, "default config", privileged=True)
  269. def update(self, config, source=None, privileged=False):
  270. """Update the configuration.
  271. ``config`` a dict of the format {SECTION: {OPTION: VALUE, ...}, ...}.
  272. The configuration is checked for errors according to the config schema.
  273. The content of ``config`` must not change afterwards, it is kept
  274. as an internal reference.
  275. ``source`` a description of the configuration source (used in error
  276. messages).
  277. ``privileged`` allows updating sections and options starting with "_".
  278. """
  279. source = source or "unspecified config"
  280. new_values = {}
  281. for section in config:
  282. if (section not in self._schema or
  283. section.startswith("_") and not privileged):
  284. raise ValueError(
  285. "Invalid section %r in %s" % (section, source))
  286. new_values[section] = {}
  287. extra_type = None
  288. extra_type = self._schema[section].get("_allow_extra")
  289. if "type" in self._schema[section]:
  290. if "type" in config[section]:
  291. plugin = config[section]["type"]
  292. else:
  293. plugin = self.get(section, "type")
  294. if plugin not in self._schema[section]["type"]["internal"]:
  295. extra_type = unspecified_type
  296. for option in config[section]:
  297. type_ = extra_type
  298. if option in self._schema[section]:
  299. type_ = self._schema[section][option]["type"]
  300. if (not type_ or option in INTERNAL_OPTIONS or
  301. option.startswith("_") and not privileged):
  302. raise RuntimeError("Invalid option %r in section %r in "
  303. "%s" % (option, section, source))
  304. raw_value = config[section][option]
  305. try:
  306. if type_ == bool and not isinstance(raw_value, bool):
  307. raw_value = _convert_to_bool(raw_value)
  308. new_values[section][option] = type_(raw_value)
  309. except Exception as e:
  310. raise RuntimeError(
  311. "Invalid %s value for option %r in section %r in %s: "
  312. "%r" % (type_.__name__, option, section, source,
  313. raw_value)) from e
  314. self._configs.append((config, source, bool(privileged)))
  315. for section in new_values:
  316. self._values[section] = self._values.get(section, {})
  317. self._values[section].update(new_values[section])
  318. def get(self, section, option):
  319. """Get the value of ``option`` in ``section``."""
  320. with contextlib.suppress(KeyError):
  321. return self._values[section][option]
  322. raise KeyError(section, option)
  323. def get_raw(self, section, option):
  324. """Get the raw value of ``option`` in ``section``."""
  325. for config, _, _ in reversed(self._configs):
  326. if option in config.get(section, {}):
  327. return config[section][option]
  328. raise KeyError(section, option)
  329. def get_source(self, section, option):
  330. """Get the source that provides ``option`` in ``section``."""
  331. for config, source, _ in reversed(self._configs):
  332. if option in config.get(section, {}):
  333. return source
  334. raise KeyError(section, option)
  335. def sections(self):
  336. """List all sections."""
  337. return self._values.keys()
  338. def options(self, section):
  339. """List all options in ``section``"""
  340. return self._values[section].keys()
  341. def sources(self):
  342. """List all config sources."""
  343. return [(source, config is self.SOURCE_MISSING) for
  344. config, source, _ in self._configs]
  345. def copy(self, plugin_schema=None):
  346. """Create a copy of the configuration
  347. ``plugin_schema`` is a optional dict that contains additional options
  348. for usage with a plugin. See ``DEFAULT_CONFIG_SCHEMA``.
  349. """
  350. if plugin_schema is None:
  351. schema = self._schema
  352. else:
  353. schema = self._schema.copy()
  354. for section, options in plugin_schema.items():
  355. if (section not in schema or "type" not in schema[section] or
  356. "internal" not in schema[section]["type"]):
  357. raise ValueError("not a plugin section: %r" % section)
  358. schema[section] = schema[section].copy()
  359. schema[section]["type"] = schema[section]["type"].copy()
  360. schema[section]["type"]["internal"] = [
  361. self.get(section, "type")]
  362. for option, value in options.items():
  363. if option in schema[section]:
  364. raise ValueError("option already exists in %r: %r" % (
  365. section, option))
  366. schema[section][option] = value
  367. copy = type(self)(schema)
  368. for config, source, privileged in self._configs:
  369. copy.update(config, source, privileged)
  370. return copy