report.py 14 KB

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