report.py 23 KB

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