__init__.py 37 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865
  1. # This file is part of Radicale Server - Calendar Server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2008-2017 Guillaume Ayoub
  5. #
  6. # This library is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This library is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. Radicale WSGI application.
  20. Can be used with an external WSGI server or the built-in server.
  21. """
  22. import base64
  23. import datetime
  24. import io
  25. import itertools
  26. import logging
  27. import os
  28. import pkg_resources
  29. import posixpath
  30. import pprint
  31. import random
  32. import socket
  33. import threading
  34. import time
  35. import zlib
  36. from http import client
  37. from urllib.parse import urlparse
  38. from xml.etree import ElementTree as ET
  39. import vobject
  40. from radicale import auth, config, log, rights, storage, web, xmlutils
  41. from radicale.log import logger
  42. VERSION = pkg_resources.get_distribution('radicale').version
  43. NOT_ALLOWED = (
  44. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  45. "Access to the requested resource forbidden.")
  46. FORBIDDEN = (
  47. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  48. "Action on the requested resource refused.")
  49. BAD_REQUEST = (
  50. client.BAD_REQUEST, (("Content-Type", "text/plain"),), "Bad Request")
  51. NOT_FOUND = (
  52. client.NOT_FOUND, (("Content-Type", "text/plain"),),
  53. "The requested resource could not be found.")
  54. CONFLICT = (
  55. client.CONFLICT, (("Content-Type", "text/plain"),),
  56. "Conflict in the request.")
  57. WEBDAV_PRECONDITION_FAILED = (
  58. client.CONFLICT, (("Content-Type", "text/plain"),),
  59. "WebDAV precondition failed.")
  60. METHOD_NOT_ALLOWED = (
  61. client.METHOD_NOT_ALLOWED, (("Content-Type", "text/plain"),),
  62. "The method is not allowed on the requested resource.")
  63. PRECONDITION_FAILED = (
  64. client.PRECONDITION_FAILED,
  65. (("Content-Type", "text/plain"),), "Precondition failed.")
  66. REQUEST_TIMEOUT = (
  67. client.REQUEST_TIMEOUT, (("Content-Type", "text/plain"),),
  68. "Connection timed out.")
  69. REQUEST_ENTITY_TOO_LARGE = (
  70. client.REQUEST_ENTITY_TOO_LARGE, (("Content-Type", "text/plain"),),
  71. "Request body too large.")
  72. REMOTE_DESTINATION = (
  73. client.BAD_GATEWAY, (("Content-Type", "text/plain"),),
  74. "Remote destination not supported.")
  75. DIRECTORY_LISTING = (
  76. client.FORBIDDEN, (("Content-Type", "text/plain"),),
  77. "Directory listings are not supported.")
  78. INTERNAL_SERVER_ERROR = (
  79. client.INTERNAL_SERVER_ERROR, (("Content-Type", "text/plain"),),
  80. "A server error occurred. Please contact the administrator.")
  81. DAV_HEADERS = "1, 2, 3, calendar-access, addressbook, extended-mkcol"
  82. class Application:
  83. """WSGI application managing collections."""
  84. def __init__(self, configuration):
  85. """Initialize application."""
  86. super().__init__()
  87. self.configuration = configuration
  88. self.Auth = auth.load(configuration)
  89. self.Collection = storage.load(configuration)
  90. self.Rights = rights.load(configuration)
  91. self.Web = web.load(configuration)
  92. self.encoding = configuration.get("encoding", "request")
  93. def headers_log(self, environ):
  94. """Sanitize headers for logging."""
  95. request_environ = dict(environ)
  96. # Mask passwords
  97. mask_passwords = self.configuration.getboolean(
  98. "logging", "mask_passwords")
  99. authorization = request_environ.get("HTTP_AUTHORIZATION", "")
  100. if mask_passwords and authorization.startswith("Basic"):
  101. request_environ["HTTP_AUTHORIZATION"] = "Basic **masked**"
  102. if request_environ.get("HTTP_COOKIE"):
  103. request_environ["HTTP_COOKIE"] = "**masked**"
  104. return request_environ
  105. def decode(self, text, environ):
  106. """Try to magically decode ``text`` according to given ``environ``."""
  107. # List of charsets to try
  108. charsets = []
  109. # First append content charset given in the request
  110. content_type = environ.get("CONTENT_TYPE")
  111. if content_type and "charset=" in content_type:
  112. charsets.append(
  113. content_type.split("charset=")[1].split(";")[0].strip())
  114. # Then append default Radicale charset
  115. charsets.append(self.encoding)
  116. # Then append various fallbacks
  117. charsets.append("utf-8")
  118. charsets.append("iso8859-1")
  119. # Try to decode
  120. for charset in charsets:
  121. try:
  122. return text.decode(charset)
  123. except UnicodeDecodeError:
  124. pass
  125. raise UnicodeDecodeError
  126. def collect_allowed_items(self, items, user):
  127. """Get items from request that user is allowed to access."""
  128. read_allowed_items = []
  129. write_allowed_items = []
  130. for item in items:
  131. if isinstance(item, storage.BaseCollection):
  132. path = storage.sanitize_path("/%s/" % item.path)
  133. can_read = self.Rights.authorized(user, path, "r")
  134. can_write = self.Rights.authorized(user, path, "w")
  135. target = "collection %r" % item.path
  136. else:
  137. path = storage.sanitize_path("/%s/%s" % (item.collection.path,
  138. item.href))
  139. can_read = self.Rights.authorized_item(user, path, "r")
  140. can_write = self.Rights.authorized_item(user, path, "w")
  141. target = "item %r from %r" % (item.href, item.collection.path)
  142. text_status = []
  143. if can_read:
  144. text_status.append("read")
  145. read_allowed_items.append(item)
  146. if can_write:
  147. text_status.append("write")
  148. write_allowed_items.append(item)
  149. logger.debug(
  150. "%s has %s access to %s",
  151. repr(user) if user else "anonymous user",
  152. " and ".join(text_status) if text_status else "NO", target)
  153. return read_allowed_items, write_allowed_items
  154. def __call__(self, environ, start_response):
  155. with log.register_stream(environ["wsgi.errors"]):
  156. try:
  157. status, headers, answers = self._handle_request(environ)
  158. except Exception as e:
  159. try:
  160. method = str(environ["REQUEST_METHOD"])
  161. except Exception:
  162. method = "unknown"
  163. try:
  164. path = str(environ.get("PATH_INFO", ""))
  165. except Exception:
  166. path = ""
  167. logger.error("An exception occurred during %s request on %r: "
  168. "%s", method, path, e, exc_info=True)
  169. status, headers, answer = INTERNAL_SERVER_ERROR
  170. answer = answer.encode("ascii")
  171. status = "%d %s" % (
  172. status, client.responses.get(status, "Unknown"))
  173. headers = [
  174. ("Content-Length", str(len(answer)))] + list(headers)
  175. answers = [answer]
  176. start_response(status, headers)
  177. return answers
  178. def _handle_request(self, environ):
  179. """Manage a request."""
  180. def response(status, headers=(), answer=None):
  181. headers = dict(headers)
  182. # Set content length
  183. if answer:
  184. if hasattr(answer, "encode"):
  185. logger.debug("Response content:\n%s", answer)
  186. headers["Content-Type"] += "; charset=%s" % self.encoding
  187. answer = answer.encode(self.encoding)
  188. accept_encoding = [
  189. encoding.strip() for encoding in
  190. environ.get("HTTP_ACCEPT_ENCODING", "").split(",")
  191. if encoding.strip()]
  192. if "gzip" in accept_encoding:
  193. zcomp = zlib.compressobj(wbits=16 + zlib.MAX_WBITS)
  194. answer = zcomp.compress(answer) + zcomp.flush()
  195. headers["Content-Encoding"] = "gzip"
  196. headers["Content-Length"] = str(len(answer))
  197. # Add extra headers set in configuration
  198. if self.configuration.has_section("headers"):
  199. for key in self.configuration.options("headers"):
  200. headers[key] = self.configuration.get("headers", key)
  201. # Start response
  202. time_end = datetime.datetime.now()
  203. status = "%d %s" % (
  204. status, client.responses.get(status, "Unknown"))
  205. logger.info(
  206. "%s response status for %r%s in %.3f seconds: %s",
  207. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""),
  208. depthinfo, (time_end - time_begin).total_seconds(), status)
  209. # Return response content
  210. return status, list(headers.items()), [answer] if answer else []
  211. remote_host = "unknown"
  212. if environ.get("REMOTE_HOST"):
  213. remote_host = repr(environ["REMOTE_HOST"])
  214. elif environ.get("REMOTE_ADDR"):
  215. remote_host = environ["REMOTE_ADDR"]
  216. if environ.get("HTTP_X_FORWARDED_FOR"):
  217. remote_host = "%r (forwarded by %s)" % (
  218. environ["HTTP_X_FORWARDED_FOR"], remote_host)
  219. remote_useragent = ""
  220. if environ.get("HTTP_USER_AGENT"):
  221. remote_useragent = " using %r" % environ["HTTP_USER_AGENT"]
  222. depthinfo = ""
  223. if environ.get("HTTP_DEPTH"):
  224. depthinfo = " with depth %r" % environ["HTTP_DEPTH"]
  225. time_begin = datetime.datetime.now()
  226. logger.info(
  227. "%s request for %r%s received from %s%s",
  228. environ["REQUEST_METHOD"], environ.get("PATH_INFO", ""), depthinfo,
  229. remote_host, remote_useragent)
  230. headers = pprint.pformat(self.headers_log(environ))
  231. logger.debug("Request headers:\n%s", headers)
  232. # Let reverse proxies overwrite SCRIPT_NAME
  233. if "HTTP_X_SCRIPT_NAME" in environ:
  234. # script_name must be removed from PATH_INFO by the client.
  235. unsafe_base_prefix = environ["HTTP_X_SCRIPT_NAME"]
  236. logger.debug("Script name overwritten by client: %r",
  237. unsafe_base_prefix)
  238. else:
  239. # SCRIPT_NAME is already removed from PATH_INFO, according to the
  240. # WSGI specification.
  241. unsafe_base_prefix = environ.get("SCRIPT_NAME", "")
  242. # Sanitize base prefix
  243. base_prefix = storage.sanitize_path(unsafe_base_prefix).rstrip("/")
  244. logger.debug("Sanitized script name: %r", base_prefix)
  245. # Sanitize request URI (a WSGI server indicates with an empty path,
  246. # that the URL targets the application root without a trailing slash)
  247. path = storage.sanitize_path(environ.get("PATH_INFO", ""))
  248. logger.debug("Sanitized path: %r", path)
  249. # Get function corresponding to method
  250. function = getattr(self, "do_%s" % environ["REQUEST_METHOD"].upper())
  251. # If "/.well-known" is not available, clients query "/"
  252. if path == "/.well-known" or path.startswith("/.well-known/"):
  253. return response(*NOT_FOUND)
  254. # Ask authentication backend to check rights
  255. login = password = ""
  256. external_login = self.Auth.get_external_login(environ)
  257. authorization = environ.get("HTTP_AUTHORIZATION", "")
  258. if external_login:
  259. login, password = external_login
  260. login, password = login or "", password or ""
  261. elif authorization.startswith("Basic"):
  262. authorization = authorization[len("Basic"):].strip()
  263. login, password = self.decode(base64.b64decode(
  264. authorization.encode("ascii")), environ).split(":", 1)
  265. user = self.Auth.login(login, password) or "" if login else ""
  266. if user and login == user:
  267. logger.info("Successful login: %r", user)
  268. elif user:
  269. logger.info("Successful login: %r -> %r", login, user)
  270. elif login:
  271. logger.info("Failed login attempt: %r", login)
  272. # Random delay to avoid timing oracles and bruteforce attacks
  273. delay = self.configuration.getfloat("auth", "delay")
  274. if delay > 0:
  275. random_delay = delay * (0.5 + random.random())
  276. logger.debug("Sleeping %.3f seconds", random_delay)
  277. time.sleep(random_delay)
  278. if user and not storage.is_safe_path_component(user):
  279. # Prevent usernames like "user/calendar.ics"
  280. logger.info("Refused unsafe username: %r", user)
  281. user = ""
  282. # Create principal collection
  283. if user:
  284. principal_path = "/%s/" % user
  285. if self.Rights.authorized(user, principal_path, "w"):
  286. with self.Collection.acquire_lock("r", user):
  287. principal = next(
  288. self.Collection.discover(principal_path, depth="1"),
  289. None)
  290. if not principal:
  291. with self.Collection.acquire_lock("w", user):
  292. try:
  293. self.Collection.create_collection(principal_path)
  294. except ValueError as e:
  295. logger.warning("Failed to create principal "
  296. "collection %r: %s", user, e)
  297. user = ""
  298. else:
  299. logger.warning("Access to principal path %r denied by "
  300. "rights backend", principal_path)
  301. if self.configuration.getboolean("internal", "internal_server"):
  302. # Verify content length
  303. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  304. if content_length:
  305. max_content_length = self.configuration.getint(
  306. "server", "max_content_length")
  307. if max_content_length and content_length > max_content_length:
  308. logger.info("Request body too large: %d", content_length)
  309. return response(*REQUEST_ENTITY_TOO_LARGE)
  310. if not login or user:
  311. status, headers, answer = function(
  312. environ, base_prefix, path, user)
  313. if (status, headers, answer) == NOT_ALLOWED:
  314. logger.info("Access to %r denied for %s", path,
  315. repr(user) if user else "anonymous user")
  316. else:
  317. status, headers, answer = NOT_ALLOWED
  318. if ((status, headers, answer) == NOT_ALLOWED and not user and
  319. not external_login):
  320. # Unknown or unauthorized user
  321. logger.debug("Asking client for authentication")
  322. status = client.UNAUTHORIZED
  323. realm = self.configuration.get("auth", "realm")
  324. headers = dict(headers)
  325. headers.update({
  326. "WWW-Authenticate":
  327. "Basic realm=\"%s\"" % realm})
  328. return response(status, headers, answer)
  329. def _access(self, user, path, permission, item=None):
  330. """Check if ``user`` can access ``path`` or the parent collection.
  331. ``permission`` must either be "r" or "w".
  332. If ``item`` is given, only access to that class of item is checked.
  333. """
  334. allowed = False
  335. if not item or isinstance(item, storage.BaseCollection):
  336. allowed |= self.Rights.authorized(user, path, permission)
  337. if not item or not isinstance(item, storage.BaseCollection):
  338. allowed |= self.Rights.authorized_item(user, path, permission)
  339. return allowed
  340. def _read_raw_content(self, environ):
  341. content_length = int(environ.get("CONTENT_LENGTH") or 0)
  342. if not content_length:
  343. return b""
  344. content = environ["wsgi.input"].read(content_length)
  345. if len(content) < content_length:
  346. raise RuntimeError("Request body too short: %d" % len(content))
  347. return content
  348. def _read_content(self, environ):
  349. content = self.decode(self._read_raw_content(environ), environ)
  350. logger.debug("Request content:\n%s", content)
  351. return content
  352. def _read_xml_content(self, environ):
  353. content = self.decode(self._read_raw_content(environ), environ)
  354. if not content:
  355. return None
  356. try:
  357. xml_content = ET.fromstring(content)
  358. except ET.ParseError as e:
  359. logger.debug("Request content (Invalid XML):\n%s", content)
  360. raise RuntimeError("Failed to parse XML: %s" % e) from e
  361. if logger.isEnabledFor(logging.DEBUG):
  362. logger.debug("Request content:\n%s",
  363. xmlutils.pretty_xml(xml_content))
  364. return xml_content
  365. def _write_xml_content(self, xml_content):
  366. if logger.isEnabledFor(logging.DEBUG):
  367. logger.debug("Response content:\n%s",
  368. xmlutils.pretty_xml(xml_content))
  369. f = io.BytesIO()
  370. ET.ElementTree(xml_content).write(f, encoding=self.encoding,
  371. xml_declaration=True)
  372. return f.getvalue()
  373. def _webdav_error_response(self, namespace, name,
  374. status=WEBDAV_PRECONDITION_FAILED[0]):
  375. """Generate XML error response."""
  376. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  377. content = self._write_xml_content(
  378. xmlutils.webdav_error(namespace, name))
  379. return status, headers, content
  380. def do_DELETE(self, environ, base_prefix, path, user):
  381. """Manage DELETE request."""
  382. if not self._access(user, path, "w"):
  383. return NOT_ALLOWED
  384. with self.Collection.acquire_lock("w", user):
  385. item = next(self.Collection.discover(path), None)
  386. if not self._access(user, path, "w", item):
  387. return NOT_ALLOWED
  388. if not item:
  389. return NOT_FOUND
  390. if_match = environ.get("HTTP_IF_MATCH", "*")
  391. if if_match not in ("*", item.etag):
  392. # ETag precondition not verified, do not delete item
  393. return PRECONDITION_FAILED
  394. if isinstance(item, storage.BaseCollection):
  395. xml_answer = xmlutils.delete(base_prefix, path, item)
  396. else:
  397. xml_answer = xmlutils.delete(
  398. base_prefix, path, item.collection, item.href)
  399. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  400. return client.OK, headers, self._write_xml_content(xml_answer)
  401. def do_GET(self, environ, base_prefix, path, user):
  402. """Manage GET request."""
  403. # Redirect to .web if the root URL is requested
  404. if not path.strip("/"):
  405. web_path = ".web"
  406. if not environ.get("PATH_INFO"):
  407. web_path = posixpath.join(posixpath.basename(base_prefix),
  408. web_path)
  409. return (client.FOUND,
  410. {"Location": web_path, "Content-Type": "text/plain"},
  411. "Redirected to %s" % web_path)
  412. # Dispatch .web URL to web module
  413. if path == "/.web" or path.startswith("/.web/"):
  414. return self.Web.get(environ, base_prefix, path, user)
  415. if not self._access(user, path, "r"):
  416. return NOT_ALLOWED
  417. with self.Collection.acquire_lock("r", user):
  418. item = next(self.Collection.discover(path), None)
  419. if not self._access(user, path, "r", item):
  420. return NOT_ALLOWED
  421. if not item:
  422. return NOT_FOUND
  423. if isinstance(item, storage.BaseCollection):
  424. tag = item.get_meta("tag")
  425. if not tag:
  426. return DIRECTORY_LISTING
  427. content_type = xmlutils.MIMETYPES[tag]
  428. else:
  429. content_type = xmlutils.OBJECT_MIMETYPES[item.name]
  430. headers = {
  431. "Content-Type": content_type,
  432. "Last-Modified": item.last_modified,
  433. "ETag": item.etag}
  434. answer = item.serialize()
  435. return client.OK, headers, answer
  436. def do_HEAD(self, environ, base_prefix, path, user):
  437. """Manage HEAD request."""
  438. status, headers, answer = self.do_GET(
  439. environ, base_prefix, path, user)
  440. return status, headers, None
  441. def do_MKCALENDAR(self, environ, base_prefix, path, user):
  442. """Manage MKCALENDAR request."""
  443. if not self.Rights.authorized(user, path, "w"):
  444. return NOT_ALLOWED
  445. try:
  446. xml_content = self._read_xml_content(environ)
  447. except RuntimeError as e:
  448. logger.warning(
  449. "Bad MKCALENDAR request on %r: %s", path, e, exc_info=True)
  450. return BAD_REQUEST
  451. except socket.timeout as e:
  452. logger.debug("client timed out", exc_info=True)
  453. return REQUEST_TIMEOUT
  454. with self.Collection.acquire_lock("w", user):
  455. item = next(self.Collection.discover(path), None)
  456. if item:
  457. return self._webdav_error_response(
  458. "D", "resource-must-be-null")
  459. parent_path = storage.sanitize_path(
  460. "/%s/" % posixpath.dirname(path.strip("/")))
  461. parent_item = next(self.Collection.discover(parent_path), None)
  462. if not parent_item:
  463. return CONFLICT
  464. if (not isinstance(parent_item, storage.BaseCollection) or
  465. parent_item.get_meta("tag")):
  466. return FORBIDDEN
  467. props = xmlutils.props_from_request(xml_content)
  468. props["tag"] = "VCALENDAR"
  469. # TODO: use this?
  470. # timezone = props.get("C:calendar-timezone")
  471. try:
  472. storage.check_and_sanitize_props(props)
  473. self.Collection.create_collection(path, props=props)
  474. except ValueError as e:
  475. logger.warning(
  476. "Bad MKCALENDAR request on %r: %s", path, e, exc_info=True)
  477. return BAD_REQUEST
  478. return client.CREATED, {}, None
  479. def do_MKCOL(self, environ, base_prefix, path, user):
  480. """Manage MKCOL request."""
  481. if not self.Rights.authorized(user, path, "w"):
  482. return NOT_ALLOWED
  483. try:
  484. xml_content = self._read_xml_content(environ)
  485. except RuntimeError as e:
  486. logger.warning(
  487. "Bad MKCOL request on %r: %s", path, e, exc_info=True)
  488. return BAD_REQUEST
  489. except socket.timeout as e:
  490. logger.debug("client timed out", exc_info=True)
  491. return REQUEST_TIMEOUT
  492. with self.Collection.acquire_lock("w", user):
  493. item = next(self.Collection.discover(path), None)
  494. if item:
  495. return METHOD_NOT_ALLOWED
  496. parent_path = storage.sanitize_path(
  497. "/%s/" % posixpath.dirname(path.strip("/")))
  498. parent_item = next(self.Collection.discover(parent_path), None)
  499. if not parent_item:
  500. return CONFLICT
  501. if (not isinstance(parent_item, storage.BaseCollection) or
  502. parent_item.get_meta("tag")):
  503. return FORBIDDEN
  504. props = xmlutils.props_from_request(xml_content)
  505. try:
  506. storage.check_and_sanitize_props(props)
  507. self.Collection.create_collection(path, props=props)
  508. except ValueError as e:
  509. logger.warning(
  510. "Bad MKCOL request on %r: %s", path, e, exc_info=True)
  511. return BAD_REQUEST
  512. return client.CREATED, {}, None
  513. def do_MOVE(self, environ, base_prefix, path, user):
  514. """Manage MOVE request."""
  515. raw_dest = environ.get("HTTP_DESTINATION", "")
  516. to_url = urlparse(raw_dest)
  517. if to_url.netloc != environ["HTTP_HOST"]:
  518. logger.info("Unsupported destination address: %r", raw_dest)
  519. # Remote destination server, not supported
  520. return REMOTE_DESTINATION
  521. if not self._access(user, path, "w"):
  522. return NOT_ALLOWED
  523. to_path = storage.sanitize_path(to_url.path)
  524. if not (to_path + "/").startswith(base_prefix + "/"):
  525. logger.warning("Destination %r from MOVE request on %r doesn't "
  526. "start with base prefix", to_path, path)
  527. return NOT_ALLOWED
  528. to_path = to_path[len(base_prefix):]
  529. if not self._access(user, to_path, "w"):
  530. return NOT_ALLOWED
  531. with self.Collection.acquire_lock("w", user):
  532. item = next(self.Collection.discover(path), None)
  533. if not self._access(user, path, "w", item):
  534. return NOT_ALLOWED
  535. if not self._access(user, to_path, "w", item):
  536. return NOT_ALLOWED
  537. if not item:
  538. return NOT_FOUND
  539. if isinstance(item, storage.BaseCollection):
  540. # TODO: support moving collections
  541. return METHOD_NOT_ALLOWED
  542. to_item = next(self.Collection.discover(to_path), None)
  543. if isinstance(to_item, storage.BaseCollection):
  544. return FORBIDDEN
  545. to_parent_path = storage.sanitize_path(
  546. "/%s/" % posixpath.dirname(to_path.strip("/")))
  547. to_collection = next(
  548. self.Collection.discover(to_parent_path), None)
  549. if not to_collection:
  550. return CONFLICT
  551. tag = item.collection.get_meta("tag")
  552. if not tag or tag != to_collection.get_meta("tag"):
  553. return FORBIDDEN
  554. if to_item and environ.get("HTTP_OVERWRITE", "F") != "T":
  555. return PRECONDITION_FAILED
  556. if (to_item and item.uid != to_item.uid or
  557. not to_item and
  558. to_collection.path != item.collection.path and
  559. to_collection.has_uid(item.uid)):
  560. return self._webdav_error_response(
  561. "C" if tag == "VCALENDAR" else "CR", "no-uid-conflict")
  562. to_href = posixpath.basename(to_path.strip("/"))
  563. try:
  564. self.Collection.move(item, to_collection, to_href)
  565. except ValueError as e:
  566. logger.warning(
  567. "Bad MOVE request on %r: %s", path, e, exc_info=True)
  568. return BAD_REQUEST
  569. return client.NO_CONTENT if to_item else client.CREATED, {}, None
  570. def do_OPTIONS(self, environ, base_prefix, path, user):
  571. """Manage OPTIONS request."""
  572. headers = {
  573. "Allow": ", ".join(
  574. name[3:] for name in dir(self) if name.startswith("do_")),
  575. "DAV": DAV_HEADERS}
  576. return client.OK, headers, None
  577. def do_PROPFIND(self, environ, base_prefix, path, user):
  578. """Manage PROPFIND request."""
  579. if not self._access(user, path, "r"):
  580. return NOT_ALLOWED
  581. try:
  582. xml_content = self._read_xml_content(environ)
  583. except RuntimeError as e:
  584. logger.warning(
  585. "Bad PROPFIND request on %r: %s", path, e, exc_info=True)
  586. return BAD_REQUEST
  587. except socket.timeout as e:
  588. logger.debug("client timed out", exc_info=True)
  589. return REQUEST_TIMEOUT
  590. with self.Collection.acquire_lock("r", user):
  591. items = self.Collection.discover(
  592. path, environ.get("HTTP_DEPTH", "0"))
  593. # take root item for rights checking
  594. item = next(items, None)
  595. if not self._access(user, path, "r", item):
  596. return NOT_ALLOWED
  597. if not item:
  598. return NOT_FOUND
  599. # put item back
  600. items = itertools.chain([item], items)
  601. read_items, write_items = self.collect_allowed_items(items, user)
  602. headers = {"DAV": DAV_HEADERS,
  603. "Content-Type": "text/xml; charset=%s" % self.encoding}
  604. status, xml_answer = xmlutils.propfind(
  605. base_prefix, path, xml_content, read_items, write_items, user)
  606. if status == client.FORBIDDEN:
  607. return NOT_ALLOWED
  608. return status, headers, self._write_xml_content(xml_answer)
  609. def do_PROPPATCH(self, environ, base_prefix, path, user):
  610. """Manage PROPPATCH request."""
  611. if not self.Rights.authorized(user, path, "w"):
  612. return NOT_ALLOWED
  613. try:
  614. xml_content = self._read_xml_content(environ)
  615. except RuntimeError as e:
  616. logger.warning(
  617. "Bad PROPPATCH request on %r: %s", path, e, exc_info=True)
  618. return BAD_REQUEST
  619. except socket.timeout as e:
  620. logger.debug("client timed out", exc_info=True)
  621. return REQUEST_TIMEOUT
  622. with self.Collection.acquire_lock("w", user):
  623. item = next(self.Collection.discover(path), None)
  624. if not item:
  625. return NOT_FOUND
  626. if not isinstance(item, storage.BaseCollection):
  627. return FORBIDDEN
  628. headers = {"DAV": DAV_HEADERS,
  629. "Content-Type": "text/xml; charset=%s" % self.encoding}
  630. try:
  631. xml_answer = xmlutils.proppatch(base_prefix, path, xml_content,
  632. item)
  633. except ValueError as e:
  634. logger.warning(
  635. "Bad PROPPATCH request on %r: %s", path, e, exc_info=True)
  636. return BAD_REQUEST
  637. return (client.MULTI_STATUS, headers,
  638. self._write_xml_content(xml_answer))
  639. def do_PUT(self, environ, base_prefix, path, user):
  640. """Manage PUT request."""
  641. if not self._access(user, path, "w"):
  642. return NOT_ALLOWED
  643. try:
  644. content = self._read_content(environ)
  645. except RuntimeError as e:
  646. logger.warning("Bad PUT request on %r: %s", path, e, exc_info=True)
  647. return BAD_REQUEST
  648. except socket.timeout as e:
  649. logger.debug("client timed out", exc_info=True)
  650. return REQUEST_TIMEOUT
  651. with self.Collection.acquire_lock("w", user):
  652. parent_path = storage.sanitize_path(
  653. "/%s/" % posixpath.dirname(path.strip("/")))
  654. item = next(self.Collection.discover(path), None)
  655. parent_item = next(self.Collection.discover(parent_path), None)
  656. if not parent_item:
  657. return CONFLICT
  658. write_whole_collection = (
  659. isinstance(item, storage.BaseCollection) or
  660. not parent_item.get_meta("tag"))
  661. if write_whole_collection:
  662. if not self.Rights.authorized(user, path, "w"):
  663. return NOT_ALLOWED
  664. elif not self.Rights.authorized_item(user, path, "w"):
  665. return NOT_ALLOWED
  666. etag = environ.get("HTTP_IF_MATCH", "")
  667. if not item and etag:
  668. # Etag asked but no item found: item has been removed
  669. return PRECONDITION_FAILED
  670. if item and etag and item.etag != etag:
  671. # Etag asked but item not matching: item has changed
  672. return PRECONDITION_FAILED
  673. match = environ.get("HTTP_IF_NONE_MATCH", "") == "*"
  674. if item and match:
  675. # Creation asked but item found: item can't be replaced
  676. return PRECONDITION_FAILED
  677. try:
  678. items = tuple(vobject.readComponents(content or ""))
  679. if write_whole_collection:
  680. content_type = environ.get("CONTENT_TYPE",
  681. "").split(";")[0]
  682. tags = {value: key
  683. for key, value in xmlutils.MIMETYPES.items()}
  684. tag = tags.get(content_type)
  685. if items and items[0].name == "VCALENDAR":
  686. tag = "VCALENDAR"
  687. elif items and items[0].name in ("VCARD", "VLIST"):
  688. tag = "VADDRESSBOOK"
  689. else:
  690. tag = parent_item.get_meta("tag")
  691. storage.check_and_sanitize_items(
  692. items, is_collection=write_whole_collection, tag=tag)
  693. except Exception as e:
  694. logger.warning(
  695. "Bad PUT request on %r: %s", path, e, exc_info=True)
  696. return BAD_REQUEST
  697. if write_whole_collection:
  698. props = {}
  699. if tag:
  700. props["tag"] = tag
  701. if tag == "VCALENDAR" and items:
  702. if hasattr(items[0], "x_wr_calname"):
  703. calname = items[0].x_wr_calname.value
  704. if calname:
  705. props["D:displayname"] = calname
  706. if hasattr(items[0], "x_wr_caldesc"):
  707. caldesc = items[0].x_wr_caldesc.value
  708. if caldesc:
  709. props["C:calendar-description"] = caldesc
  710. try:
  711. storage.check_and_sanitize_props(props)
  712. new_item = self.Collection.create_collection(
  713. path, items, props)
  714. except ValueError as e:
  715. logger.warning(
  716. "Bad PUT request on %r: %s", path, e, exc_info=True)
  717. return BAD_REQUEST
  718. else:
  719. uid = storage.get_uid_from_object(items[0])
  720. if (item and item.uid != uid or
  721. not item and parent_item.has_uid(uid)):
  722. return self._webdav_error_response(
  723. "C" if tag == "VCALENDAR" else "CR",
  724. "no-uid-conflict")
  725. href = posixpath.basename(path.strip("/"))
  726. try:
  727. if tag and not parent_item.get_meta("tag"):
  728. new_props = parent_item.get_meta()
  729. new_props["tag"] = tag
  730. storage.check_and_sanitize_props(new_props)
  731. parent_item.set_meta(new_props)
  732. new_item = parent_item.upload(href, items[0])
  733. except ValueError as e:
  734. logger.warning(
  735. "Bad PUT request on %r: %s", path, e, exc_info=True)
  736. return BAD_REQUEST
  737. headers = {"ETag": new_item.etag}
  738. return client.CREATED, headers, None
  739. def do_REPORT(self, environ, base_prefix, path, user):
  740. """Manage REPORT request."""
  741. if not self._access(user, path, "r"):
  742. return NOT_ALLOWED
  743. try:
  744. xml_content = self._read_xml_content(environ)
  745. except RuntimeError as e:
  746. logger.warning(
  747. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  748. return BAD_REQUEST
  749. except socket.timeout as e:
  750. logger.debug("client timed out", exc_info=True)
  751. return REQUEST_TIMEOUT
  752. with self.Collection.acquire_lock("r", user):
  753. item = next(self.Collection.discover(path), None)
  754. if not self._access(user, path, "r", item):
  755. return NOT_ALLOWED
  756. if not item:
  757. return NOT_FOUND
  758. if isinstance(item, storage.BaseCollection):
  759. collection = item
  760. else:
  761. collection = item.collection
  762. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  763. try:
  764. status, xml_answer = xmlutils.report(
  765. base_prefix, path, xml_content, collection)
  766. except ValueError as e:
  767. logger.warning(
  768. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  769. return BAD_REQUEST
  770. return (status, headers, self._write_xml_content(xml_answer))
  771. _application = None
  772. _application_config_path = None
  773. _application_lock = threading.Lock()
  774. def _init_application(config_path, wsgi_errors):
  775. global _application, _application_config_path
  776. with _application_lock:
  777. if _application is not None:
  778. return
  779. log.setup()
  780. with log.register_stream(wsgi_errors):
  781. _application_config_path = config_path
  782. configuration = config.load([config_path] if config_path else [],
  783. ignore_missing_paths=False)
  784. log.set_level(configuration.get("logging", "level"))
  785. _application = Application(configuration)
  786. def application(environ, start_response):
  787. config_path = environ.get("RADICALE_CONFIG",
  788. os.environ.get("RADICALE_CONFIG"))
  789. if _application is None:
  790. _init_application(config_path, environ["wsgi.errors"])
  791. if _application_config_path != config_path:
  792. raise ValueError("RADICALE_CONFIG must not change: %s != %s" %
  793. (repr(config_path), repr(_application_config_path)))
  794. return _application(environ, start_response)