report.py 20 KB

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