__init__.py 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468
  1. # This file is part of Radicale - CalDAV and CardDAV server
  2. # Copyright © 2008 Nicolas Kandel
  3. # Copyright © 2008 Pascal Halter
  4. # Copyright © 2014 Jean-Marc Martins
  5. # Copyright © 2008-2017 Guillaume Ayoub
  6. # Copyright © 2017-2018 Unrud <unrud@outlook.com>
  7. #
  8. # This library is free software: you can redistribute it and/or modify
  9. # it under the terms of the GNU General Public License as published by
  10. # the Free Software Foundation, either version 3 of the License, or
  11. # (at your option) any later version.
  12. #
  13. # This library is distributed in the hope that it will be useful,
  14. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. # GNU General Public License for more details.
  17. #
  18. # You should have received a copy of the GNU General Public License
  19. # along with Radicale. If not, see <http://www.gnu.org/licenses/>.
  20. """
  21. Module for address books and calendar entries (see ``Item``).
  22. """
  23. import binascii
  24. import contextlib
  25. import math
  26. import os
  27. import sys
  28. from datetime import datetime, timedelta
  29. from hashlib import sha256
  30. from itertools import chain
  31. from typing import (Any, Callable, List, MutableMapping, Optional, Sequence,
  32. Tuple)
  33. import vobject
  34. from radicale import storage # noqa:F401
  35. from radicale import pathutils
  36. from radicale.item import filter as radicale_filter
  37. from radicale.log import logger
  38. def predict_tag_of_parent_collection(
  39. vobject_items: Sequence[vobject.base.Component]) -> Optional[str]:
  40. """Returns the predicted tag or `None`"""
  41. if len(vobject_items) != 1:
  42. return None
  43. if vobject_items[0].name == "VCALENDAR":
  44. return "VCALENDAR"
  45. if vobject_items[0].name in ("VCARD", "VLIST"):
  46. return "VADDRESSBOOK"
  47. return None
  48. def predict_tag_of_whole_collection(
  49. vobject_items: Sequence[vobject.base.Component],
  50. fallback_tag: Optional[str] = None) -> Optional[str]:
  51. """Returns the predicted tag or `fallback_tag`"""
  52. if vobject_items and vobject_items[0].name == "VCALENDAR":
  53. return "VCALENDAR"
  54. if vobject_items and vobject_items[0].name in ("VCARD", "VLIST"):
  55. return "VADDRESSBOOK"
  56. if not fallback_tag and not vobject_items:
  57. # Maybe an empty address book
  58. return "VADDRESSBOOK"
  59. return fallback_tag
  60. def check_and_sanitize_items(
  61. vobject_items: List[vobject.base.Component],
  62. is_collection: bool = False, tag: str = "") -> None:
  63. """Check vobject items for common errors and add missing UIDs.
  64. Modifies the list `vobject_items`.
  65. ``is_collection`` indicates that vobject_item contains unrelated
  66. components.
  67. The ``tag`` of the collection.
  68. """
  69. if tag and tag not in ("VCALENDAR", "VADDRESSBOOK"):
  70. raise ValueError("Unsupported collection tag: %r" % tag)
  71. if not is_collection and len(vobject_items) != 1:
  72. raise ValueError("Item contains %d components" % len(vobject_items))
  73. if tag == "VCALENDAR":
  74. if len(vobject_items) > 1:
  75. raise RuntimeError("VCALENDAR collection contains %d "
  76. "components" % len(vobject_items))
  77. vobject_item = vobject_items[0]
  78. if vobject_item.name != "VCALENDAR":
  79. raise ValueError("Item type %r not supported in %r "
  80. "collection" % (vobject_item.name, tag))
  81. component_uids = set()
  82. for component in vobject_item.components():
  83. if component.name in ("VTODO", "VEVENT", "VJOURNAL"):
  84. component_uid = get_uid(component)
  85. if component_uid:
  86. component_uids.add(component_uid)
  87. component_name = None
  88. object_uid = None
  89. object_uid_set = False
  90. for component in vobject_item.components():
  91. # https://tools.ietf.org/html/rfc4791#section-4.1
  92. if component.name == "VTIMEZONE":
  93. continue
  94. if component_name is None or is_collection:
  95. component_name = component.name
  96. elif component_name != component.name:
  97. raise ValueError("Multiple component types in object: %r, %r" %
  98. (component_name, component.name))
  99. if component_name not in ("VTODO", "VEVENT", "VJOURNAL"):
  100. continue
  101. component_uid = get_uid(component)
  102. if not object_uid_set or is_collection:
  103. object_uid_set = True
  104. object_uid = component_uid
  105. if not component_uid:
  106. if not is_collection:
  107. raise ValueError("%s component without UID in object" %
  108. component_name)
  109. component_uid = find_available_uid(
  110. component_uids.__contains__)
  111. component_uids.add(component_uid)
  112. if hasattr(component, "uid"):
  113. component.uid.value = component_uid
  114. else:
  115. component.add("UID").value = component_uid
  116. elif not object_uid or not component_uid:
  117. raise ValueError("Multiple %s components without UID in "
  118. "object" % component_name)
  119. elif object_uid != component_uid:
  120. raise ValueError(
  121. "Multiple %s components with different UIDs in object: "
  122. "%r, %r" % (component_name, object_uid, component_uid))
  123. # Workaround for bug in Lightning (Thunderbird)
  124. # Rescheduling a single occurrence from a repeating event creates
  125. # an event with DTEND and DURATION:PT0S
  126. if (hasattr(component, "dtend") and
  127. hasattr(component, "duration") and
  128. component.duration.value == timedelta(0)):
  129. logger.debug("Quirks: Removing zero duration from %s in "
  130. "object %r", component_name, component_uid)
  131. del component.duration
  132. # Workaround for Evolution
  133. # EXDATE has value DATE even if DTSTART/DTEND is DATE-TIME.
  134. # The RFC is vaguely formulated on the issue.
  135. # To resolve the issue convert EXDATE and RDATE to
  136. # the same type as DTDSTART
  137. if hasattr(component, "dtstart"):
  138. ref_date = component.dtstart.value
  139. ref_value_param = component.dtstart.params.get("VALUE")
  140. for dates in chain(component.contents.get("exdate", []),
  141. component.contents.get("rdate", [])):
  142. if all(type(d) == type(ref_date) for d in dates.value):
  143. continue
  144. for i, date in enumerate(dates.value):
  145. dates.value[i] = ref_date.replace(
  146. date.year, date.month, date.day)
  147. with contextlib.suppress(KeyError):
  148. del dates.params["VALUE"]
  149. if ref_value_param is not None:
  150. dates.params["VALUE"] = ref_value_param
  151. # vobject interprets recurrence rules on demand
  152. try:
  153. component.rruleset
  154. except Exception as e:
  155. raise ValueError("Invalid recurrence rules in %s in object %r"
  156. % (component.name, component_uid)) from e
  157. elif tag == "VADDRESSBOOK":
  158. # https://tools.ietf.org/html/rfc6352#section-5.1
  159. object_uids = set()
  160. for vobject_item in vobject_items:
  161. if vobject_item.name == "VCARD":
  162. object_uid = get_uid(vobject_item)
  163. if object_uid:
  164. object_uids.add(object_uid)
  165. for vobject_item in vobject_items:
  166. if vobject_item.name == "VLIST":
  167. # Custom format used by SOGo Connector to store lists of
  168. # contacts
  169. continue
  170. if vobject_item.name != "VCARD":
  171. raise ValueError("Item type %r not supported in %r "
  172. "collection" % (vobject_item.name, tag))
  173. object_uid = get_uid(vobject_item)
  174. if not object_uid:
  175. if not is_collection:
  176. raise ValueError("%s object without UID" %
  177. vobject_item.name)
  178. object_uid = find_available_uid(object_uids.__contains__)
  179. object_uids.add(object_uid)
  180. if hasattr(vobject_item, "uid"):
  181. vobject_item.uid.value = object_uid
  182. else:
  183. vobject_item.add("UID").value = object_uid
  184. else:
  185. for item in vobject_items:
  186. raise ValueError("Item type %r not supported in %s collection" %
  187. (item.name, repr(tag) if tag else "generic"))
  188. def check_and_sanitize_props(props: MutableMapping[Any, Any]
  189. ) -> MutableMapping[str, str]:
  190. """Check collection properties for common errors.
  191. Modifies the dict `props`.
  192. """
  193. for k, v in list(props.items()): # Make copy to be able to delete items
  194. if not isinstance(k, str):
  195. raise ValueError("Key must be %r not %r: %r" % (
  196. str.__name__, type(k).__name__, k))
  197. if not isinstance(v, str):
  198. if v is None:
  199. del props[k]
  200. continue
  201. raise ValueError("Value of %r must be %r not %r: %r" % (
  202. k, str.__name__, type(v).__name__, v))
  203. if k == "tag":
  204. if v not in ("", "VCALENDAR", "VADDRESSBOOK"):
  205. raise ValueError("Unsupported collection tag: %r" % v)
  206. return props
  207. def find_available_uid(exists_fn: Callable[[str], bool], suffix: str = ""
  208. ) -> str:
  209. """Generate a pseudo-random UID"""
  210. # Prevent infinite loop
  211. for _ in range(1000):
  212. r = binascii.hexlify(os.urandom(16)).decode("ascii")
  213. name = "%s-%s-%s-%s-%s%s" % (
  214. r[:8], r[8:12], r[12:16], r[16:20], r[20:], suffix)
  215. if not exists_fn(name):
  216. return name
  217. # something is wrong with the PRNG
  218. raise RuntimeError("No unique random sequence found")
  219. def get_etag(text: str) -> str:
  220. """Etag from collection or item.
  221. Encoded as quoted-string (see RFC 2616).
  222. """
  223. etag = sha256()
  224. etag.update(text.encode())
  225. return '"%s"' % etag.hexdigest()
  226. def get_uid(vobject_component: vobject.base.Component) -> str:
  227. """UID value of an item if defined."""
  228. return (vobject_component.uid.value or ""
  229. if hasattr(vobject_component, "uid") else "")
  230. def get_uid_from_object(vobject_item: vobject.base.Component) -> str:
  231. """UID value of an calendar/addressbook object."""
  232. if vobject_item.name == "VCALENDAR":
  233. if hasattr(vobject_item, "vevent"):
  234. return get_uid(vobject_item.vevent)
  235. if hasattr(vobject_item, "vjournal"):
  236. return get_uid(vobject_item.vjournal)
  237. if hasattr(vobject_item, "vtodo"):
  238. return get_uid(vobject_item.vtodo)
  239. elif vobject_item.name == "VCARD":
  240. return get_uid(vobject_item)
  241. return ""
  242. def find_tag(vobject_item: vobject.base.Component) -> str:
  243. """Find component name from ``vobject_item``."""
  244. if vobject_item.name == "VCALENDAR":
  245. for component in vobject_item.components():
  246. if component.name != "VTIMEZONE":
  247. return component.name or ""
  248. return ""
  249. def find_time_range(vobject_item: vobject.base.Component, tag: str
  250. ) -> Tuple[int, int]:
  251. """Find enclosing time range from ``vobject item``.
  252. ``tag`` must be set to the return value of ``find_tag``.
  253. Returns a tuple (``start``, ``end``) where ``start`` and ``end`` are
  254. POSIX timestamps.
  255. This is intened to be used for matching against simplified prefilters.
  256. """
  257. if not tag:
  258. return radicale_filter.TIMESTAMP_MIN, radicale_filter.TIMESTAMP_MAX
  259. start = end = None
  260. def range_fn(range_start: datetime, range_end: datetime,
  261. is_recurrence: bool) -> bool:
  262. nonlocal start, end
  263. if start is None or range_start < start:
  264. start = range_start
  265. if end is None or end < range_end:
  266. end = range_end
  267. return False
  268. def infinity_fn(range_start: datetime) -> bool:
  269. nonlocal start, end
  270. if start is None or range_start < start:
  271. start = range_start
  272. end = radicale_filter.DATETIME_MAX
  273. return True
  274. radicale_filter.visit_time_ranges(vobject_item, tag, range_fn, infinity_fn)
  275. if start is None:
  276. start = radicale_filter.DATETIME_MIN
  277. if end is None:
  278. end = radicale_filter.DATETIME_MAX
  279. try:
  280. return math.floor(start.timestamp()), math.ceil(end.timestamp())
  281. except ValueError as e:
  282. if str(e) == ("offset must be a timedelta representing a whole "
  283. "number of minutes") and sys.version_info < (3, 6):
  284. raise RuntimeError("Unsupported in Python < 3.6: %s" % e) from e
  285. raise
  286. class Item:
  287. """Class for address book and calendar entries."""
  288. collection: Optional["storage.BaseCollection"]
  289. href: Optional[str]
  290. last_modified: Optional[str]
  291. _collection_path: str
  292. _text: Optional[str]
  293. _vobject_item: Optional[vobject.base.Component]
  294. _etag: Optional[str]
  295. _uid: Optional[str]
  296. _name: Optional[str]
  297. _component_name: Optional[str]
  298. _time_range: Optional[Tuple[int, int]]
  299. def __init__(self,
  300. collection_path: Optional[str] = None,
  301. collection: Optional["storage.BaseCollection"] = None,
  302. vobject_item: Optional[vobject.base.Component] = None,
  303. href: Optional[str] = None,
  304. last_modified: Optional[str] = None,
  305. text: Optional[str] = None,
  306. etag: Optional[str] = None,
  307. uid: Optional[str] = None,
  308. name: Optional[str] = None,
  309. component_name: Optional[str] = None,
  310. time_range: Optional[Tuple[int, int]] = None):
  311. """Initialize an item.
  312. ``collection_path`` the path of the parent collection (optional if
  313. ``collection`` is set).
  314. ``collection`` the parent collection (optional).
  315. ``href`` the href of the item.
  316. ``last_modified`` the HTTP-datetime of when the item was modified.
  317. ``text`` the text representation of the item (optional if
  318. ``vobject_item`` is set).
  319. ``vobject_item`` the vobject item (optional if ``text`` is set).
  320. ``etag`` the etag of the item (optional). See ``get_etag``.
  321. ``uid`` the UID of the object (optional). See ``get_uid_from_object``.
  322. ``name`` the name of the item (optional). See ``vobject_item.name``.
  323. ``component_name`` the name of the primary component (optional).
  324. See ``find_tag``.
  325. ``time_range`` the enclosing time range. See ``find_time_range``.
  326. """
  327. if text is None and vobject_item is None:
  328. raise ValueError(
  329. "At least one of 'text' or 'vobject_item' must be set")
  330. if collection_path is None:
  331. if collection is None:
  332. raise ValueError("At least one of 'collection_path' or "
  333. "'collection' must be set")
  334. collection_path = collection.path
  335. assert collection_path == pathutils.strip_path(
  336. pathutils.sanitize_path(collection_path))
  337. self._collection_path = collection_path
  338. self.collection = collection
  339. self.href = href
  340. self.last_modified = last_modified
  341. self._text = text
  342. self._vobject_item = vobject_item
  343. self._etag = etag
  344. self._uid = uid
  345. self._name = name
  346. self._component_name = component_name
  347. self._time_range = time_range
  348. def serialize(self) -> str:
  349. if self._text is None:
  350. try:
  351. self._text = self.vobject_item.serialize()
  352. except Exception as e:
  353. raise RuntimeError("Failed to serialize item %r from %r: %s" %
  354. (self.href, self._collection_path,
  355. e)) from e
  356. return self._text
  357. @property
  358. def vobject_item(self):
  359. if self._vobject_item is None:
  360. try:
  361. self._vobject_item = vobject.readOne(self._text)
  362. except Exception as e:
  363. raise RuntimeError("Failed to parse item %r from %r: %s" %
  364. (self.href, self._collection_path,
  365. e)) from e
  366. return self._vobject_item
  367. @property
  368. def etag(self) -> str:
  369. """Encoded as quoted-string (see RFC 2616)."""
  370. if self._etag is None:
  371. self._etag = get_etag(self.serialize())
  372. return self._etag
  373. @property
  374. def uid(self) -> str:
  375. if self._uid is None:
  376. self._uid = get_uid_from_object(self.vobject_item)
  377. return self._uid
  378. @property
  379. def name(self) -> str:
  380. if self._name is None:
  381. self._name = self.vobject_item.name or ""
  382. return self._name
  383. @property
  384. def component_name(self) -> str:
  385. if self._component_name is None:
  386. self._component_name = find_tag(self.vobject_item)
  387. return self._component_name
  388. @property
  389. def time_range(self) -> Tuple[int, int]:
  390. if self._time_range is None:
  391. self._time_range = find_time_range(
  392. self.vobject_item, self.component_name)
  393. return self._time_range
  394. def prepare(self) -> None:
  395. """Fill cache with values."""
  396. orig_vobject_item = self._vobject_item
  397. self.serialize()
  398. self.etag
  399. self.uid
  400. self.name
  401. self.time_range
  402. self.component_name
  403. self._vobject_item = orig_vobject_item