report.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409
  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 datetime
  21. import posixpath
  22. import socket
  23. import copy
  24. import xml.etree.ElementTree as ET
  25. from vobject.base import ContentLine
  26. from http import client
  27. from typing import (
  28. Callable, Iterable, Iterator,
  29. Optional, Sequence, Tuple, List,
  30. )
  31. from urllib.parse import unquote, urlparse
  32. import radicale.item as radicale_item
  33. from radicale import httputils, pathutils, storage, types, xmlutils
  34. from radicale.app.base import Access, ApplicationBase
  35. from radicale.item import filter as radicale_filter
  36. from radicale.log import logger
  37. def xml_report(base_prefix: str, path: str, xml_request: Optional[ET.Element],
  38. collection: storage.BaseCollection, encoding: str,
  39. unlock_storage_fn: Callable[[], None]
  40. ) -> Tuple[int, ET.Element]:
  41. """Read and answer REPORT requests.
  42. Read rfc3253-3.6 for info.
  43. """
  44. multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
  45. if xml_request is None:
  46. return client.MULTI_STATUS, multistatus
  47. root = xml_request
  48. if root.tag in (xmlutils.make_clark("D:principal-search-property-set"),
  49. xmlutils.make_clark("D:principal-property-search"),
  50. xmlutils.make_clark("D:expand-property")):
  51. # We don't support searching for principals or indirect retrieving of
  52. # properties, just return an empty result.
  53. # InfCloud asks for expand-property reports (even if we don't announce
  54. # support for them) and stops working if an error code is returned.
  55. logger.warning("Unsupported REPORT method %r on %r requested",
  56. xmlutils.make_human_tag(root.tag), path)
  57. return client.MULTI_STATUS, multistatus
  58. if (root.tag == xmlutils.make_clark("C:calendar-multiget") and
  59. collection.tag != "VCALENDAR" or
  60. root.tag == xmlutils.make_clark("CR:addressbook-multiget") and
  61. collection.tag != "VADDRESSBOOK" or
  62. root.tag == xmlutils.make_clark("D:sync-collection") and
  63. collection.tag not in ("VADDRESSBOOK", "VCALENDAR")):
  64. logger.warning("Invalid REPORT method %r on %r requested",
  65. xmlutils.make_human_tag(root.tag), path)
  66. return client.FORBIDDEN, xmlutils.webdav_error("D:supported-report")
  67. props = root.find(xmlutils.make_clark("D:prop")) or []
  68. hreferences: Iterable[str]
  69. if root.tag in (
  70. xmlutils.make_clark("C:calendar-multiget"),
  71. xmlutils.make_clark("CR:addressbook-multiget")):
  72. # Read rfc4791-7.9 for info
  73. hreferences = set()
  74. for href_element in root.findall(xmlutils.make_clark("D:href")):
  75. temp_url_path = urlparse(href_element.text).path
  76. assert isinstance(temp_url_path, str)
  77. href_path = pathutils.sanitize_path(unquote(temp_url_path))
  78. if (href_path + "/").startswith(base_prefix + "/"):
  79. hreferences.add(href_path[len(base_prefix):])
  80. else:
  81. logger.warning("Skipping invalid path %r in REPORT request on "
  82. "%r", href_path, path)
  83. elif root.tag == xmlutils.make_clark("D:sync-collection"):
  84. old_sync_token_element = root.find(
  85. xmlutils.make_clark("D:sync-token"))
  86. old_sync_token = ""
  87. if old_sync_token_element is not None and old_sync_token_element.text:
  88. old_sync_token = old_sync_token_element.text.strip()
  89. logger.debug("Client provided sync token: %r", old_sync_token)
  90. try:
  91. sync_token, names = collection.sync(old_sync_token)
  92. except ValueError as e:
  93. # Invalid sync token
  94. logger.warning("Client provided invalid sync token %r: %s",
  95. old_sync_token, e, exc_info=True)
  96. # client.CONFLICT doesn't work with some clients (e.g. InfCloud)
  97. return (client.FORBIDDEN,
  98. xmlutils.webdav_error("D:valid-sync-token"))
  99. hreferences = (pathutils.unstrip_path(
  100. posixpath.join(collection.path, n)) for n in names)
  101. # Append current sync token to response
  102. sync_token_element = ET.Element(xmlutils.make_clark("D:sync-token"))
  103. sync_token_element.text = sync_token
  104. multistatus.append(sync_token_element)
  105. else:
  106. hreferences = (path,)
  107. filters = (
  108. root.findall(xmlutils.make_clark("C:filter")) +
  109. root.findall(xmlutils.make_clark("CR:filter")))
  110. # Retrieve everything required for finishing the request.
  111. retrieved_items = list(retrieve_items(
  112. base_prefix, path, collection, hreferences, filters, multistatus))
  113. collection_tag = collection.tag
  114. # !!! Don't access storage after this !!!
  115. unlock_storage_fn()
  116. while retrieved_items:
  117. # ``item.vobject_item`` might be accessed during filtering.
  118. # Don't keep reference to ``item``, because VObject requires a lot of
  119. # memory.
  120. item, filters_matched = retrieved_items.pop(0)
  121. if filters and not filters_matched:
  122. try:
  123. if not all(test_filter(collection_tag, item, filter_)
  124. for filter_ in filters):
  125. continue
  126. except ValueError as e:
  127. raise ValueError("Failed to filter item %r from %r: %s" %
  128. (item.href, collection.path, e)) from e
  129. except Exception as e:
  130. raise RuntimeError("Failed to filter item %r from %r: %s" %
  131. (item.href, collection.path, e)) from e
  132. found_props = []
  133. not_found_props = []
  134. for prop in props:
  135. element = ET.Element(prop.tag)
  136. if prop.tag == xmlutils.make_clark("D:getetag"):
  137. element.text = item.etag
  138. found_props.append(element)
  139. elif prop.tag == xmlutils.make_clark("D:getcontenttype"):
  140. element.text = xmlutils.get_content_type(item, encoding)
  141. found_props.append(element)
  142. elif prop.tag in (
  143. xmlutils.make_clark("C:calendar-data"),
  144. xmlutils.make_clark("CR:address-data")):
  145. element.text = item.serialize()
  146. expand = prop.find(xmlutils.make_clark("C:expand"))
  147. if expand is not None:
  148. start = expand.get('start')
  149. end = expand.get('end')
  150. if (start is None) or (end is None):
  151. return client.FORBIDDEN, \
  152. xmlutils.webdav_error("C:expand")
  153. start = datetime.datetime.strptime(
  154. start, '%Y%m%dT%H%M%SZ'
  155. ).replace(tzinfo=datetime.timezone.utc)
  156. end = datetime.datetime.strptime(
  157. end, '%Y%m%dT%H%M%SZ'
  158. ).replace(tzinfo=datetime.timezone.utc)
  159. expanded_elements = _expand(
  160. element, copy.copy(item), start, end)
  161. found_props.extend(expanded_elements)
  162. else:
  163. found_props.append(element)
  164. else:
  165. not_found_props.append(element)
  166. assert item.href
  167. uri = pathutils.unstrip_path(
  168. posixpath.join(collection.path, item.href))
  169. multistatus.append(xml_item_response(
  170. base_prefix, uri, found_props=found_props,
  171. not_found_props=not_found_props, found_item=True))
  172. return client.MULTI_STATUS, multistatus
  173. def _expand(
  174. element: ET.Element,
  175. item: radicale_item.Item,
  176. start: datetime.datetime,
  177. end: datetime.datetime,
  178. ) -> List[ET.Element]:
  179. expanded = [element]
  180. if hasattr(item.vobject_item.vevent, "rrule"):
  181. rulleset = item.vobject_item.vevent.getrruleset()
  182. recurrences = rulleset.between(start, end)
  183. recurring_item = _make_vobject_recurring_item(item)
  184. expanded = []
  185. for recurrence_dt in recurrences:
  186. try:
  187. delattr(recurring_item.vobject_item.vevent, 'recurrence-id')
  188. except AttributeError:
  189. pass
  190. recurrence_utc = recurrence_dt.astimezone(datetime.timezone.utc)
  191. recurring_item.vobject_item.vevent.recurrence_id = ContentLine(
  192. name='RECURRENCE-ID',
  193. value=recurrence_utc.strftime('%Y%m%dT%H%M%SZ'), params={}
  194. )
  195. element = copy.copy(element)
  196. element.text = recurring_item.vobject_item.serialize()
  197. expanded.append(element)
  198. return expanded
  199. def _make_vobject_recurring_item(
  200. item: radicale_item.Item
  201. ) -> radicale_item.Item:
  202. # https://www.rfc-editor.org/rfc/rfc4791#section-9.6.5
  203. # The returned calendar components MUST NOT use recurrence
  204. # properties (i.e., EXDATE, EXRULE, RDATE, and RRULE) and MUST NOT
  205. # have reference to or include VTIMEZONE components. Date and local
  206. # time with reference to time zone information MUST be converted
  207. # into date with UTC time.
  208. item = copy.copy(item)
  209. vevent = item.vobject_item.vevent
  210. start_utc = vevent.dtstart.value.astimezone(datetime.timezone.utc)
  211. end_utc = vevent.dtend.value.astimezone(datetime.timezone.utc)
  212. vevent.dtstart = ContentLine(
  213. name='DTSTART',
  214. value=start_utc.strftime('%Y%m%dT%H%M%SZ'), params={})
  215. vevent.dtend = ContentLine(
  216. name='DTEND',
  217. value=end_utc.strftime('%Y%m%dT%H%M%SZ'), params={})
  218. timezones_to_remove = []
  219. for component in item.vobject_item.components():
  220. if component.name == 'VTIMEZONE':
  221. timezones_to_remove.append(component)
  222. for timezone in timezones_to_remove:
  223. item.vobject_item.remove(timezone)
  224. try:
  225. delattr(item.vobject_item.vevent, 'rrule')
  226. delattr(item.vobject_item.vevent, 'exdate')
  227. delattr(item.vobject_item.vevent, 'exrule')
  228. delattr(item.vobject_item.vevent, 'rdate')
  229. except AttributeError:
  230. pass
  231. return item
  232. def xml_item_response(base_prefix: str, href: str,
  233. found_props: Sequence[ET.Element] = (),
  234. not_found_props: Sequence[ET.Element] = (),
  235. found_item: bool = True) -> ET.Element:
  236. response = ET.Element(xmlutils.make_clark("D:response"))
  237. href_element = ET.Element(xmlutils.make_clark("D:href"))
  238. href_element.text = xmlutils.make_href(base_prefix, href)
  239. response.append(href_element)
  240. if found_item:
  241. for code, props in ((200, found_props), (404, not_found_props)):
  242. if props:
  243. propstat = ET.Element(xmlutils.make_clark("D:propstat"))
  244. status = ET.Element(xmlutils.make_clark("D:status"))
  245. status.text = xmlutils.make_response(code)
  246. prop_element = ET.Element(xmlutils.make_clark("D:prop"))
  247. for prop in props:
  248. prop_element.append(prop)
  249. propstat.append(prop_element)
  250. propstat.append(status)
  251. response.append(propstat)
  252. else:
  253. status = ET.Element(xmlutils.make_clark("D:status"))
  254. status.text = xmlutils.make_response(404)
  255. response.append(status)
  256. return response
  257. def retrieve_items(
  258. base_prefix: str, path: str, collection: storage.BaseCollection,
  259. hreferences: Iterable[str], filters: Sequence[ET.Element],
  260. multistatus: ET.Element) -> Iterator[Tuple[radicale_item.Item, bool]]:
  261. """Retrieves all items that are referenced in ``hreferences`` from
  262. ``collection`` and adds 404 responses for missing and invalid items
  263. to ``multistatus``."""
  264. collection_requested = False
  265. def get_names() -> Iterator[str]:
  266. """Extracts all names from references in ``hreferences`` and adds
  267. 404 responses for invalid references to ``multistatus``.
  268. If the whole collections is referenced ``collection_requested``
  269. gets set to ``True``."""
  270. nonlocal collection_requested
  271. for hreference in hreferences:
  272. try:
  273. name = pathutils.name_from_path(hreference, collection)
  274. except ValueError as e:
  275. logger.warning("Skipping invalid path %r in REPORT request on "
  276. "%r: %s", hreference, path, e)
  277. response = xml_item_response(base_prefix, hreference,
  278. found_item=False)
  279. multistatus.append(response)
  280. continue
  281. if name:
  282. # Reference is an item
  283. yield name
  284. else:
  285. # Reference is a collection
  286. collection_requested = True
  287. for name, item in collection.get_multi(get_names()):
  288. if not item:
  289. uri = pathutils.unstrip_path(posixpath.join(collection.path, name))
  290. response = xml_item_response(base_prefix, uri, found_item=False)
  291. multistatus.append(response)
  292. else:
  293. yield item, False
  294. if collection_requested:
  295. yield from collection.get_filtered(filters)
  296. def test_filter(collection_tag: str, item: radicale_item.Item,
  297. filter_: ET.Element) -> bool:
  298. """Match an item against a filter."""
  299. if (collection_tag == "VCALENDAR" and
  300. filter_.tag != xmlutils.make_clark("C:%s" % filter_)):
  301. if len(filter_) == 0:
  302. return True
  303. if len(filter_) > 1:
  304. raise ValueError("Filter with %d children" % len(filter_))
  305. if filter_[0].tag != xmlutils.make_clark("C:comp-filter"):
  306. raise ValueError("Unexpected %r in filter" % filter_[0].tag)
  307. return radicale_filter.comp_match(item, filter_[0])
  308. if (collection_tag == "VADDRESSBOOK" and
  309. filter_.tag != xmlutils.make_clark("CR:%s" % filter_)):
  310. for child in filter_:
  311. if child.tag != xmlutils.make_clark("CR:prop-filter"):
  312. raise ValueError("Unexpected %r in filter" % child.tag)
  313. test = filter_.get("test", "anyof")
  314. if test == "anyof":
  315. return any(radicale_filter.prop_match(item.vobject_item, f, "CR")
  316. for f in filter_)
  317. if test == "allof":
  318. return all(radicale_filter.prop_match(item.vobject_item, f, "CR")
  319. for f in filter_)
  320. raise ValueError("Unsupported filter test: %r" % test)
  321. raise ValueError("Unsupported filter %r for %r" %
  322. (filter_.tag, collection_tag))
  323. class ApplicationPartReport(ApplicationBase):
  324. def do_REPORT(self, environ: types.WSGIEnviron, base_prefix: str,
  325. path: str, user: str) -> types.WSGIResponse:
  326. """Manage REPORT request."""
  327. access = Access(self._rights, user, path)
  328. if not access.check("r"):
  329. return httputils.NOT_ALLOWED
  330. try:
  331. xml_content = self._read_xml_request_body(environ)
  332. except RuntimeError as e:
  333. logger.warning("Bad REPORT request on %r: %s", path, e,
  334. exc_info=True)
  335. return httputils.BAD_REQUEST
  336. except socket.timeout:
  337. logger.debug("Client timed out", exc_info=True)
  338. return httputils.REQUEST_TIMEOUT
  339. with contextlib.ExitStack() as lock_stack:
  340. lock_stack.enter_context(self._storage.acquire_lock("r", user))
  341. item = next(iter(self._storage.discover(path)), None)
  342. if not item:
  343. return httputils.NOT_FOUND
  344. if not access.check("r", item):
  345. return httputils.NOT_ALLOWED
  346. if isinstance(item, storage.BaseCollection):
  347. collection = item
  348. else:
  349. assert item.collection is not None
  350. collection = item.collection
  351. try:
  352. status, xml_answer = xml_report(
  353. base_prefix, path, xml_content, collection, self._encoding,
  354. lock_stack.close)
  355. except ValueError as e:
  356. logger.warning(
  357. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  358. return httputils.BAD_REQUEST
  359. headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
  360. return status, headers, self._xml_response(xml_answer)