config.py 15 KB

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