config.py 30 KB

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