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 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_tag("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_tag("D", "principal-search-property-set"),
  39. xmlutils.make_tag("D", "principal-property-search"),
  40. xmlutils.make_tag("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.tag_from_clark(root.tag), path)
  47. return client.MULTI_STATUS, multistatus
  48. if (root.tag == xmlutils.make_tag("C", "calendar-multiget") and
  49. collection.get_meta("tag") != "VCALENDAR" or
  50. root.tag == xmlutils.make_tag("CR", "addressbook-multiget") and
  51. collection.get_meta("tag") != "VADDRESSBOOK" or
  52. root.tag == xmlutils.make_tag("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.tag_from_clark(root.tag), path)
  56. return (client.CONFLICT,
  57. xmlutils.webdav_error("D", "supported-report"))
  58. prop_element = root.find(xmlutils.make_tag("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_tag("C", "calendar-multiget"),
  64. xmlutils.make_tag("CR", "addressbook-multiget")):
  65. # Read rfc4791-7.9 for info
  66. hreferences = set()
  67. for href_element in root.findall(xmlutils.make_tag("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_tag("D", "sync-collection"):
  76. old_sync_token_element = root.find(
  77. xmlutils.make_tag("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. return (client.CONFLICT,
  89. xmlutils.webdav_error("D", "valid-sync-token"))
  90. hreferences = (pathutils.unstrip_path(
  91. posixpath.join(collection.path, n)) for n in names)
  92. # Append current sync token to response
  93. sync_token_element = ET.Element(xmlutils.make_tag("D", "sync-token"))
  94. sync_token_element.text = sync_token
  95. multistatus.append(sync_token_element)
  96. else:
  97. hreferences = (path,)
  98. filters = (
  99. root.findall("./%s" % xmlutils.make_tag("C", "filter")) +
  100. root.findall("./%s" % xmlutils.make_tag("CR", "filter")))
  101. def retrieve_items(collection, hreferences, multistatus):
  102. """Retrieves all items that are referenced in ``hreferences`` from
  103. ``collection`` and adds 404 responses for missing and invalid items
  104. to ``multistatus``."""
  105. collection_requested = False
  106. def get_names():
  107. """Extracts all names from references in ``hreferences`` and adds
  108. 404 responses for invalid references to ``multistatus``.
  109. If the whole collections is referenced ``collection_requested``
  110. gets set to ``True``."""
  111. nonlocal collection_requested
  112. for hreference in hreferences:
  113. try:
  114. name = pathutils.name_from_path(hreference, collection)
  115. except ValueError as e:
  116. logger.warning("Skipping invalid path %r in REPORT request"
  117. " on %r: %s", hreference, path, e)
  118. response = xml_item_response(base_prefix, hreference,
  119. found_item=False)
  120. multistatus.append(response)
  121. continue
  122. if name:
  123. # Reference is an item
  124. yield name
  125. else:
  126. # Reference is a collection
  127. collection_requested = True
  128. for name, item in collection.get_multi(get_names()):
  129. if not item:
  130. uri = pathutils.unstrip_path(
  131. posixpath.join(collection.path, name))
  132. response = xml_item_response(base_prefix, uri,
  133. found_item=False)
  134. multistatus.append(response)
  135. else:
  136. yield item, False
  137. if collection_requested:
  138. yield from collection.get_filtered(filters)
  139. # Retrieve everything required for finishing the request.
  140. retrieved_items = list(retrieve_items(collection, hreferences,
  141. multistatus))
  142. collection_tag = collection.get_meta("tag")
  143. # Don't access storage after this!
  144. unlock_storage_fn()
  145. def match(item, filter_):
  146. tag = collection_tag
  147. if (tag == "VCALENDAR" and
  148. filter_.tag != xmlutils.make_tag("C", filter_)):
  149. if len(filter_) == 0:
  150. return True
  151. if len(filter_) > 1:
  152. raise ValueError("Filter with %d children" % len(filter_))
  153. if filter_[0].tag != xmlutils.make_tag("C", "comp-filter"):
  154. raise ValueError("Unexpected %r in filter" % filter_[0].tag)
  155. return radicale_filter.comp_match(item, filter_[0])
  156. if (tag == "VADDRESSBOOK" and
  157. filter_.tag != xmlutils.make_tag("CR", filter_)):
  158. for child in filter_:
  159. if child.tag != xmlutils.make_tag("CR", "prop-filter"):
  160. raise ValueError("Unexpected %r in filter" % child.tag)
  161. test = filter_.get("test", "anyof")
  162. if test == "anyof":
  163. return any(
  164. radicale_filter.prop_match(item.vobject_item, f, "CR")
  165. for f in filter_)
  166. if test == "allof":
  167. return all(
  168. radicale_filter.prop_match(item.vobject_item, f, "CR")
  169. for f in filter_)
  170. raise ValueError("Unsupported filter test: %r" % test)
  171. return all(radicale_filter.prop_match(item.vobject_item, f, "CR")
  172. for f in filter_)
  173. raise ValueError("unsupported filter %r for %r" % (filter_.tag, tag))
  174. while retrieved_items:
  175. # ``item.vobject_item`` might be accessed during filtering.
  176. # Don't keep reference to ``item``, because VObject requires a lot of
  177. # memory.
  178. item, filters_matched = retrieved_items.pop(0)
  179. if filters and not filters_matched:
  180. try:
  181. if not all(match(item, filter_) for filter_ in filters):
  182. continue
  183. except ValueError as e:
  184. raise ValueError("Failed to filter item %r from %r: %s" %
  185. (item.href, collection.path, e)) from e
  186. except Exception as e:
  187. raise RuntimeError("Failed to filter item %r from %r: %s" %
  188. (item.href, collection.path, e)) from e
  189. found_props = []
  190. not_found_props = []
  191. for tag in props:
  192. element = ET.Element(tag)
  193. if tag == xmlutils.make_tag("D", "getetag"):
  194. element.text = item.etag
  195. found_props.append(element)
  196. elif tag == xmlutils.make_tag("D", "getcontenttype"):
  197. element.text = xmlutils.get_content_type(item, encoding)
  198. found_props.append(element)
  199. elif tag in (
  200. xmlutils.make_tag("C", "calendar-data"),
  201. xmlutils.make_tag("CR", "address-data")):
  202. element.text = item.serialize()
  203. found_props.append(element)
  204. else:
  205. not_found_props.append(element)
  206. uri = pathutils.unstrip_path(
  207. posixpath.join(collection.path, item.href))
  208. multistatus.append(xml_item_response(
  209. base_prefix, uri, found_props=found_props,
  210. not_found_props=not_found_props, found_item=True))
  211. return client.MULTI_STATUS, multistatus
  212. def xml_item_response(base_prefix, href, found_props=(), not_found_props=(),
  213. found_item=True):
  214. response = ET.Element(xmlutils.make_tag("D", "response"))
  215. href_tag = ET.Element(xmlutils.make_tag("D", "href"))
  216. href_tag.text = xmlutils.make_href(base_prefix, href)
  217. response.append(href_tag)
  218. if found_item:
  219. for code, props in ((200, found_props), (404, not_found_props)):
  220. if props:
  221. propstat = ET.Element(xmlutils.make_tag("D", "propstat"))
  222. status = ET.Element(xmlutils.make_tag("D", "status"))
  223. status.text = xmlutils.make_response(code)
  224. prop_tag = ET.Element(xmlutils.make_tag("D", "prop"))
  225. for prop in props:
  226. prop_tag.append(prop)
  227. propstat.append(prop_tag)
  228. propstat.append(status)
  229. response.append(propstat)
  230. else:
  231. status = ET.Element(xmlutils.make_tag("D", "status"))
  232. status.text = xmlutils.make_response(404)
  233. response.append(status)
  234. return response
  235. class ApplicationReportMixin:
  236. def do_REPORT(self, environ, base_prefix, path, user):
  237. """Manage REPORT request."""
  238. if not self.access(user, path, "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 self.access(user, path, "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))