report.py 26 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638
  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-2021 Unrud <unrud@outlook.com>
  6. # Copyright © 2024-2024 Pieter Hijma <pieterhijma@users.noreply.github.com>
  7. # Copyright © 2024-2024 Ray <ray@react0r.com>
  8. # Copyright © 2024-2024 Georgiy <metallerok@gmail.com>
  9. # Copyright © 2024-2025 Peter Bieringer <pb@bieringer.de>
  10. #
  11. # This library is free software: you can redistribute it and/or modify
  12. # it under the terms of the GNU General Public License as published by
  13. # the Free Software Foundation, either version 3 of the License, or
  14. # (at your option) any later version.
  15. #
  16. # This library is distributed in the hope that it will be useful,
  17. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  18. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  19. # GNU General Public License for more details.
  20. #
  21. # You should have received a copy of the GNU General Public License
  22. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  23. import contextlib
  24. import copy
  25. import datetime
  26. import posixpath
  27. import socket
  28. import xml.etree.ElementTree as ET
  29. from http import client
  30. from typing import (Callable, Iterable, Iterator, List, Optional, Sequence,
  31. Tuple, Union)
  32. from urllib.parse import unquote, urlparse
  33. import vobject
  34. import vobject.base
  35. from vobject.base import ContentLine
  36. import radicale.item as radicale_item
  37. from radicale import httputils, pathutils, storage, types, xmlutils
  38. from radicale.app.base import Access, ApplicationBase
  39. from radicale.item import filter as radicale_filter
  40. from radicale.log import logger
  41. def free_busy_report(base_prefix: str, path: str, xml_request: Optional[ET.Element],
  42. collection: storage.BaseCollection, encoding: str,
  43. unlock_storage_fn: Callable[[], None],
  44. max_occurrence: int
  45. ) -> Tuple[int, Union[ET.Element, str]]:
  46. # NOTE: this function returns both an Element and a string because
  47. # free-busy reports are an edge-case on the return type according
  48. # to the spec.
  49. multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
  50. if xml_request is None:
  51. return client.MULTI_STATUS, multistatus
  52. root = xml_request
  53. if (root.tag == xmlutils.make_clark("C:free-busy-query") and
  54. collection.tag != "VCALENDAR"):
  55. logger.warning("Invalid REPORT method %r on %r requested",
  56. xmlutils.make_human_tag(root.tag), path)
  57. return client.FORBIDDEN, xmlutils.webdav_error("D:supported-report")
  58. time_range_element = root.find(xmlutils.make_clark("C:time-range"))
  59. assert isinstance(time_range_element, ET.Element)
  60. # Build a single filter from the free busy query for retrieval
  61. # TODO: filter for VFREEBUSY in additional to VEVENT but
  62. # test_filter doesn't support that yet.
  63. vevent_cf_element = ET.Element(xmlutils.make_clark("C:comp-filter"),
  64. attrib={'name': 'VEVENT'})
  65. vevent_cf_element.append(time_range_element)
  66. vcalendar_cf_element = ET.Element(xmlutils.make_clark("C:comp-filter"),
  67. attrib={'name': 'VCALENDAR'})
  68. vcalendar_cf_element.append(vevent_cf_element)
  69. filter_element = ET.Element(xmlutils.make_clark("C:filter"))
  70. filter_element.append(vcalendar_cf_element)
  71. filters = (filter_element,)
  72. # First pull from storage
  73. retrieved_items = list(collection.get_filtered(filters))
  74. # !!! Don't access storage after this !!!
  75. unlock_storage_fn()
  76. cal = vobject.iCalendar()
  77. collection_tag = collection.tag
  78. while retrieved_items:
  79. # Second filtering before evaluating occurrences.
  80. # ``item.vobject_item`` might be accessed during filtering.
  81. # Don't keep reference to ``item``, because VObject requires a lot of
  82. # memory.
  83. item, filter_matched = retrieved_items.pop(0)
  84. if not filter_matched:
  85. try:
  86. if not test_filter(collection_tag, item, filter_element):
  87. continue
  88. except ValueError as e:
  89. raise ValueError("Failed to free-busy filter item %r from %r: %s" %
  90. (item.href, collection.path, e)) from e
  91. except Exception as e:
  92. raise RuntimeError("Failed to free-busy filter item %r from %r: %s" %
  93. (item.href, collection.path, e)) from e
  94. fbtype = None
  95. if item.component_name == 'VEVENT':
  96. transp = getattr(item.vobject_item.vevent, 'transp', None)
  97. if transp and transp.value != 'OPAQUE':
  98. continue
  99. status = getattr(item.vobject_item.vevent, 'status', None)
  100. if not status or status.value == 'CONFIRMED':
  101. fbtype = 'BUSY'
  102. elif status.value == 'CANCELLED':
  103. fbtype = 'FREE'
  104. elif status.value == 'TENTATIVE':
  105. fbtype = 'BUSY-TENTATIVE'
  106. else:
  107. # Could do fbtype = status.value for x-name, I prefer this
  108. fbtype = 'BUSY'
  109. # TODO: coalesce overlapping periods
  110. if max_occurrence > 0:
  111. n_occurrences = max_occurrence+1
  112. else:
  113. n_occurrences = 0
  114. occurrences = radicale_filter.time_range_fill(item.vobject_item,
  115. time_range_element,
  116. "VEVENT",
  117. n=n_occurrences)
  118. if len(occurrences) >= max_occurrence:
  119. raise ValueError("FREEBUSY occurrences limit of {} hit"
  120. .format(max_occurrence))
  121. for occurrence in occurrences:
  122. vfb = cal.add('vfreebusy')
  123. vfb.add('dtstamp').value = item.vobject_item.vevent.dtstamp.value
  124. vfb.add('dtstart').value, vfb.add('dtend').value = occurrence
  125. if fbtype:
  126. vfb.add('fbtype').value = fbtype
  127. return (client.OK, cal.serialize())
  128. def xml_report(base_prefix: str, path: str, xml_request: Optional[ET.Element],
  129. collection: storage.BaseCollection, encoding: str,
  130. unlock_storage_fn: Callable[[], None]
  131. ) -> Tuple[int, ET.Element]:
  132. """Read and answer REPORT requests that return XML.
  133. Read rfc3253-3.6 for info.
  134. """
  135. multistatus = ET.Element(xmlutils.make_clark("D:multistatus"))
  136. if xml_request is None:
  137. return client.MULTI_STATUS, multistatus
  138. root = xml_request
  139. if root.tag in (xmlutils.make_clark("D:principal-search-property-set"),
  140. xmlutils.make_clark("D:principal-property-search"),
  141. xmlutils.make_clark("D:expand-property")):
  142. # We don't support searching for principals or indirect retrieving of
  143. # properties, just return an empty result.
  144. # InfCloud asks for expand-property reports (even if we don't announce
  145. # support for them) and stops working if an error code is returned.
  146. logger.warning("Unsupported REPORT method %r on %r requested",
  147. xmlutils.make_human_tag(root.tag), path)
  148. return client.MULTI_STATUS, multistatus
  149. if (root.tag == xmlutils.make_clark("C:calendar-multiget") and
  150. collection.tag != "VCALENDAR" or
  151. root.tag == xmlutils.make_clark("CR:addressbook-multiget") and
  152. collection.tag != "VADDRESSBOOK" or
  153. root.tag == xmlutils.make_clark("D:sync-collection") and
  154. collection.tag not in ("VADDRESSBOOK", "VCALENDAR")):
  155. logger.warning("Invalid REPORT method %r on %r requested",
  156. xmlutils.make_human_tag(root.tag), path)
  157. return client.FORBIDDEN, xmlutils.webdav_error("D:supported-report")
  158. props: Union[ET.Element, List] = root.find(xmlutils.make_clark("D:prop")) or []
  159. hreferences: Iterable[str]
  160. if root.tag in (
  161. xmlutils.make_clark("C:calendar-multiget"),
  162. xmlutils.make_clark("CR:addressbook-multiget")):
  163. # Read rfc4791-7.9 for info
  164. hreferences = set()
  165. for href_element in root.findall(xmlutils.make_clark("D:href")):
  166. temp_url_path = urlparse(href_element.text).path
  167. assert isinstance(temp_url_path, str)
  168. href_path = pathutils.sanitize_path(unquote(temp_url_path))
  169. if (href_path + "/").startswith(base_prefix + "/"):
  170. hreferences.add(href_path[len(base_prefix):])
  171. else:
  172. logger.warning("Skipping invalid path %r in REPORT request on "
  173. "%r", href_path, path)
  174. elif root.tag == xmlutils.make_clark("D:sync-collection"):
  175. old_sync_token_element = root.find(
  176. xmlutils.make_clark("D:sync-token"))
  177. old_sync_token = ""
  178. if old_sync_token_element is not None and old_sync_token_element.text:
  179. old_sync_token = old_sync_token_element.text.strip()
  180. logger.debug("Client provided sync token: %r", old_sync_token)
  181. try:
  182. sync_token, names = collection.sync(old_sync_token)
  183. except ValueError as e:
  184. # Invalid sync token
  185. logger.warning("Client provided invalid sync token %r: %s",
  186. old_sync_token, e, exc_info=True)
  187. # client.CONFLICT doesn't work with some clients (e.g. InfCloud)
  188. return (client.FORBIDDEN,
  189. xmlutils.webdav_error("D:valid-sync-token"))
  190. hreferences = (pathutils.unstrip_path(
  191. posixpath.join(collection.path, n)) for n in names)
  192. # Append current sync token to response
  193. sync_token_element = ET.Element(xmlutils.make_clark("D:sync-token"))
  194. sync_token_element.text = sync_token
  195. multistatus.append(sync_token_element)
  196. else:
  197. hreferences = (path,)
  198. filters = (
  199. root.findall(xmlutils.make_clark("C:filter")) +
  200. root.findall(xmlutils.make_clark("CR:filter")))
  201. # Retrieve everything required for finishing the request.
  202. retrieved_items = list(retrieve_items(
  203. base_prefix, path, collection, hreferences, filters, multistatus))
  204. collection_tag = collection.tag
  205. # !!! Don't access storage after this !!!
  206. unlock_storage_fn()
  207. while retrieved_items:
  208. # ``item.vobject_item`` might be accessed during filtering.
  209. # Don't keep reference to ``item``, because VObject requires a lot of
  210. # memory.
  211. item, filters_matched = retrieved_items.pop(0)
  212. if filters and not filters_matched:
  213. try:
  214. if not all(test_filter(collection_tag, item, filter_)
  215. for filter_ in filters):
  216. continue
  217. except ValueError as e:
  218. raise ValueError("Failed to filter item %r from %r: %s" %
  219. (item.href, collection.path, e)) from e
  220. except Exception as e:
  221. raise RuntimeError("Failed to filter item %r from %r: %s" %
  222. (item.href, collection.path, e)) from e
  223. found_props = []
  224. not_found_props = []
  225. for prop in props:
  226. element = ET.Element(prop.tag)
  227. if prop.tag == xmlutils.make_clark("D:getetag"):
  228. element.text = item.etag
  229. found_props.append(element)
  230. elif prop.tag == xmlutils.make_clark("D:getcontenttype"):
  231. element.text = xmlutils.get_content_type(item, encoding)
  232. found_props.append(element)
  233. elif prop.tag in (
  234. xmlutils.make_clark("C:calendar-data"),
  235. xmlutils.make_clark("CR:address-data")):
  236. element.text = item.serialize()
  237. expand = prop.find(xmlutils.make_clark("C:expand"))
  238. if expand is not None and item.component_name == 'VEVENT':
  239. start = expand.get('start')
  240. end = expand.get('end')
  241. if (start is None) or (end is None):
  242. return client.FORBIDDEN, \
  243. xmlutils.webdav_error("C:expand")
  244. start = datetime.datetime.strptime(
  245. start, '%Y%m%dT%H%M%SZ'
  246. ).replace(tzinfo=datetime.timezone.utc)
  247. end = datetime.datetime.strptime(
  248. end, '%Y%m%dT%H%M%SZ'
  249. ).replace(tzinfo=datetime.timezone.utc)
  250. expanded_element = _expand(
  251. element, copy.copy(item), start, end)
  252. found_props.append(expanded_element)
  253. else:
  254. found_props.append(element)
  255. else:
  256. not_found_props.append(element)
  257. assert item.href
  258. uri = pathutils.unstrip_path(
  259. posixpath.join(collection.path, item.href))
  260. multistatus.append(xml_item_response(
  261. base_prefix, uri, found_props=found_props,
  262. not_found_props=not_found_props, found_item=True))
  263. return client.MULTI_STATUS, multistatus
  264. def _expand(
  265. element: ET.Element,
  266. item: radicale_item.Item,
  267. start: datetime.datetime,
  268. end: datetime.datetime,
  269. ) -> ET.Element:
  270. vevent_component: vobject.base.Component = copy.copy(item.vobject_item)
  271. # Split the vevents included in the component into one that contains the
  272. # recurrence information and others that contain a recurrence id to
  273. # override instances.
  274. vevent_recurrence, vevents_overridden = _split_overridden_vevents(vevent_component)
  275. dt_format = '%Y%m%dT%H%M%SZ'
  276. all_day_event = False
  277. if type(vevent_recurrence.dtstart.value) is datetime.date:
  278. # If an event comes to us with a dtstart specified as a date
  279. # then in the response we return the date, not datetime
  280. dt_format = '%Y%m%d'
  281. all_day_event = True
  282. # In case of dates, we need to remove timezone information since
  283. # rruleset.between computes with datetimes without timezone information
  284. start = start.replace(tzinfo=None)
  285. end = end.replace(tzinfo=None)
  286. for vevent in vevents_overridden:
  287. _strip_single_event(vevent, dt_format)
  288. duration = None
  289. if hasattr(vevent_recurrence, "dtend"):
  290. duration = vevent_recurrence.dtend.value - vevent_recurrence.dtstart.value
  291. rruleset = None
  292. if hasattr(vevent_recurrence, 'rrule'):
  293. rruleset = vevent_recurrence.getrruleset()
  294. if rruleset:
  295. # This function uses datetimes internally without timezone info for dates
  296. recurrences = rruleset.between(start, end, inc=True)
  297. _strip_component(vevent_component)
  298. _strip_single_event(vevent_recurrence, dt_format)
  299. is_component_filled: bool = False
  300. i_overridden = 0
  301. for recurrence_dt in recurrences:
  302. recurrence_utc = recurrence_dt.astimezone(datetime.timezone.utc)
  303. i_overridden, vevent = _find_overridden(i_overridden, vevents_overridden, recurrence_utc, dt_format)
  304. if not vevent:
  305. # We did not find an overridden instance, so create a new one
  306. vevent = copy.deepcopy(vevent_recurrence)
  307. # For all day events, the system timezone may influence the
  308. # results, so use recurrence_dt
  309. recurrence_id = recurrence_dt if all_day_event else recurrence_utc
  310. vevent.recurrence_id = ContentLine(
  311. name='RECURRENCE-ID',
  312. value=recurrence_id, params={}
  313. )
  314. _convert_to_utc(vevent, 'recurrence_id', dt_format)
  315. vevent.dtstart = ContentLine(
  316. name='DTSTART',
  317. value=recurrence_id.strftime(dt_format), params={}
  318. )
  319. if duration:
  320. vevent.dtend = ContentLine(
  321. name='DTEND',
  322. value=(recurrence_id + duration).strftime(dt_format), params={}
  323. )
  324. if not is_component_filled:
  325. vevent_component.vevent = vevent
  326. is_component_filled = True
  327. else:
  328. vevent_component.add(vevent)
  329. element.text = vevent_component.serialize()
  330. return element
  331. def _convert_timezone(vevent: vobject.icalendar.RecurringComponent,
  332. name_prop: str,
  333. name_content_line: str):
  334. prop = getattr(vevent, name_prop, None)
  335. if prop:
  336. if type(prop.value) is datetime.date:
  337. date_time = datetime.datetime.fromordinal(
  338. prop.value.toordinal()
  339. ).replace(tzinfo=datetime.timezone.utc)
  340. else:
  341. date_time = prop.value.astimezone(datetime.timezone.utc)
  342. setattr(vevent, name_prop, ContentLine(name=name_content_line, value=date_time, params=[]))
  343. def _convert_to_utc(vevent: vobject.icalendar.RecurringComponent,
  344. name_prop: str,
  345. dt_format: str):
  346. prop = getattr(vevent, name_prop, None)
  347. if prop:
  348. setattr(vevent, name_prop, ContentLine(name=prop.name, value=prop.value.strftime(dt_format), params=[]))
  349. def _strip_single_event(vevent: vobject.icalendar.RecurringComponent, dt_format: str) -> None:
  350. _convert_timezone(vevent, 'dtstart', 'DTSTART')
  351. _convert_timezone(vevent, 'dtend', 'DTEND')
  352. _convert_timezone(vevent, 'recurrence_id', 'RECURRENCE-ID')
  353. # There is something strange behaviour during serialization native datetime, so converting manually
  354. _convert_to_utc(vevent, 'dtstart', dt_format)
  355. _convert_to_utc(vevent, 'dtend', dt_format)
  356. _convert_to_utc(vevent, 'recurrence_id', dt_format)
  357. try:
  358. delattr(vevent, 'rrule')
  359. delattr(vevent, 'exdate')
  360. delattr(vevent, 'exrule')
  361. delattr(vevent, 'rdate')
  362. except AttributeError:
  363. pass
  364. def _strip_component(vevent: vobject.base.Component) -> None:
  365. timezones_to_remove = []
  366. for component in vevent.components():
  367. if component.name == 'VTIMEZONE':
  368. timezones_to_remove.append(component)
  369. for timezone in timezones_to_remove:
  370. vevent.remove(timezone)
  371. def _split_overridden_vevents(
  372. component: vobject.base.Component,
  373. ) -> Tuple[
  374. vobject.icalendar.RecurringComponent,
  375. List[vobject.icalendar.RecurringComponent]
  376. ]:
  377. vevent_recurrence = None
  378. vevents_overridden = []
  379. for vevent in component.vevent_list:
  380. if hasattr(vevent, 'recurrence_id'):
  381. vevents_overridden += [vevent]
  382. elif vevent_recurrence:
  383. raise ValueError(
  384. f"component with UID {vevent.uid} "
  385. f"has more than one vevent with recurrence information"
  386. )
  387. else:
  388. vevent_recurrence = vevent
  389. if vevent_recurrence:
  390. return (
  391. vevent_recurrence, sorted(
  392. vevents_overridden,
  393. key=lambda vevent: vevent.recurrence_id.value
  394. )
  395. )
  396. else:
  397. raise ValueError(
  398. f"component with UID {vevent.uid} "
  399. f"does not have a vevent without a recurrence_id"
  400. )
  401. def _find_overridden(
  402. start: int,
  403. vevents: List[vobject.icalendar.RecurringComponent],
  404. dt: datetime.datetime,
  405. dt_format: str
  406. ) -> Tuple[int, Optional[vobject.icalendar.RecurringComponent]]:
  407. for i in range(start, len(vevents)):
  408. dt_event = datetime.datetime.strptime(
  409. vevents[i].recurrence_id.value,
  410. dt_format
  411. ).replace(tzinfo=datetime.timezone.utc)
  412. if dt_event == dt:
  413. return (i + 1, vevents[i])
  414. return (start, None)
  415. def xml_item_response(base_prefix: str, href: str,
  416. found_props: Sequence[ET.Element] = (),
  417. not_found_props: Sequence[ET.Element] = (),
  418. found_item: bool = True) -> ET.Element:
  419. response = ET.Element(xmlutils.make_clark("D:response"))
  420. href_element = ET.Element(xmlutils.make_clark("D:href"))
  421. href_element.text = xmlutils.make_href(base_prefix, href)
  422. response.append(href_element)
  423. if found_item:
  424. for code, props in ((200, found_props), (404, not_found_props)):
  425. if props:
  426. propstat = ET.Element(xmlutils.make_clark("D:propstat"))
  427. status = ET.Element(xmlutils.make_clark("D:status"))
  428. status.text = xmlutils.make_response(code)
  429. prop_element = ET.Element(xmlutils.make_clark("D:prop"))
  430. for prop in props:
  431. prop_element.append(prop)
  432. propstat.append(prop_element)
  433. propstat.append(status)
  434. response.append(propstat)
  435. else:
  436. status = ET.Element(xmlutils.make_clark("D:status"))
  437. status.text = xmlutils.make_response(404)
  438. response.append(status)
  439. return response
  440. def retrieve_items(
  441. base_prefix: str, path: str, collection: storage.BaseCollection,
  442. hreferences: Iterable[str], filters: Sequence[ET.Element],
  443. multistatus: ET.Element) -> Iterator[Tuple[radicale_item.Item, bool]]:
  444. """Retrieves all items that are referenced in ``hreferences`` from
  445. ``collection`` and adds 404 responses for missing and invalid items
  446. to ``multistatus``."""
  447. collection_requested = False
  448. def get_names() -> Iterator[str]:
  449. """Extracts all names from references in ``hreferences`` and adds
  450. 404 responses for invalid references to ``multistatus``.
  451. If the whole collections is referenced ``collection_requested``
  452. gets set to ``True``."""
  453. nonlocal collection_requested
  454. for hreference in hreferences:
  455. try:
  456. name = pathutils.name_from_path(hreference, collection)
  457. except ValueError as e:
  458. logger.warning("Skipping invalid path %r in REPORT request on "
  459. "%r: %s", hreference, path, e)
  460. response = xml_item_response(base_prefix, hreference,
  461. found_item=False)
  462. multistatus.append(response)
  463. continue
  464. if name:
  465. # Reference is an item
  466. yield name
  467. else:
  468. # Reference is a collection
  469. collection_requested = True
  470. for name, item in collection.get_multi(get_names()):
  471. if not item:
  472. uri = pathutils.unstrip_path(posixpath.join(collection.path, name))
  473. response = xml_item_response(base_prefix, uri, found_item=False)
  474. multistatus.append(response)
  475. else:
  476. yield item, False
  477. if collection_requested:
  478. yield from collection.get_filtered(filters)
  479. def test_filter(collection_tag: str, item: radicale_item.Item,
  480. filter_: ET.Element) -> bool:
  481. """Match an item against a filter."""
  482. if (collection_tag == "VCALENDAR" and
  483. filter_.tag != xmlutils.make_clark("C:%s" % filter_)):
  484. if len(filter_) == 0:
  485. return True
  486. if len(filter_) > 1:
  487. raise ValueError("Filter with %d children" % len(filter_))
  488. if filter_[0].tag != xmlutils.make_clark("C:comp-filter"):
  489. raise ValueError("Unexpected %r in filter" % filter_[0].tag)
  490. return radicale_filter.comp_match(item, filter_[0])
  491. if (collection_tag == "VADDRESSBOOK" and
  492. filter_.tag != xmlutils.make_clark("CR:%s" % filter_)):
  493. for child in filter_:
  494. if child.tag != xmlutils.make_clark("CR:prop-filter"):
  495. raise ValueError("Unexpected %r in filter" % child.tag)
  496. test = filter_.get("test", "anyof")
  497. if test == "anyof":
  498. return any(radicale_filter.prop_match(item.vobject_item, f, "CR")
  499. for f in filter_)
  500. if test == "allof":
  501. return all(radicale_filter.prop_match(item.vobject_item, f, "CR")
  502. for f in filter_)
  503. raise ValueError("Unsupported filter test: %r" % test)
  504. raise ValueError("Unsupported filter %r for %r" %
  505. (filter_.tag, collection_tag))
  506. class ApplicationPartReport(ApplicationBase):
  507. def do_REPORT(self, environ: types.WSGIEnviron, base_prefix: str,
  508. path: str, user: str) -> types.WSGIResponse:
  509. """Manage REPORT request."""
  510. access = Access(self._rights, user, path)
  511. if not access.check("r"):
  512. return httputils.NOT_ALLOWED
  513. try:
  514. xml_content = self._read_xml_request_body(environ)
  515. except RuntimeError as e:
  516. logger.warning("Bad REPORT request on %r: %s", path, e,
  517. exc_info=True)
  518. return httputils.BAD_REQUEST
  519. except socket.timeout:
  520. logger.debug("Client timed out", exc_info=True)
  521. return httputils.REQUEST_TIMEOUT
  522. with contextlib.ExitStack() as lock_stack:
  523. lock_stack.enter_context(self._storage.acquire_lock("r", user))
  524. item = next(iter(self._storage.discover(path)), None)
  525. if not item:
  526. return httputils.NOT_FOUND
  527. if not access.check("r", item):
  528. return httputils.NOT_ALLOWED
  529. if isinstance(item, storage.BaseCollection):
  530. collection = item
  531. else:
  532. assert item.collection is not None
  533. collection = item.collection
  534. if xml_content is not None and \
  535. xml_content.tag == xmlutils.make_clark("C:free-busy-query"):
  536. max_occurrence = self.configuration.get("reporting", "max_freebusy_occurrence")
  537. try:
  538. status, body = free_busy_report(
  539. base_prefix, path, xml_content, collection, self._encoding,
  540. lock_stack.close, max_occurrence)
  541. except ValueError as e:
  542. logger.warning(
  543. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  544. return httputils.BAD_REQUEST
  545. headers = {"Content-Type": "text/calendar; charset=%s" % self._encoding}
  546. return status, headers, str(body)
  547. else:
  548. try:
  549. status, xml_answer = xml_report(
  550. base_prefix, path, xml_content, collection, self._encoding,
  551. lock_stack.close)
  552. except ValueError as e:
  553. logger.warning(
  554. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  555. return httputils.BAD_REQUEST
  556. headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
  557. return status, headers, self._xml_response(xml_answer)