report.py 23 KB

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