__init__.py 28 KB

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