config.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700
  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-2025 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 imap_address(value):
  84. if "]" in value:
  85. pre_address, pre_address_port = value.rsplit("]", 1)
  86. else:
  87. pre_address, pre_address_port = "", value
  88. if ":" in pre_address_port:
  89. pre_address2, port = pre_address_port.rsplit(":", 1)
  90. address = pre_address + pre_address2
  91. else:
  92. address, port = pre_address + pre_address_port, None
  93. try:
  94. return (address.strip(string.whitespace + "[]"),
  95. None if port is None else int(port))
  96. except ValueError:
  97. raise ValueError("malformed IMAP address: %r" % value)
  98. def imap_security(value):
  99. if value not in ("tls", "starttls", "none"):
  100. raise ValueError("unsupported IMAP security: %r" % value)
  101. return value
  102. def json_str(value: Any) -> dict:
  103. if not value:
  104. return {}
  105. ret = json.loads(value)
  106. for (name_coll, props) in ret.items():
  107. checked_props = check_and_sanitize_props(props)
  108. ret[name_coll] = checked_props
  109. return ret
  110. INTERNAL_OPTIONS: Sequence[str] = ("_allow_extra",)
  111. # Default configuration
  112. DEFAULT_CONFIG_SCHEMA: types.CONFIG_SCHEMA = OrderedDict([
  113. ("server", OrderedDict([
  114. ("hosts", {
  115. "value": "localhost:5232",
  116. "help": "set server hostnames including ports",
  117. "aliases": ("-H", "--hosts",),
  118. "type": list_of_ip_address}),
  119. ("max_connections", {
  120. "value": "8",
  121. "help": "maximum number of parallel connections",
  122. "type": positive_int}),
  123. ("max_content_length", {
  124. "value": "100000000",
  125. "help": "maximum size of request body in bytes",
  126. "type": positive_int}),
  127. ("timeout", {
  128. "value": "30",
  129. "help": "socket timeout",
  130. "type": positive_float}),
  131. ("ssl", {
  132. "value": "False",
  133. "help": "use SSL connection",
  134. "aliases": ("-s", "--ssl",),
  135. "opposite_aliases": ("-S", "--no-ssl",),
  136. "type": bool}),
  137. ("protocol", {
  138. "value": "",
  139. "help": "SSL/TLS protocol (Apache SSLProtocol format)",
  140. "type": str}),
  141. ("ciphersuite", {
  142. "value": "",
  143. "help": "SSL/TLS Cipher Suite (OpenSSL cipher list format)",
  144. "type": str}),
  145. ("certificate", {
  146. "value": "/etc/ssl/radicale.cert.pem",
  147. "help": "set certificate file",
  148. "aliases": ("-c", "--certificate",),
  149. "type": filepath}),
  150. ("key", {
  151. "value": "/etc/ssl/radicale.key.pem",
  152. "help": "set private key file",
  153. "aliases": ("-k", "--key",),
  154. "type": filepath}),
  155. ("certificate_authority", {
  156. "value": "",
  157. "help": "set CA certificate for validating clients",
  158. "aliases": ("--certificate-authority",),
  159. "type": filepath}),
  160. ("script_name", {
  161. "value": "",
  162. "help": "script name to strip from URI if called by reverse proxy (default taken from HTTP_X_SCRIPT_NAME or SCRIPT_NAME)",
  163. "type": str}),
  164. ("_internal_server", {
  165. "value": "False",
  166. "help": "the internal server is used",
  167. "type": bool})])),
  168. ("encoding", OrderedDict([
  169. ("request", {
  170. "value": "utf-8",
  171. "help": "encoding for responding requests",
  172. "type": str}),
  173. ("stock", {
  174. "value": "utf-8",
  175. "help": "encoding for storing local collections",
  176. "type": str})])),
  177. ("auth", OrderedDict([
  178. ("type", {
  179. "value": "denyall",
  180. "help": "authentication method (" + "|".join(auth.INTERNAL_TYPES) + ")",
  181. "type": str_or_callable,
  182. "internal": auth.INTERNAL_TYPES}),
  183. ("cache_logins", {
  184. "value": "false",
  185. "help": "cache successful/failed logins for until expiration time",
  186. "type": bool}),
  187. ("cache_successful_logins_expiry", {
  188. "value": "15",
  189. "help": "expiration time for caching successful logins in seconds",
  190. "type": int}),
  191. ("cache_failed_logins_expiry", {
  192. "value": "90",
  193. "help": "expiration time for caching failed logins in seconds",
  194. "type": int}),
  195. ("htpasswd_filename", {
  196. "value": "/etc/radicale/users",
  197. "help": "htpasswd filename",
  198. "type": filepath}),
  199. ("htpasswd_encryption", {
  200. "value": "autodetect",
  201. "help": "htpasswd encryption method",
  202. "type": str}),
  203. ("htpasswd_cache", {
  204. "value": "False",
  205. "help": "enable caching of htpasswd file",
  206. "type": bool}),
  207. ("dovecot_connection_type", {
  208. "value": "AF_UNIX",
  209. "help": "Connection type for dovecot authentication",
  210. "type": str_or_callable,
  211. "internal": auth.AUTH_SOCKET_FAMILY}),
  212. ("dovecot_socket", {
  213. "value": "/var/run/dovecot/auth-client",
  214. "help": "dovecot auth AF_UNIX socket",
  215. "type": str}),
  216. ("dovecot_host", {
  217. "value": "localhost",
  218. "help": "dovecot auth AF_INET or AF_INET6 host",
  219. "type": str}),
  220. ("dovecot_port", {
  221. "value": "12345",
  222. "help": "dovecot auth port",
  223. "type": int}),
  224. ("realm", {
  225. "value": "Radicale - Password Required",
  226. "help": "message displayed when a password is needed",
  227. "type": str}),
  228. ("delay", {
  229. "value": "1",
  230. "help": "incorrect authentication delay",
  231. "type": positive_float}),
  232. ("ldap_ignore_attribute_create_modify_timestamp", {
  233. "value": "false",
  234. "help": "Ignore modifyTimestamp and createTimestamp attributes. Need if Authentik LDAP server is used.",
  235. "type": bool}),
  236. ("ldap_uri", {
  237. "value": "ldap://localhost",
  238. "help": "URI to the ldap server",
  239. "type": str}),
  240. ("ldap_base", {
  241. "value": "",
  242. "help": "LDAP base DN of the ldap server",
  243. "type": str}),
  244. ("ldap_reader_dn", {
  245. "value": "",
  246. "help": "the DN of a ldap user with read access to get the user accounts",
  247. "type": str}),
  248. ("ldap_secret", {
  249. "value": "",
  250. "help": "the password of the ldap_reader_dn",
  251. "type": str}),
  252. ("ldap_secret_file", {
  253. "value": "",
  254. "help": "path of the file containing the password of the ldap_reader_dn",
  255. "type": str}),
  256. ("ldap_filter", {
  257. "value": "(cn={0})",
  258. "help": "the search filter to find the user DN to authenticate by the username",
  259. "type": str}),
  260. ("ldap_user_attribute", {
  261. "value": "",
  262. "help": "the attribute to be used as username after authentication",
  263. "type": str}),
  264. ("ldap_groups_attribute", {
  265. "value": "",
  266. "help": "attribute to read the group memberships from",
  267. "type": str}),
  268. ("ldap_use_ssl", {
  269. "value": "False",
  270. "help": "Use ssl on the ldap connection",
  271. "type": bool}),
  272. ("ldap_ssl_verify_mode", {
  273. "value": "REQUIRED",
  274. "help": "The certificate verification mode. NONE, OPTIONAL, default is REQUIRED",
  275. "type": str}),
  276. ("ldap_ssl_ca_file", {
  277. "value": "",
  278. "help": "The path to the CA file in pem format which is used to certificate the server certificate",
  279. "type": str}),
  280. ("imap_host", {
  281. "value": "localhost",
  282. "help": "IMAP server hostname: address|address:port|[address]:port|*localhost*",
  283. "type": imap_address}),
  284. ("imap_security", {
  285. "value": "tls",
  286. "help": "Secure the IMAP connection: *tls*|starttls|none",
  287. "type": imap_security}),
  288. ("oauth2_token_endpoint", {
  289. "value": "",
  290. "help": "OAuth2 token endpoint URL",
  291. "type": str}),
  292. ("pam_group_membership", {
  293. "value": "",
  294. "help": "PAM group user should be member of",
  295. "type": str}),
  296. ("pam_service", {
  297. "value": "radicale",
  298. "help": "PAM service",
  299. "type": str}),
  300. ("strip_domain", {
  301. "value": "False",
  302. "help": "strip domain from username",
  303. "type": bool}),
  304. ("uc_username", {
  305. "value": "False",
  306. "help": "convert username to uppercase, must be true for case-insensitive auth providers",
  307. "type": bool}),
  308. ("lc_username", {
  309. "value": "False",
  310. "help": "convert username to lowercase, must be true for case-insensitive auth providers",
  311. "type": bool})])),
  312. ("rights", OrderedDict([
  313. ("type", {
  314. "value": "owner_only",
  315. "help": "rights backend",
  316. "type": str_or_callable,
  317. "internal": rights.INTERNAL_TYPES}),
  318. ("permit_delete_collection", {
  319. "value": "True",
  320. "help": "permit delete of a collection",
  321. "type": bool}),
  322. ("permit_overwrite_collection", {
  323. "value": "True",
  324. "help": "permit overwrite of a collection",
  325. "type": bool}),
  326. ("file", {
  327. "value": "/etc/radicale/rights",
  328. "help": "file for rights management from_file",
  329. "type": filepath})])),
  330. ("storage", OrderedDict([
  331. ("type", {
  332. "value": "multifilesystem",
  333. "help": "storage backend",
  334. "type": str_or_callable,
  335. "internal": storage.INTERNAL_TYPES}),
  336. ("filesystem_folder", {
  337. "value": "/var/lib/radicale/collections",
  338. "help": "path where collections are stored",
  339. "type": filepath}),
  340. ("filesystem_cache_folder", {
  341. "value": "",
  342. "help": "path where cache of collections is stored in case of use_cache_subfolder_* options are active",
  343. "type": filepath}),
  344. ("use_cache_subfolder_for_item", {
  345. "value": "False",
  346. "help": "use subfolder 'collection-cache' for 'item' cache file structure instead of inside collection folder",
  347. "type": bool}),
  348. ("use_cache_subfolder_for_history", {
  349. "value": "False",
  350. "help": "use subfolder 'collection-cache' for 'history' cache file structure instead of inside collection folder",
  351. "type": bool}),
  352. ("use_cache_subfolder_for_synctoken", {
  353. "value": "False",
  354. "help": "use subfolder 'collection-cache' for 'sync-token' cache file structure instead of inside collection folder",
  355. "type": bool}),
  356. ("use_mtime_and_size_for_item_cache", {
  357. "value": "False",
  358. "help": "use mtime and file size instead of SHA256 for 'item' cache (improves speed)",
  359. "type": bool}),
  360. ("folder_umask", {
  361. "value": "",
  362. "help": "umask for folder creation (empty: system default)",
  363. "type": str}),
  364. ("max_sync_token_age", {
  365. "value": "2592000", # 30 days
  366. "help": "delete sync token that are older",
  367. "type": positive_int}),
  368. ("skip_broken_item", {
  369. "value": "True",
  370. "help": "skip broken item instead of triggering exception",
  371. "type": bool}),
  372. ("hook", {
  373. "value": "",
  374. "help": "command that is run after changes to storage",
  375. "type": str}),
  376. ("_filesystem_fsync", {
  377. "value": "True",
  378. "help": "sync all changes to filesystem during requests",
  379. "type": bool}),
  380. ("predefined_collections", {
  381. "value": "",
  382. "help": "predefined user collections",
  383. "type": json_str})])),
  384. ("hook", OrderedDict([
  385. ("type", {
  386. "value": "none",
  387. "help": "hook backend",
  388. "type": str,
  389. "internal": hook.INTERNAL_TYPES}),
  390. ("rabbitmq_endpoint", {
  391. "value": "",
  392. "help": "endpoint where rabbitmq server is running",
  393. "type": str}),
  394. ("rabbitmq_topic", {
  395. "value": "",
  396. "help": "topic to declare queue",
  397. "type": str}),
  398. ("rabbitmq_queue_type", {
  399. "value": "",
  400. "help": "queue type for topic declaration",
  401. "type": str})])),
  402. ("web", OrderedDict([
  403. ("type", {
  404. "value": "internal",
  405. "help": "web interface backend",
  406. "type": str_or_callable,
  407. "internal": web.INTERNAL_TYPES})])),
  408. ("logging", OrderedDict([
  409. ("level", {
  410. "value": "info",
  411. "help": "threshold for the logger",
  412. "type": logging_level}),
  413. ("bad_put_request_content", {
  414. "value": "False",
  415. "help": "log bad PUT request content",
  416. "type": bool}),
  417. ("backtrace_on_debug", {
  418. "value": "False",
  419. "help": "log backtrace on level=debug",
  420. "type": bool}),
  421. ("request_header_on_debug", {
  422. "value": "False",
  423. "help": "log request header on level=debug",
  424. "type": bool}),
  425. ("request_content_on_debug", {
  426. "value": "False",
  427. "help": "log request content on level=debug",
  428. "type": bool}),
  429. ("response_content_on_debug", {
  430. "value": "False",
  431. "help": "log response content on level=debug",
  432. "type": bool}),
  433. ("rights_rule_doesnt_match_on_debug", {
  434. "value": "False",
  435. "help": "log rights rules which doesn't match on level=debug",
  436. "type": bool}),
  437. ("storage_cache_actions_on_debug", {
  438. "value": "False",
  439. "help": "log storage cache action on level=debug",
  440. "type": bool}),
  441. ("mask_passwords", {
  442. "value": "True",
  443. "help": "mask passwords in logs",
  444. "type": bool})])),
  445. ("headers", OrderedDict([
  446. ("_allow_extra", str)])),
  447. ("reporting", OrderedDict([
  448. ("max_freebusy_occurrence", {
  449. "value": "10000",
  450. "help": "number of occurrences per event when reporting",
  451. "type": positive_int})]))
  452. ])
  453. def parse_compound_paths(*compound_paths: Optional[str]
  454. ) -> List[Tuple[str, bool]]:
  455. """Parse a compound path and return the individual paths.
  456. Paths in a compound path are joined by ``os.pathsep``. If a path starts
  457. with ``?`` the return value ``IGNORE_IF_MISSING`` is set.
  458. When multiple ``compound_paths`` are passed, the last argument that is
  459. not ``None`` is used.
  460. Returns a dict of the format ``[(PATH, IGNORE_IF_MISSING), ...]``
  461. """
  462. compound_path = ""
  463. for p in compound_paths:
  464. if p is not None:
  465. compound_path = p
  466. paths = []
  467. for path in compound_path.split(os.pathsep):
  468. ignore_if_missing = path.startswith("?")
  469. if ignore_if_missing:
  470. path = path[1:]
  471. path = filepath(path)
  472. if path:
  473. paths.append((path, ignore_if_missing))
  474. return paths
  475. def load(paths: Optional[Iterable[Tuple[str, bool]]] = None
  476. ) -> "Configuration":
  477. """
  478. Create instance of ``Configuration`` for use with
  479. ``radicale.app.Application``.
  480. ``paths`` a list of configuration files with the format
  481. ``[(PATH, IGNORE_IF_MISSING), ...]``.
  482. If a configuration file is missing and IGNORE_IF_MISSING is set, the
  483. config is set to ``Configuration.SOURCE_MISSING``.
  484. The configuration can later be changed with ``Configuration.update()``.
  485. """
  486. if paths is None:
  487. paths = []
  488. configuration = Configuration(DEFAULT_CONFIG_SCHEMA)
  489. for path, ignore_if_missing in paths:
  490. parser = RawConfigParser()
  491. config_source = "config file %r" % path
  492. config: types.CONFIG
  493. try:
  494. with open(path) as f:
  495. parser.read_file(f)
  496. config = {s: {o: parser[s][o] for o in parser.options(s)}
  497. for s in parser.sections()}
  498. except Exception as e:
  499. if not (ignore_if_missing and isinstance(e, (
  500. FileNotFoundError, NotADirectoryError, PermissionError))):
  501. raise RuntimeError("Failed to load %s: %s" % (config_source, e)
  502. ) from e
  503. config = Configuration.SOURCE_MISSING
  504. configuration.update(config, config_source)
  505. return configuration
  506. _Self = TypeVar("_Self", bound="Configuration")
  507. class Configuration:
  508. SOURCE_MISSING: ClassVar[types.CONFIG] = {}
  509. _schema: types.CONFIG_SCHEMA
  510. _values: types.MUTABLE_CONFIG
  511. _configs: List[Tuple[types.CONFIG, str, bool]]
  512. def __init__(self, schema: types.CONFIG_SCHEMA) -> None:
  513. """Initialize configuration.
  514. ``schema`` a dict that describes the configuration format.
  515. See ``DEFAULT_CONFIG_SCHEMA``.
  516. The content of ``schema`` must not change afterwards, it is kept
  517. as an internal reference.
  518. Use ``load()`` to create an instance for use with
  519. ``radicale.app.Application``.
  520. """
  521. self._schema = schema
  522. self._values = {}
  523. self._configs = []
  524. default = {section: {option: self._schema[section][option]["value"]
  525. for option in self._schema[section]
  526. if option not in INTERNAL_OPTIONS}
  527. for section in self._schema}
  528. self.update(default, "default config", privileged=True)
  529. def update(self, config: types.CONFIG, source: Optional[str] = None,
  530. privileged: bool = False) -> None:
  531. """Update the configuration.
  532. ``config`` a dict of the format {SECTION: {OPTION: VALUE, ...}, ...}.
  533. The configuration is checked for errors according to the config schema.
  534. The content of ``config`` must not change afterwards, it is kept
  535. as an internal reference.
  536. ``source`` a description of the configuration source (used in error
  537. messages).
  538. ``privileged`` allows updating sections and options starting with "_".
  539. """
  540. if source is None:
  541. source = "unspecified config"
  542. new_values: types.MUTABLE_CONFIG = {}
  543. for section in config:
  544. if (section not in self._schema or
  545. section.startswith("_") and not privileged):
  546. raise ValueError(
  547. "Invalid section %r in %s" % (section, source))
  548. new_values[section] = {}
  549. extra_type = None
  550. extra_type = self._schema[section].get("_allow_extra")
  551. if "type" in self._schema[section]:
  552. if "type" in config[section]:
  553. plugin = config[section]["type"]
  554. else:
  555. plugin = self.get(section, "type")
  556. if plugin not in self._schema[section]["type"]["internal"]:
  557. extra_type = unspecified_type
  558. for option in config[section]:
  559. type_ = extra_type
  560. if option in self._schema[section]:
  561. type_ = self._schema[section][option]["type"]
  562. if (not type_ or option in INTERNAL_OPTIONS or
  563. option.startswith("_") and not privileged):
  564. raise RuntimeError("Invalid option %r in section %r in "
  565. "%s" % (option, section, source))
  566. raw_value = config[section][option]
  567. try:
  568. if type_ == bool and not isinstance(raw_value, bool):
  569. raw_value = _convert_to_bool(raw_value)
  570. new_values[section][option] = type_(raw_value)
  571. except Exception as e:
  572. raise RuntimeError(
  573. "Invalid %s value for option %r in section %r in %s: "
  574. "%r" % (type_.__name__, option, section, source,
  575. raw_value)) from e
  576. self._configs.append((config, source, bool(privileged)))
  577. for section in new_values:
  578. self._values[section] = self._values.get(section, {})
  579. self._values[section].update(new_values[section])
  580. def get(self, section: str, option: str) -> Any:
  581. """Get the value of ``option`` in ``section``."""
  582. with contextlib.suppress(KeyError):
  583. return self._values[section][option]
  584. raise KeyError(section, option)
  585. def get_raw(self, section: str, option: str) -> Any:
  586. """Get the raw value of ``option`` in ``section``."""
  587. for config, _, _ in reversed(self._configs):
  588. if option in config.get(section, {}):
  589. return config[section][option]
  590. raise KeyError(section, option)
  591. def get_source(self, section: str, option: str) -> str:
  592. """Get the source that provides ``option`` in ``section``."""
  593. for config, source, _ in reversed(self._configs):
  594. if option in config.get(section, {}):
  595. return source
  596. raise KeyError(section, option)
  597. def sections(self) -> List[str]:
  598. """List all sections."""
  599. return list(self._values.keys())
  600. def options(self, section: str) -> List[str]:
  601. """List all options in ``section``"""
  602. return list(self._values[section].keys())
  603. def sources(self) -> List[Tuple[str, bool]]:
  604. """List all config sources."""
  605. return [(source, config is self.SOURCE_MISSING) for
  606. config, source, _ in self._configs]
  607. def copy(self: _Self, plugin_schema: Optional[types.CONFIG_SCHEMA] = None
  608. ) -> _Self:
  609. """Create a copy of the configuration
  610. ``plugin_schema`` is a optional dict that contains additional options
  611. for usage with a plugin. See ``DEFAULT_CONFIG_SCHEMA``.
  612. """
  613. if plugin_schema is None:
  614. schema = self._schema
  615. else:
  616. new_schema = dict(self._schema)
  617. for section, options in plugin_schema.items():
  618. if (section not in new_schema or
  619. "type" not in new_schema[section] or
  620. "internal" not in new_schema[section]["type"]):
  621. raise ValueError("not a plugin section: %r" % section)
  622. new_section = dict(new_schema[section])
  623. new_type = dict(new_section["type"])
  624. new_type["internal"] = (self.get(section, "type"),)
  625. new_section["type"] = new_type
  626. for option, value in options.items():
  627. if option in new_section:
  628. raise ValueError("option already exists in %r: %r" %
  629. (section, option))
  630. new_section[option] = value
  631. new_schema[section] = new_section
  632. schema = new_schema
  633. copy = type(self)(schema)
  634. for config, source, privileged in self._configs:
  635. copy.update(config, source, privileged)
  636. return copy