report.py 27 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642
  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]
  159. if root.find(xmlutils.make_clark("D:prop")) is not None:
  160. props = root.find(xmlutils.make_clark("D:prop")) # type: ignore[assignment]
  161. else:
  162. props = []
  163. hreferences: Iterable[str]
  164. if root.tag in (
  165. xmlutils.make_clark("C:calendar-multiget"),
  166. xmlutils.make_clark("CR:addressbook-multiget")):
  167. # Read rfc4791-7.9 for info
  168. hreferences = set()
  169. for href_element in root.findall(xmlutils.make_clark("D:href")):
  170. temp_url_path = urlparse(href_element.text).path
  171. assert isinstance(temp_url_path, str)
  172. href_path = pathutils.sanitize_path(unquote(temp_url_path))
  173. if (href_path + "/").startswith(base_prefix + "/"):
  174. hreferences.add(href_path[len(base_prefix):])
  175. else:
  176. logger.warning("Skipping invalid path %r in REPORT request on "
  177. "%r", href_path, path)
  178. elif root.tag == xmlutils.make_clark("D:sync-collection"):
  179. old_sync_token_element = root.find(
  180. xmlutils.make_clark("D:sync-token"))
  181. old_sync_token = ""
  182. if old_sync_token_element is not None and old_sync_token_element.text:
  183. old_sync_token = old_sync_token_element.text.strip()
  184. logger.debug("Client provided sync token: %r", old_sync_token)
  185. try:
  186. sync_token, names = collection.sync(old_sync_token)
  187. except ValueError as e:
  188. # Invalid sync token
  189. logger.warning("Client provided invalid sync token %r: %s",
  190. old_sync_token, e, exc_info=True)
  191. # client.CONFLICT doesn't work with some clients (e.g. InfCloud)
  192. return (client.FORBIDDEN,
  193. xmlutils.webdav_error("D:valid-sync-token"))
  194. hreferences = (pathutils.unstrip_path(
  195. posixpath.join(collection.path, n)) for n in names)
  196. # Append current sync token to response
  197. sync_token_element = ET.Element(xmlutils.make_clark("D:sync-token"))
  198. sync_token_element.text = sync_token
  199. multistatus.append(sync_token_element)
  200. else:
  201. hreferences = (path,)
  202. filters = (
  203. root.findall(xmlutils.make_clark("C:filter")) +
  204. root.findall(xmlutils.make_clark("CR:filter")))
  205. # Retrieve everything required for finishing the request.
  206. retrieved_items = list(retrieve_items(
  207. base_prefix, path, collection, hreferences, filters, multistatus))
  208. collection_tag = collection.tag
  209. # !!! Don't access storage after this !!!
  210. unlock_storage_fn()
  211. while retrieved_items:
  212. # ``item.vobject_item`` might be accessed during filtering.
  213. # Don't keep reference to ``item``, because VObject requires a lot of
  214. # memory.
  215. item, filters_matched = retrieved_items.pop(0)
  216. if filters and not filters_matched:
  217. try:
  218. if not all(test_filter(collection_tag, item, filter_)
  219. for filter_ in filters):
  220. continue
  221. except ValueError as e:
  222. raise ValueError("Failed to filter item %r from %r: %s" %
  223. (item.href, collection.path, e)) from e
  224. except Exception as e:
  225. raise RuntimeError("Failed to filter item %r from %r: %s" %
  226. (item.href, collection.path, e)) from e
  227. found_props = []
  228. not_found_props = []
  229. for prop in props:
  230. element = ET.Element(prop.tag)
  231. if prop.tag == xmlutils.make_clark("D:getetag"):
  232. element.text = item.etag
  233. found_props.append(element)
  234. elif prop.tag == xmlutils.make_clark("D:getcontenttype"):
  235. element.text = xmlutils.get_content_type(item, encoding)
  236. found_props.append(element)
  237. elif prop.tag in (
  238. xmlutils.make_clark("C:calendar-data"),
  239. xmlutils.make_clark("CR:address-data")):
  240. element.text = item.serialize()
  241. expand = prop.find(xmlutils.make_clark("C:expand"))
  242. if expand is not None and item.component_name == 'VEVENT':
  243. start = expand.get('start')
  244. end = expand.get('end')
  245. if (start is None) or (end is None):
  246. return client.FORBIDDEN, \
  247. xmlutils.webdav_error("C:expand")
  248. start = datetime.datetime.strptime(
  249. start, '%Y%m%dT%H%M%SZ'
  250. ).replace(tzinfo=datetime.timezone.utc)
  251. end = datetime.datetime.strptime(
  252. end, '%Y%m%dT%H%M%SZ'
  253. ).replace(tzinfo=datetime.timezone.utc)
  254. expanded_element = _expand(
  255. element, copy.copy(item), start, end)
  256. found_props.append(expanded_element)
  257. else:
  258. found_props.append(element)
  259. else:
  260. not_found_props.append(element)
  261. assert item.href
  262. uri = pathutils.unstrip_path(
  263. posixpath.join(collection.path, item.href))
  264. multistatus.append(xml_item_response(
  265. base_prefix, uri, found_props=found_props,
  266. not_found_props=not_found_props, found_item=True))
  267. return client.MULTI_STATUS, multistatus
  268. def _expand(
  269. element: ET.Element,
  270. item: radicale_item.Item,
  271. start: datetime.datetime,
  272. end: datetime.datetime,
  273. ) -> ET.Element:
  274. vevent_component: vobject.base.Component = copy.copy(item.vobject_item)
  275. # Split the vevents included in the component into one that contains the
  276. # recurrence information and others that contain a recurrence id to
  277. # override instances.
  278. vevent_recurrence, vevents_overridden = _split_overridden_vevents(vevent_component)
  279. dt_format = '%Y%m%dT%H%M%SZ'
  280. all_day_event = False
  281. if type(vevent_recurrence.dtstart.value) is datetime.date:
  282. # If an event comes to us with a dtstart specified as a date
  283. # then in the response we return the date, not datetime
  284. dt_format = '%Y%m%d'
  285. all_day_event = True
  286. # In case of dates, we need to remove timezone information since
  287. # rruleset.between computes with datetimes without timezone information
  288. start = start.replace(tzinfo=None)
  289. end = end.replace(tzinfo=None)
  290. for vevent in vevents_overridden:
  291. _strip_single_event(vevent, dt_format)
  292. duration = None
  293. if hasattr(vevent_recurrence, "dtend"):
  294. duration = vevent_recurrence.dtend.value - vevent_recurrence.dtstart.value
  295. rruleset = None
  296. if hasattr(vevent_recurrence, 'rrule'):
  297. rruleset = vevent_recurrence.getrruleset()
  298. if rruleset:
  299. # This function uses datetimes internally without timezone info for dates
  300. recurrences = rruleset.between(start, end, inc=True)
  301. _strip_component(vevent_component)
  302. _strip_single_event(vevent_recurrence, dt_format)
  303. is_component_filled: bool = False
  304. i_overridden = 0
  305. for recurrence_dt in recurrences:
  306. recurrence_utc = recurrence_dt.astimezone(datetime.timezone.utc)
  307. i_overridden, vevent = _find_overridden(i_overridden, vevents_overridden, recurrence_utc, dt_format)
  308. if not vevent:
  309. # We did not find an overridden instance, so create a new one
  310. vevent = copy.deepcopy(vevent_recurrence)
  311. # For all day events, the system timezone may influence the
  312. # results, so use recurrence_dt
  313. recurrence_id = recurrence_dt if all_day_event else recurrence_utc
  314. vevent.recurrence_id = ContentLine(
  315. name='RECURRENCE-ID',
  316. value=recurrence_id, params={}
  317. )
  318. _convert_to_utc(vevent, 'recurrence_id', dt_format)
  319. vevent.dtstart = ContentLine(
  320. name='DTSTART',
  321. value=recurrence_id.strftime(dt_format), params={}
  322. )
  323. if duration:
  324. vevent.dtend = ContentLine(
  325. name='DTEND',
  326. value=(recurrence_id + duration).strftime(dt_format), params={}
  327. )
  328. if not is_component_filled:
  329. vevent_component.vevent = vevent
  330. is_component_filled = True
  331. else:
  332. vevent_component.add(vevent)
  333. element.text = vevent_component.serialize()
  334. return element
  335. def _convert_timezone(vevent: vobject.icalendar.RecurringComponent,
  336. name_prop: str,
  337. name_content_line: str):
  338. prop = getattr(vevent, name_prop, None)
  339. if prop:
  340. if type(prop.value) is datetime.date:
  341. date_time = datetime.datetime.fromordinal(
  342. prop.value.toordinal()
  343. ).replace(tzinfo=datetime.timezone.utc)
  344. else:
  345. date_time = prop.value.astimezone(datetime.timezone.utc)
  346. setattr(vevent, name_prop, ContentLine(name=name_content_line, value=date_time, params=[]))
  347. def _convert_to_utc(vevent: vobject.icalendar.RecurringComponent,
  348. name_prop: str,
  349. dt_format: str):
  350. prop = getattr(vevent, name_prop, None)
  351. if prop:
  352. setattr(vevent, name_prop, ContentLine(name=prop.name, value=prop.value.strftime(dt_format), params=[]))
  353. def _strip_single_event(vevent: vobject.icalendar.RecurringComponent, dt_format: str) -> None:
  354. _convert_timezone(vevent, 'dtstart', 'DTSTART')
  355. _convert_timezone(vevent, 'dtend', 'DTEND')
  356. _convert_timezone(vevent, 'recurrence_id', 'RECURRENCE-ID')
  357. # There is something strange behaviour during serialization native datetime, so converting manually
  358. _convert_to_utc(vevent, 'dtstart', dt_format)
  359. _convert_to_utc(vevent, 'dtend', dt_format)
  360. _convert_to_utc(vevent, 'recurrence_id', dt_format)
  361. try:
  362. delattr(vevent, 'rrule')
  363. delattr(vevent, 'exdate')
  364. delattr(vevent, 'exrule')
  365. delattr(vevent, 'rdate')
  366. except AttributeError:
  367. pass
  368. def _strip_component(vevent: vobject.base.Component) -> None:
  369. timezones_to_remove = []
  370. for component in vevent.components():
  371. if component.name == 'VTIMEZONE':
  372. timezones_to_remove.append(component)
  373. for timezone in timezones_to_remove:
  374. vevent.remove(timezone)
  375. def _split_overridden_vevents(
  376. component: vobject.base.Component,
  377. ) -> Tuple[
  378. vobject.icalendar.RecurringComponent,
  379. List[vobject.icalendar.RecurringComponent]
  380. ]:
  381. vevent_recurrence = None
  382. vevents_overridden = []
  383. for vevent in component.vevent_list:
  384. if hasattr(vevent, 'recurrence_id'):
  385. vevents_overridden += [vevent]
  386. elif vevent_recurrence:
  387. raise ValueError(
  388. f"component with UID {vevent.uid} "
  389. f"has more than one vevent with recurrence information"
  390. )
  391. else:
  392. vevent_recurrence = vevent
  393. if vevent_recurrence:
  394. return (
  395. vevent_recurrence, sorted(
  396. vevents_overridden,
  397. key=lambda vevent: vevent.recurrence_id.value
  398. )
  399. )
  400. else:
  401. raise ValueError(
  402. f"component with UID {vevent.uid} "
  403. f"does not have a vevent without a recurrence_id"
  404. )
  405. def _find_overridden(
  406. start: int,
  407. vevents: List[vobject.icalendar.RecurringComponent],
  408. dt: datetime.datetime,
  409. dt_format: str
  410. ) -> Tuple[int, Optional[vobject.icalendar.RecurringComponent]]:
  411. for i in range(start, len(vevents)):
  412. dt_event = datetime.datetime.strptime(
  413. vevents[i].recurrence_id.value,
  414. dt_format
  415. ).replace(tzinfo=datetime.timezone.utc)
  416. if dt_event == dt:
  417. return (i + 1, vevents[i])
  418. return (start, None)
  419. def xml_item_response(base_prefix: str, href: str,
  420. found_props: Sequence[ET.Element] = (),
  421. not_found_props: Sequence[ET.Element] = (),
  422. found_item: bool = True) -> ET.Element:
  423. response = ET.Element(xmlutils.make_clark("D:response"))
  424. href_element = ET.Element(xmlutils.make_clark("D:href"))
  425. href_element.text = xmlutils.make_href(base_prefix, href)
  426. response.append(href_element)
  427. if found_item:
  428. for code, props in ((200, found_props), (404, not_found_props)):
  429. if props:
  430. propstat = ET.Element(xmlutils.make_clark("D:propstat"))
  431. status = ET.Element(xmlutils.make_clark("D:status"))
  432. status.text = xmlutils.make_response(code)
  433. prop_element = ET.Element(xmlutils.make_clark("D:prop"))
  434. for prop in props:
  435. prop_element.append(prop)
  436. propstat.append(prop_element)
  437. propstat.append(status)
  438. response.append(propstat)
  439. else:
  440. status = ET.Element(xmlutils.make_clark("D:status"))
  441. status.text = xmlutils.make_response(404)
  442. response.append(status)
  443. return response
  444. def retrieve_items(
  445. base_prefix: str, path: str, collection: storage.BaseCollection,
  446. hreferences: Iterable[str], filters: Sequence[ET.Element],
  447. multistatus: ET.Element) -> Iterator[Tuple[radicale_item.Item, bool]]:
  448. """Retrieves all items that are referenced in ``hreferences`` from
  449. ``collection`` and adds 404 responses for missing and invalid items
  450. to ``multistatus``."""
  451. collection_requested = False
  452. def get_names() -> Iterator[str]:
  453. """Extracts all names from references in ``hreferences`` and adds
  454. 404 responses for invalid references to ``multistatus``.
  455. If the whole collections is referenced ``collection_requested``
  456. gets set to ``True``."""
  457. nonlocal collection_requested
  458. for hreference in hreferences:
  459. try:
  460. name = pathutils.name_from_path(hreference, collection)
  461. except ValueError as e:
  462. logger.warning("Skipping invalid path %r in REPORT request on "
  463. "%r: %s", hreference, path, e)
  464. response = xml_item_response(base_prefix, hreference,
  465. found_item=False)
  466. multistatus.append(response)
  467. continue
  468. if name:
  469. # Reference is an item
  470. yield name
  471. else:
  472. # Reference is a collection
  473. collection_requested = True
  474. for name, item in collection.get_multi(get_names()):
  475. if not item:
  476. uri = pathutils.unstrip_path(posixpath.join(collection.path, name))
  477. response = xml_item_response(base_prefix, uri, found_item=False)
  478. multistatus.append(response)
  479. else:
  480. yield item, False
  481. if collection_requested:
  482. yield from collection.get_filtered(filters)
  483. def test_filter(collection_tag: str, item: radicale_item.Item,
  484. filter_: ET.Element) -> bool:
  485. """Match an item against a filter."""
  486. if (collection_tag == "VCALENDAR" and
  487. filter_.tag != xmlutils.make_clark("C:%s" % filter_)):
  488. if len(filter_) == 0:
  489. return True
  490. if len(filter_) > 1:
  491. raise ValueError("Filter with %d children" % len(filter_))
  492. if filter_[0].tag != xmlutils.make_clark("C:comp-filter"):
  493. raise ValueError("Unexpected %r in filter" % filter_[0].tag)
  494. return radicale_filter.comp_match(item, filter_[0])
  495. if (collection_tag == "VADDRESSBOOK" and
  496. filter_.tag != xmlutils.make_clark("CR:%s" % filter_)):
  497. for child in filter_:
  498. if child.tag != xmlutils.make_clark("CR:prop-filter"):
  499. raise ValueError("Unexpected %r in filter" % child.tag)
  500. test = filter_.get("test", "anyof")
  501. if test == "anyof":
  502. return any(radicale_filter.prop_match(item.vobject_item, f, "CR")
  503. for f in filter_)
  504. if test == "allof":
  505. return all(radicale_filter.prop_match(item.vobject_item, f, "CR")
  506. for f in filter_)
  507. raise ValueError("Unsupported filter test: %r" % test)
  508. raise ValueError("Unsupported filter %r for %r" %
  509. (filter_.tag, collection_tag))
  510. class ApplicationPartReport(ApplicationBase):
  511. def do_REPORT(self, environ: types.WSGIEnviron, base_prefix: str,
  512. path: str, user: str) -> types.WSGIResponse:
  513. """Manage REPORT request."""
  514. access = Access(self._rights, user, path)
  515. if not access.check("r"):
  516. return httputils.NOT_ALLOWED
  517. try:
  518. xml_content = self._read_xml_request_body(environ)
  519. except RuntimeError as e:
  520. logger.warning("Bad REPORT request on %r: %s", path, e,
  521. exc_info=True)
  522. return httputils.BAD_REQUEST
  523. except socket.timeout:
  524. logger.debug("Client timed out", exc_info=True)
  525. return httputils.REQUEST_TIMEOUT
  526. with contextlib.ExitStack() as lock_stack:
  527. lock_stack.enter_context(self._storage.acquire_lock("r", user))
  528. item = next(iter(self._storage.discover(path)), None)
  529. if not item:
  530. return httputils.NOT_FOUND
  531. if not access.check("r", item):
  532. return httputils.NOT_ALLOWED
  533. if isinstance(item, storage.BaseCollection):
  534. collection = item
  535. else:
  536. assert item.collection is not None
  537. collection = item.collection
  538. if xml_content is not None and \
  539. xml_content.tag == xmlutils.make_clark("C:free-busy-query"):
  540. max_occurrence = self.configuration.get("reporting", "max_freebusy_occurrence")
  541. try:
  542. status, body = free_busy_report(
  543. base_prefix, path, xml_content, collection, self._encoding,
  544. lock_stack.close, max_occurrence)
  545. except ValueError as e:
  546. logger.warning(
  547. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  548. return httputils.BAD_REQUEST
  549. headers = {"Content-Type": "text/calendar; charset=%s" % self._encoding}
  550. return status, headers, str(body)
  551. else:
  552. try:
  553. status, xml_answer = xml_report(
  554. base_prefix, path, xml_content, collection, self._encoding,
  555. lock_stack.close)
  556. except ValueError as e:
  557. logger.warning(
  558. "Bad REPORT request on %r: %s", path, e, exc_info=True)
  559. return httputils.BAD_REQUEST
  560. headers = {"Content-Type": "text/xml; charset=%s" % self._encoding}
  561. return status, headers, self._xml_response(xml_answer)