report.py 17 KB

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