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 socket
  21. from http import client
  22. from urllib.parse import unquote, urlparse
  23. from xml.etree import ElementTree as ET
  24. from radicale import httputils, pathutils, storage, xmlutils
  25. from radicale.item import filter as radicale_filter
  26. from radicale.log import logger
  27. import posixpath # isort:skip
  28. def xml_report(base_prefix, path, xml_request, collection, unlock_storage_fn):
  29. """Read and answer REPORT requests.
  30. Read rfc3253-3.6 for info.
  31. """
  32. multistatus = ET.Element(xmlutils.make_tag("D", "multistatus"))
  33. if xml_request is None:
  34. return client.MULTI_STATUS, multistatus
  35. root = xml_request
  36. if root.tag in (
  37. xmlutils.make_tag("D", "principal-search-property-set"),
  38. xmlutils.make_tag("D", "principal-property-search"),
  39. xmlutils.make_tag("D", "expand-property")):
  40. # We don't support searching for principals or indirect retrieving of
  41. # properties, just return an empty result.
  42. # InfCloud asks for expand-property reports (even if we don't announce
  43. # support for them) and stops working if an error code is returned.
  44. logger.warning("Unsupported REPORT method %r on %r requested",
  45. xmlutils.tag_from_clark(root.tag), path)
  46. return client.MULTI_STATUS, multistatus
  47. if (root.tag == xmlutils.make_tag("C", "calendar-multiget") and
  48. collection.get_meta("tag") != "VCALENDAR" or
  49. root.tag == xmlutils.make_tag("CR", "addressbook-multiget") and
  50. collection.get_meta("tag") != "VADDRESSBOOK" or
  51. root.tag == xmlutils.make_tag("D", "sync-collection") and
  52. collection.get_meta("tag") not in ("VADDRESSBOOK", "VCALENDAR")):
  53. logger.warning("Invalid REPORT method %r on %r requested",
  54. xmlutils.tag_from_clark(root.tag), path)
  55. return (client.CONFLICT,
  56. xmlutils.webdav_error("D", "supported-report"))
  57. prop_element = root.find(xmlutils.make_tag("D", "prop"))
  58. props = (
  59. [prop.tag for prop in prop_element]
  60. if prop_element is not None else [])
  61. if root.tag in (
  62. xmlutils.make_tag("C", "calendar-multiget"),
  63. xmlutils.make_tag("CR", "addressbook-multiget")):
  64. # Read rfc4791-7.9 for info
  65. hreferences = set()
  66. for href_element in root.findall(xmlutils.make_tag("D", "href")):
  67. href_path = pathutils.sanitize_path(
  68. unquote(urlparse(href_element.text).path))
  69. if (href_path + "/").startswith(base_prefix + "/"):
  70. hreferences.add(href_path[len(base_prefix):])
  71. else:
  72. logger.warning("Skipping invalid path %r in REPORT request on "
  73. "%r", href_path, path)
  74. elif root.tag == xmlutils.make_tag("D", "sync-collection"):
  75. old_sync_token_element = root.find(
  76. xmlutils.make_tag("D", "sync-token"))
  77. old_sync_token = ""
  78. if old_sync_token_element is not None and old_sync_token_element.text:
  79. old_sync_token = old_sync_token_element.text.strip()
  80. logger.debug("Client provided sync token: %r", old_sync_token)
  81. try:
  82. sync_token, names = collection.sync(old_sync_token)
  83. except ValueError as e:
  84. # Invalid sync token
  85. logger.warning("Client provided invalid sync token %r: %s",
  86. old_sync_token, e, exc_info=True)
  87. return (client.CONFLICT,
  88. xmlutils.webdav_error("D", "valid-sync-token"))
  89. hreferences = (pathutils.unstrip_path(
  90. posixpath.join(collection.path, n)) for n in names)
  91. # Append current sync token to response
  92. sync_token_element = ET.Element(xmlutils.make_tag("D", "sync-token"))
  93. sync_token_element.text = sync_token
  94. multistatus.append(sync_token_element)
  95. else:
  96. hreferences = (path,)
  97. filters = (
  98. root.findall("./%s" % xmlutils.make_tag("C", "filter")) +
  99. root.findall("./%s" % xmlutils.make_tag("CR", "filter")))
  100. def retrieve_items(collection, hreferences, multistatus):
  101. """Retrieves all items that are referenced in ``hreferences`` from
  102. ``collection`` and adds 404 responses for missing and invalid items
  103. to ``multistatus``."""
  104. collection_requested = False
  105. def get_names():
  106. """Extracts all names from references in ``hreferences`` and adds
  107. 404 responses for invalid references to ``multistatus``.
  108. If the whole collections is referenced ``collection_requested``
  109. gets set to ``True``."""
  110. nonlocal collection_requested
  111. for hreference in hreferences:
  112. try:
  113. name = pathutils.name_from_path(hreference, collection)
  114. except ValueError as e:
  115. logger.warning("Skipping invalid path %r in REPORT request"
  116. " on %r: %s", hreference, path, e)
  117. response = xml_item_response(base_prefix, hreference,
  118. found_item=False)
  119. multistatus.append(response)
  120. continue
  121. if name:
  122. # Reference is an item
  123. yield name
  124. else:
  125. # Reference is a collection
  126. collection_requested = True
  127. for name, item in collection.get_multi(get_names()):
  128. if not item:
  129. uri = pathutils.unstrip_path(
  130. posixpath.join(collection.path, name))
  131. response = xml_item_response(base_prefix, uri,
  132. found_item=False)
  133. multistatus.append(response)
  134. else:
  135. yield item, False
  136. if collection_requested:
  137. yield from collection.get_filtered(filters)
  138. # Retrieve everything required for finishing the request.
  139. retrieved_items = list(retrieve_items(collection, hreferences,
  140. multistatus))
  141. collection_tag = collection.get_meta("tag")
  142. # Don't access storage after this!
  143. unlock_storage_fn()
  144. def match(item, filter_):
  145. tag = collection_tag
  146. if (tag == "VCALENDAR" and
  147. filter_.tag != xmlutils.make_tag("C", filter_)):
  148. if len(filter_) == 0:
  149. return True
  150. if len(filter_) > 1:
  151. raise ValueError("Filter with %d children" % len(filter_))
  152. if filter_[0].tag != xmlutils.make_tag("C", "comp-filter"):
  153. raise ValueError("Unexpected %r in filter" % filter_[0].tag)
  154. return radicale_filter.comp_match(item, filter_[0])
  155. if (tag == "VADDRESSBOOK" and
  156. filter_.tag != xmlutils.make_tag("CR", filter_)):
  157. for child in filter_:
  158. if child.tag != xmlutils.make_tag("CR", "prop-filter"):
  159. raise ValueError("Unexpected %r in filter" % child.tag)
  160. test = filter_.get("test", "anyof")
  161. if test == "anyof":
  162. return any(
  163. radicale_filter.prop_match(item.vobject_item, f, "CR")
  164. for f in filter_)
  165. if test == "allof":
  166. return all(
  167. radicale_filter.prop_match(item.vobject_item, f, "CR")
  168. for f in filter_)
  169. raise ValueError("Unsupported filter test: %r" % test)
  170. return all(radicale_filter.prop_match(item.vobject_item, f, "CR")
  171. for f in filter_)
  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_tag("D", "getetag"):
  193. element.text = item.etag
  194. found_props.append(element)
  195. elif tag == xmlutils.make_tag("D", "getcontenttype"):
  196. element.text = xmlutils.get_content_type(item)
  197. found_props.append(element)
  198. elif tag in (
  199. xmlutils.make_tag("C", "calendar-data"),
  200. xmlutils.make_tag("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_tag("D", "response"))
  214. href_tag = ET.Element(xmlutils.make_tag("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_tag("D", "propstat"))
  221. status = ET.Element(xmlutils.make_tag("D", "status"))
  222. status.text = xmlutils.make_response(code)
  223. prop_tag = ET.Element(xmlutils.make_tag("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_tag("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. if not self.access(user, path, "r"):
  238. return httputils.NOT_ALLOWED
  239. try:
  240. xml_content = self.read_xml_content(environ)
  241. except RuntimeError as e:
  242. logger.warning(
  243. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  244. return httputils.BAD_REQUEST
  245. except socket.timeout:
  246. logger.debug("client timed out", exc_info=True)
  247. return httputils.REQUEST_TIMEOUT
  248. with contextlib.ExitStack() as lock_stack:
  249. lock_stack.enter_context(self.Collection.acquire_lock("r", user))
  250. item = next(self.Collection.discover(path), None)
  251. if not item:
  252. return httputils.NOT_FOUND
  253. if not self.access(user, path, "r", item):
  254. return httputils.NOT_ALLOWED
  255. if isinstance(item, storage.BaseCollection):
  256. collection = item
  257. else:
  258. collection = item.collection
  259. headers = {"Content-Type": "text/xml; charset=%s" % self.encoding}
  260. try:
  261. status, xml_answer = xml_report(
  262. base_prefix, path, xml_content, collection,
  263. lock_stack.close)
  264. except ValueError as e:
  265. logger.warning(
  266. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  267. return httputils.BAD_REQUEST
  268. return (status, headers, self.write_xml_content(xml_answer))