__init__.py 18 KB

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