report.py 17 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417
  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_element = _expand(
  160. element, copy.copy(item), start, end)
  161. found_props.append(expanded_element)
  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. ) -> ET.Element:
  179. rruleset = None
  180. if hasattr(item.vobject_item.vevent, 'rrule'):
  181. rruleset = item.vobject_item.vevent.getrruleset()
  182. expanded_item = _make_vobject_expanded_item(item)
  183. if rruleset:
  184. recurrences = rruleset.between(start, end)
  185. expanded = None
  186. for recurrence_dt in recurrences:
  187. vobject_item = copy.copy(expanded_item.vobject_item)
  188. recurrence_utc = recurrence_dt.astimezone(datetime.timezone.utc)
  189. vevent = copy.deepcopy(vobject_item.vevent)
  190. vevent.recurrence_id = ContentLine(
  191. name='RECURRENCE-ID',
  192. value=recurrence_utc.strftime('%Y%m%dT%H%M%SZ'), params={}
  193. )
  194. if expanded is None:
  195. vobject_item.vevent = vevent
  196. expanded = vobject_item
  197. else:
  198. expanded.add(vevent)
  199. element.text = expanded.serialize()
  200. else:
  201. element.text = expanded_item.vobject_item.serialize()
  202. return element
  203. def _make_vobject_expanded_item(
  204. item: radicale_item.Item
  205. ) -> radicale_item.Item:
  206. # https://www.rfc-editor.org/rfc/rfc4791#section-9.6.5
  207. # The returned calendar components MUST NOT use recurrence
  208. # properties (i.e., EXDATE, EXRULE, RDATE, and RRULE) and MUST NOT
  209. # have reference to or include VTIMEZONE components. Date and local
  210. # time with reference to time zone information MUST be converted
  211. # into date with UTC time.
  212. item = copy.copy(item)
  213. vevent = item.vobject_item.vevent
  214. start_utc = vevent.dtstart.value.astimezone(datetime.timezone.utc)
  215. vevent.dtstart = ContentLine(
  216. name='DTSTART',
  217. value=start_utc.strftime('%Y%m%dT%H%M%SZ'), params={})
  218. dt_end = getattr(vevent, 'dtend', None)
  219. if dt_end is not None:
  220. end_utc = dt_end.value.astimezone(datetime.timezone.utc)
  221. vevent.dtend = ContentLine(
  222. name='DTEND',
  223. value=end_utc.strftime('%Y%m%dT%H%M%SZ'), params={})
  224. timezones_to_remove = []
  225. for component in item.vobject_item.components():
  226. if component.name == 'VTIMEZONE':
  227. timezones_to_remove.append(component)
  228. for timezone in timezones_to_remove:
  229. item.vobject_item.remove(timezone)
  230. try:
  231. delattr(item.vobject_item.vevent, 'rrule')
  232. delattr(item.vobject_item.vevent, 'exdate')
  233. delattr(item.vobject_item.vevent, 'exrule')
  234. delattr(item.vobject_item.vevent, 'rdate')
  235. except AttributeError:
  236. pass
  237. return item
  238. def xml_item_response(base_prefix: str, href: str,
  239. found_props: Sequence[ET.Element] = (),
  240. not_found_props: Sequence[ET.Element] = (),
  241. found_item: bool = True) -> ET.Element:
  242. response = ET.Element(xmlutils.make_clark("D:response"))
  243. href_element = ET.Element(xmlutils.make_clark("D:href"))
  244. href_element.text = xmlutils.make_href(base_prefix, href)
  245. response.append(href_element)
  246. if found_item:
  247. for code, props in ((200, found_props), (404, not_found_props)):
  248. if props:
  249. propstat = ET.Element(xmlutils.make_clark("D:propstat"))
  250. status = ET.Element(xmlutils.make_clark("D:status"))
  251. status.text = xmlutils.make_response(code)
  252. prop_element = ET.Element(xmlutils.make_clark("D:prop"))
  253. for prop in props:
  254. prop_element.append(prop)
  255. propstat.append(prop_element)
  256. propstat.append(status)
  257. response.append(propstat)
  258. else:
  259. status = ET.Element(xmlutils.make_clark("D:status"))
  260. status.text = xmlutils.make_response(404)
  261. response.append(status)
  262. return response
  263. def retrieve_items(
  264. base_prefix: str, path: str, collection: storage.BaseCollection,
  265. hreferences: Iterable[str], filters: Sequence[ET.Element],
  266. multistatus: ET.Element) -> Iterator[Tuple[radicale_item.Item, bool]]:
  267. """Retrieves all items that are referenced in ``hreferences`` from
  268. ``collection`` and adds 404 responses for missing and invalid items
  269. to ``multistatus``."""
  270. collection_requested = False
  271. def get_names() -> Iterator[str]:
  272. """Extracts all names from references in ``hreferences`` and adds
  273. 404 responses for invalid references to ``multistatus``.
  274. If the whole collections is referenced ``collection_requested``
  275. gets set to ``True``."""
  276. nonlocal collection_requested
  277. for hreference in hreferences:
  278. try:
  279. name = pathutils.name_from_path(hreference, collection)
  280. except ValueError as e:
  281. logger.warning("Skipping invalid path %r in REPORT request on "
  282. "%r: %s", hreference, path, e)
  283. response = xml_item_response(base_prefix, hreference,
  284. found_item=False)
  285. multistatus.append(response)
  286. continue
  287. if name:
  288. # Reference is an item
  289. yield name
  290. else:
  291. # Reference is a collection
  292. collection_requested = True
  293. for name, item in collection.get_multi(get_names()):
  294. if not item:
  295. uri = pathutils.unstrip_path(posixpath.join(collection.path, name))
  296. response = xml_item_response(base_prefix, uri, found_item=False)
  297. multistatus.append(response)
  298. else:
  299. yield item, False
  300. if collection_requested:
  301. yield from collection.get_filtered(filters)
  302. def test_filter(collection_tag: str, item: radicale_item.Item,
  303. filter_: ET.Element) -> bool:
  304. """Match an item against a filter."""
  305. if (collection_tag == "VCALENDAR" and
  306. filter_.tag != xmlutils.make_clark("C:%s" % filter_)):
  307. if len(filter_) == 0:
  308. return True
  309. if len(filter_) > 1:
  310. raise ValueError("Filter with %d children" % len(filter_))
  311. if filter_[0].tag != xmlutils.make_clark("C:comp-filter"):
  312. raise ValueError("Unexpected %r in filter" % filter_[0].tag)
  313. return radicale_filter.comp_match(item, filter_[0])
  314. if (collection_tag == "VADDRESSBOOK" and
  315. filter_.tag != xmlutils.make_clark("CR:%s" % filter_)):
  316. for child in filter_:
  317. if child.tag != xmlutils.make_clark("CR:prop-filter"):
  318. raise ValueError("Unexpected %r in filter" % child.tag)
  319. test = filter_.get("test", "anyof")
  320. if test == "anyof":
  321. return any(radicale_filter.prop_match(item.vobject_item, f, "CR")
  322. for f in filter_)
  323. if test == "allof":
  324. return all(radicale_filter.prop_match(item.vobject_item, f, "CR")
  325. for f in filter_)
  326. raise ValueError("Unsupported filter test: %r" % test)
  327. raise ValueError("Unsupported filter %r for %r" %
  328. (filter_.tag, collection_tag))
  329. class ApplicationPartReport(ApplicationBase):
  330. def do_REPORT(self, environ: types.WSGIEnviron, base_prefix: str,
  331. path: str, user: str) -> types.WSGIResponse:
  332. """Manage REPORT request."""
  333. access = Access(self._rights, user, path)
  334. if not access.check("r"):
  335. return httputils.NOT_ALLOWED
  336. try:
  337. xml_content = self._read_xml_request_body(environ)
  338. except RuntimeError as e:
  339. logger.warning("Bad REPORT request on %r: %s", path, e,
  340. exc_info=True)
  341. return httputils.BAD_REQUEST
  342. except socket.timeout:
  343. logger.debug("Client timed out", exc_info=True)
  344. return httputils.REQUEST_TIMEOUT
  345. with contextlib.ExitStack() as lock_stack:
  346. lock_stack.enter_context(self._storage.acquire_lock("r", user))
  347. item = next(iter(self._storage.discover(path)), None)
  348. if not item:
  349. return httputils.NOT_FOUND
  350. if not access.check("r", item):
  351. return httputils.NOT_ALLOWED
  352. if isinstance(item, storage.BaseCollection):
  353. collection = item
  354. else:
  355. assert item.collection is not None
  356. collection = item.collection
  357. try:
  358. status, xml_answer = xml_report(
  359. base_prefix, path, xml_content, collection, self._encoding,
  360. lock_stack.close)
  361. except ValueError as e:
  362. logger.warning(
  363. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  364. return httputils.BAD_REQUEST
  365. headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
  366. return status, headers, self._xml_response(xml_answer)