__init__.py 25 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 Guillaume Ayoub
  5. # Copyright © 2017-2019 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. Radicale WSGI application.
  22. Can be used with an external WSGI server (see ``radicale.application()``) or
  23. the built-in server (see ``radicale.server`` module).
  24. """
  25. import base64
  26. import cProfile
  27. import datetime
  28. import io
  29. import pprint
  30. import pstats
  31. import random
  32. import time
  33. import zlib
  34. from http import client
  35. from typing import Iterable, List, Mapping, Sequence, Tuple, Union
  36. from radicale import config, httputils, log, pathutils, types
  37. from radicale.app.base import ApplicationBase
  38. from radicale.app.delete import ApplicationPartDelete
  39. from radicale.app.get import ApplicationPartGet
  40. from radicale.app.head import ApplicationPartHead
  41. from radicale.app.mkcalendar import ApplicationPartMkcalendar
  42. from radicale.app.mkcol import ApplicationPartMkcol
  43. from radicale.app.move import ApplicationPartMove
  44. from radicale.app.options import ApplicationPartOptions
  45. from radicale.app.post import ApplicationPartPost
  46. from radicale.app.propfind import ApplicationPartPropfind
  47. from radicale.app.proppatch import ApplicationPartProppatch
  48. from radicale.app.put import ApplicationPartPut
  49. from radicale.app.report import ApplicationPartReport
  50. from radicale.auth import AuthContext
  51. from radicale.log import logger
  52. # Combination of types.WSGIStartResponse and WSGI application return value
  53. _IntermediateResponse = Tuple[str, List[Tuple[str, str]], Iterable[bytes]]
  54. REQUEST_METHODS = ["DELETE", "GET", "HEAD", "MKCALENDAR", "MKCOL", "MOVE", "OPTIONS", "POST", "PROPFIND", "PROPPATCH", "PUT", "REPORT"]
  55. PROFILING: Sequence[str] = ("per_request", "per_request_method")
  56. class Application(ApplicationPartDelete, ApplicationPartHead,
  57. ApplicationPartGet, ApplicationPartMkcalendar,
  58. ApplicationPartMkcol, ApplicationPartMove,
  59. ApplicationPartOptions, ApplicationPartPropfind,
  60. ApplicationPartProppatch, ApplicationPartPost,
  61. ApplicationPartPut, ApplicationPartReport, ApplicationBase):
  62. """WSGI application."""
  63. _mask_passwords: bool
  64. _auth_delay: float
  65. _internal_server: bool
  66. _max_content_length: int
  67. _auth_realm: str
  68. _auth_type: str
  69. _web_type: str
  70. _script_name: str
  71. _extra_headers: Mapping[str, str]
  72. _profiling_per_request: bool = False
  73. _profiling_per_request_method: bool = False
  74. profiler_per_request_method: dict[str, cProfile.Profile] = {}
  75. profiler_per_request_method_counter: dict[str, int] = {}
  76. profiler_per_request_method_starttime: datetime.datetime
  77. profiler_per_request_method_logtime: datetime.datetime
  78. def __init__(self, configuration: config.Configuration) -> None:
  79. """Initialize Application.
  80. ``configuration`` see ``radicale.config`` module.
  81. The ``configuration`` must not change during the lifetime of
  82. this object, it is kept as an internal reference.
  83. """
  84. super().__init__(configuration)
  85. self._mask_passwords = configuration.get("logging", "mask_passwords")
  86. self._bad_put_request_content = configuration.get("logging", "bad_put_request_content")
  87. self._request_header_on_debug = configuration.get("logging", "request_header_on_debug")
  88. self._response_content_on_debug = configuration.get("logging", "response_content_on_debug")
  89. self._auth_delay = configuration.get("auth", "delay")
  90. self._auth_type = configuration.get("auth", "type")
  91. self._web_type = configuration.get("web", "type")
  92. self._internal_server = configuration.get("server", "_internal_server")
  93. self._script_name = configuration.get("server", "script_name")
  94. if self._script_name:
  95. if self._script_name[0] != "/":
  96. logger.error("server.script_name must start with '/': %r", self._script_name)
  97. raise RuntimeError("server.script_name option has to start with '/'")
  98. else:
  99. if self._script_name.endswith("/"):
  100. logger.error("server.script_name must not end with '/': %r", self._script_name)
  101. raise RuntimeError("server.script_name option must not end with '/'")
  102. else:
  103. logger.info("Provided script name to strip from URI if called by reverse proxy: %r", self._script_name)
  104. else:
  105. logger.info("Default script name to strip from URI if called by reverse proxy is taken from HTTP_X_SCRIPT_NAME or SCRIPT_NAME")
  106. self._max_content_length = configuration.get(
  107. "server", "max_content_length")
  108. self._auth_realm = configuration.get("auth", "realm")
  109. self._permit_delete_collection = configuration.get("rights", "permit_delete_collection")
  110. logger.info("permit delete of collection: %s", self._permit_delete_collection)
  111. self._permit_overwrite_collection = configuration.get("rights", "permit_overwrite_collection")
  112. logger.info("permit overwrite of collection: %s", self._permit_overwrite_collection)
  113. self._extra_headers = dict()
  114. for key in self.configuration.options("headers"):
  115. self._extra_headers[key] = configuration.get("headers", key)
  116. self._strict_preconditions = configuration.get("storage", "strict_preconditions")
  117. logger.info("strict preconditions check: %s", self._strict_preconditions)
  118. # Profiling options
  119. self._profiling = configuration.get("logging", "profiling")
  120. self._profiling_per_request_min_duration = configuration.get("logging", "profiling_per_request_min_duration")
  121. self._profiling_per_request_method_interval = configuration.get("logging", "profiling_per_request_method_interval")
  122. self._profiling_top_x_functions = configuration.get("logging", "profiling_top_x_functions")
  123. if self._profiling == "per_request":
  124. self._profiling_per_request = True
  125. elif self._profiling == "per_request_method":
  126. self._profiling_per_request_method = True
  127. else:
  128. logger.warning("profiling: %s (not supported, disabled)", self._profiling)
  129. if self._profiling_per_request or self._profiling_per_request_method:
  130. logger.info("profiling: %s", self._profiling)
  131. logger.info("profiling top X functions: %d", self._profiling_top_x_functions)
  132. if self._profiling_per_request:
  133. logger.info("profiling per request minimum duration: %d (below are skipped)", self._profiling_per_request_min_duration)
  134. if self._profiling_per_request_method:
  135. logger.info("profiling per request method interval: %d seconds", self._profiling_per_request_method_interval)
  136. # Profiling per request method initialization
  137. if self._profiling_per_request_method:
  138. for method in REQUEST_METHODS:
  139. self.profiler_per_request_method[method] = cProfile.Profile()
  140. self.profiler_per_request_method_counter[method] = False
  141. self.profiler_per_request_method_starttime = datetime.datetime.now()
  142. self.profiler_per_request_method_logtime = self.profiler_per_request_method_starttime
  143. def __del__(self) -> None:
  144. """Shutdown application."""
  145. if self._profiling_per_request_method:
  146. # Profiling since startup
  147. self._profiler_per_request_method(True)
  148. def _profiler_per_request_method(self, shutdown: bool = False) -> None:
  149. """Display profiler data per method."""
  150. profiler_timedelta_start = (datetime.datetime.now() - self.profiler_per_request_method_starttime).total_seconds()
  151. for method in REQUEST_METHODS:
  152. if self.profiler_per_request_method_counter[method] > 0:
  153. s = io.StringIO()
  154. stats = pstats.Stats(self.profiler_per_request_method[method], stream=s).sort_stats('cumulative')
  155. stats.print_stats(self._profiling_top_x_functions) # Print top X functions
  156. logger.info("Profiling data per request method after %d seconds and %d requests: %s: %s", profiler_timedelta_start, self.profiler_per_request_method_counter[method], method, s.getvalue())
  157. else:
  158. if shutdown:
  159. logger.info("Profiling data per request method after %d seconds: %s: (no requests seen so far)", profiler_timedelta_start, method)
  160. else:
  161. logger.debug("Profiling data per request method after %d seconds: %s: (no requests seen so far)", profiler_timedelta_start, method)
  162. def _scrub_headers(self, environ: types.WSGIEnviron) -> types.WSGIEnviron:
  163. """Mask passwords and cookies."""
  164. headers = dict(environ)
  165. if (self._mask_passwords and
  166. headers.get("HTTP_AUTHORIZATION", "").startswith("Basic")):
  167. headers["HTTP_AUTHORIZATION"] = "Basic **masked**"
  168. if headers.get("HTTP_COOKIE"):
  169. headers["HTTP_COOKIE"] = "**masked**"
  170. return headers
  171. def __call__(self, environ: types.WSGIEnviron, start_response:
  172. types.WSGIStartResponse) -> Iterable[bytes]:
  173. with log.register_stream(environ["wsgi.errors"]):
  174. try:
  175. status_text, headers, answers = self._handle_request(environ)
  176. except Exception as e:
  177. logger.error("An exception occurred during %s request on %r: "
  178. "%s", environ.get("REQUEST_METHOD", "unknown"),
  179. environ.get("PATH_INFO", ""), e, exc_info=True)
  180. # Make minimal response
  181. status, raw_headers, raw_answer = (
  182. httputils.INTERNAL_SERVER_ERROR)
  183. assert isinstance(raw_answer, str)
  184. answer = raw_answer.encode("ascii")
  185. status_text = "%d %s" % (
  186. status, client.responses.get(status, "Unknown"))
  187. headers = [*raw_headers, ("Content-Length", str(len(answer)))]
  188. answers = [answer]
  189. start_response(status_text, headers)
  190. if environ.get("REQUEST_METHOD") == "HEAD":
  191. return []
  192. return answers
  193. def _handle_request(self, environ: types.WSGIEnviron
  194. ) -> _IntermediateResponse:
  195. time_begin = datetime.datetime.now()
  196. request_method = environ["REQUEST_METHOD"].upper()
  197. unsafe_path = environ.get("PATH_INFO", "")
  198. https = environ.get("HTTPS", "")
  199. profiler = None
  200. context = AuthContext()
  201. """Manage a request."""
  202. def response(status: int, headers: types.WSGIResponseHeaders,
  203. answer: Union[None, str, bytes]) -> _IntermediateResponse:
  204. """Helper to create response from internal types.WSGIResponse"""
  205. headers = dict(headers)
  206. content_encoding = "plain"
  207. # Set content length
  208. answers = []
  209. if answer is not None:
  210. if isinstance(answer, str):
  211. if self._response_content_on_debug:
  212. logger.debug("Response content:\n%s", answer)
  213. else:
  214. logger.debug("Response content: suppressed by config/option [logging] response_content_on_debug")
  215. headers["Content-Type"] += "; charset=%s" % self._encoding
  216. answer = answer.encode(self._encoding)
  217. accept_encoding = [
  218. encoding.strip() for encoding in
  219. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  220. if encoding.strip()]
  221. if "gzip" in accept_encoding:
  222. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  223. answer = zcomp.compress(answer) + zcomp.flush()
  224. headers["Content-Encoding"] = "gzip"
  225. content_encoding = "gzip"
  226. headers["Content-Length"] = str(len(answer))
  227. answers.append(answer)
  228. # Add extra headers set in configuration
  229. headers.update(self._extra_headers)
  230. # Start response
  231. time_end = datetime.datetime.now()
  232. time_delta_seconds = (time_end - time_begin).total_seconds()
  233. status_text = "%d %s" % (
  234. status, client.responses.get(status, "Unknown"))
  235. if answer is not None:
  236. logger.info("%s response status for %r%s in %.3f seconds %s %s bytes: %s",
  237. request_method, unsafe_path, depthinfo,
  238. (time_end - time_begin).total_seconds(), content_encoding, str(len(answer)), status_text)
  239. else:
  240. logger.info("%s response status for %r%s in %.3f seconds: %s",
  241. request_method, unsafe_path, depthinfo,
  242. time_delta_seconds, status_text)
  243. # Profiling end
  244. if self._profiling_per_request:
  245. if profiler is not None:
  246. # Profiling per request
  247. if time_delta_seconds < self._profiling_per_request_min_duration:
  248. logger.debug("Profiling data %s response for %r%s: (supressed because duration below minimum %.3f < %.3f)", request_method, unsafe_path, depthinfo, time_delta_seconds, self._profiling_per_request_min_duration)
  249. else:
  250. s = io.StringIO()
  251. stats = pstats.Stats(profiler, stream=s).sort_stats('cumulative')
  252. stats.print_stats(self._profiling_top_x_functions) # Print top X functions
  253. logger.info("Profiling data %s response for %r%s: %s", request_method, unsafe_path, depthinfo, s.getvalue())
  254. else:
  255. logger.debug("Profiling data %s response for %r%s: (supressed because of no data)", request_method, unsafe_path, depthinfo)
  256. elif self._profiling_per_request_method:
  257. self.profiler_per_request_method[request_method].disable()
  258. self.profiler_per_request_method_counter[request_method] += 1
  259. profiler_timedelta = (datetime.datetime.now() - self.profiler_per_request_method_logtime).total_seconds()
  260. if profiler_timedelta > self._profiling_per_request_method_interval:
  261. self._profiler_per_request_method()
  262. self.profiler_per_request_method_logtime = datetime.datetime.now()
  263. # Return response content
  264. return status_text, list(headers.items()), answers
  265. reverse_proxy = False
  266. remote_host = "unknown"
  267. if environ.get("REMOTE_HOST"):
  268. remote_host = repr(environ["REMOTE_HOST"])
  269. if environ.get("REMOTE_ADDR"):
  270. if remote_host == 'unknown':
  271. remote_host = environ["REMOTE_ADDR"]
  272. context.remote_addr = environ["REMOTE_ADDR"]
  273. if environ.get("HTTP_X_FORWARDED_FOR"):
  274. reverse_proxy = True
  275. remote_host = "%s (forwarded for %r)" % (
  276. remote_host, environ["HTTP_X_FORWARDED_FOR"])
  277. if environ.get("HTTP_X_REMOTE_ADDR"):
  278. context.x_remote_addr = environ["HTTP_X_REMOTE_ADDR"]
  279. if environ.get("HTTP_X_FORWARDED_HOST") or environ.get("HTTP_X_FORWARDED_PROTO") or environ.get("HTTP_X_FORWARDED_SERVER"):
  280. reverse_proxy = True
  281. remote_useragent = ""
  282. if environ.get("HTTP_USER_AGENT"):
  283. remote_useragent = " using %r" % environ["HTTP_USER_AGENT"]
  284. depthinfo = ""
  285. if environ.get("HTTP_DEPTH"):
  286. depthinfo = " with depth %r" % environ["HTTP_DEPTH"]
  287. if https:
  288. https_info = " " + environ.get("SSL_PROTOCOL", "") + " " + environ.get("SSL_CIPHER", "")
  289. else:
  290. https_info = ""
  291. logger.info("%s request for %r%s received from %s%s%s",
  292. request_method, unsafe_path, depthinfo,
  293. remote_host, remote_useragent, https_info)
  294. if self._request_header_on_debug:
  295. logger.debug("Request header:\n%s",
  296. pprint.pformat(self._scrub_headers(environ)))
  297. else:
  298. logger.debug("Request header: suppressed by config/option [logging] request_header_on_debug")
  299. # SCRIPT_NAME is already removed from PATH_INFO, according to the
  300. # WSGI specification.
  301. # Reverse proxies can overwrite SCRIPT_NAME with X-SCRIPT-NAME header
  302. if self._script_name and (reverse_proxy is True):
  303. base_prefix_src = "config"
  304. base_prefix = self._script_name
  305. else:
  306. base_prefix_src = ("HTTP_X_SCRIPT_NAME" if "HTTP_X_SCRIPT_NAME" in
  307. environ else "SCRIPT_NAME")
  308. base_prefix = environ.get(base_prefix_src, "")
  309. if base_prefix and base_prefix[0] != "/":
  310. logger.error("Base prefix (from %s) must start with '/': %r",
  311. base_prefix_src, base_prefix)
  312. if base_prefix_src == "HTTP_X_SCRIPT_NAME":
  313. return response(*httputils.BAD_REQUEST)
  314. return response(*httputils.INTERNAL_SERVER_ERROR)
  315. if base_prefix.endswith("/"):
  316. logger.warning("Base prefix (from %s) must not end with '/': %r",
  317. base_prefix_src, base_prefix)
  318. base_prefix = base_prefix.rstrip("/")
  319. if base_prefix:
  320. logger.debug("Base prefix (from %s): %r", base_prefix_src, base_prefix)
  321. # Sanitize request URI (a WSGI server indicates with an empty path,
  322. # that the URL targets the application root without a trailing slash)
  323. path = pathutils.sanitize_path(unsafe_path)
  324. logger.debug("Sanitized path: %r", path)
  325. if (reverse_proxy is True) and (len(base_prefix) > 0):
  326. if path.startswith(base_prefix):
  327. path_new = path.removeprefix(base_prefix)
  328. logger.debug("Called by reverse proxy, remove base prefix %r from path: %r => %r", base_prefix, path, path_new)
  329. path = path_new
  330. else:
  331. if self._auth_type in ['remote_user', 'http_remote_user', 'http_x_remote_user'] and self._web_type == 'internal':
  332. logger.warning("Called by reverse proxy, cannot remove base prefix %r from path: %r as not matching (may cause authentication issues using internal WebUI)", base_prefix, path)
  333. else:
  334. logger.debug("Called by reverse proxy, cannot remove base prefix %r from path: %r as not matching", base_prefix, path)
  335. # Get function corresponding to method
  336. function = getattr(self, "do_%s" % request_method, None)
  337. if not function:
  338. return response(*httputils.METHOD_NOT_ALLOWED)
  339. # Redirect all "…/.well-known/{caldav,carddav}" paths to "/".
  340. # This shouldn't be necessary but some clients like TbSync require it.
  341. # Status must be MOVED PERMANENTLY using FOUND causes problems
  342. if (path.rstrip("/").endswith("/.well-known/caldav") or
  343. path.rstrip("/").endswith("/.well-known/carddav")):
  344. return response(*httputils.redirect(
  345. base_prefix + "/", client.MOVED_PERMANENTLY))
  346. # Return NOT FOUND for all other paths containing ".well-known"
  347. if path.endswith("/.well-known") or "/.well-known/" in path:
  348. return response(*httputils.NOT_FOUND)
  349. # Ask authentication backend to check rights
  350. login = password = ""
  351. external_login = self._auth.get_external_login(environ)
  352. authorization = environ.get("HTTP_AUTHORIZATION", "")
  353. if external_login:
  354. login, password = external_login
  355. login, password = login or "", password or ""
  356. elif authorization.startswith("Basic"):
  357. authorization = authorization[len("Basic"):].strip()
  358. login, password = httputils.decode_request(
  359. self.configuration, environ, base64.b64decode(
  360. authorization.encode("ascii"))).split(":", 1)
  361. (user, info) = self._auth.login(login, password, context) or ("", "") if login else ("", "")
  362. if self.configuration.get("auth", "type") == "ldap":
  363. try:
  364. logger.debug("Groups received from LDAP: %r", ",".join(self._auth._ldap_groups))
  365. self._rights._user_groups = self._auth._ldap_groups
  366. except AttributeError:
  367. pass
  368. if user and login == user:
  369. logger.info("Successful login: %r (%s)", user, info)
  370. elif user:
  371. logger.info("Successful login: %r -> %r (%s)", login, user, info)
  372. elif login:
  373. logger.warning("Failed login attempt from %s: %r (%s)",
  374. remote_host, login, info)
  375. # Random delay to avoid timing oracles and bruteforce attacks
  376. if self._auth_delay > 0:
  377. random_delay = self._auth_delay * (0.5 + random.random())
  378. logger.debug("Failed login, sleeping random: %.3f sec", random_delay)
  379. time.sleep(random_delay)
  380. if user and not pathutils.is_safe_path_component(user):
  381. # Prevent usernames like "user/calendar.ics"
  382. logger.info("Refused unsafe username: %r", user)
  383. user = ""
  384. # Create principal collection
  385. if user:
  386. principal_path = "/%s/" % user
  387. with self._storage.acquire_lock("r", user):
  388. principal = next(iter(self._storage.discover(
  389. principal_path, depth="1")), None)
  390. if not principal:
  391. if "W" in self._rights.authorization(user, principal_path):
  392. with self._storage.acquire_lock("w", user):
  393. try:
  394. new_coll, _, _ = self._storage.create_collection(principal_path)
  395. if new_coll:
  396. jsn_coll = self.configuration.get("storage", "predefined_collections")
  397. for (name_coll, props) in jsn_coll.items():
  398. try:
  399. self._storage.create_collection(principal_path + name_coll, props=props)
  400. except ValueError as e:
  401. logger.warning("Failed to create predefined collection %r: %s", name_coll, e)
  402. except ValueError as e:
  403. logger.warning("Failed to create principal "
  404. "collection %r: %s", user, e)
  405. user = ""
  406. else:
  407. logger.warning("Access to principal path %r denied by "
  408. "rights backend", principal_path)
  409. if self._internal_server:
  410. # Verify content length
  411. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  412. if content_length:
  413. if (self._max_content_length > 0 and
  414. content_length > self._max_content_length):
  415. logger.info("Request body too large: %d", content_length)
  416. return response(*httputils.REQUEST_ENTITY_TOO_LARGE)
  417. if not login or user:
  418. # Profiling
  419. if self._profiling_per_request:
  420. profiler = cProfile.Profile()
  421. profiler.enable()
  422. elif self._profiling_per_request_method:
  423. self.profiler_per_request_method[request_method].enable()
  424. status, headers, answer = function(
  425. environ, base_prefix, path, user, remote_host, remote_useragent)
  426. # Profiling
  427. if self._profiling_per_request:
  428. if profiler is not None:
  429. profiler.disable()
  430. elif self._profiling_per_request_method:
  431. self.profiler_per_request_method[request_method].disable()
  432. if (status, headers, answer) == httputils.NOT_ALLOWED:
  433. logger.info("Access to %r denied for %s", path,
  434. repr(user) if user else "anonymous user")
  435. else:
  436. status, headers, answer = httputils.NOT_ALLOWED
  437. if ((status, headers, answer) == httputils.NOT_ALLOWED and not user and
  438. not external_login):
  439. # Unknown or unauthorized user
  440. logger.debug("Asking client for authentication")
  441. status = client.UNAUTHORIZED
  442. headers = dict(headers)
  443. headers.update({
  444. "WWW-Authenticate":
  445. "Basic realm=\"%s\"" % self._auth_realm})
  446. return response(status, headers, answer)