report.py 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293
  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. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  6. #
  7. # This library is free software: you can redistribute it and/or modify
  8. # it under the terms of the GNU General Public License as published by
  9. # the Free Software Foundation, either version 3 of the License, or
  10. # (at your option) any later version.
  11. #
  12. # This library is distributed in the hope that it will be useful,
  13. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  14. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  15. # GNU General Public License for more details.
  16. #
  17. # You should have received a copy of the GNU General Public License
  18. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  19. import contextlib
  20. import posixpath
  21. import socket
  22. from http import client
  23. from urllib.parse import unquote, urlparse
  24. from xml.etree import ElementTree as ET
  25. from radicale import app, httputils, pathutils, storage, xmlutils
  26. from radicale.item import filter as radicale_filter
  27. from radicale.log import logger
  28. def xml_report(base_prefix, path, xml_request, collection, encoding,
  29. unlock_storage_fn):
  30. """Read and answer REPORT requests.
  31. Read rfc3253-3.6 for info.
  32. """
  33. multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
  34. if xml_request is None:
  35. return client.MULTI_STATUS, multistatus
  36. root = xml_request
  37. if root.tag in (
  38. xmlutils.make_clark("D:principal-search-property-set"),
  39. xmlutils.make_clark("D:principal-property-search"),
  40. xmlutils.make_clark("D:expand-property")):
  41. # We don't support searching for principals or indirect retrieving of
  42. # properties, just return an empty result.
  43. # InfCloud asks for expand-property reports (even if we don't announce
  44. # support for them) and stops working if an error code is returned.
  45. logger.warning("Unsupported REPORT method %r on %r requested",
  46. xmlutils.make_human_tag(root.tag), path)
  47. return client.MULTI_STATUS, multistatus
  48. if (root.tag == xmlutils.make_clark("C:calendar-multiget") and
  49. collection.get_meta("tag") != "VCALENDAR" or
  50. root.tag == xmlutils.make_clark("CR:addressbook-multiget") and
  51. collection.get_meta("tag") != "VADDRESSBOOK" or
  52. root.tag == xmlutils.make_clark("D:sync-collection") and
  53. collection.get_meta("tag") not in ("VADDRESSBOOK", "VCALENDAR")):
  54. logger.warning("Invalid REPORT method %r on %r requested",
  55. xmlutils.make_human_tag(root.tag), path)
  56. return (client.FORBIDDEN,
  57. xmlutils.webdav_error("D:supported-report"))
  58. prop_element = root.find(xmlutils.make_clark("D:prop"))
  59. props = (
  60. [prop.tag for prop in prop_element]
  61. if prop_element is not None else [])
  62. if root.tag in (
  63. xmlutils.make_clark("C:calendar-multiget"),
  64. xmlutils.make_clark("CR:addressbook-multiget")):
  65. # Read rfc4791-7.9 for info
  66. hreferences = set()
  67. for href_element in root.findall(xmlutils.make_clark("D:href")):
  68. href_path = pathutils.sanitize_path(
  69. unquote(urlparse(href_element.text).path))
  70. if (href_path + "/").startswith(base_prefix + "/"):
  71. hreferences.add(href_path[len(base_prefix):])
  72. else:
  73. logger.warning("Skipping invalid path %r in REPORT request on "
  74. "%r", href_path, path)
  75. elif root.tag == xmlutils.make_clark("D:sync-collection"):
  76. old_sync_token_element = root.find(
  77. xmlutils.make_clark("D:sync-token"))
  78. old_sync_token = ""
  79. if old_sync_token_element is not None and old_sync_token_element.text:
  80. old_sync_token = old_sync_token_element.text.strip()
  81. logger.debug("Client provided sync token: %r", old_sync_token)
  82. try:
  83. sync_token, names = collection.sync(old_sync_token)
  84. except ValueError as e:
  85. # Invalid sync token
  86. logger.warning("Client provided invalid sync token %r: %s",
  87. old_sync_token, e, exc_info=True)
  88. # client.CONFLICT doesn't work with some clients (e.g. InfCloud)
  89. return (client.FORBIDDEN,
  90. xmlutils.webdav_error("D:valid-sync-token"))
  91. hreferences = (pathutils.unstrip_path(
  92. posixpath.join(collection.path, n)) for n in names)
  93. # Append current sync token to response
  94. sync_token_element = ET.Element(xmlutils.make_clark("D:sync-token"))
  95. sync_token_element.text = sync_token
  96. multistatus.append(sync_token_element)
  97. else:
  98. hreferences = (path,)
  99. filters = (
  100. root.findall("./%s" % xmlutils.make_clark("C:filter")) +
  101. root.findall("./%s" % xmlutils.make_clark("CR:filter")))
  102. def retrieve_items(collection, hreferences, multistatus):
  103. """Retrieves all items that are referenced in ``hreferences`` from
  104. ``collection`` and adds 404 responses for missing and invalid items
  105. to ``multistatus``."""
  106. collection_requested = False
  107. def get_names():
  108. """Extracts all names from references in ``hreferences`` and adds
  109. 404 responses for invalid references to ``multistatus``.
  110. If the whole collections is referenced ``collection_requested``
  111. gets set to ``True``."""
  112. nonlocal collection_requested
  113. for hreference in hreferences:
  114. try:
  115. name = pathutils.name_from_path(hreference, collection)
  116. except ValueError as e:
  117. logger.warning("Skipping invalid path %r in REPORT request"
  118. " on %r: %s", hreference, path, e)
  119. response = xml_item_response(base_prefix, hreference,
  120. found_item=False)
  121. multistatus.append(response)
  122. continue
  123. if name:
  124. # Reference is an item
  125. yield name
  126. else:
  127. # Reference is a collection
  128. collection_requested = True
  129. for name, item in collection.get_multi(get_names()):
  130. if not item:
  131. uri = pathutils.unstrip_path(
  132. posixpath.join(collection.path, name))
  133. response = xml_item_response(base_prefix, uri,
  134. found_item=False)
  135. multistatus.append(response)
  136. else:
  137. yield item, False
  138. if collection_requested:
  139. yield from collection.get_filtered(filters)
  140. # Retrieve everything required for finishing the request.
  141. retrieved_items = list(retrieve_items(collection, hreferences,
  142. multistatus))
  143. collection_tag = collection.get_meta("tag")
  144. # Don't access storage after this!
  145. unlock_storage_fn()
  146. def match(item, filter_):
  147. tag = collection_tag
  148. if (tag == "VCALENDAR" and
  149. filter_.tag != xmlutils.make_clark("C:%s" % filter_)):
  150. if len(filter_) == 0:
  151. return True
  152. if len(filter_) > 1:
  153. raise ValueError("Filter with %d children" % len(filter_))
  154. if filter_[0].tag != xmlutils.make_clark("C:comp-filter"):
  155. raise ValueError("Unexpected %r in filter" % filter_[0].tag)
  156. return radicale_filter.comp_match(item, filter_[0])
  157. if (tag == "VADDRESSBOOK" and
  158. filter_.tag != xmlutils.make_clark("CR:%s" % filter_)):
  159. for child in filter_:
  160. if child.tag != xmlutils.make_clark("CR:prop-filter"):
  161. raise ValueError("Unexpected %r in filter" % child.tag)
  162. test = filter_.get("test", "anyof")
  163. if test == "anyof":
  164. return any(
  165. radicale_filter.prop_match(item.vobject_item, f, "CR")
  166. for f in filter_)
  167. if test == "allof":
  168. return all(
  169. radicale_filter.prop_match(item.vobject_item, f, "CR")
  170. for f in filter_)
  171. raise ValueError("Unsupported filter test: %r" % test)
  172. raise ValueError("unsupported filter %r for %r" % (filter_.tag, tag))
  173. while retrieved_items:
  174. # ``item.vobject_item`` might be accessed during filtering.
  175. # Don't keep reference to ``item``, because VObject requires a lot of
  176. # memory.
  177. item, filters_matched = retrieved_items.pop(0)
  178. if filters and not filters_matched:
  179. try:
  180. if not all(match(item, filter_) for filter_ in filters):
  181. continue
  182. except ValueError as e:
  183. raise ValueError("Failed to filter item %r from %r: %s" %
  184. (item.href, collection.path, e)) from e
  185. except Exception as e:
  186. raise RuntimeError("Failed to filter item %r from %r: %s" %
  187. (item.href, collection.path, e)) from e
  188. found_props = []
  189. not_found_props = []
  190. for tag in props:
  191. element = ET.Element(tag)
  192. if tag == xmlutils.make_clark("D:getetag"):
  193. element.text = item.etag
  194. found_props.append(element)
  195. elif tag == xmlutils.make_clark("D:getcontenttype"):
  196. element.text = xmlutils.get_content_type(item, encoding)
  197. found_props.append(element)
  198. elif tag in (
  199. xmlutils.make_clark("C:calendar-data"),
  200. xmlutils.make_clark("CR:address-data")):
  201. element.text = item.serialize()
  202. found_props.append(element)
  203. else:
  204. not_found_props.append(element)
  205. uri = pathutils.unstrip_path(
  206. posixpath.join(collection.path, item.href))
  207. multistatus.append(xml_item_response(
  208. base_prefix, uri, found_props=found_props,
  209. not_found_props=not_found_props, found_item=True))
  210. return client.MULTI_STATUS, multistatus
  211. def xml_item_response(base_prefix, href, found_props=(), not_found_props=(),
  212. found_item=True):
  213. response = ET.Element(xmlutils.make_clark("D:response"))
  214. href_tag = ET.Element(xmlutils.make_clark("D:href"))
  215. href_tag.text = xmlutils.make_href(base_prefix, href)
  216. response.append(href_tag)
  217. if found_item:
  218. for code, props in ((200, found_props), (404, not_found_props)):
  219. if props:
  220. propstat = ET.Element(xmlutils.make_clark("D:propstat"))
  221. status = ET.Element(xmlutils.make_clark("D:status"))
  222. status.text = xmlutils.make_response(code)
  223. prop_tag = ET.Element(xmlutils.make_clark("D:prop"))
  224. for prop in props:
  225. prop_tag.append(prop)
  226. propstat.append(prop_tag)
  227. propstat.append(status)
  228. response.append(propstat)
  229. else:
  230. status = ET.Element(xmlutils.make_clark("D:status"))
  231. status.text = xmlutils.make_response(404)
  232. response.append(status)
  233. return response
  234. class ApplicationReportMixin:
  235. def do_REPORT(self, environ, base_prefix, path, user):
  236. """Manage REPORT request."""
  237. access = app.Access(self._rights, user, path)
  238. if not access.check("r"):
  239. return httputils.NOT_ALLOWED
  240. try:
  241. xml_content = self._read_xml_content(environ)
  242. except RuntimeError as e:
  243. logger.warning(
  244. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  245. return httputils.BAD_REQUEST
  246. except socket.timeout:
  247. logger.debug("client timed out", exc_info=True)
  248. return httputils.REQUEST_TIMEOUT
  249. with contextlib.ExitStack() as lock_stack:
  250. lock_stack.enter_context(self._storage.acquire_lock("r", user))
  251. item = next(self._storage.discover(path), None)
  252. if not item:
  253. return httputils.NOT_FOUND
  254. if not access.check("r", item):
  255. return httputils.NOT_ALLOWED
  256. if isinstance(item, storage.BaseCollection):
  257. collection = item
  258. else:
  259. collection = item.collection
  260. headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
  261. try:
  262. status, xml_answer = xml_report(
  263. base_prefix, path, xml_content, collection, self._encoding,
  264. lock_stack.close)
  265. except ValueError as e:
  266. logger.warning(
  267. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  268. return httputils.BAD_REQUEST
  269. return (status, headers, self._write_xml_content(xml_answer))